forked from mtusi2026/mtusi2026lab6
Реализована лабораторная 6 на оценку 4
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
"""Read stored signals through internal backend APIs; no public admin ports."""
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import base64
|
||||
from pipeline_helpers import *
|
||||
|
||||
|
||||
def backend(url, text=False):
|
||||
# Query via Grafana proxy: observation must work even while worker is stopped.
|
||||
target=urllib.parse.urlsplit(url)
|
||||
sources={'prometheus:9090':'prometheus','loki:3100':'loki','tempo:3200':'tempo'}
|
||||
check(target.netloc in sources,'unknown telemetry backend')
|
||||
password=(ROOT/'secrets/grafana_admin_password').read_text().strip()
|
||||
base=os.environ.get('GRAFANA_URL','http://localhost:13000').rstrip('/')
|
||||
address=base+'/api/datasources/proxy/uid/'+sources[target.netloc]+target.path
|
||||
if target.query:address+='?'+target.query
|
||||
auth=base64.b64encode(('admin:'+password).encode()).decode()
|
||||
request=urllib.request.Request(address,headers={'Accept':'application/json','Authorization':'Basic '+auth})
|
||||
try:
|
||||
with urllib.request.urlopen(request,timeout=8) as response:output=response.read().decode()
|
||||
return output if text else json.loads(output)
|
||||
except (urllib.error.URLError,OSError,ValueError):
|
||||
raise Failure('telemetry backend not ready: '+sources[target.netloc]) from None
|
||||
|
||||
|
||||
def prom(expr):
|
||||
result=backend('http://prometheus:9090/api/v1/query?'+urllib.parse.urlencode({'query':expr}))
|
||||
check(result['status']=='success','Prometheus query failed')
|
||||
return result['data']['result']
|
||||
|
||||
|
||||
def number(expr, default=0):
|
||||
values=prom(expr)
|
||||
return float(values[0]['value'][1]) if values else default
|
||||
|
||||
|
||||
def trace_data(trace_id):
|
||||
return backend('http://tempo:3200/api/traces/'+trace_id)
|
||||
|
||||
|
||||
def spans(value):
|
||||
found=[]
|
||||
if isinstance(value,dict):
|
||||
if 'spanId' in value and 'name' in value:found.append(value)
|
||||
for child in value.values():found.extend(spans(child))
|
||||
elif isinstance(value,list):
|
||||
for child in value:found.extend(spans(child))
|
||||
return found
|
||||
|
||||
|
||||
def logs(trace_id=None, service=None):
|
||||
selector='{service_name="'+service+'"}' if service else '{service_name=~"messenger-api|messenger-worker|messenger-dispatcher"}'
|
||||
query=selector+' | json'
|
||||
if trace_id:query+=' | trace_id="'+trace_id+'"'
|
||||
data=backend('http://loki:3100/loki/api/v1/query_range?'+urllib.parse.urlencode({'query':query,'start':str(time.time_ns()-900_000_000_000),'limit':'1000'}))
|
||||
return [json.loads(row[1]) for stream in data['data']['result'] for row in stream['values']]
|
||||
|
||||
|
||||
def alert(name):
|
||||
result=backend('http://prometheus:9090/api/v1/alerts')
|
||||
matches=[a for a in result['data']['alerts'] if a['labels'].get('alertname')==name]
|
||||
return matches[0]['state'] if matches else 'resolved'
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Local synthetic tests; credentials stay in memory and never enter evidence."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, check, run
|
||||
|
||||
|
||||
def compose(*args, data=None):
|
||||
result = subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT,
|
||||
input=data, capture_output=True, text=True)
|
||||
check(result.returncode == 0, 'compose command failed: ' + ' '.join(args[:3]))
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def psql(sql):
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-XAtq', '-v', 'ON_ERROR_STOP=1',
|
||||
'-U', 'messenger', '-d', 'messenger', data=sql)
|
||||
|
||||
|
||||
def wait_for(test, message, timeout=100):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = test()
|
||||
if value:
|
||||
return value
|
||||
except Failure:
|
||||
pass
|
||||
time.sleep(.3)
|
||||
raise Failure(message)
|
||||
|
||||
|
||||
def ready(client):
|
||||
wait_for(lambda: client.call('GET', '/health/ready', schema='Health'), 'API not ready')
|
||||
|
||||
|
||||
def upload(client, actor, chat, raw=None):
|
||||
if raw is None:
|
||||
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
result = client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=test.png',
|
||||
202, actor=actor, raw=raw, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
|
||||
check(result['status'] == 'queued', '202 must contain queued snapshot')
|
||||
return result
|
||||
|
||||
|
||||
def state(client, actor, attachment):
|
||||
return client.call('GET', '/api/v1/attachments/' + attachment['id'], actor=actor, schema='Attachment')['json']
|
||||
|
||||
|
||||
def wait_state(client, actor, attachment, wanted='ready', timeout=100):
|
||||
def poll():
|
||||
result = state(client, actor, attachment)
|
||||
if wanted == 'ready':
|
||||
check(result['status'] != 'failed', 'job unexpectedly failed')
|
||||
return result if result['status'] == wanted else None
|
||||
return wait_for(poll, 'attachment did not become ' + wanted, timeout)
|
||||
|
||||
|
||||
def fault(point):
|
||||
compose('exec', '-T', 'api1', '/messenger', 'fault', 'arm', point)
|
||||
|
||||
|
||||
def hit(point):
|
||||
wait_for(lambda: psql("SELECT hit_at IS NOT NULL FROM pipeline_faults WHERE point='" + point + "';") == 't',
|
||||
'fault not reached: ' + point)
|
||||
|
||||
|
||||
def dump_evidence(name, value):
|
||||
(ROOT / 'evidence').mkdir(exist_ok=True)
|
||||
(ROOT / 'evidence' / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
|
||||
|
||||
|
||||
def start_only(service):
|
||||
# Compose start can also start dependencies; fault tests need exactly this container.
|
||||
container = compose('ps', '--all', '-q', service)
|
||||
result = subprocess.run(['docker', 'start', container], capture_output=True, text=True)
|
||||
check(result.returncode == 0, 'cannot start container ' + service)
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Two diagnosed incidents + bounded telemetry outage, using stored observations."""
|
||||
import concurrent.futures
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from obs_helpers import *
|
||||
|
||||
|
||||
def send_load(client,actor,chat,seconds,workers=2):
|
||||
deadline=time.monotonic()+seconds
|
||||
path='/api/v1/chats/'+chat['id']+'/messages'
|
||||
def task(_):
|
||||
c=Client(client.base,timeout=8);ok=failed=0;durations=[]
|
||||
while time.monotonic()<deadline:
|
||||
begin=time.monotonic()
|
||||
try:
|
||||
c.call('POST',path,201,actor=actor,body={'text':'synthetic load'},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
ok+=1;durations.append(time.monotonic()-begin)
|
||||
except Failure:failed+=1
|
||||
return ok,failed,durations
|
||||
start=time.monotonic()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:rows=list(pool.map(task,range(workers)))
|
||||
elapsed=time.monotonic()-start
|
||||
durations=sorted(d for r in rows for d in r[2]);count=sum(r[0] for r in rows)
|
||||
def percentile(fraction):
|
||||
import math
|
||||
return round(durations[max(0,math.ceil(len(durations)*fraction)-1)]*1000,3) if durations else None
|
||||
return dict(seconds=round(elapsed,3),workers=workers,successful_requests=count,failed_requests=sum(r[1] for r in rows),
|
||||
successful_rps=round(count/elapsed,3),latency_ms_successes={k:percentile(f) for k,f in [('p50',.5),('p95',.95),('p99',.99)]})
|
||||
|
||||
|
||||
def collector_stats():
|
||||
container=compose('ps','-q','otel-collector')
|
||||
r=subprocess.run(['docker','stats','--no-stream','--format','{{json .}}',container],capture_output=True,text=True,check=True)
|
||||
value=json.loads(r.stdout)
|
||||
return {'memory':value['MemUsage'],'cpu':value['CPUPerc']}
|
||||
|
||||
|
||||
def main():
|
||||
client=Client(timeout=8);actor,_,_,chat=client.bootstrap()
|
||||
output={'warmup_load':send_load(client,actor,chat,5)}
|
||||
try:
|
||||
# 1. Queue lag: no worker; HTTP remains usable; stored heartbeat reveals cause.
|
||||
compose('stop','worker');began=time.monotonic()
|
||||
pending=[upload(client,actor,chat) for _ in range(3)]
|
||||
wait_for(lambda:alert('MessengerQueueLag')=='firing','queue lag alert did not fire',60)
|
||||
queue=dict(firing=True,detected_seconds=round(time.monotonic()-began,3),
|
||||
depth=number('max(messenger_queue_depth)'),oldest_age_seconds=number('max(messenger_queue_oldest_age_seconds)'),
|
||||
worker_busy=number('max(messenger_worker_busy)'),
|
||||
worker_heartbeat_age_seconds=number('max(time()-messenger_process_last_observed_seconds{service_name="messenger-worker"})'))
|
||||
check(queue['depth']>=3 and queue['oldest_age_seconds']>10,'queue metrics do not explain lag')
|
||||
check(queue['worker_heartbeat_age_seconds']>10,'worker absence not observable')
|
||||
client.message(actor,chat,'messages continue with worker stopped')
|
||||
start_only('worker')
|
||||
for item in pending:wait_state(client,actor,item)
|
||||
wait_for(lambda:alert('MessengerQueueLag')=='resolved','queue alert did not resolve',40)
|
||||
queue.update(resolved=True,depth_after=number('max(messenger_queue_depth)'))
|
||||
output['worker_stopped']=queue
|
||||
print('PASS: queue lag firing -> resolved, heartbeat stale, backlog drained',flush=True)
|
||||
|
||||
# 2. PostgreSQL unavailable; identify dependency spans, not generic slow handler.
|
||||
compose('stop','postgres');begin=time.monotonic();error_trace=None;errors=0
|
||||
while time.monotonic()-begin<50:
|
||||
response=client.call('POST','/api/v1/chats/'+chat['id']+'/messages',503,actor=actor,
|
||||
body={'text':'synthetic outage'},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
error_trace=response['headers']['X-Trace-Id'];errors+=1
|
||||
if alert('MessengerHighErrorRate')=='firing' and time.monotonic()-begin>=15:break
|
||||
check(alert('MessengerHighErrorRate')=='firing','5xx alert did not fire')
|
||||
database=dict(firing=True,detected_seconds=round(time.monotonic()-begin,3),failed_requests=errors,
|
||||
error_ratio=number('messenger:api_error_ratio:rate1m'),
|
||||
db_available=number('min_over_time(messenger_db_available[1m])'),
|
||||
pool_waiting_peak=number('max(max_over_time(messenger_db_pool_waiting[1m]))'),trace_id=error_trace)
|
||||
data=wait_for(lambda:trace_data(error_trace),'DB failure trace not stored',25)
|
||||
children=[s for s in spans(data) if s['name'].startswith('db.')]
|
||||
check(children,'no DB child span explains HTTP failure')
|
||||
check(any(s.get('status',{}).get('code') in (2,'STATUS_CODE_ERROR') for s in children),'DB spans lack error status')
|
||||
check(database['db_available']==0,'DB availability signal did not show outage')
|
||||
dump_evidence('db-incident-trace.json',data)
|
||||
compose('start','postgres');ready(client)
|
||||
# Real recovered traffic, no time-series manipulation.
|
||||
deadline=time.monotonic()+90
|
||||
while alert('MessengerHighErrorRate')!='resolved' and time.monotonic()<deadline:
|
||||
for _ in range(10):client.message(actor,chat,'healthy recovery')
|
||||
time.sleep(.5)
|
||||
check(alert('MessengerHighErrorRate')=='resolved','5xx alert did not resolve')
|
||||
database.update(resolved=True,db_available_after=number('messenger_db_available'))
|
||||
output['postgres_stopped']=database
|
||||
print('PASS: DB error spans + 5xx alert firing -> resolved',flush=True)
|
||||
|
||||
# 3. A telemetry backend down: business writes still work; buffers are finite.
|
||||
before_failed=number('sum(otelcol_exporter_send_failed_spans_total{exporter="otlphttp/tempo"})')
|
||||
before_stats=collector_stats()
|
||||
since=datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
compose('stop','tempo')
|
||||
result=send_load(client,actor,chat,20)
|
||||
check(result['successful_requests']>0 and result['failed_requests']==0,'telemetry backend broke business API')
|
||||
# wait beyond bounded retry deadline so final drops can be observed.
|
||||
time.sleep(8)
|
||||
failed=number('sum(otelcol_exporter_send_failed_spans_total{exporter="otlphttp/tempo"})')-before_failed
|
||||
queued=number('max(max_over_time(otelcol_exporter_queue_size{exporter="otlphttp/tempo"}[1m]))')
|
||||
check(failed>0,'Collector failures not observable')
|
||||
check(queued<=32,'Collector exceeded configured buffer')
|
||||
after_stats=collector_stats()
|
||||
raw_logs=compose('logs','--no-log-prefix','--since',since,'otel-collector')
|
||||
dropped=0
|
||||
for line in raw_logs.splitlines():
|
||||
try:record=json.loads(line)
|
||||
except ValueError:continue
|
||||
if record.get('otelcol.signal')=='traces':dropped+=int(record.get('dropped_items',0))
|
||||
check(dropped>0,'actual dropped trace records not counted')
|
||||
output['tempo_stopped']=dict(workload=result,collector_before=before_stats,collector_during=after_stats,
|
||||
failed_span_send_records_delta=failed,max_queue_batches=queued,queue_limit_batches=32,
|
||||
dropped_spans_from_collector_logs=dropped,business_api_preserved=True)
|
||||
compose('start','tempo')
|
||||
wait_for(lambda:backend('http://tempo:3200/ready',text=True),'Tempo did not recover',40)
|
||||
probe=client.call('GET','/api/v1/users/me',actor=actor)
|
||||
wait_for(lambda:trace_data(probe['headers']['X-Trace-Id']),'traces did not resume',40)
|
||||
output['tempo_stopped']['export_resumed']=True
|
||||
print('PASS: telemetry backend outage preserves writes, queues bounded, dropped spans counted',flush=True)
|
||||
dump_evidence('incidents-grade4.json',output)
|
||||
finally:
|
||||
compose('start','postgres','worker','tempo');ready(client)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Grade 4: real stored signals, W3C chain with retry, dashboard and privacy."""
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from obs_helpers import *
|
||||
|
||||
|
||||
def normalized_id(value):
|
||||
if not value:return ''
|
||||
if all(c in '0123456789abcdef' for c in value.lower()) and len(value) in (16,32):return value.lower()
|
||||
return base64.b64decode(value).hex()
|
||||
|
||||
|
||||
def main():
|
||||
client=Client(timeout=30)
|
||||
actor,_,_,chat=client.bootstrap()
|
||||
marker='PRIVATE-BODY-'+uuid.uuid4().hex
|
||||
client.message(actor,chat,marker)
|
||||
trace_id=uuid.uuid4().hex
|
||||
raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
try:
|
||||
compose('stop','worker')
|
||||
response=client.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=private-canary.png',202,
|
||||
actor=actor,raw=raw,headers={'Content-Type':'image/png','traceparent':'00-'+trace_id+'-0123456789abcdef-01','tracestate':'lab=synthetic'},schema='Attachment')
|
||||
item=response['json'];request_id=response['headers']['X-Request-Id']
|
||||
check(response['headers']['X-Trace-Id']==trace_id,'incoming W3C traceparent not honored')
|
||||
compose('stop','s3');start_only('worker')
|
||||
wait_for(lambda: psql("SELECT attempts>=1 AND state='queued' FROM attachment_jobs WHERE id='"+item['id']+"';")=='t','retry not observed',35)
|
||||
compose('start','s3');ready(client)
|
||||
wait_state(client,actor,item)
|
||||
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'original changed')
|
||||
def linked():
|
||||
data=trace_data(trace_id);found=spans(data)
|
||||
names={s['name'] for s in found}
|
||||
consumers=[s for s in found if s['name']=='attachment.consume']
|
||||
if len(consumers)>=2 and {'attachment.publish','image.process','s3.put','db.update','db.commit'}.issubset(names):return data
|
||||
return None
|
||||
data=wait_for(linked,'complete upload/publish/retry/consume/result trace missing',60)
|
||||
found=spans(data)
|
||||
publishers={normalized_id(s['spanId']) for s in found if s['name']=='attachment.publish'}
|
||||
consumers=[s for s in found if s['name']=='attachment.consume']
|
||||
check(all(normalized_id(s.get('parentSpanId','')) in publishers for s in consumers),'consumer parent is not producer')
|
||||
correlated=wait_for(lambda: [entry for entry in logs(trace_id) if entry.get('event')=='job.completed' and entry.get('outcome')=='success'], 'worker log missing',40)
|
||||
all_logs=logs(trace_id)
|
||||
events={entry['event'] for entry in all_logs}
|
||||
check({'http.request','job.published','job.started','job.completed'}.issubset(events),'API/publisher/worker logs not correlated')
|
||||
check(any(e.get('request_id')==request_id and e['event']=='http.request' for e in all_logs),'request id correlation missing')
|
||||
check(correlated[0]['request_id']==request_id,'worker lost originating request id')
|
||||
encoded=json.dumps(data)+json.dumps(all_logs)+json.dumps(logs(service='messenger-api'))
|
||||
for secret in (marker,actor['token'],actor['registration']['password'],'private-canary.png'):
|
||||
check(secret not in encoded,'sensitive payload/header/filename entered telemetry')
|
||||
# Actual stored metric names, not assumptions from SDK naming.
|
||||
expressions={
|
||||
'http_requests':'sum(messenger_http_requests_total)',
|
||||
'http_histogram':'sum(messenger_http_duration_seconds_count)',
|
||||
'jobs_success':'sum(messenger_jobs_processed_total{outcome="success"})',
|
||||
'jobs_retry':'sum(messenger_jobs_processed_total{outcome="retry"})',
|
||||
'ready_histogram':'sum(messenger_time_to_ready_seconds_count)',
|
||||
'queue':'max(messenger_queue_depth)',
|
||||
'pool':'max(messenger_db_pool_capacity)',
|
||||
'worker_capacity':'max(messenger_worker_capacity)',
|
||||
'memory':'max(messenger_container_memory_bytes)',
|
||||
}
|
||||
values={}
|
||||
for name,expression in expressions.items():
|
||||
wait_for(lambda: prom(expression),'missing metric '+name,20)
|
||||
values[name]=number(expression)
|
||||
check(values['jobs_success']>0 and values['jobs_retry']>0,'worker outcomes absent')
|
||||
metric_rows=prom('{__name__=~"messenger_.*"}')
|
||||
forbidden={'user_id','chat_id','message_id','attachment_id','request_id','filename','url','path','job_id'}
|
||||
check(not any(forbidden.intersection(row['metric']) for row in metric_rows),'high-cardinality metric labels')
|
||||
password=(ROOT/'secrets/grafana_admin_password').read_text().strip()
|
||||
code='''
|
||||
import base64,json,sys,urllib.request
|
||||
p=sys.stdin.read().strip();req=urllib.request.Request('http://grafana:3000/api/dashboards/uid/mtusi-messenger',headers={'Authorization':'Basic '+base64.b64encode(('admin:'+p).encode()).decode()})
|
||||
with urllib.request.urlopen(req,timeout=10) as r:d=json.load(r)
|
||||
print(json.dumps({'title':d['dashboard']['title'],'panels':len(d['dashboard']['panels'])}))
|
||||
'''
|
||||
dashboard=json.loads(compose('exec','-T','worker','python3','-c',code,data=password))
|
||||
check(dashboard['panels']>=18,'provisioned dashboard missing')
|
||||
dump_evidence('trace-example.json',data)
|
||||
dump_evidence('correlated-logs.json',all_logs)
|
||||
output=dict(status='PASS',trace_id=trace_id,request_id=request_id,consumer_attempt_spans=len(consumers),
|
||||
events=sorted(events),metrics=values,dashboard=dashboard,privacy='PASS',low_cardinality='PASS')
|
||||
dump_evidence('observability-grade4.json',output)
|
||||
print('PASS:',json.dumps(output))
|
||||
finally:
|
||||
compose('start','s3','worker');ready(client)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Grade 4: durable acceptance, outbox, crashes, lease, retries, explicit replay."""
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from pipeline_helpers import *
|
||||
|
||||
|
||||
def main():
|
||||
client = Client(timeout=30)
|
||||
ready(client)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
results = {}
|
||||
try:
|
||||
# Worker absent: no resize in API, accepted job survives real restarts.
|
||||
compose('stop', 'worker')
|
||||
attachment = upload(client, actor, chat)
|
||||
client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', 409, actor=actor)
|
||||
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
|
||||
body={'text': '', 'attachment_ids': [attachment['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')
|
||||
services = ('api1', 'api2', 'broker')
|
||||
def starts():
|
||||
values = {}
|
||||
for service in services:
|
||||
container = compose('ps', '-q', service)
|
||||
data = subprocess.run(['docker', 'inspect', container], capture_output=True, text=True, check=True)
|
||||
values[service] = json.loads(data.stdout)[0]['State']['StartedAt']
|
||||
return values
|
||||
before = starts()
|
||||
compose('restart', *services)
|
||||
ready(client)
|
||||
after = starts()
|
||||
check(all(before[s] != after[s] for s in services), 'actual restart not observed')
|
||||
check(state(client, actor, attachment)['status'] == 'queued', 'worker stopped but state changed')
|
||||
start_only('worker')
|
||||
result = wait_state(client, actor, attachment)
|
||||
check({v['name'] for v in result['variants']} == {'thumbnail', 'crop', 'optimized'}, 'missing grade4 variants')
|
||||
check(client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=actor)['bytes'] == raw, 'original changed')
|
||||
wait_for(lambda: psql("SELECT staging_deleted_at IS NOT NULL FROM attachment_jobs WHERE id='" + attachment['id'] + "';") == 't', 'staging not cleaned')
|
||||
results['stopped_worker_and_restart'] = dict(status='PASS', before=before, after=after)
|
||||
|
||||
# Committed outbox remains when dispatcher dies before XADD.
|
||||
compose('stop', 'dispatcher')
|
||||
fault('dispatcher_before_publish')
|
||||
item = upload(client, actor, chat)
|
||||
check(psql("SELECT count(*) FROM attachment_outbox WHERE job_id='" + item['id'] + "';") == '1', 'outbox absent')
|
||||
compose('start', 'dispatcher')
|
||||
hit('dispatcher_before_publish')
|
||||
wait_state(client, actor, item)
|
||||
results['commit_publish_gap'] = 'PASS: actual dispatcher exit 86 and automatic restart'
|
||||
|
||||
# Crash after S3 objects, before final PG COMMIT; reclaim expired processing.
|
||||
fault('worker_after_objects')
|
||||
item = upload(client, actor, chat)
|
||||
hit('worker_after_objects')
|
||||
check(psql("SELECT state FROM attachment_jobs WHERE id='" + item['id'] + "';") == 'processing', 'crash did not leave processing')
|
||||
started = time.monotonic()
|
||||
result = wait_state(client, actor, item, timeout=110)
|
||||
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == '2', 'expired lease not recovered')
|
||||
check(len(result['variants']) == 3, 'duplicate variant metadata')
|
||||
results['crash_after_objects'] = dict(status='PASS', recovery_seconds=round(time.monotonic()-started, 3), attempts=2)
|
||||
|
||||
# COMMIT ready then death before ack: ready must never regress/reprocess.
|
||||
fault('worker_before_ack')
|
||||
item = upload(client, actor, chat)
|
||||
hit('worker_before_ack')
|
||||
result = wait_state(client, actor, item)
|
||||
attempts = psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';")
|
||||
duplicate = dict(schema_version=1, job_id=item['id'], type='attachment.process.v1', attachment_id=item['id'],
|
||||
pipeline_version=1, attempt=1, created_at=item['created_at'])
|
||||
# Use broker password only inside the container, never in evidence.
|
||||
duplicate_id = compose('exec', '-T', 'broker', 'sh', '-ec',
|
||||
'redis-cli --no-auth-warning -a "$(cat /run/secrets/broker_password)" XADD attachment.jobs.v1 "*" job "$1"',
|
||||
'sh', json.dumps(duplicate))
|
||||
wait_for(lambda: compose('exec', '-T', 'broker', 'sh', '-ec',
|
||||
'redis-cli --raw --no-auth-warning -a "$(cat /run/secrets/broker_password)" XRANGE attachment.jobs.v1 "$1" "$1"',
|
||||
'sh', duplicate_id) == '', 'ready duplicate was not acknowledged')
|
||||
check(state(client, actor, item) == result, 'ready duplicate changed result')
|
||||
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == attempts, 'ready duplicate processed again')
|
||||
results['commit_before_ack_and_duplicate'] = 'PASS'
|
||||
|
||||
# Temporary S3 failure: attempt budget/backoff, failed registry, audited replay.
|
||||
compose('stop', 'worker')
|
||||
item = upload(client, actor, chat)
|
||||
psql("UPDATE attachment_jobs SET max_attempts=2 WHERE id='" + item['id'] + "';")
|
||||
compose('stop', 's3')
|
||||
start_only('worker')
|
||||
check(compose('ps', '--status', 'running', '-q', 's3') == '', 'fault test unexpectedly restarted S3')
|
||||
wait_for(lambda: psql("SELECT state FROM attachment_jobs WHERE id='" + item['id'] + "';") == 'failed', 'temporary errors did not exhaust retries', 100)
|
||||
compose('start', 's3')
|
||||
ready(client)
|
||||
failed = state(client, actor, item)
|
||||
check(failed['error_code'] == 'retry_exhausted', 'unsafe or missing final error')
|
||||
client.call('GET', '/api/v1/attachments/' + item['id'] + '/content', 409, actor=actor)
|
||||
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=actor,
|
||||
body={'text':'failed', 'attachment_ids':[item['id']]}, headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
registry = compose('exec', '-T', 'dispatcher', '/messenger', 'failed-jobs')
|
||||
check(item['id'] in registry, 'failed registry missing job')
|
||||
compose('exec', '-T', 'dispatcher', '/messenger', 'replay', item['id'])
|
||||
wait_state(client, actor, item)
|
||||
check(psql("SELECT count(*) FROM attachment_replays WHERE job_id='" + item['id'] + "';") == '1', 'replay audit missing')
|
||||
proc = subprocess.run(['docker','compose','--env-file','.env','exec','-T','dispatcher','/messenger','replay',item['id']], cwd=ROOT, capture_output=True)
|
||||
check(proc.returncode != 0, 'ready replay must be refused')
|
||||
results['retry_failed_registry_replay'] = dict(status='PASS', exhausted_attempts=2, error_code='retry_exhausted', replay_audit_rows=1, ready_replay_rejected=True)
|
||||
|
||||
# Permanent invalid staging: no endless retries, safe machine error.
|
||||
compose('stop', 'worker')
|
||||
item = upload(client, actor, chat)
|
||||
original_key = uuid.uuid4().hex
|
||||
original_body = {'text':'accepted while queued', 'attachment_ids':[item['id']]}
|
||||
original_message = client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
|
||||
actor=actor, body=original_body, headers={'Idempotency-Key':original_key}, schema='Message')['json']
|
||||
# Integrity metadata mismatch represents invalid durable source.
|
||||
psql("UPDATE attachments SET sha256=repeat('0',64) WHERE id='" + item['id'] + "';")
|
||||
start_only('worker')
|
||||
failed = wait_state(client, actor, item, 'failed')
|
||||
check(failed['error_code'] == 'invalid_image', 'permanent invalid source must fail safely')
|
||||
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == '1', 'permanent error retried')
|
||||
repeated = client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
|
||||
actor=actor, body=original_body, headers={'Idempotency-Key':original_key}, schema='Message')['json']
|
||||
check(repeated == original_message, 'committed message replay changed after attachment failed')
|
||||
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409,
|
||||
actor=actor, body=original_body, headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
results['permanent_error'] = 'PASS'
|
||||
results['message_replay_after_attachment_failure'] = 'PASS'
|
||||
results['crash_points'] = json.loads(psql("SELECT json_agg(json_build_object('point',point,'armed',armed,'hit_at',hit_at) ORDER BY point) FROM pipeline_faults WHERE hit_at IS NOT NULL;"))
|
||||
dump_evidence('pipeline-grade4.json', results)
|
||||
print('PASS:', json.dumps(results))
|
||||
finally:
|
||||
compose('start', 's3', 'broker', 'dispatcher', 'worker', 'api1', 'api2')
|
||||
psql('DELETE FROM pipeline_faults;')
|
||||
ready(client)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Public persistence/failover hooks plus actual container restart evidence."""
|
||||
import json
|
||||
import datetime
|
||||
import subprocess
|
||||
import uuid
|
||||
from pipeline_helpers import *
|
||||
|
||||
|
||||
def snapshots():
|
||||
services=('postgres','redis','s3','broker','api1','api2','dispatcher','worker','cleanup','nginx','otel-collector','prometheus','loki','tempo','grafana')
|
||||
result={}
|
||||
for service in services:
|
||||
container=compose('ps','-q',service)
|
||||
info=subprocess.run(['docker','inspect',container],capture_output=True,text=True,check=True)
|
||||
data=json.loads(info.stdout)[0]
|
||||
result[service]=dict(id=data['Id'],started_at=data['State']['StartedAt'])
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
client=Client();ready(client)
|
||||
before=snapshots()
|
||||
base=client.base
|
||||
command=['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL='+base]
|
||||
result=subprocess.run(command,cwd=ROOT,capture_output=True,text=True)
|
||||
check(result.returncode==0,'public persistence failed: '+result.stdout[-500:])
|
||||
after=snapshots()
|
||||
check(all(before[s]['started_at']!=after[s]['started_at'] for s in before),'hook did not restart all required services')
|
||||
|
||||
output={'persistence':dict(status='PASS',before=before,after=after),'failover':[]}
|
||||
public=subprocess.run(['make','test-failover','ACTION_SCRIPT=scripts/stop-one.sh','BASE_URL='+base],cwd=ROOT,capture_output=True,text=True)
|
||||
check(public.returncode==0,'public failover failed: '+public.stdout[-500:])
|
||||
output['public_failover']=dict(status='PASS',output=public.stdout.strip())
|
||||
try:
|
||||
compose('start','api1','api2');ready(client)
|
||||
actor,_,_,chat=client.bootstrap()
|
||||
item=upload(client,actor,chat);wait_state(client,actor,item)
|
||||
raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
path='/api/v1/chats/'+chat['id']+'/messages'
|
||||
for target in ('api-1','api-2'):
|
||||
compose('start','api1','api2');ready(client)
|
||||
seen=set()
|
||||
wait_for(lambda: (seen.add(client.call('GET','/health/ready')['headers']['X-Instance-Id']) or len(seen)==2),'two replicas not visible')
|
||||
process=subprocess.Popen([str(ROOT/'scripts/stop-one.sh')],cwd=ROOT,
|
||||
env=dict(os.environ,TARGET_INSTANCE_ID=target),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
began=time.monotonic();deadline=began+8;first=None;confirmed=set();failures=0
|
||||
key=uuid.uuid4().hex
|
||||
while time.monotonic()<deadline:
|
||||
try:
|
||||
response=client.call('POST',path,201,actor=actor,body={'text':key},headers={'Idempotency-Key':key},schema='Message')
|
||||
confirmed.add(response['json']['id'])
|
||||
if process.poll() is not None and response['headers']['X-Instance-Id']!=target and first is None:
|
||||
first=time.monotonic()-began
|
||||
key=uuid.uuid4().hex
|
||||
except Failure:
|
||||
failures+=1
|
||||
time.sleep(.1)
|
||||
check(process.wait(timeout=10)==0,'stop hook failed')
|
||||
check(first is not None and first<=10,'surviving API did not recover within 10 seconds')
|
||||
service={'api-1':'api1','api-2':'api2'}[target]
|
||||
check(not compose('ps','--status','running','-q',service),'target was not actually stopped')
|
||||
page=client.call('GET',path+'?limit=100',actor=actor,schema='MessagePage')['json']
|
||||
visible={m['id'] for m in page['items']}
|
||||
# At most 80 requests per case: walk pages to include both cases.
|
||||
while page['next_cursor']:
|
||||
from urllib.parse import quote
|
||||
page=client.call('GET',path+'?limit=100&cursor='+quote(page['next_cursor']),actor=actor,schema='MessagePage')['json']
|
||||
visible.update(m['id'] for m in page['items'])
|
||||
check(confirmed.issubset(visible),'confirmed messages lost')
|
||||
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'original lost on API failover')
|
||||
output['failover'].append(dict(status='PASS',stopped_service=service,confirmed_messages=len(confirmed),
|
||||
transient_failures=failures,first_survivor_seconds=round(first,3),original_preserved=True))
|
||||
finally:
|
||||
compose('start','api1','api2');ready(client)
|
||||
saved=ROOT/'evidence/observability-grade4.json'
|
||||
if saved.exists():
|
||||
from obs_helpers import trace_data, logs, number
|
||||
trace_id=json.loads(saved.read_text())['trace_id']
|
||||
wait_for(lambda:trace_data(trace_id),'stored trace lost after telemetry restart',60)
|
||||
wait_for(lambda:logs(trace_id),'stored logs lost after telemetry restart',60)
|
||||
check(number('sum(messenger_http_requests_total)')>0,'metrics unavailable after restart')
|
||||
stamp=datetime.datetime.fromisoformat(after['prometheus']['started_at'].replace('Z','+00:00')).timestamp()-10
|
||||
historical=number('sum(messenger_http_requests_total @ '+str(stamp)+')')
|
||||
check(historical>0,'historical metrics lost after Prometheus restart')
|
||||
output['metric_history_before_restart']={'unix_time':stamp,'http_counter_sum':historical}
|
||||
output['telemetry_history_preserved']=True
|
||||
dump_evidence('resilience.json',output)
|
||||
print('PASS: all fifteen core/telemetry services restarted, same token/data/original preserved; both API failures covered')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Grade 4 image contract: actual decoding, EXIF, alpha, limits and private storage."""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import struct
|
||||
import uuid
|
||||
import zlib
|
||||
from pipeline_helpers import *
|
||||
|
||||
|
||||
def make_fixture(kind):
|
||||
code = '''
|
||||
import base64,io,sys
|
||||
from PIL import Image
|
||||
kind=sys.argv[1]
|
||||
if kind=='orientation':
|
||||
im=Image.new('RGB',(320,200),'red');exif=Image.Exif();exif[274]=6;exif[315]='synthetic test';kw=dict(format='JPEG',exif=exif)
|
||||
elif kind=='alpha':
|
||||
im=Image.new('RGBA',(8,4),(255,0,0,0));kw=dict(format='PNG')
|
||||
elif kind=='boundary':
|
||||
im=Image.new('RGB',(8000,5000),'blue');kw=dict(format='PNG')
|
||||
else:
|
||||
im=Image.new('RGB',(1601,801),'blue');kw=dict(format='PNG')
|
||||
b=io.BytesIO();im.save(b,**kw);print(base64.b64encode(b.getvalue()).decode())
|
||||
'''
|
||||
return base64.b64decode(compose('exec', '-T', 'worker', 'python3', '-c', code, kind))
|
||||
|
||||
|
||||
def inspect_image(raw):
|
||||
code = '''
|
||||
import base64,io,json,sys
|
||||
from PIL import Image
|
||||
im=Image.open(io.BytesIO(base64.b64decode(sys.stdin.read())));im.load()
|
||||
print(json.dumps(dict(format=im.format,width=im.width,height=im.height,exif=len(im.getexif()),pixel=list(im.convert('RGB').getpixel((0,0))))))
|
||||
'''
|
||||
return json.loads(compose('exec', '-T', 'worker', 'python3', '-c', code, data=base64.b64encode(raw).decode()))
|
||||
|
||||
|
||||
def chunk(kind, payload):
|
||||
return struct.pack('>I', len(payload)) + kind + payload + struct.pack('>I', zlib.crc32(kind+payload) & 0xffffffff)
|
||||
|
||||
|
||||
def main():
|
||||
client=Client(timeout=60)
|
||||
actor, _, outsider, chat=client.bootstrap()
|
||||
results={}
|
||||
for kind in ('orientation','alpha','large','boundary'):
|
||||
raw=make_fixture(kind)
|
||||
content_type='image/jpeg' if kind=='orientation' else 'image/png'
|
||||
item=client.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=synthetic',202,actor=actor,raw=raw,
|
||||
headers={'Content-Type':content_type},schema='Attachment')['json']
|
||||
result=wait_state(client,actor,item)
|
||||
variants={v['name']:v for v in result['variants']}
|
||||
expected={'orientation':(160,256),'alpha':(8,4),'large':(256,128),'boundary':(256,160)}[kind]
|
||||
check((variants['thumbnail']['width'],variants['thumbnail']['height'])==expected,'thumbnail dimensions/orientation')
|
||||
check((variants['crop']['width'],variants['crop']['height'])==(128,128),'crop dimensions')
|
||||
optimized={'orientation':(200,320),'alpha':(8,4),'large':(1280,640),'boundary':(1280,800)}[kind]
|
||||
check((variants['optimized']['width'],variants['optimized']['height'])==optimized,'optimized fit dimensions')
|
||||
for name,meta in variants.items():
|
||||
blob=client.call('GET','/api/v1/attachments/'+item['id']+'/content?variant='+name,actor=actor)['bytes']
|
||||
check(hashlib.sha256(blob).hexdigest()==meta['sha256'] and len(blob)==meta['size_bytes'],'variant checksum/size')
|
||||
decoded=inspect_image(blob)
|
||||
check(decoded['format']==('WEBP' if name=='optimized' else 'JPEG'),'actual variant encoding')
|
||||
check(decoded['exif']==0,'EXIF leaked into variant')
|
||||
if kind=='alpha':
|
||||
check(all(v>=250 for v in decoded['pixel']),'alpha not composited on white')
|
||||
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'original changed')
|
||||
client.call('GET','/api/v1/attachments/'+item['id'],404,actor=outsider)
|
||||
client.call('GET','/api/v1/attachments/'+item['id']+'/content?variant=crop',404,actor=outsider)
|
||||
client.call('GET','/api/v1/attachments/'+item['id']+'/content?variant=missing',404,actor=actor)
|
||||
results[kind]={'status':'PASS','variants':variants}
|
||||
original=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
for size in (6294458,10485760):
|
||||
extra=size-len(original)-12
|
||||
raw=original[:-12]+chunk(b'paDd',bytes(extra))+original[-12:]
|
||||
check(len(raw)==size,'fixture exact size')
|
||||
item=upload(client,actor,chat,raw)
|
||||
wait_state(client,actor,item)
|
||||
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'large original changed')
|
||||
path='/api/v1/chats/'+chat['id']+'/attachments?filename=bad.png'
|
||||
client.call('POST',path,413,actor=actor,raw=bytes(10485761),headers={'Content-Type':'image/png'})
|
||||
for raw in (original[:40],original[:-12],b'not an image'):
|
||||
client.call('POST',path,415,actor=actor,raw=raw,headers={'Content-Type':'image/png'})
|
||||
huge=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',20000,10000,8,2,0,0,0))+chunk(b'IEND',b'')
|
||||
client.call('POST',path,413,actor=actor,raw=huge,headers={'Content-Type':'image/png'})
|
||||
results['byte_limits_corrupt_pixel_limits']='PASS'
|
||||
item=upload(client,actor,chat)
|
||||
wait_state(client,actor,item)
|
||||
audit=compose('exec','-T','api1','/messenger','s3-audit','originals/'+item['id'])
|
||||
check('PASS' in audit,'S3 credential audit failed')
|
||||
results['private_bucket_limited_credentials']='PASS'
|
||||
metrics=json.loads(compose('exec','-T','worker','/messenger','memory'))
|
||||
check(metrics['memory.peak'] < metrics['memory.max'],'worker reached memory limit')
|
||||
results['worker_memory_bytes']=metrics
|
||||
dump_evidence('variants-grade4.json',results)
|
||||
print('PASS: actual JPEG/WebP, EXIF orientation, white alpha, bounds, ACL, checksums, private S3')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user