#!/usr/bin/env python3 """Deterministic fault windows for the versioned attachment pipeline. Run in a one-shot worker image while the normal worker and publisher are stopped. All rows and objects are synthetic and stay in the educational volumes. """ import hashlib import json import os import subprocess import sys import time from io import BytesIO from uuid import uuid4 from PIL import Image from src.attachments import BUCKET, storage from src.db import pool from src.pipeline_jobs import ( claim_job, finish_attempt, queue_attachment, recover_expired, reserve_upload, ) from src.replay import replay_failed from src.reprocess import start_new_version from src.worker import process_message image = BytesIO() Image.new("RGB", (320, 200), "#2765a8").save(image, format="PNG") DATA = image.getvalue() SHA = hashlib.sha256(DATA).hexdigest() def create_case(): user_id, chat_id, attachment_id = uuid4(), uuid4(), uuid4() staging_key = f"staging/{attachment_id}" with pool().connection() as conn: with conn.transaction(): conn.execute( "INSERT INTO users (id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)", (user_id, f"fault_{user_id.hex[:20]}", "Pipeline fault fixture", "synthetic"), ) conn.execute("INSERT INTO chats (id,title) VALUES (%s,%s)", (chat_id, "Pipeline fault fixture")) conn.execute( "INSERT INTO memberships (chat_id,user_id,position) VALUES (%s,%s,0)", (chat_id, user_id), ) reserve_upload(conn, attachment_id, staging_key) storage().put_object(BUCKET, staging_key, BytesIO(DATA), len(DATA), content_type="image/png") with pool().connection() as conn: _, job_id = queue_attachment( conn, attachment_id=attachment_id, chat_id=chat_id, owner_id=user_id, filename="fixture.png", staging_key=staging_key, object_key=f"originals/{attachment_id}", content_type="image/png", size_bytes=len(DATA), sha256=SHA, ) return attachment_id, job_id def item(job_id, attempt=1): return {"job_id": str(job_id), "attempt": attempt} def state(attachment_id, version): with pool().connection() as conn: attachment = conn.execute( "SELECT status,pipeline_version,sha256 FROM attachments WHERE id=%s", (attachment_id,) ).fetchone() rows = conn.execute( "SELECT name,sha256 FROM attachment_variants " "WHERE attachment_id=%s AND pipeline_version=%s ORDER BY name", (attachment_id, version), ).fetchall() return attachment, {row["name"]: row["sha256"] for row in rows} def assert_ready(attachment_id, version): attachment, variants = state(attachment_id, version) assert attachment["status"] == "ready" and attachment["pipeline_version"] == version assert attachment["sha256"] == SHA assert set(variants) == {"original", "thumbnail", "crop", "optimized"} assert variants["original"] == SHA return variants def expire_and_recover(job_id): with pool().connection() as conn: conn.execute( "UPDATE attachment_jobs SET lease_expires_at=clock_timestamp()-interval '1 second' " "WHERE id=%s AND status='processing'", (job_id,), ) recovered = recover_expired(conn, max_attempts=5) assert (job_id, "queued") in recovered def crash(job_id, point): child = subprocess.run( [sys.executable, "-c", "from src.worker import process_message; " f"process_message({{'job_id': '{job_id}', 'attempt': 1}})"], env={**os.environ, "LAB5_FAULT_POINT": point, "LAB5_FAULT_JOB_ID": str(job_id)}, capture_output=True, text=True, ) assert child.returncode == 72, (point, child.returncode, child.stderr) def main(): results = {} attachment, job = create_case() crash(job, "after_result_commit_before_ack") first = assert_ready(attachment, 1) assert process_message(item(job)) == "duplicate_or_stale" assert assert_ready(attachment, 1) == first results["after_result_commit_before_ack_duplicate"] = "pass" attachment, job = create_case() crash(job, "after_claim_before_s3") expire_and_recover(job) assert process_message(item(job, 2)) == "ready" assert_ready(attachment, 1) results["before_side_effect_lease_recovery"] = "pass" attachment, job = create_case() crash(job, "after_s3_before_result_commit") expire_and_recover(job) assert process_message(item(job, 2)) == "ready" assert_ready(attachment, 1) results["after_s3_before_result_commit"] = "pass" attachment, old_job = create_case() assert process_message(item(old_job)) == "ready" with pool().connection() as conn: version, new_job = start_new_version(conn, attachment) assert version == 2 assert process_message(item(old_job)) == "duplicate_or_stale" assert process_message(item(new_job)) == "ready" newer = assert_ready(attachment, 2) assert process_message(item(old_job)) == "duplicate_or_stale" assert assert_ready(attachment, 2) == newer assert len(state(attachment, 1)[1]) == 4 results["duplicate_reorder_new_version"] = "pass" attachment, job = create_case() with pool().connection() as conn: claimed = claim_job(conn, job, 1) assert finish_attempt( conn, job, claimed["lease_token"], max_attempts=5, error_code="invalid_image", permanent=True, ) == "failed" attempt = replay_failed(conn, job, "lab5-test", "verified synthetic replay") assert attempt == 2 assert process_message(item(job, attempt)) == "ready" assert_ready(attachment, 1) with pool().connection() as conn: count = conn.execute( "SELECT count(*) AS n FROM attachment_job_replays WHERE job_id=%s", (job,) ).fetchone()["n"] assert count == 1 results["failed_registry_operator_replay"] = "pass" attachment, job = create_case() with pool().connection() as conn: claimed = claim_job(conn, job, 1) assert finish_attempt( conn, job, claimed["lease_token"], max_attempts=2, delay_seconds=0.01, error_code="storage_unavailable", ) == "queued" time.sleep(0.03) with pool().connection() as conn: claimed = claim_job(conn, job, 2) assert claimed is not None assert finish_attempt( conn, job, claimed["lease_token"], max_attempts=2, error_code="storage_unavailable", ) == "failed" attempt = replay_failed(conn, job, "lab5-test", "retry budget reset after repair") assert attempt == 3 assert process_message(item(job, attempt)) == "ready" assert_ready(attachment, 1) results["bounded_transient_retry_then_replay"] = "pass" print(json.dumps(results, sort_keys=True)) if __name__ == "__main__": main()