"""Interrupt upload, fail S3 and metadata writes, then verify grace cleanup.""" import json import socket import time import uuid from urllib.parse import urlsplit from verify_attachments import ROOT, Client, check, compose, psql, run, upload, wait_ready def stat(key): return json.loads(compose("exec", "-T", "api1", "/messenger", "s3-stat", key)) def cleanup(): return json.loads(compose("exec", "-T", "-e", "CLEANUP_GRACE_SECONDS=120", "cleanup", "/messenger", "cleanup")) def main(): client = Client(timeout=30) actor, _, _, chat = client.bootstrap() raw = (ROOT / "tests/fixtures/sample.png").read_bytes() good = upload(client, actor, chat, raw)["json"] ready_key = psql("SELECT object_key FROM attachments WHERE id='" + good["id"] + "';") count_before = psql("SELECT count(*) FROM attachments;") # Abort a real HTTP upload with a body shorter than its Content-Length. address = urlsplit(client.base) with socket.create_connection((address.hostname, address.port or 80), timeout=5) as connection: headers = ("POST /api/v1/chats/" + chat["id"] + "/attachments?filename=interrupted.png HTTP/1.1\r\n" "Host: localhost\r\nAuthorization: Bearer " + actor["token"] + "\r\n" "Content-Type: image/png\r\nContent-Length: " + str(len(raw) + 1000) + "\r\nConnection: close\r\n\r\n") connection.sendall(headers.encode() + raw[:40]) time.sleep(1) check(psql("SELECT count(*) FROM attachments;") == count_before, "interrupted upload left ready metadata") try: compose("stop", "s3") client.call("GET", "/health/ready", 503) upload(client, actor, chat, raw, expected=503) client.call("GET", "/api/v1/users/me", 401) finally: compose("start", "s3") wait_ready(client) check(client.call("GET", "/api/v1/attachments/" + good["id"] + "/content", actor=actor)["bytes"] == raw, "S3 restart lost original") constraint = "injected_" + uuid.uuid4().hex failed_keys = [] try: psql("ALTER TABLE attachments ADD CONSTRAINT " + constraint + " CHECK (filename NOT LIKE 'failure-%') NOT VALID;") for number in range(2): before = set(psql("SELECT object_key FROM attachment_uploads;").splitlines()) upload(client, actor, chat, raw, filename="failure-%d.png" % number, expected=503) after = set(psql("SELECT object_key FROM attachment_uploads;").splitlines()) new = after - before check(len(new) == 1, "failed metadata write did not leave one durable intent") key = new.pop() check(stat(key)["exists"], "failure was not injected after successful S3 PUT") failed_keys.append(key) finally: psql("ALTER TABLE attachments DROP CONSTRAINT IF EXISTS " + constraint + ";") # Also cover an object whose intent is missing, as with late S3 completion. psql("DELETE FROM attachment_uploads WHERE object_key='" + failed_keys[1] + "';") fresh = cleanup() check(all(stat(key)["exists"] for key in failed_keys), "fresh objects removed before safe grace") print("Waiting 122 seconds for safe cleanup grace; fresh objects were preserved.", flush=True) deadline = time.monotonic() + 122 while time.monotonic() < deadline: time.sleep(max(0, min(1, deadline - time.monotonic()))) cleaned = cleanup() check(all(not stat(key)["exists"] for key in failed_keys), "orphan objects survived cleanup") check(stat(ready_key)["exists"], "cleanup deleted ready referenced data") repeat = cleanup() check(repeat["removed_objects"] == 0 and repeat["removed_intents"] == 0, "cleanup repeat is not idempotent") result = {"partial_upload": "PASS", "s3_outage_503_and_recovery": "PASS", "metadata_failure_after_put": "PASS", "orphan_without_intent": "PASS", "grace_seconds": 120, "fresh_preserved": True, "ready_preserved": True, "fresh_sweep": fresh, "cleanup": cleaned, "repeat": repeat} (ROOT / "evidence/upload-recovery.json").write_text(json.dumps(result, indent=2) + "\n") print("PASS:", json.dumps(result)) if __name__ == "__main__": run(main)