"""State machine of attachment jobs in PostgreSQL (lab 5). Every transition is ONE transaction. Lock order, everywhere both rows are locked: the jobs row FIRST, then the attachments row (claim, complete, retry, lease expiry). Replay/reprocess/cleanup lock only the attachments row and insert NEW job rows. So two transitions never wait on each other in opposite order. Fencing: a claim gives the attempt a fresh random `lease_token`. Every later write of that attempt (heartbeat, result, retry) is conditional on `jobs.lease_token = ` under the jobs row lock. When the lease expires, the reaper clears the token; from then on the old attempt - even if its process is still alive (paused, slow) - can neither publish nor schedule anything, and the objects it wrote under its own keys are garbage for the cleanup. Monotonic publication: a result of pipeline version V is published only if V is greater than the published version of the attachment; otherwise the job ends as `superseded` and nothing visible changes. `ready` never goes back to queued/processing. """ from __future__ import annotations import datetime as dt import json import random import uuid from dataclasses import dataclass import psycopg from . import telemetry from .pipeline import VARIANT_NAMES from .storage import attempt_key ACTIVE = ("queued", "processing") def backoff_delay(attempt: int, base: float, cap: float, rnd=random.random) -> float: """Full jitter (AWS Architecture Blog, "Exponential Backoff And Jitter"): uniform in [0, min(cap, base * 2^(attempt-1))]. Spreads the retries of many jobs that failed together.""" return rnd() * min(cap, base * (2 ** max(0, attempt - 1))) async def event(conn: psycopg.AsyncConnection, job_id, name: str, actor: str, *, attempt: int | None = None, error_code: str | None = None, **detail) -> None: await conn.execute( "INSERT INTO job_events (job_id, event, attempt, actor, error_code, detail) VALUES (%s, %s, %s, %s, %s, %s)", (job_id, name, attempt, actor, error_code, json.dumps(detail, default=str))) async def create_job(conn: psycopg.AsyncConnection, attachment_id, pipeline_version: int, kind: str, max_attempts: int, actor: str, *, replay_of=None, **detail) -> uuid.UUID: """jobs row + its first outbox row + audit, in the CALLER's transaction. Lab 6: the current W3C trace context (the upload request) is stored with the job: every message of this job is published as a child of it (migrations/0006_observability.sql).""" job_id = uuid.uuid4() carrier = telemetry.inject() await conn.execute( "INSERT INTO jobs (id, attachment_id, pipeline_version, kind, replay_of, max_attempts, traceparent, tracestate) " "VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", (job_id, attachment_id, pipeline_version, kind, replay_of, max_attempts, carrier.get("traceparent"), carrier.get("tracestate"))) await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, 1)", (job_id,)) await event(conn, job_id, "created", actor, kind=kind, pipeline_version=pipeline_version, replay_of=str(replay_of) if replay_of else None, **detail) return job_id # ------------------------------------------------------------------ relay @dataclass(frozen=True, slots=True) class Due: outbox_id: int job_id: str attachment_id: str pipeline_version: int attempt: int created_at: dt.datetime job_state: str traceparent: str | None = None tracestate: str | None = None kind: str = "upload" async def due_outbox(conn: psycopg.AsyncConnection, batch: int) -> list[Due]: """Due, unpublished outbox rows, locked for this relay pass (SKIP LOCKED: several relays never publish the same row at the same time - a crash may still publish it twice).""" cur = await conn.execute( "SELECT o.id, o.job_id, j.attachment_id, j.pipeline_version, o.attempt, j.created_at, j.state, " "j.traceparent, j.tracestate, j.kind " "FROM outbox o JOIN jobs j ON j.id = o.job_id " "WHERE o.published_at IS NULL AND o.available_at <= clock_timestamp() " "ORDER BY o.available_at, o.id LIMIT %s FOR UPDATE OF o SKIP LOCKED", (batch,)) return [Due(r[0], str(r[1]), str(r[2]), r[3], r[4], r[5], r[6], r[7], r[8], r[9]) for r in await cur.fetchall()] async def mark_published(conn: psycopg.AsyncConnection, ids: list[int]) -> None: if ids: await conn.execute("UPDATE outbox SET published_at = clock_timestamp() WHERE id = ANY(%s)", (ids,)) async def count_publish_failure(conn: psycopg.AsyncConnection, ids: list[int]) -> None: if ids: await conn.execute("UPDATE outbox SET publish_failures = publish_failures + 1 WHERE id = ANY(%s)", (ids,)) async def expire_leases(conn: psycopg.AsyncConnection, actor: str, limit: int = 50) -> int: """Reaper: processing jobs whose lease ran out (the worker died, hung or lost its database). The attempt is abandoned; the job goes back to queued with a new outbox row, or to failed `retry_exhausted` when it used all its attempts.""" cur = await conn.execute( "SELECT id, attempt, max_attempts, lease_token, attachment_id FROM jobs " "WHERE state = 'processing' AND lease_until < clock_timestamp() " "ORDER BY lease_until LIMIT %s FOR UPDATE SKIP LOCKED", (limit,)) rows = await cur.fetchall() for job_id, attempt, max_attempts, token, attachment_id in rows: await conn.execute( "UPDATE job_attempts SET outcome = 'abandoned', error_code = 'lease_expired', finished_at = clock_timestamp() " "WHERE token = %s AND outcome = 'running'", (token,)) if attempt >= max_attempts: await _fail(conn, job_id, attachment_id, "retry_exhausted", actor, attempt, cause="lease_expired") else: await conn.execute( "UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, " "available_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (job_id,)) await conn.execute( "UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() " "WHERE id = %s AND status = 'processing'", (attachment_id,)) await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (job_id, attempt + 1)) await event(conn, job_id, "lease_expired", actor, attempt=attempt) return len(rows) async def republish_stale(conn: psycopg.AsyncConnection, older_than: float, actor: str, limit: int = 50) -> int: """Lost-message guard: a queued, due job that has had no unpublished outbox row and no publish for `older_than` seconds gets a new outbox row (its message was lost by the broker, dead-lettered after too many redeliveries, or the queue was purged).""" cur = await conn.execute( "SELECT j.id, j.attempt FROM jobs j " "WHERE j.state = 'queued' AND j.available_at < clock_timestamp() - make_interval(secs => %s) " "AND j.updated_at < clock_timestamp() - make_interval(secs => %s) " "AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.job_id = j.id AND (o.published_at IS NULL " " OR o.published_at > clock_timestamp() - make_interval(secs => %s))) " "ORDER BY j.updated_at LIMIT %s FOR UPDATE OF j SKIP LOCKED", (older_than, older_than, older_than, limit)) rows = await cur.fetchall() for job_id, attempt in rows: await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (job_id, attempt + 1)) await event(conn, job_id, "republished", actor, attempt=attempt) return len(rows) async def queue_stats(conn: psycopg.AsyncConnection) -> dict: """Backlog for the gauges (relay, every few seconds): two aggregates over partial indexes.""" cur = await conn.execute( "SELECT count(*) FILTER (WHERE state = 'queued'), count(*) FILTER (WHERE state = 'processing'), " "COALESCE(EXTRACT(EPOCH FROM clock_timestamp() - min(created_at)), 0)::float8 " "FROM jobs WHERE state IN ('queued', 'processing')") queued, processing, oldest = await cur.fetchone() cur = await conn.execute( "SELECT count(*) FILTER (WHERE available_at <= clock_timestamp()), " "count(*) FILTER (WHERE available_at > clock_timestamp()), " "COALESCE(EXTRACT(EPOCH FROM clock_timestamp() - min(available_at) " " FILTER (WHERE available_at <= clock_timestamp())), 0)::float8 " "FROM outbox WHERE published_at IS NULL") due, delayed, outbox_age = await cur.fetchone() return {"queued": queued, "processing": processing, "oldest_age": float(oldest), "outbox_due": due, "outbox_delayed": delayed, "outbox_oldest_due_age": float(outbox_age)} async def purge_outbox(conn: psycopg.AsyncConnection, keep_seconds: int = 7 * 86400) -> int: cur = await conn.execute( "DELETE FROM outbox WHERE id IN (SELECT id FROM outbox WHERE published_at < clock_timestamp() " "- make_interval(secs => %s) LIMIT 1000)", (keep_seconds,)) return cur.rowcount # ------------------------------------------------------------------ worker @dataclass(frozen=True, slots=True) class Claim: job_id: str attachment_id: str pipeline_version: int attempt: int max_attempts: int token: str source: str # staging | original source_key: str content_type: str size_bytes: int sha256: bytes write_original: bool # the original is not published yet: this attempt publishes it too kind: str = "upload" # upload | replay | reprocess | migrate accepted_at: dt.datetime | None = None # jobs.created_at = the durable acceptance (202) of an upload def key(self, name: str) -> str: return attempt_key(self.attachment_id, self.token, name) @dataclass(frozen=True, slots=True) class Noop: reason: str # finished | leased | not_due | superseded | unknown_job async def claim(conn: psycopg.AsyncConnection, job_id: str, worker: str, lease_seconds: float) -> Claim | Noop: cur = await conn.execute( "SELECT state, attempt, max_attempts, available_at > clock_timestamp(), attachment_id, pipeline_version, " "kind, created_at FROM jobs WHERE id = %s FOR UPDATE", (job_id,)) row = await cur.fetchone() if row is None: return Noop("unknown_job") state, attempt, max_attempts, not_due, attachment_id, version, kind, accepted_at = row if state not in ACTIVE: return Noop("finished") # duplicate/redelivery of a finished job: ack, nothing else if state == "processing": return Noop("leased") # another attempt holds the lease; the reaper handles its death if not_due: return Noop("not_due") # backoff not over: the outbox publishes it at available_at cur = await conn.execute( "SELECT status, published_version, object_key, staging_key, staging_state, content_type, size_bytes, sha256 " "FROM attachments WHERE id = %s FOR UPDATE", (attachment_id,)) status, published, object_key, staging_key, staging_state, content_type, size, sha = await cur.fetchone() actor = "worker:" + worker if published is not None and published >= version: # A newer (or the same) version is already published: this job can only be stale. await _finish(conn, job_id, "superseded", None) await event(conn, job_id, "superseded", actor, attempt=attempt, published_version=published) return Noop("superseded") if object_key is not None: source, source_key = "original", object_key elif staging_state == "present": source, source_key = "staging", staging_key else: # Cannot happen while the CHECK attachments_active_has_source holds; fail visibly anyway. await _fail(conn, job_id, attachment_id, "source_missing", actor, attempt) return Noop("finished") token = uuid.uuid4().hex attempt += 1 write_original = object_key is None names = (("original",) if write_original else ()) + VARIANT_NAMES planned = [attempt_key(str(attachment_id), token, n) for n in names] await conn.execute( "UPDATE jobs SET state = 'processing', attempt = %s, lease_token = %s, lease_owner = %s, " "lease_until = clock_timestamp() + make_interval(secs => %s), updated_at = clock_timestamp() WHERE id = %s", (attempt, token, worker, lease_seconds, job_id)) await conn.execute( "INSERT INTO job_attempts (token, job_id, attempt, worker, source, planned_keys) VALUES (%s, %s, %s, %s, %s, %s)", (token, job_id, attempt, worker, source, planned)) await conn.execute( "UPDATE attachments SET status = 'processing', updated_at = clock_timestamp() WHERE id = %s AND status = 'queued'", (attachment_id,)) await event(conn, job_id, "claimed", actor, attempt=attempt, source=source, token=token) return Claim(str(job_id), str(attachment_id), version, attempt, max_attempts, token, source, source_key, content_type, size, bytes(sha), write_original, kind, accepted_at) async def heartbeat(conn: psycopg.AsyncConnection, claim: Claim, lease_seconds: float) -> bool: """Extend the lease; False = the lease was lost (expired and taken over): stop the attempt.""" cur = await conn.execute( "UPDATE jobs SET lease_until = clock_timestamp() + make_interval(secs => %s) " "WHERE id = %s AND state = 'processing' AND lease_token = %s", (lease_seconds, claim.job_id, claim.token)) return cur.rowcount == 1 async def _holds_lease(conn: psycopg.AsyncConnection, claim: Claim) -> bool: cur = await conn.execute("SELECT state = 'processing' AND lease_token = %s FROM jobs WHERE id = %s FOR UPDATE", (claim.token, claim.job_id)) row = await cur.fetchone() return bool(row and row[0]) async def complete(conn: psycopg.AsyncConnection, claim: Claim, variants, worker: str) -> str: """Publish the result of an attempt atomically: variant rows + attachment ready + job succeeded. Returns succeeded | superseded | fenced (this attempt lost its lease: nothing written).""" actor = "worker:" + worker if not await _holds_lease(conn, claim): return "fenced" cur = await conn.execute("SELECT published_version FROM attachments WHERE id = %s FOR UPDATE", (claim.attachment_id,)) (published,) = await cur.fetchone() if published is not None and published >= claim.pipeline_version: await _end_attempt(conn, claim, "superseded", None) await _finish(conn, claim.job_id, "superseded", None) await event(conn, claim.job_id, "superseded", actor, attempt=claim.attempt, published_version=published) return "superseded" for v in variants: await conn.execute( "INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, " "size_bytes, width, height, sha256, attempt_token) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", (claim.attachment_id, claim.pipeline_version, v.name, claim.key(v.name), v.content_type, len(v.data), v.width, v.height, v.sha256, claim.token)) await conn.execute( "UPDATE attachments SET status = 'ready', published_version = %s, error_code = NULL, failed_at = NULL, " "object_key = COALESCE(object_key, %s), updated_at = clock_timestamp() WHERE id = %s", (claim.pipeline_version, claim.key("original") if claim.write_original else None, claim.attachment_id)) await _end_attempt(conn, claim, "succeeded", None) await _finish(conn, claim.job_id, "succeeded", None) await event(conn, claim.job_id, "succeeded", actor, attempt=claim.attempt, pipeline_version=claim.pipeline_version) return "succeeded" async def retry_or_fail(conn: psycopg.AsyncConnection, claim: Claim, code: str, permanent: bool, worker: str, base: float, cap: float) -> tuple[str, float]: """After a failed attempt: permanent error or no attempts left -> failed (failed registry); otherwise queued again after a jittered backoff. Returns (outcome, delay seconds).""" actor = "worker:" + worker if not await _holds_lease(conn, claim): return "fenced", 0.0 if permanent or claim.attempt >= claim.max_attempts: final = code if permanent else "retry_exhausted" await _end_attempt(conn, claim, "failed", code) await _fail(conn, claim.job_id, claim.attachment_id, final, actor, claim.attempt, cause=code) return "failed", 0.0 delay = backoff_delay(claim.attempt, base, cap) await _end_attempt(conn, claim, "retry", code) await conn.execute( "UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, error_code = %s, " "available_at = clock_timestamp() + make_interval(secs => %s), updated_at = clock_timestamp() WHERE id = %s", (code, delay, claim.job_id)) await conn.execute( "UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() WHERE id = %s AND status = 'processing'", (claim.attachment_id,)) await conn.execute( "INSERT INTO outbox (job_id, attempt, available_at) " "VALUES (%s, %s, clock_timestamp() + make_interval(secs => %s))", (claim.job_id, claim.attempt + 1, delay)) await event(conn, claim.job_id, "retry_scheduled", actor, attempt=claim.attempt, error_code=code, delay_s=round(delay, 3)) return "retry", delay async def release(conn: psycopg.AsyncConnection, claim: Claim, worker: str) -> str: """Graceful stop of a worker with an attempt still running: give the job back at once (without waiting for the lease to expire). The claim already counted as an attempt.""" if not await _holds_lease(conn, claim): return "fenced" await _end_attempt(conn, claim, "abandoned", "worker_shutdown") if claim.attempt >= claim.max_attempts: await _fail(conn, claim.job_id, claim.attachment_id, "retry_exhausted", "worker:" + worker, claim.attempt, cause="worker_shutdown") return "failed" await conn.execute( "UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, " "available_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (claim.job_id,)) await conn.execute( "UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() WHERE id = %s AND status = 'processing'", (claim.attachment_id,)) await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (claim.job_id, claim.attempt + 1)) await event(conn, claim.job_id, "released", "worker:" + worker, attempt=claim.attempt) return "released" async def _end_attempt(conn: psycopg.AsyncConnection, claim: Claim, outcome: str, code: str | None) -> None: await conn.execute( "UPDATE job_attempts SET outcome = %s, error_code = %s, finished_at = clock_timestamp() " "WHERE token = %s AND outcome = 'running'", (outcome, code, claim.token)) async def _finish(conn: psycopg.AsyncConnection, job_id, state: str, code: str | None) -> None: await conn.execute( "UPDATE jobs SET state = %s, error_code = %s, lease_token = NULL, lease_owner = NULL, lease_until = NULL, " "finished_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (state, code, job_id)) async def _fail(conn: psycopg.AsyncConnection, job_id, attachment_id, code: str, actor: str, attempt: int, **detail) -> None: """Job -> failed (registry). The attachment becomes failed only if it is not ready: a failed reprocess of a newer version leaves the published result in place.""" await _finish(conn, job_id, "failed", code) await conn.execute( "UPDATE attachments SET status = 'failed', error_code = %s, failed_at = clock_timestamp(), " "updated_at = clock_timestamp() WHERE id = %s AND status IN ('queued', 'processing')", (code, attachment_id)) await event(conn, job_id, "failed", actor, attempt=attempt, error_code=code, **detail) # ------------------------------------------------------------------ cleanup (worker) async def staging_to_delete(conn: psycopg.AsyncConnection, retention_seconds: int, limit: int = 50) -> list[str]: """Candidates only (no lock): ready attachments (staging no longer needed) and failed ones older than the retention. The decision is re-checked under the row lock in mark_staging_deleting.""" cur = await conn.execute( "SELECT id FROM attachments WHERE staging_state IN ('present', 'deleting') AND (status = 'ready' OR " "(status = 'failed' AND failed_at < clock_timestamp() - make_interval(secs => %s))) " "ORDER BY updated_at LIMIT %s", (retention_seconds, limit)) return [str(r[0]) for r in await cur.fetchall()] async def mark_staging_deleting(conn: psycopg.AsyncConnection, attachment_id: str, retention_seconds: int) -> str | None: """Under the attachment row lock, decide AGAIN from the committed state and mark the staging copy `deleting` BEFORE the S3 DELETE. A replay that committed in between made the row queued, so it no longer matches; a replay that comes later sees `deleting` and refuses. Queued/processing rows never match (and the CHECK attachments_active_has_source forbids it anyway).""" cur = await conn.execute( "UPDATE attachments SET staging_state = 'deleting' " # internal state: updated_at stays (public field) "WHERE id = %s AND staging_state IN ('present', 'deleting') AND (status = 'ready' OR (status = 'failed' " "AND failed_at < clock_timestamp() - make_interval(secs => %s) AND NOT EXISTS (SELECT 1 FROM jobs j " "WHERE j.attachment_id = attachments.id AND j.state IN ('queued', 'processing')))) RETURNING staging_key", (attachment_id, retention_seconds)) row = await cur.fetchone() return row[0] if row else None async def mark_staging_deleted(conn: psycopg.AsyncConnection, attachment_id: str) -> None: await conn.execute( "UPDATE attachments SET staging_state = 'deleted' WHERE id = %s AND staging_state = 'deleting'", (attachment_id,)) async def attempts_to_clean(conn: psycopg.AsyncConnection, grace_seconds: int, limit: int = 50) -> list[str]: cur = await conn.execute( "SELECT token FROM job_attempts WHERE outcome IN ('retry', 'failed', 'abandoned', 'superseded') " "AND objects_cleaned_at IS NULL AND finished_at < clock_timestamp() - make_interval(secs => %s) " "ORDER BY finished_at LIMIT %s", (grace_seconds, limit)) return [r[0].hex for r in await cur.fetchall()] async def lock_attempt_for_cleanup(conn: psycopg.AsyncConnection, token: str) -> list[str] | None: """Keys of an attempt that can never publish: it ended without success, it is not the lease holder of its job (tokens are never reused) and nothing published references its keys.""" cur = await conn.execute( "SELECT ja.planned_keys FROM job_attempts ja JOIN jobs j ON j.id = ja.job_id " "WHERE ja.token = %s AND ja.objects_cleaned_at IS NULL " "AND ja.outcome IN ('retry', 'failed', 'abandoned', 'superseded') " "AND j.lease_token IS DISTINCT FROM ja.token FOR UPDATE OF ja", (token,)) row = await cur.fetchone() if row is None: return None keys = list(row[0]) cur = await conn.execute( "SELECT EXISTS (SELECT 1 FROM attachment_variants WHERE object_key = ANY(%s)) " "OR EXISTS (SELECT 1 FROM attachments WHERE object_key = ANY(%s))", (keys, keys)) if (await cur.fetchone())[0]: return None # published: never delete (would be a bug elsewhere; logged by the caller) return keys async def mark_attempt_cleaned(conn: psycopg.AsyncConnection, token: str) -> None: await conn.execute("UPDATE job_attempts SET objects_cleaned_at = clock_timestamp() WHERE token = %s", (token,))