"""Explicit reordered deliveries, retry backoff, and synchronized cleanup/replay races.""" import hashlib import json import sys import time from concurrent.futures import ThreadPoolExecutor from datetime import datetime from pathlib import Path from fault_suite import ( COMPOSE, command, compose, fault, job, operation, reached, runtime, sql, wait_until, ) sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) from client import Client def main(): result = {"scenarios": []} compose("up", "-d", "--no-build", "--wait", "api", "worker", "dispatcher", "lb") c = Client("http://127.0.0.1:8085") alice, bob, _, chat = c.bootstrap() def upload(): return c.attachment(alice, chat)[0]["id"] def ready(aid): return c.wait_ready(bob, {"id": aid}) def replay_command(aid): return command( COMPOSE + [ "exec", "-T", "--index", "2", "api", "python", "-m", "messenger.jobctl", "replay", aid, ], check=False, ) def make_failed(): compose("stop", "worker") aid = upload() 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") return aid try: # Two real transient failures before eventual successful processing. compose("stop", "worker") aid = upload() fault("before_effect", aid, "error") fault("before_effect", aid, "error") compose("start", "worker") ready(aid) assert job(aid)["attempt"] == 3 audits = sql( f"SELECT event,attempt,created_at FROM job_audit WHERE job_id='{job(aid)['id']}' ORDER BY id", rows=True, ) retries = [a for a in audits if a["event"] == "retry_scheduled"] claims = [a for a in audits if a["event"] == "claimed"] delays = [ ( datetime.fromisoformat(claims[i + 1]["created_at"]) - datetime.fromisoformat(retries[i]["created_at"]) ).total_seconds() for i in range(2) ] assert delays[0] >= 1 and delays[1] >= 2 result["scenarios"].append( { "name": "transient_retry_backoff_and_jitter", "attachment_id": aid, "attempts": 3, "observed_delays_seconds": delays, "audit": audits, "passed": True, } ) # Reorder actual broker messages AFTER v2 is already public. operation(f"print(j.reprocess('{aid}',2,o))") before = ready(aid) ids = sql( f"SELECT id,pipeline_version FROM attachment_jobs WHERE attachment_id='{aid}' ORDER BY pipeline_version", rows=True, ) v1, v2 = ids snippet = ( "import json; from messenger.jobs import broker_client,STREAM; b=broker_client(); " f"versions=[('{v2['id']}',2),('{v1['id']}',1),('{v2['id']}',2)]; " f"[b.xadd(STREAM,{{'body':json.dumps({{'schema_version':1,'job_id':jid,'type':'attachment.process.v1','attachment_id':'{aid}','pipeline_version':version,'attempt':1,'created_at':'2026-11-06T00:00:00Z'}})}}) for jid,version in versions]; print('reordered v2,v1,v2')" ) operation(snippet) time.sleep(2) assert ready(aid) == before hashes = {} for variant in ["original", "thumbnail", "crop", "optimized"]: data = c.call("GET", f"/api/v1/attachments/{aid}/content?variant={variant}", actor=bob)[ "bytes" ] hashes[variant] = hashlib.sha256(data).hexdigest() publications = sql( f"SELECT pipeline_version,count(*) AS n FROM attachment_jobs j JOIN job_audit a ON a.job_id=j.id WHERE j.attachment_id='{aid}' AND a.event='published' GROUP BY pipeline_version ORDER BY pipeline_version", rows=True, ) assert publications == [{"pipeline_version": 1, "n": 1}, {"pipeline_version": 2, "n": 1}] result["scenarios"].append( { "name": "broker_reorder_v2_v1_v2_no_regression", "attachment_id": aid, "hashes": hashes, "publications": publications, "passed": True, } ) # Malformed jobs are rejected and acknowledged, including non-UTF8 bytes. worker_before = next(item for item in runtime() if item["service"] == "worker") snippet = ( "import json; from messenger.jobs import broker_client,STREAM; b=broker_client(); " f"base={{'schema_version':1,'job_id':'{v2['id']}','type':'attachment.process.v1','attachment_id':'{aid}','pipeline_version':2,'attempt':1,'created_at':'2026-11-06T00:00:00Z'}}; " "bad=[json.dumps({**base,'job_id':123}),json.dumps({**base,'attachment_id':[]}),json.dumps({**base,'schema_version':True}),json.dumps({**base,'created_at':123}),bytes([255]),b'not-json','['*2000+']'*2000,b' '*10000+b'{}',json.dumps({**base,'attachment_id':'urn:uuid:'+base['attachment_id']})]; " "[b.xadd(STREAM,{'body':payload}) for payload in bad]; print('9 malformed deliveries')" ) operation(snippet) normal = upload() ready(normal) worker_after = next(item for item in runtime() if item["service"] == "worker") assert worker_after["container_id"] == worker_before["container_id"] assert worker_after["restart_count"] == worker_before["restart_count"] logs = compose("logs", "--tail", "100", "worker").stdout assert logs.count('"event": "invalid_delivery"') >= 9 result["scenarios"].append( { "name": "nine_poison_deliveries_rejected_without_worker_crash", "attachment_id": normal, "worker_before": worker_before, "worker_after": worker_after, "safe_log_events": 9, "passed": True, } ) # The only notification for this queued job uses uppercase UUIDs. There # is no lowercase dispatcher publication available to mask a lost job. compose("stop", "worker", "dispatcher") aid = upload() jid = job(aid)["id"] operation( "import json; from messenger.jobs import broker_client,STREAM; " f"body={{'schema_version':1,'job_id':'{jid.upper()}','type':'attachment.process.v1','attachment_id':'{aid.upper()}','pipeline_version':1,'attempt':1,'created_at':'2026-11-06T00:00:00Z'}}; " "broker_client().xadd(STREAM,{'body':json.dumps(body)}); print('uppercase notification accepted by broker')" ) sql(f"UPDATE job_outbox SET published_at=now() WHERE job_id='{jid}'") compose("start", "worker") ready(aid) assert job(aid)["attempt"] == 1 compose("start", "dispatcher") result["scenarios"].append( { "name": "uppercase_uuid_only_delivery_completes_queued_job", "attachment_id": aid, "no_lowercase_publication": True, "attempts": 1, "passed": True, } ) # A ready result can precede worker staging cleanup. First prove a real # S3 DELETE outage rolls reprocess back; then retry and prove no orphan. compose("stop", "worker") aid = upload() old_stage = sql(f"SELECT stage_key FROM attachments WHERE id='{aid}'", rows=True)[0][ "stage_key" ] old_worker_barrier = fault("after_result_commit", aid, "pause") compose("start", "worker") wait_until(lambda: reached(old_worker_barrier)) version1 = ready(aid) delete_barrier = fault("reprocess_before_staging_delete", aid, "pause") with ThreadPoolExecutor(1) as executor: replacing = executor.submit( command, COMPOSE + [ "exec", "-T", "--index", "2", "api", "python", "-m", "messenger.jobctl", "reprocess", aid, "--version", "2", ], False, ) wait_until(lambda: reached(delete_barrier)) compose("stop", "s3") sql(f"UPDATE test_faults SET released=true WHERE id={delete_barrier}") refused = replacing.result(timeout=20) assert refused.returncode == 1 and json.loads(refused.stdout)["status"] == 503 assert job(aid)["pipeline_version"] == 1 and job(aid)["state"] == "ready" compose("start", "s3") compose("up", "-d", "--no-recreate", "--wait", "api", "lb") command([sys.executable, "scripts/wait_replicas.py", "2"]) assert ready(aid) == version1 assert operation(f"print(o.exists('{old_stage}'))") == "True" result["scenarios"].append( { "name": "reprocess_staging_delete_outage_keeps_ready_version1", "attachment_id": aid, "reprocess_error": 503, "source_and_final_content_intact": True, "passed": True, } ) operation(f"print(j.reprocess('{aid}',2,o))") compose("up", "-d", "--no-deps", "--scale", "worker=2", "worker") version2 = ready(aid) sql(f"UPDATE test_faults SET released=true WHERE id={old_worker_barrier}") time.sleep(1) operation("from messenger.jobctl import cleanup; print(cleanup(s,o,0,3600))") assert operation(f"print(o.exists('{old_stage}'))") == "False" assert ready(aid) == version2 for variant in ["original", "thumbnail", "crop", "optimized"]: c.call("GET", f"/api/v1/attachments/{aid}/content?variant={variant}", actor=bob) compose("up", "-d", "--no-deps", "--scale", "worker=1", "worker") result["scenarios"].append( { "name": "ready_reprocess_before_old_cleanup_does_not_orphan_staging", "attachment_id": aid, "old_staging_absent": True, "version2_metadata_and_content_unchanged": True, "passed": True, } ) # Simulated old metadata must not make accepted queued staging eligible for cleanup. compose("stop", "worker") aid = upload() sql( f"UPDATE attachments SET created_at=now()-interval '8 days',updated_at=now()-interval '8 days' WHERE id='{aid}'" ) operation("from messenger.jobctl import cleanup; print(cleanup(s,o,0,0))") assert job(aid)["state"] == "queued" source_present = operation( f"\nwith s.connection() as conn:\n a=conn.execute(\"SELECT stage_key FROM attachments WHERE id=%s\",('{aid}',)).fetchone()\n print(o.exists(a['stage_key']))" ) assert source_present == "True" compose("start", "worker") ready(aid) result["scenarios"].append( { "name": "eight_day_old_queued_metadata_never_expires_staging", "attachment_id": aid, "age_simulated_in_database": True, "passed": True, } ) # Cleanup stops AFTER its final state check, BEFORE actual S3 DELETE, holding row lock. aid = make_failed() fid = fault("cleanup_before_delete", aid, "pause") with ThreadPoolExecutor(2) as executor: cleaner = executor.submit( operation, "from messenger.jobctl import cleanup; print(cleanup(s,o,0,3600))" ) wait_until(lambda: reached(fid)) replay = executor.submit(replay_command, aid).result(timeout=15) assert replay.returncode == 1 assert json.loads(replay.stdout)["status"] == 503 sql(f"UPDATE test_faults SET released=true WHERE id={fid}") cleaner.result(timeout=15) refused = replay_command(aid) assert refused.returncode == 1 and json.loads(refused.stdout)["status"] == 409 assert job(aid)["state"] == "failed" result["scenarios"].append( { "name": "cleanup_paused_before_delete_blocks_concurrent_replay", "attachment_id": aid, "while_locked_status": 503, "after_source_expiry_status": 409, "passed": True, } ) # Reverse ordering: replay holds the lock before its queued COMMIT. aid = make_failed() fid = fault("replay_before_commit", aid, "pause") with ThreadPoolExecutor(2) as executor: replayer = executor.submit(replay_command, aid) wait_until(lambda: reached(fid)) cleaning = executor.submit( command, COMPOSE + [ "exec", "-T", "--index", "2", "api", "python", "-m", "messenger.jobctl", "cleanup", "--failed-hours", "0", ], False, ).result(timeout=15) assert cleaning.returncode == 1 and json.loads(cleaning.stdout)["status"] == 503 sql(f"UPDATE test_faults SET released=true WHERE id={fid}") assert replayer.result(timeout=15).returncode == 0 ready(aid) operation("from messenger.jobctl import cleanup; print(cleanup(s,o,0,3600))") ready(aid) result["scenarios"].append( { "name": "replay_holds_lock_cleanup_cannot_delete_then_ready", "attachment_id": aid, "cleanup_while_locked_status": 503, "passed": True, } ) result["passed"] = True finally: sql("UPDATE test_faults SET released=true WHERE reached_at IS NOT NULL") command( ["docker", "compose", "up", "-d", "--no-build", "--wait", "api", "worker", "dispatcher"] ) Path("evidence/extra-invariants.json").write_text(json.dumps(result, indent=2)) print("PASS: backoff, reordered deliveries and both real cleanup/replay interleavings") if __name__ == "__main__": main()