#!/usr/bin/env python3 """Verify failed-job routing and explicit replay against the local Compose stack.""" import os from pathlib import Path import subprocess import sys import time import uuid from urllib.parse import urlparse ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, LAB, check def compose(args, env, input_bytes=None, timeout=90): result = subprocess.run( ["docker", "compose", *args], cwd=ROOT, env=env, input=input_bytes, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout, ) if result.returncode: output = result.stdout.decode("utf-8", errors="replace") raise RuntimeError("docker compose failed: " + "\n".join(output.splitlines()[-25:])) return result.stdout.decode("utf-8", errors="replace").strip() def put_staging_object(key, data, env): code = ( "import os,sys,boto3; " "from botocore.config import Config; " "boto3.client('s3',endpoint_url=os.environ['S3_ENDPOINT']," "region_name=os.environ.get('S3_REGION','us-east-1')," "aws_access_key_id=os.environ['S3_ACCESS_KEY_ID']," "aws_secret_access_key=os.environ['S3_SECRET_ACCESS_KEY']," "config=Config(signature_version='s3v4',s3={'addressing_style':'path'})).put_object(" "Bucket=os.environ['S3_BUCKET'],Key=sys.argv[1],Body=sys.stdin.buffer.read()," "ContentType='image/png')" ) compose( ["run", "--rm", "--no-deps", "-T", "--entrypoint", "python", "worker", "-c", code, key], env, input_bytes=data, timeout=45, ) def psql(query, env): return compose( ["exec", "-T", "postgres", "psql", "-X", "-A", "-t", "-U", "messenger", "-d", "messenger", "-c", query], env, timeout=15, ) def main(): if LAB < 5: raise RuntimeError("live replay test requires lab5") base_url = os.environ.get("BASE_URL", "http://localhost:8080") parsed = urlparse(base_url) if not parsed.hostname: raise ValueError("BASE_URL must be an absolute HTTP(S) URL") env = dict(os.environ) env["HTTP_PORT"] = str(parsed.port or (443 if parsed.scheme == "https" else 80)) env["WORKER_FAULT_INJECTION"] = "" client = Client(base_url, timeout=10) alice, _, _, chat = client.bootstrap() attachment = None original = None staging_key = None try: compose(["stop", "worker"], env) attachment, original = client.attachment(alice, chat) staging_key = f"staging/{attachment['id']}/original" put_staging_object(staging_key, b"invalid-test-payload", env) compose(["up", "-d", "worker"], env) deadline = time.monotonic() + 60 failed = None while time.monotonic() < deadline: failed = client.call( "GET", f"/api/v1/attachments/{attachment['id']}", actor=alice, schema="Attachment", )["json"] if failed["status"] == "failed": break time.sleep(0.25) check(failed is not None and failed["status"] == "failed", "invalid staging object did not fail permanently") check(failed["error_code"] == "processing_failed", "unexpected permanent error code") attachment_id = str(uuid.UUID(attachment["id"])) failed_event_count = psql( "SELECT count(*) FROM outbox WHERE event_type='attachment.failed' " f"AND payload->>'attachment_id'='{attachment_id}' AND published_at IS NOT NULL", env, ) check(failed_event_count == "1", "failed event was not publisher-confirmed") put_staging_object(staging_key, original, env) replay_output = compose( ["exec", "-T", "worker", "python", "-m", "src.replay", attachment_id, "--operator", "live-lab5-test"], env, timeout=30, ) ready = client.wait_ready(alice, failed, wait_seconds=60) downloaded = client.call( "GET", f"/api/v1/attachments/{attachment_id}/content", actor=alice, ) check(downloaded["bytes"] == original, "replayed original differs from accepted bytes") state = psql( "SELECT concat_ws('|',j.status,j.attempt::text,j.replay_count::text,count(ja.id)::text) " "FROM jobs j LEFT JOIN job_attempts ja ON ja.job_id=j.id " f"WHERE j.attachment_id='{attachment_id}' GROUP BY j.id", env, ) check(state == "ready|1|1|1", "unexpected job state after replay: " + state) operator = psql( "SELECT operator FROM job_replays " f"WHERE attachment_id='{attachment_id}' ORDER BY replayed_at DESC LIMIT 1", env, ) check(operator == "live-lab5-test", "replay audit entry is missing") psql( "UPDATE jobs SET status='processing',attempt=2,lease_until=NOW()-INTERVAL '1 second' " f"WHERE attachment_id='{attachment_id}'; " "UPDATE attachments SET status='processing',updated_at=NOW() " f"WHERE id='{attachment_id}'", env, ) lease_deadline = time.monotonic() + 60 leased = None while time.monotonic() < lease_deadline: leased = client.call( "GET", f"/api/v1/attachments/{attachment_id}", actor=alice, schema="Attachment", )["json"] if leased["status"] == "ready": break time.sleep(0.25) check(leased is not None and leased["status"] == "ready", "expired lease did not recover") lease_state = psql( "SELECT concat_ws('|',j.status,j.attempt::text,j.replay_count::text,count(ja.id)::text) " "FROM jobs j LEFT JOIN job_attempts ja ON ja.job_id=j.id " f"WHERE j.attachment_id='{attachment_id}' GROUP BY j.id", env, ) check(lease_state == "ready|3|1|1", "unexpected state after lease recovery: " + lease_state) print({ "result": "PASS", "attachment_id": attachment_id, "failed_event_published": True, "replay_state": state, "lease_recovery_state": lease_state, "operator": operator, "original_unchanged": True, "replay_command_result": replay_output, "final_status": ready["status"], }) finally: if attachment and original and staging_key: put_staging_object(staging_key, original, env) compose(["up", "-d", "worker"], env) if __name__ == "__main__": main()