#!/usr/bin/env python3 """Explicitly replay a failed attachment while its verified staging bytes remain.""" import hashlib import os import sys import uuid import psycopg from jobs import s3_client from psycopg.rows import dict_row DB=os.environ["DATABASE_URL"] BUCKET=os.getenv("S3_BUCKET","messenger-attachments") def main(): if len(sys.argv) not in (2,3) or (len(sys.argv)==3 and sys.argv[2]!="--apply"): raise SystemExit("usage: python scripts/replay_failed.py ATTACHMENT_UUID [--apply]") aid=uuid.UUID(sys.argv[1]); apply=len(sys.argv)==3 s3=s3_client() with psycopg.connect(DB,row_factory=dict_row) as conn: with conn.transaction(): row=conn.execute("SELECT * FROM attachments WHERE id=%s FOR UPDATE",(aid,)).fetchone() if not row: raise SystemExit("attachment not found") if row["status"]!="failed" or not row["staging_key"]: raise SystemExit("only failed attachments with retained staging can be replayed") obj=s3.get_object(Bucket=BUCKET,Key=row["staging_key"]) body=obj["Body"].read(int(row["size_bytes"])+1) if len(body)!=row["size_bytes"] or hashlib.sha256(body).hexdigest()!=row["sha256"]: raise SystemExit("staging original failed checksum verification") if not apply: print(f"dry-run attachment={aid} version={row['pipeline_version']} error={row['error_code']} verified_bytes={len(body)}") return job_id=uuid.uuid4() conn.execute("UPDATE attachments SET job_id=%s,status='queued',attempts=0,error_code=NULL,lease_until=NULL,next_attempt_at=NULL,updated_at=now() WHERE id=%s", (job_id,aid)) conn.execute("INSERT INTO job_outbox(job_id,attempt,attachment_id,pipeline_version) VALUES (%s,1,%s,%s)",(job_id,aid,row["pipeline_version"])) conn.execute("INSERT INTO pipeline_audit(attachment_id,job_id,pipeline_version,event,detail) VALUES (%s,%s,%s,'manual_replay',jsonb_build_object('previous_error',%s::text))", (aid,job_id,row["pipeline_version"],row["error_code"])) print(f"queued attachment={aid} version={row['pipeline_version']}") if __name__=="__main__": main()