from __future__ import annotations import base64 import hashlib import json import secrets import subprocess import time from uuid import UUID, uuid4 from queued_restart import ROOT, DC, api, dc, http, wait_ready from outbox_gap import snapshot from before_ack import sql, object_keys EVIDENCE = ROOT / "evidence" / "failed_replay.json" def staging_write(attachment_id, *, original=None): code = """ import sys from uuid import UUID from app.job_db import connect_db from app.storage import _put attachment_id = UUID(sys.argv[1]) mode = sys.argv[2] with connect_db() as db: row = db.execute( ''' SELECT staging_key, content_type FROM attachments WHERE id = %s ''', (attachment_id,), ).fetchone() if row is None or not row["staging_key"]: raise SystemExit(2) data = ( b"deliberate synthetic staging corruption" if mode == "corrupt" else sys.stdin.buffer.read() ) _put(row["staging_key"], data, row["content_type"]) """ mode = "corrupt" if original is None else "restore" result = subprocess.run( [ DC, "exec", "-T", "api", "python", "-c", code, attachment_id, mode, ], cwd=ROOT, input=b"" if original is None else original, capture_output=True, timeout=90, ) if result.returncode: raise RuntimeError(f"Staging operation failed: {mode}") def replay_command(job_id, *, apply=False): args = [ DC, "exec", "-T", "worker", "python", "-m", "app.replay", "--job-id", job_id, "--actor", "student-test", "--reason", "Synthetic staging integrity fault repaired", ] if apply: args.append("--apply") result = subprocess.run( args, cwd=ROOT, capture_output=True, text=True, timeout=90, ) return result.returncode, json.loads(result.stdout) def audit_count(job_id): return int(sql(f""" SELECT count(*) FROM attachment_job_replays WHERE job_id = '{job_id}'::uuid; """)) def wait_status(path, token, expected, timeout=90): deadline = time.monotonic() + timeout while time.monotonic() < deadline: current = api("GET", path, 200, token=token) if current["status"] == expected: return current if expected == "ready" and current["status"] == "failed": raise AssertionError( "Replay failed: " + str(current["error_code"]) ) time.sleep(0.5) raise AssertionError(f"Timeout waiting for {expected}") def main(): evidence = {"scenario": "failed staging integrity and audited replay"} restore_worker = False corrupted = False attachment_id = None original = None try: assert sql( "SELECT to_regclass('attachment_job_replays') IS NOT NULL;" ) == "t", "Apply migration 007 first" wait_ready() if not dc("ps", "--status", "running", "-q", "worker"): raise AssertionError("Start worker before this test") username = "rep_" + uuid4().hex[:16] password = secrets.token_hex(16) user = api( "POST", "/api/v1/users", 201, payload={ "username": username, "display_name": "Failed replay test", "password": password, }, ) basic = base64.b64encode( f"{username}:{password}".encode() ).decode() token = api( "POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + basic}, )["token"] chat = api( "POST", "/api/v1/chats", 201, token=token, payload={ "title": "Failed replay", "member_ids": [user["id"]], }, ) restore_worker = True dc("stop", "worker") if dc("ps", "--status", "running", "-q", "worker"): raise AssertionError("Worker is still running") original = (ROOT / "tests/fixtures/sample.png").read_bytes() attachment = api( "POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", 202, token=token, data=original, headers={"Content-Type": "image/png"}, ) attachment_id = str(UUID(attachment["id"])) path = f"/api/v1/attachments/{attachment_id}" job_id = str(UUID(snapshot(attachment_id)["job_id"])) evidence["attachment_id"] = attachment_id evidence["job_id"] = job_id # Отмечаем до вызова, чтобы finally попытался восстановить # исходник даже при неопределённом результате S3-записи. corrupted = True staging_write(attachment_id) dc("start", "worker") failed = wait_status(path, token, "failed") assert failed["error_code"] == "invalid_image" assert failed["variants"] == [] failed_job = snapshot(attachment_id) assert failed_job["status"] == "failed" assert failed_job["attempt"] == 1 assert failed_job["outbox_count"] == 1 assert audit_count(job_id) == 0 registry = json.loads( dc("exec", "-T", "worker", "python", "-m", "app.replay", "--list") ) assert any(item["job_id"] == job_id for item in registry) api("GET", path + "/content", 409, token=token) api( "POST", f"/api/v1/chats/{chat['id']}/messages", 409, token=token, payload={"text": "", "attachment_ids": [attachment_id]}, headers={"Idempotency-Key": str(uuid4())}, ) evidence["failed_job"] = failed_job print("Corrupted staging produced failed/invalid_image; API returns 409") code, rejected = replay_command(job_id, apply=True) assert code != 0 assert rejected["result"] == "error" assert snapshot(attachment_id) == failed_job assert audit_count(job_id) == 0 evidence["rejected_replay"] = rejected print("Replay rejected corrupted staging without state changes or audit") staging_write(attachment_id, original=original) corrupted = False code, dry_run = replay_command(job_id) assert code == 0 and dry_run["result"] == "dry_run" assert snapshot(attachment_id) == failed_job assert audit_count(job_id) == 0 evidence["dry_run"] = dry_run print("Original restored; dry-run left job unchanged") code, applied = replay_command(job_id, apply=True) assert code == 0 and applied["result"] == "replayed" assert applied["new_attempt"] == 2 ready = wait_status(path, token, "ready") final = snapshot(attachment_id) assert final["job_id"] == job_id assert final["status"] == "ready" assert final["attempt"] == 2 assert final["outbox_count"] == 2 assert audit_count(job_id) == 1 status, body = http("GET", path + "/content", token=token) assert status == 200 and body == original variants = {item["name"]: item for item in ready["variants"]} assert len(ready["variants"]) == 3 assert set(variants) == {"thumbnail", "crop", "optimized"} for name, metadata in variants.items(): status, body = http( "GET", path + "/content?variant=" + name, token=token, ) assert status == 200 assert len(body) == metadata["size_bytes"] assert hashlib.sha256(body).hexdigest() == metadata["sha256"] keys_before_noop = object_keys(attachment_id) assert len(keys_before_noop) == 4 code, noop = replay_command(job_id, apply=True) assert code == 0 assert noop["result"] == "noop" assert noop["status"] == "ready" assert snapshot(attachment_id) == final assert audit_count(job_id) == 1 assert object_keys(attachment_id) == keys_before_noop evidence["applied_replay"] = applied evidence["final_job"] = final evidence["ready_replay"] = noop evidence["audit_rows"] = 1 evidence["object_count"] = len(keys_before_noop) evidence["result"] = "PASS" except BaseException as exc: evidence["result"] = "FAIL" evidence["error_type"] = type(exc).__name__ raise finally: try: if corrupted and attachment_id is not None: staging_write(attachment_id, original=original) finally: try: if restore_worker: dc("start", "worker") finally: EVIDENCE.parent.mkdir(exist_ok=True) EVIDENCE.write_text( json.dumps(evidence, ensure_ascii=False, indent=2) + "\n" ) print( "PASS: failed registry, integrity guard, dry-run, audited replay " "and ready noop verified; same job, attempt=2" ) if __name__ == "__main__": main()