"""DB <-> S3 reconciliation and staging retention (lab4 reconciler extended for the lab5 key layout). Key layout (all keys are generated by the server): staging/ written by the API before 202, read by the worker attachments//original server-side copy made by the worker attachments//v/.* variants of pipeline version N Invariant: a row is inserted as 'uploading' BEFORE the staging object is written, so every object has a row. Cases (all gated by a grace period so in-flight work is never touched): stale_uploading row 'uploading' older than grace AND its staging object (if any) older than grace -> delete both orphan_object object without any row/variant row, older than grace -> delete object staging_done staging object of a 'ready' attachment (worker crashed before its own cleanup) -> delete staging_expired staging object of a 'failed' attachment older than STAGING_RETENTION_SECONDS -> delete (after that a replay is refused; the attachment stays failed and visible) missing_object 'ready' row whose original is gone (re-checked by HEAD) -> 'failed'/object_missing Queued/processing work is never touched: its staging object is the input of a live job. """ import logging import time from datetime import datetime, timedelta, timezone from starlette.concurrency import run_in_threadpool from app import config log = logging.getLogger("messenger.reconcile") LOCK_ID = 2026_0104 PREFIXES = ("staging/", "attachments/") BATCH = 500 async def run(db, s3, grace_seconds: int, dry_run: bool = True) -> dict: started = time.monotonic() result = { "dry_run": dry_run, "grace_seconds": grace_seconds, "stale_uploading": 0, "orphan_objects": 0, "missing_objects": 0, "staging_done": 0, "staging_expired": 0, "deleted_objects": 0, "removed_rows": 0, "marked_failed": 0, "objects_scanned": 0, "rows_scanned": 0, "protected_fresh_objects": 0, } async with db.connection() as conn: cur = await conn.execute("SELECT pg_try_advisory_lock(%s) AS got", (LOCK_ID,)) if not (await cur.fetchone())["got"]: return {"skipped": "another reconciler is running"} try: now = datetime.now(timezone.utc) cutoff = now - timedelta(seconds=grace_seconds) await _stale_uploading(conn, s3, cutoff, dry_run, result) await _staging_cleanup(conn, s3, now - timedelta(seconds=config.STAGING_RETENTION_SECONDS), dry_run, result) await _orphan_objects(conn, s3, cutoff, dry_run, result) await _missing_objects(conn, s3, cutoff, dry_run, result) finally: await conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,)) result["seconds"] = round(time.monotonic() - started, 3) return result async def _stale_uploading(conn, s3, cutoff, dry_run, result): cur = await conn.execute( "SELECT id, coalesce(staging_key, object_key) AS key FROM attachments" " WHERE status = 'uploading' AND created_at < %s", (cutoff,), ) for row in await cur.fetchall(): modified = await run_in_threadpool(s3.head, row["key"]) if modified is not None and modified >= cutoff: result["protected_fresh_objects"] += 1 continue result["stale_uploading"] += 1 if dry_run: continue if modified is not None: await run_in_threadpool(s3.delete, row["key"]) result["deleted_objects"] += 1 done = await conn.execute( "DELETE FROM attachments WHERE id = %s AND status = 'uploading' AND created_at < %s", (row["id"], cutoff), ) result["removed_rows"] += done.rowcount async def _staging_cleanup(conn, s3, retention_cutoff, dry_run, result): cur = await conn.execute( "SELECT id, staging_key, status FROM attachments WHERE staging_key IS NOT NULL" " AND (status = 'ready' OR (status = 'failed' AND updated_at < %s))", (retention_cutoff,), ) for row in await cur.fetchall(): if await run_in_threadpool(s3.head, row["staging_key"]) is None: continue result["staging_done" if row["status"] == "ready" else "staging_expired"] += 1 if dry_run: continue again = await conn.execute( "SELECT status FROM attachments WHERE id = %s AND (status = 'ready' OR (status = 'failed' AND updated_at < %s))", (row["id"], retention_cutoff), ) if await again.fetchone() is not None: await run_in_threadpool(s3.delete, row["staging_key"]) result["deleted_objects"] += 1 async def _known_keys(conn, keys): cur = await conn.execute( "SELECT object_key AS k FROM attachments WHERE object_key = ANY(%s)" " UNION SELECT staging_key FROM attachments WHERE staging_key = ANY(%s)" " UNION SELECT object_key FROM attachment_variants WHERE object_key = ANY(%s)", (keys, keys, keys), ) return {row["k"] for row in await cur.fetchall()} async def _orphan_objects(conn, s3, cutoff, dry_run, result): for prefix in PREFIXES: pages = await run_in_threadpool(lambda: iter(s3.list_pages(prefix))) while True: page = await run_in_threadpool(next, pages, None) if page is None: break result["objects_scanned"] += len(page) keys = [o["Key"] for o in page] if not keys: continue known = await _known_keys(conn, keys) for obj in page: if obj["Key"] in known or obj["LastModified"] >= cutoff: continue result["orphan_objects"] += 1 if not dry_run and not await _known_keys(conn, [obj["Key"]]): await run_in_threadpool(s3.delete, obj["Key"]) result["deleted_objects"] += 1 async def _missing_objects(conn, s3, cutoff, dry_run, result): last = None while True: cur = await conn.execute( "SELECT id, object_key FROM attachments WHERE status = 'ready' AND updated_at < %s" " AND (%s::uuid IS NULL OR id > %s::uuid) ORDER BY id LIMIT %s", (cutoff, last, last, BATCH), ) rows = await cur.fetchall() if not rows: return for row in rows: result["rows_scanned"] += 1 if await run_in_threadpool(s3.exists, row["object_key"]): continue result["missing_objects"] += 1 if not dry_run: done = await conn.execute( "UPDATE attachments SET status = 'failed', error_code = 'object_missing'," " updated_at = clock_timestamp() WHERE id = %s AND status = 'ready'", (row["id"],), ) result["marked_failed"] += done.rowcount last = str(rows[-1]["id"])