refactor code

This commit is contained in:
Матвей
2026-11-06 11:12:38 +03:00
parent c885462c04
commit 7fe48e38c1
50 changed files with 5674 additions and 564 deletions
+41
View File
@@ -0,0 +1,41 @@
"""Export synthetic trace/log evidence through Grafana; credentials never enter artifacts."""
import argparse
import base64
from datetime import datetime, timezone
import json
from pathlib import Path
import urllib.parse
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
auth = 'Basic ' + base64.b64encode(('admin:' + (ROOT/'secrets/grafana_password').read_text().strip()).encode()).decode()
def get(source, path, params=None):
url = f'http://127.0.0.1:3000/api/datasources/proxy/uid/{source}/' + path
if params: url += '?' + urllib.parse.urlencode(params)
with urllib.request.urlopen(urllib.request.Request(url,headers={'Authorization':auth}),timeout=15) as r:
return json.load(r)
def capture(trace_id=None, query=None):
query = query or '{service_name="messenger-api"} | status="503"'
if trace_id:
query = '{service_name=~"messenger-api|messenger-worker"} | trace_id="' + trace_id + '"'
logs = get('loki','loki/api/v1/query_range',{'query':query,'since':'30m','limit':20,'direction':'backward'})
if not trace_id:
for stream in logs['data']['result']:
for value in stream['values']:
metadata = dict(stream['stream'])
if len(value)>2: metadata.update(value[2])
trace_id = metadata.get('trace_id')
if trace_id: break
if trace_id: break
if not trace_id:
raise RuntimeError('No correlated log/trace found')
trace = get('tempo','api/traces/'+trace_id)
return {'captured_at':datetime.now(timezone.utc).isoformat(),'query':query,'trace_id':trace_id,'logs':logs,'trace':trace}
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--trace-id');parser.add_argument('--output',required=True)
args=parser.parse_args()
result=capture(args.trace_id)
(ROOT/args.output).write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n')
print('Saved correlated evidence:',args.output,'trace_id:',result['trace_id'])
+18
View File
@@ -0,0 +1,18 @@
"""Execute every provisioned PromQL target against the running Grafana datasource."""
import importlib.util
import json
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
spec=importlib.util.spec_from_file_location('capture',ROOT/'student-tests/capture_observability.py')
capture=importlib.util.module_from_spec(spec);spec.loader.exec_module(capture)
dashboard=json.loads((ROOT/'infra/grafana/dashboards/messenger.json').read_text())
results=[]
for panel in dashboard['panels']:
for target in panel.get('targets',[]):
if 'expr' not in target:continue
query=target['expr'].replace('$__rate_interval','1m').replace('$__interval','5s')
result=capture.get('prometheus','api/v1/query',{'query':query})
assert result['status']=='success',result
results.append({'panel':panel['title'],'query':query,'series':len(result['data']['result'])})
(ROOT/'evidence/review-dashboard.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n')
print('PASS:',len(results),'dashboard queries; empty targets:',sum(r['series']==0 for r in results))
+31
View File
@@ -0,0 +1,31 @@
"""Verify exported parent relationships and the completed retry, not just trace existence."""
import base64
import json
from collections import Counter
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
data=json.loads((ROOT/'evidence/review-retry-trace.json').read_text())
spans=[s for batch in data['trace']['batches'] for scope in batch.get('scopeSpans',[]) for s in scope.get('spans',[])]
by_id={s['spanId']:s for s in spans}
counts=Counter(s['name'] for s in spans)
producers=[s for s in spans if s['kind']=='SPAN_KIND_PRODUCER']
consumers=[s for s in spans if s['kind']=='SPAN_KIND_CONSUMER']
assert len(producers)>=2 and consumers,counts
for producer in producers:
ancestor = producer
for _ in range(len(spans)):
ancestor = by_id[ancestor['parentSpanId']]
if ancestor['kind']=='SPAN_KIND_SERVER': break
else: raise AssertionError('producer has no API ancestor')
for consumer in consumers:
assert by_id[consumer['parentSpanId']]['kind']=='SPAN_KIND_PRODUCER'
assert counts['postgres.complete_attachment_job']>=1,counts
assert any(s['name'].startswith('s3.') for s in spans),counts
assert all(base64.b64decode(s['traceId']).hex()==data['trace_id'] for s in spans)
services={stream['stream']['service_name'] for stream in data['logs']['data']['result']}
assert {'messenger-api','messenger-worker'}<=services,services
result={'trace_id':data['trace_id'],'span_count':len(spans),'span_names':dict(counts),
'producer_count':len(producers),'consumer_count':len(consumers),'log_services':sorted(services),
'parent_relationships':'PASS','note':'Abrupt os._exit may lose unfinished spans of the crashed attempt; redelivery and committed retry remain visible.'}
(ROOT/'evidence/review-retry-summary.json').write_text(json.dumps(result,indent=2)+'\n')
print('PASS:',json.dumps(result))
+11 -1
View File
@@ -53,12 +53,14 @@ class CriticalTests(unittest.IsolatedAsyncioTestCase):
'content_type': 'image/png', 'size_bytes': 1, 'sha256': 'unused',
}
store.complete_attachment_job.return_value = committed
store.ready_seconds.return_value = 0.25
s3.settings = SimpleNamespace(max_pixels=40000000)
s3.download_key.return_value = b'fixture'
s3.delete.side_effect = RuntimeError('storage temporarily unavailable')
payload = {'attachment_id': str(uuid4())}
with patch('src.worker.render_isolated', return_value=[('thumbnail', b'jpeg', 'image/jpeg', 1, 1)]):
await process(store, s3, payload, 60)
outcome = await process(store, s3, payload, 60)
self.assertEqual(outcome, "success" if committed else "skipped")
self.assertEqual(store.complete_attachment_job.call_args.args[-1], stamp)
return store, s3
@@ -71,6 +73,14 @@ class CriticalTests(unittest.IsolatedAsyncioTestCase):
_, s3 = await self.run_processing(False)
s3.delete.assert_not_awaited()
async def test_duplicate_is_skipped_not_successful(self):
store, s3 = AsyncMock(), AsyncMock()
store.claim_attachment_job.return_value = None
result = await process(store, s3, {'attachment_id': str(uuid4())}, 60)
self.assertEqual(result, 'skipped')
store.complete_attachment_job.assert_not_awaited()
s3.copy.assert_not_awaited()
async def test_stale_claim_cannot_publish_metadata(self):
store = PostgresStore('unused')
connection = AsyncMock()
+30
View File
@@ -0,0 +1,30 @@
"""Crash one idle lab worker after S3 writes; restore normal configuration in finally."""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT=Path(__file__).resolve().parents[1]
def compose(*args, env=None):
return subprocess.run(['docker','compose',*args],cwd=ROOT,env=env,check=True,capture_output=True,text=True).stdout
count=compose('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',"SELECT count(*) FROM attachment_jobs WHERE status IN ('queued','processing')")
if int(count.strip()):raise RuntimeError('Pending work; refusing crash injection')
try:
compose('stop','-t','5','worker')
compose('up','-d','--no-deps','worker',env={**os.environ,'WORKER_FAULT_AFTER_S3_PUT':'1'})
subprocess.run([sys.executable,'student-tests/trace_retry.py'],cwd=ROOT,check=True,timeout=180)
out=json.loads((ROOT/'evidence/review-retry-job.json').read_text())
from uuid import UUID
identity=str(UUID(out['attachment_id']))
out['db_attempt']=int(compose('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',f"SELECT attempt FROM attachment_jobs WHERE attachment_id='{identity}'").strip())
cid=compose('ps','-q','worker').strip()
out['restart_count']=int(subprocess.run(['docker','inspect','--format','{{.RestartCount}}',cid],check=True,capture_output=True,text=True).stdout.strip())
assert out['db_attempt']==2 and out['restart_count']==1,out
(ROOT/'evidence/review-retry-job.json').write_text(json.dumps(out,indent=2)+'\n')
time.sleep(10)
subprocess.run([sys.executable,'student-tests/capture_observability.py','--trace-id',out['trace_id'],'--output','evidence/review-retry-trace.json'],cwd=ROOT,check=True)
finally:
compose('stop','-t','5','worker')
compose('up','-d','--no-deps','worker',env={**os.environ,'WORKER_FAULT_AFTER_S3_PUT':'0'})
print('PASS: attempt 2, one restart, normal worker restored')
+22
View File
@@ -0,0 +1,22 @@
"""Repeat short review checks; experiments are separate and intentionally disruptive."""
from datetime import datetime, timezone
import json
from pathlib import Path
import subprocess
ROOT=Path(__file__).resolve().parents[1]
checks=[['make','check'],['make','validate','PYTHON=.venv/bin/python'],
['docker','compose','config','--quiet'],
['docker','run','--rm','-v',f'{ROOT}:/workspace:ro','--entrypoint','promtool','prom/prometheus:v3.2.1','test','rules',
'/workspace/student-tests/alerts.test.yaml','/workspace/student-tests/burn_rules.test.yaml','/workspace/student-tests/telemetry_alerts.test.yaml'],
['make','test'],['python3','student-tests/check_dashboard.py']]
results=[]
for command in checks:
proc=subprocess.run(command,cwd=ROOT,capture_output=True,text=True,timeout=180)
results.append({'command':command,'exit_code':proc.returncode,'output':proc.stdout+proc.stderr})
for filename in ('telemetry_unit.py','pipeline_critical.py','slo_commit_integration.py'):
command=['docker','compose','exec','-T','api-a','/app/.venv/bin/python','-']
proc=subprocess.run(command,input=(ROOT/'student-tests'/filename).read_text(),cwd=ROOT,capture_output=True,text=True,timeout=60)
results.append({'command':command,'stdin':f'student-tests/{filename}','exit_code':proc.returncode,'output':proc.stdout+proc.stderr})
(ROOT/'evidence/review-checks.json').write_text(json.dumps({'utc':datetime.now(timezone.utc).isoformat(),'checks':results},ensure_ascii=False,indent=2)+'\n')
for r in results:print('PASS' if r['exit_code']==0 else 'FAIL',r.get('stdin',r['command']))
raise SystemExit(any(r['exit_code'] for r in results))
+13
View File
@@ -0,0 +1,13 @@
"""Read current health of telemetry, without printing access credentials."""
import importlib.util
import json
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
spec=importlib.util.spec_from_file_location('capture',ROOT/'student-tests/capture_observability.py')
c=importlib.util.module_from_spec(spec);spec.loader.exec_module(c)
queries=['messenger_slo_unknown{service_name="messenger-outbox"}',
'time()-max(messenger_queue_sample_time_seconds{service_name="messenger-outbox"})',
'messenger_queue_depth{service_name="messenger-outbox"}',
'messenger_job_ready_duration_seconds_count{service_name="messenger-worker"}']
for q in queries:
print(q,json.dumps(c.get('prometheus','api/v1/query',{'query':q})['data']['result']))
+20
View File
@@ -0,0 +1,20 @@
"""Run inherited public durability/failover checks and restore both API replicas."""
from datetime import datetime, timezone
import json
from pathlib import Path
import subprocess
ROOT=Path(__file__).resolve().parents[1]
results=[]
try:
for command in [
['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh'],
['make','test-failover','ACTION_SCRIPT=scripts/stop-one.sh']]:
result=subprocess.run(command,cwd=ROOT,capture_output=True,text=True,timeout=240)
results.append({'command':command,'exit_code':result.returncode,'output':result.stdout+result.stderr})
print('PASS' if result.returncode==0 else 'FAIL',command,flush=True)
if result.returncode:break
finally:
restore=subprocess.run(['docker','compose','up','-d','--no-deps','--wait','api-a','api-b','worker','outbox'],cwd=ROOT,capture_output=True,text=True,timeout=90)
results.append({'restore_exit_code':restore.returncode,'output':restore.stdout+restore.stderr})
(ROOT/'evidence/review-resilience.json').write_text(json.dumps({'utc':datetime.now(timezone.utc).isoformat(),'checks':results},ensure_ascii=False,indent=2)+'\n')
raise SystemExit(any(r.get('exit_code',r.get('restore_exit_code')) for r in results))
+8
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
"""Summarize observed alert transitions; sampling bounds detection precision."""
import json
from datetime import datetime
from pathlib import Path
root = Path(__file__).resolve().parents[1]
@@ -8,6 +9,13 @@ data = json.loads((root / 'evidence/slo-incidents.json').read_text())
samples = sorted((s for s in data['samples'] if 'firing' in s), key=lambda s: s['monotonic'])
alerts = ['MessengerApiBurnFast', 'MessengerApiBurnSlow']
output = {'sampling_interval_seconds': 5, 'monitor_errors': sum('monitor_error' in s for s in data['samples']), 'phases': {}}
drifts = [abs((datetime.fromisoformat(b['time']) - datetime.fromisoformat(a['time'])).total_seconds()
- (b['monotonic'] - a['monotonic'])) for a, b in zip(samples, samples[1:])]
gaps = [b['monotonic'] - a['monotonic'] for a, b in zip(samples, samples[1:])]
output['timing_quality'] = {'max_wall_monotonic_disagreement_seconds': round(max(drifts, default=0), 3),
'max_observed_sampling_gap_seconds': round(max(gaps, default=0), 3),
'valid_for_elapsed_time_claims': max(drifts, default=0) <= 1,
'note': 'Disagreement does not identify its cause; rerun if invalid. Precision is bounded by actual gaps, not the configured sleep.'}
base = [s for s in samples if s['phase'] == 'baseline']
output['baseline'] = {'samples': len(base), 'samples_with_burn_alert': sum(bool(s['firing']) for s in base), 'scope': 'one observed healthy baseline, not a long-term false-positive rate'}
for name, period in data['periods'].items():
+45
View File
@@ -0,0 +1,45 @@
"""Run inside api-a; session-local table shadows real SLO data (no business mutations)."""
import asyncio
from datetime import datetime, timezone
from uuid import uuid4
import asyncpg
from src.config import load_settings
from src.storage.postgres import PostgresStore
async def main():
store = PostgresStore(load_settings().database_url)
store._pool = await asyncpg.create_pool(load_settings().database_url, min_size=1, max_size=1)
try:
async with store.pool.acquire() as conn:
await conn.execute('CREATE TEMP TABLE attachment_slo (LIKE public.attachment_slo INCLUDING DEFAULTS)')
identity = uuid4()
async with conn.transaction():
await conn.execute('INSERT INTO attachment_slo (attachment_id) VALUES ($1)', identity)
await asyncio.sleep(.2)
before_accept_commit = await conn.fetchval('SELECT clock_timestamp()')
async with conn.transaction():
await conn.execute('UPDATE attachment_slo SET ready_xid=pg_current_xact_id()::xid')
await asyncio.sleep(.2)
before_ready_commit = await conn.fetchval('SELECT clock_timestamp()')
await store.sample_ready_slo()
row = await store.pool.fetchrow('SELECT * FROM attachment_slo')
assert row['accepted_at'] >= before_accept_commit
assert row['ready_at'] >= before_ready_commit
elapsed = await store.ready_seconds(identity)
assert elapsed >= .2, elapsed
# Mature a successful synthetic cohort, then emulate replay metadata changes.
await store.pool.execute("UPDATE attachment_slo SET accepted_at=now()-interval '32 seconds',ready_at=now()-interval '31 seconds'")
first = dict(await store.sample_ready_slo())
assert first == {'eligible': 1, 'bad': 0, 'unknown': 0}, first
await store.pool.execute("UPDATE attachment_slo SET ready_at=now()+interval '1 minute'")
assert dict(await store.sample_ready_slo()) == first
await store.pool.execute("INSERT INTO attachment_slo (attachment_id,accepted_at) VALUES ($1,now()-interval '31 seconds')", uuid4())
late = dict(await store.sample_ready_slo())
assert late == {'eligible': 2, 'bad': 1, 'unknown': 0}, late
await store.pool.execute('UPDATE attachment_slo SET ready_at=now(),ready_xid=pg_current_xact_id()::xid WHERE ready_at IS NULL')
assert dict(await store.sample_ready_slo()) == late
print('PASS: commit boundaries; immutable good/bad cohorts; late completion remains bad')
finally:
await store.close()
asyncio.run(main())
+11 -9
View File
@@ -2,7 +2,7 @@
"""Run two bounded DB-lock incidents against the local Compose project.
Creates synthetic data, records only aggregate counts/alert states, and releases
all locks on exit. Run on the isolated lab6 stack, never a shared database.
bounded locks; interrupted server-side sleeps may persist until their deadline. Run on the isolated lab6 stack, never a shared database.
"""
import base64
from concurrent.futures import ThreadPoolExecutor
@@ -43,7 +43,7 @@ def monitor():
try:
alerts = get('alerts')['alerts']
firing = sorted(a['labels']['alertname'] for a in alerts if a['state'] == 'firing' and 'Burn' in a['labels']['alertname'])
with LOCK: sample = {'time': utc(), 'monotonic': time.monotonic(), 'phase': SCENARIO['phase'], 'counts': dict(COUNTS), 'firing': firing}
with LOCK: sample = {'time': utc(), 'monotonic': time.monotonic(), 'phase': SCENARIO['phase'], 'counts': dict(COUNTS), 'firing': firing, 'all_firing': sorted(a['labels']['alertname'] for a in alerts if a['state'] == 'firing')}
SAMPLES.append(sample)
except Exception as error:
SAMPLES.append({'time': utc(), 'monotonic': time.monotonic(), 'phase': SCENARIO['phase'], 'monitor_error': type(error).__name__})
@@ -103,13 +103,15 @@ def main():
try:
with ThreadPoolExecutor(max_workers=3) as pool:
futures = [pool.submit(worker, actor, chat) for _ in range(3)]
phase('baseline'); time.sleep(60)
result['periods']['burst'] = incident('burst', 75)
time.sleep(100)
result['periods']['sustained'] = incident('sustained', 180)
time.sleep(100)
phase('complete')
STOP.set()
try:
phase('baseline'); time.sleep(60)
result['periods']['burst'] = incident('burst', 75)
time.sleep(100)
result['periods']['sustained'] = incident('sustained', 180)
time.sleep(100)
phase('complete')
finally:
STOP.set()
for future in futures: future.result(timeout=15)
finally:
STOP.set(); monitor_thread.join(timeout=10)
+10 -6
View File
@@ -22,12 +22,14 @@ def prom(path, query=None):
if query is not None: url += '?' + urllib.parse.urlencode({'query': query})
with urllib.request.urlopen(urllib.request.Request(url, headers={'Authorization': auth}), timeout=5) as r: return json.load(r)['data']
def metric(name):
result = prom('query', name + '{service_name="messenger-outbox"}')['result']
result = prom('query', 'max(' + name + '{service_name="messenger-outbox"})')['result']
return float(result[0]['value'][1]) if result else None
def sample(phase):
alerts = prom('alerts')['alerts']
return {'time': utc(), 'monotonic': time.monotonic(), 'phase': phase,
'firing': sorted(a['labels']['alertname'] for a in alerts if a['state']=='firing' and a['labels']['alertname'].startswith('MessengerReadyBurn')),
'all_firing': sorted(a['labels']['alertname'] for a in alerts if a['state']=='firing'),
'queue_depth': metric('messenger_queue_depth'), 'queue_age': metric('messenger_queue_age_seconds'),
'eligible': metric('messenger_slo_ready_eligible_total'), 'bad': metric('messenger_slo_ready_bad_total')}
def docker(*args): subprocess.run(['docker','compose',*args], cwd=ROOT, check=True, stdout=subprocess.DEVNULL)
def run():
@@ -43,13 +45,15 @@ def run():
for _ in range(8): accepted.append(client.attachment(actor,chat)[0])
out['accepted_at']={'time':utc(),'monotonic':time.monotonic()}
print('8 synthetic jobs accepted; waiting for burn alert', flush=True)
seen=set()
deadline=time.monotonic()+100
while time.monotonic()<deadline:
s=sample('worker_stopped'); samples.append(s)
if 'MessengerReadyBurnFast' in s['firing']: break
seen.update(s['all_firing'])
if {'MessengerReadyBurnFast','MessengerQueueLag'} <= seen: break
time.sleep(5)
else: raise RuntimeError('Ready fast burn did not fire in 100 seconds')
docker('start','worker'); worker_stopped=False
else: raise RuntimeError('Both ready fast burn and QueueLag were not observed in 100 seconds')
docker('up','-d','--no-deps','worker'); worker_stopped=False
out['worker_started']={'time':utc(),'monotonic':time.monotonic()}
for att in accepted: client.wait_ready(actor,att,wait_seconds=90)
out['all_ready']={'time':utc(),'monotonic':time.monotonic()}
@@ -57,13 +61,13 @@ def run():
deadline=time.monotonic()+100
while time.monotonic()<deadline:
s=sample('recovery');samples.append(s)
if not s['firing']: break
if not s['firing'] and 'MessengerQueueLag' not in s['all_firing']: break
time.sleep(5)
else: raise RuntimeError('Ready burn alert did not clear in 100 seconds')
out['result']='PASS'
finally:
if worker_stopped:
try: docker('start','worker')
try: docker('up','-d','--no-deps','worker')
except Exception: out['worker_restore_failed']=True
(ROOT/'evidence/slo-ready-incident.json').write_text(json.dumps(out,ensure_ascii=False,indent=2)+'\n')
print('PASS: ready SLO incident; evidence/slo-ready-incident.json',flush=True)
+31
View File
@@ -0,0 +1,31 @@
rule_files:
- /workspace/infra/prometheus/alerts.yaml
evaluation_interval: 5s
tests:
- interval: 5s
input_series: []
alert_rule_test:
- eval_time: 30s
alertname: MessengerQueueTelemetryStale
exp_alerts:
- exp_labels: {severity: warning}
exp_annotations:
summary: 'Queue and ready SLO telemetry is stale'
runbook: 'See docs/slo-runbook.md; check outbox and DB before interpreting ready SLO.'
- interval: 5s
input_series:
- series: 'messenger_queue_sample_time_seconds{service_name="messenger-outbox"}'
values: '0+5x20'
- series: 'messenger_slo_unknown{service_name="messenger-outbox"}'
values: '1x20'
alert_rule_test:
- eval_time: 30s
alertname: MessengerQueueTelemetryStale
exp_alerts: []
- eval_time: 30s
alertname: MessengerReadyTimestampUnknown
exp_alerts:
- exp_labels: {severity: warning}
exp_annotations:
summary: 'Ready SLO commit timestamps unavailable'
runbook: 'Check track_commit_timestamp and outbox; unknown events are not proof of SLO compliance.'
+38
View File
@@ -65,4 +65,42 @@ class TelemetryTests(unittest.TestCase):
self.assertEqual(point.value, 1)
self.assertEqual(set(point.attributes), {'method', 'route', 'status_class'})
def test_otlp_log_drops_secrets_and_exception(self):
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import InMemoryLogExporter, SimpleLogRecordProcessor
exporter = InMemoryLogExporter()
provider = LoggerProvider()
provider.add_log_record_processor(SimpleLogRecordProcessor(exporter))
handler = LoggingHandler(logger_provider=provider)
tel.log.addHandler(handler)
try:
with tel.tracer.start_as_current_span('log-test') as span:
try:
raise ValueError('secret exception body')
except ValueError:
tel.log.exception('http.request', extra={'authorization': 'secret token', 'body': 'private', 'route': '/api/v1/users'})
record = exporter.get_finished_logs()[0].log_record
self.assertEqual(record.body, 'http.request')
self.assertEqual(record.trace_id, span.get_span_context().trace_id)
self.assertNotIn('authorization', record.attributes)
self.assertNotIn('body', record.attributes)
self.assertFalse(any(k.startswith('exception.') for k in record.attributes))
finally:
tel.log.removeHandler(handler)
provider.shutdown()
def test_failed_publish_marks_span_without_exception_content(self):
self.exporter.clear()
with patch.object(broker, '_publish', side_effect=OSError('private broker URL')):
with self.assertRaises(broker.ApiError):
asyncio.run(broker.publish({'attempt': 1}))
span, = self.exporter.get_finished_spans()
self.assertEqual(span.status.status_code, tel.StatusCode.ERROR)
self.assertEqual(span.events, ())
def test_custom_http_methods_have_bounded_label(self):
self.assertEqual(tel.http_method('POST'), 'POST')
for value in ('CUSTOM1', 'CUSTOM2', 'secret'):
self.assertEqual(tel.http_method(value), '_OTHER')
if __name__ == '__main__': unittest.main()
+60
View File
@@ -0,0 +1,60 @@
"""Bounded Tempo failure with before/after counters and sampled Collector memory."""
import importlib.util
import json
from pathlib import Path
import subprocess
import sys
import time
from datetime import datetime, timezone
ROOT=Path(__file__).resolve().parents[1]
spec=importlib.util.spec_from_file_location('capture',ROOT/'student-tests/capture_observability.py')
capture=importlib.util.module_from_spec(spec);spec.loader.exec_module(capture)
QUERIES={name:f'sum({name}{{exporter="otlp/tempo"}}) or vector(0)' for name in (
'otelcol_exporter_enqueue_failed_spans_total','otelcol_exporter_send_failed_spans_total',
'otelcol_exporter_sent_spans_total','otelcol_exporter_queue_size','otelcol_exporter_queue_capacity')}
def docker(*args):
return subprocess.run(['docker','compose',*args],cwd=ROOT,check=True,capture_output=True,text=True).stdout
def sample(phase):
row={'phase':phase,'utc':datetime.now(timezone.utc).isoformat(),'monotonic':time.monotonic(),'metrics':{}}
for name,query in QUERIES.items():
result=capture.get('prometheus','api/v1/query',{'query':query})['data']['result']
row['metrics'][name]=float(result[0]['value'][1])
container=docker('ps','-q','otel-collector').strip()
row['container_id']=container
row['memory']=subprocess.run(['docker','stats','--no-stream','--format','{{.MemUsage}}',container],check=True,capture_output=True,text=True).stdout.strip()
return row
def main():
out={'queries':QUERIES,'samples':[]};stopped=False;load=None
try:
out['samples'].append(sample('before'))
docker('stop','tempo');stopped=True
subprocess.run(['make','test'],cwd=ROOT,check=True)
load=subprocess.Popen([sys.executable,'tests/load.py','--duration','75','--concurrency','4','--output','evidence/review-tempo-load.json'],cwd=ROOT,stdout=subprocess.DEVNULL)
while load.poll() is None:
out['samples'].append(sample('outage'))
time.sleep(10)
if load.returncode: raise RuntimeError('load process failed')
out['samples'].append(sample('before_restore'))
docker('up','-d','--no-deps','tempo');stopped=False
deadline=time.monotonic()+90
while time.monotonic()<deadline:
time.sleep(5)
out['samples'].append(sample('recovery'))
if out['samples'][-1]['metrics']['otelcol_exporter_queue_size']<=1: break
else: raise RuntimeError('Tempo export queue did not drain within 90 seconds')
first,last=out['samples'][0],out['samples'][-1]
assert first['container_id']==last['container_id'],'Collector was recreated; deltas invalid'
out['counter_deltas']={key:last['metrics'][key]-first['metrics'][key] for key in QUERIES if key.endswith('_total')}
assert all(value>=0 for value in out['counter_deltas'].values()),'counter reset'
out['load']=json.loads((ROOT/'evidence/review-tempo-load.json').read_text())
assert out['load']['failed_requests']==0,out['load']
out['result']='PASS'
finally:
if load is not None and load.poll() is None:
load.terminate();load.wait(timeout=15)
if stopped: docker('up','-d','--no-deps','tempo')
(ROOT/'evidence/review-tempo-outage.json').write_text(json.dumps(out,indent=2)+'\n')
print('PASS: Tempo outage; baseline/deltas/memory in evidence/review-tempo-outage.json')
if __name__=='__main__': main()
+7
View File
@@ -1,5 +1,7 @@
"""Synthetic upload with a known W3C trace ID; wait through a worker restart."""
import secrets
import json
from datetime import datetime, timezone
import sys
import time
from pathlib import Path
@@ -18,3 +20,8 @@ print('trace_id:', trace_id, 'attachment_id:', attachment['id'], flush=True)
started = time.monotonic()
result = client.wait_ready(actor, attachment, wait_seconds=150)
print('status:', result['status'], 'elapsed_seconds:', round(time.monotonic()-started, 3), flush=True)
(Path(__file__).resolve().parents[1] / 'evidence/review-retry-job.json').write_text(json.dumps({
'utc': datetime.now(timezone.utc).isoformat(), 'trace_id': trace_id,
'attachment_id': attachment['id'], 'status': result['status'],
'elapsed_seconds': round(time.monotonic()-started, 3)}, indent=2)+'\n')