"""Track 2: real PostgreSQL/S3/broker and process crashes, no mocked effects. Run from this repository using uv run --locked python research/fault_suite.py. The driver enables the explicit local fault overlay and creates synthetic records. """ import argparse import hashlib import json import random import subprocess import sys import time from datetime import UTC, datetime from io import BytesIO from pathlib import Path import httpx from PIL import Image sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) from client import Client COMPOSE = ["docker", "compose", "-f", "compose.yaml", "-f", "compose.fault.yaml"] def command(args, check=True): result = subprocess.run(args, capture_output=True, text=True, timeout=120) if check and result.returncode: raise RuntimeError("Command failed: " + " ".join(args[:5]) + "\n" + result.stderr[-1500:]) return result def compose(*args): return command(COMPOSE + list(args)) def sql(statement, rows=False): if rows: statement = "SELECT coalesce(json_agg(q),'[]'::json) FROM (" + statement + ") q" result = compose( "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-v", "ON_ERROR_STOP=1", "-c", statement, ) return json.loads(result.stdout) if rows else result.stdout.strip() def operation(code): prefix = "from messenger.postgres import PostgresStore; from messenger.storage import ObjectStorage; from messenger.jobs import Jobs; s=PostgresStore(); o=ObjectStorage(); j=Jobs(s); " result = compose("exec", "-T", "--index", "2", "api", "python", "-c", prefix + code) return result.stdout.strip() def runtime(): ids = compose("ps", "-a", "-q", "api", "worker", "dispatcher").stdout.split() inspected = json.loads(command(["docker", "inspect", *ids]).stdout) return [ { "container_id": item["Id"], "service": item["Config"]["Labels"]["com.docker.compose.service"], "restart_count": item["RestartCount"], "status": item["State"]["Status"], "exit_code": item["State"]["ExitCode"], "started_at": item["State"]["StartedAt"], } for item in inspected ] def wait_until(predicate, timeout=45): deadline = time.monotonic() + timeout while time.monotonic() < deadline: value = predicate() if value: return value time.sleep(0.2) raise AssertionError("Timed out waiting for invariant") def fault(point, aid=None, action="crash"): target = "NULL" if aid is None else "'" + aid + "'" return sql( f"INSERT INTO test_faults(point,attachment_id,action) VALUES ('{point}',{target},'{action}') RETURNING id" ).splitlines()[0] def reached(fid): return bool( sql(f"SELECT id FROM test_faults WHERE id={fid} AND reached_at IS NOT NULL", rows=True) ) def job(aid): return sql( f"SELECT j.id,j.state,j.attempt,j.pipeline_version,a.status FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.attachment_id='{aid}' ORDER BY j.pipeline_version DESC", rows=True, )[0] def main(): parser = argparse.ArgumentParser() parser.add_argument("--output", default="evidence/fault-study.json") args = parser.parse_args() evidence = {"started_at": datetime.now(UTC).isoformat(), "track": 2, "scenarios": []} began = time.monotonic() compose("up", "-d", "--no-build", "--wait", "api", "worker", "dispatcher") c = Client("http://127.0.0.1:8085") alice, bob, _, chat = c.bootstrap() image = BytesIO() Image.frombytes("RGB", (319, 200), random.Random(42).randbytes(319 * 200 * 3)).save( image, "PNG" ) data = image.getvalue() original_sha = hashlib.sha256(data).hexdigest() def upload(): return c.call( "POST", f"/api/v1/chats/{chat['id']}/attachments?filename=synthetic.png", 202, actor=alice, raw=data, headers={"Content-Type": "image/png"}, schema="Attachment", )["json"] def ready(aid): a = c.wait_ready(bob, {"id": aid}) assert a["status"] == "ready" and a["sha256"] == original_sha assert {v["name"] for v in a["variants"]} == {"thumbnail", "crop", "optimized"} assert c.call("GET", f"/api/v1/attachments/{aid}/content", actor=bob)["bytes"] == data for v in a["variants"]: result = c.call( "GET", f"/api/v1/attachments/{aid}/content?variant={v['name']}", actor=bob ) assert hashlib.sha256(result["bytes"]).hexdigest() == v["sha256"] with Image.open(BytesIO(result["bytes"])) as decoded: assert decoded.size == (v["width"], v["height"]) thumb = next(v for v in a["variants"] if v["name"] == "thumbnail") assert (thumb["width"], thumb["height"]) == (256, 160) return a def record(name, aid, **extra): item = { "name": name, "attachment_id": aid, "job": job(aid), **extra, "passed": True, "runtime": runtime(), } evidence["scenarios"].append(item) print("PASS:", name, flush=True) try: # 202 while no worker, then all accepted bytes and same session survive API/broker restart. compose("stop", "worker") a = upload() aid = a["id"] assert a["status"] == "queued" c.message(alice, chat, "", attachments=[aid]) c.call("GET", f"/api/v1/attachments/{aid}/content", 409, actor=bob) wait_until( lambda: sql( f"SELECT o.job_id FROM job_outbox o JOIN attachment_jobs j ON j.id=o.job_id WHERE j.attachment_id='{aid}' AND o.published_at IS NOT NULL", rows=True, ) ) before = compose("ps", "--format", "json").stdout compose("restart", "api", "broker") compose("up", "-d", "--wait", "--no-recreate", "api", "broker", "lb") assert ( c.call("GET", f"/api/v1/attachments/{aid}", actor=bob, schema="Attachment")["json"][ "status" ] == "queued" ) compose("start", "worker") ready(aid) record( "accepted_202_worker_absent_api_broker_restart", aid, containers_before=json.loads("[" + ",".join(before.strip().splitlines()) + "]"), ) # Crash the API after DB COMMIT while dispatcher is absent: outbox fills the gap. compose("stop", "dispatcher") fid = fault("after_upload_commit") response = httpx.post( c.base + f"/api/v1/chats/{chat['id']}/attachments?filename=synthetic.png", headers={"Authorization": "Bearer " + alice["token"], "Content-Type": "image/png"}, content=data, timeout=15, ) assert response.status_code >= 500 wait_until(lambda fid=fid: reached(fid)) aid = sql( f"SELECT id FROM attachments WHERE chat_id='{chat['id']}' ORDER BY created_at DESC LIMIT 1", rows=True, )[0]["id"] assert job(aid)["state"] == "queued" def api_exited(): snapshot = runtime() return ( snapshot if any(item["service"] == "api" and item["exit_code"] == 86 for item in snapshot) else None ) crashed_api = wait_until(api_exited) compose("start", "api") compose("up", "-d", "--wait", "--no-recreate", "api") compose("start", "dispatcher") ready(aid) record( "api_crash_after_commit_before_publish", aid, response_status=response.status_code, crashed_api=crashed_api, ) # Dispatcher dies after broker accepted the delivery, before outbox mark; duplicate is safe. compose("stop", "worker") fid = fault("after_publish") aid = upload()["id"] wait_until(lambda fid=fid: reached(fid)) wait_until( lambda: sql( f"SELECT o.job_id FROM job_outbox o JOIN attachment_jobs j ON j.id=o.job_id WHERE j.attachment_id='{aid}' AND o.published_at IS NOT NULL", rows=True, ) ) compose("start", "worker") ready(aid) record("dispatcher_crash_after_broker_acceptance", aid) # Real process exit at each effect boundary; durable lease/outbox recovers it. for point in ("before_effect", "after_effect", "after_result_commit"): compose("stop", "worker") before_crash = runtime() fid = fault(point) aid = upload()["id"] compose("start", "worker") wait_until(lambda fid=fid: reached(fid)) ready(aid) before_worker = next(item for item in before_crash if item["service"] == "worker") def worker_restarted(before_worker=before_worker): snapshot = runtime() current = next(item for item in snapshot if item["service"] == "worker") return ( snapshot if current["restart_count"] >= 1 and current["started_at"] != before_worker["started_at"] else None ) after_crash = wait_until(worker_restarted) after_worker = next(item for item in after_crash if item["service"] == "worker") assert before_worker["container_id"] == after_worker["container_id"] # Manual docker start resets RestartCount; observe an automatic restart # in this fresh start rather than comparing unrelated counters. assert after_worker["restart_count"] >= 1 record("worker_crash_" + point, aid, before_crash=before_crash) # Duplicate a completed job concurrently: no new effect and ready never regresses. previous = ready(aid) jid = job(aid)["id"] snippet = ( "import json,concurrent.futures; from messenger.jobs import broker_client,STREAM; " f"body={{'schema_version':1,'job_id':'{jid}','type':'attachment.process.v1','attachment_id':'{aid}','pipeline_version':1,'attempt':1,'created_at':'2026-11-06T00:00:00Z'}}; " "b=broker_client(); pool=concurrent.futures.ThreadPoolExecutor(8); list(pool.map(lambda _:b.xadd(STREAM,{'body':json.dumps(body)}),range(20))); print('20 duplicate deliveries')" ) operation(snippet) time.sleep(2) assert ready(aid) == previous published = sql( f"SELECT count(*) AS n FROM job_audit WHERE job_id='{jid}' AND event='published'", rows=True, )[0]["n"] assert published == 1 record("20_concurrent_duplicate_deliveries", aid, published_effects=published) # Reprocess an accepted queued attachment: use existing staging, never a nonexistent final key. compose("stop", "worker") aid = upload()["id"] operation(f"print(j.reprocess('{aid}',2,o))") compose("start", "worker") v2 = ready(aid) assert job(aid)["pipeline_version"] == 2 record("queued_reprocess_version2_uses_staging", aid) # Old worker is paused after S3 effects. New pipeline publishes first; old cannot overwrite it. compose("stop", "worker") fid = fault("after_effect", action="pause") aid = upload()["id"] compose("start", "worker") wait_until(lambda fid=fid: reached(fid)) operation(f"print(j.reprocess('{aid}',2,o))") compose("up", "-d", "--no-deps", "--scale", "worker=2", "worker") v2 = ready(aid) sql(f"UPDATE test_faults SET released=true WHERE id={fid}") wait_until( lambda: sql( f"SELECT id FROM job_audit WHERE job_id IN (SELECT id FROM attachment_jobs WHERE attachment_id='{aid}' AND pipeline_version=1) AND event='stale_publish_rejected'", rows=True, ) ) assert ready(aid) == v2 compose("up", "-d", "--no-deps", "--scale", "worker=1", "worker") record("stale_version1_after_version2_publish_rejected", aid) # Permanent failed registry + explicit replay; cleanup cannot race a queued replay. compose("stop", "worker") aid = upload()["id"] sql(f"UPDATE attachment_jobs SET attempt_limit=1 WHERE attachment_id='{aid}'") fid = fault("before_effect", aid, "error") compose("start", "worker") wait_until(lambda: job(aid)["state"] == "failed") compose("stop", "worker") operation(f"print(j.replay('{aid}',o))") operation("from messenger.jobctl import cleanup; print(cleanup(s,o,0,3600))") assert job(aid)["state"] == "queued" compose("start", "worker") ready(aid) operation("from messenger.jobctl import cleanup; print(cleanup(s,o,0,3600))") ready(aid) record("failed_replay_before_cleanup_preserves_source_and_results", aid) # Cleanup first expires failed source under the same lock: replay safely refuses. compose("stop", "worker") aid = upload()["id"] sql(f"UPDATE attachment_jobs SET attempt_limit=1 WHERE attachment_id='{aid}'") fault("before_effect", aid, "error") compose("start", "worker") wait_until(lambda: job(aid)["state"] == "failed") operation("from messenger.jobctl import cleanup; print(cleanup(s,o,0,3600))") result = command( COMPOSE + [ "exec", "-T", "--index", "2", "api", "python", "-m", "messenger.jobctl", "replay", aid, ], check=False, ) assert result.returncode == 1 and job(aid)["state"] == "failed" record("cleanup_before_replay_safe_refusal", aid) evidence["passed"] = True finally: # Release barriers even after assertion failure and restore the normal production configuration. try: sql("UPDATE test_faults SET released=true WHERE reached_at IS NOT NULL") compose("start", "api", "dispatcher", "worker") command( [ "docker", "compose", "up", "-d", "--no-build", "--wait", "--scale", "worker=1", "api", "worker", "dispatcher", ] ) finally: evidence["duration_seconds"] = round(time.monotonic() - began, 3) evidence["finished_at"] = datetime.now(UTC).isoformat() Path(args.output).write_text(json.dumps(evidence, ensure_ascii=False, indent=2)) print("PASS: all real fault scenarios; report", args.output) if __name__ == "__main__": main()