:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add generic job queue tables and SDK (#91398)
Tom Owers6647bc49d6ff
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex 14ed7cf7f16b..fcb3c71a31ad 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -376,6 +376,11 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"SessionRecordingPlaylistItem", # via Playlist"SharePassword", # via SharingConfiguration"SourceBatchStatus", # via SourceBatch+ "QueueJobStatus", # via QueueJob+ # Keyed by (lane, group_key), not a direct team_id column — group_key is a+ # generic caller-defined string (e.g. "team:schema") rather than always a+ # team scope, unlike SourceGroupLease which carries team_id explicitly.+ "QueueJobLease","StreamlitAppSandbox", # via StreamlitApp"TaggedItem", # via Tag/Dashboard/Insight"TicketAssignment", # via Ticketdiff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 438ef4a1980c..37f3d1516a60 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -323,6 +323,7 @@ rules:|PullRequestAudience|QuarantinedIdentifier|QueryTabState+ |QueueJob|QuickFilter|QuickFilterContext|ReplayObservation@@ -753,6 +754,7 @@ rules:|PullRequestAudience|QuarantinedIdentifier|QueryTabState+ |QueueJob|QuickFilter|QuickFilterContext|ReplayObservationdiff --git a/posthog/models/scoping/baseline_unmigrated.txt b/posthog/models/scoping/baseline_unmigrated.txtindex 32014c464eeb..067735f1381f 100644--- a/posthog/models/scoping/baseline_unmigrated.txt+++ b/posthog/models/scoping/baseline_unmigrated.txt@@ -130,6 +130,7 @@ ProductTourProjectSecretAPIKeyPropertyAccessControlQueryTabState+QueueJobQuickFilterQuickFilterContextReminderdiff --git a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py b/posthog/temporal/warehouse_sources_queue_partition_management/activities.pyindex fbc46b9dc962..af884d753221 100644--- a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py+++ b/posthog/temporal/warehouse_sources_queue_partition_management/activities.py@@ -14,7 +14,7 @@ from asgiref.sync import sync_to_asynclogger = structlog.get_logger(__name__)-PARTITIONED_TABLES = ["sourcebatch", "sourcebatchstatus"]+PARTITIONED_TABLES = ["sourcebatch", "sourcebatchstatus", "queuejob", "queuejobstatus"]PARTITIONS_AHEAD = 7RETENTION_DAYS = 7DEFAULT_PARTITION_DELETE_BATCH_SIZE = 10_000diff --git a/products/warehouse_sources_queue/backend/README.md b/products/warehouse_sources_queue/backend/README.mdindex 9f158044ead7..0da8dd4e9295 100644--- a/products/warehouse_sources_queue/backend/README.md+++ b/products/warehouse_sources_queue/backend/README.md@@ -124,3 +124,14 @@ For ad-hoc inspection (state summaries, active runs, leases, force-release), use- **Partition health**: monitor that the `warehouse-sources-queue-partition-management` Temporal schedule is running. Alert on rows landing in DEFAULT partitions (means partition creation failed).- **Poll duration vs lease TTL**: leases are claimed when the poll query starts, so a poll slower than half the 300s TTL hands groups over mostly expired; the consumer logs `poll_duration_approaching_lease_ttl` when this starts happening.++## Generic jobs (phase 1)++`queuejob` / `queuejobstatus` / `queuejoblease` carry heterogeneous work items on the same physics as the batch tables: denormalized state on the row, an append-only status log written in the same statement, and lease-based group ownership. Two additions over the batch layer:++- **`kind`** names the work; a consumer claims only the kinds it has handlers for (`sdk.JobConsumer`).+- **`lane`** partitions leases, so one `group_key` can hold an extract-lane lease and a load-lane lease at the same time — extraction and loading run on separate fleets without contending.++Followers returned by a successful handler (`sdk.Success(followers=...)`) are enqueued in the same transaction as the terminal status write. Dedup of live `(kind, dedup_key)` pairs is enforced by the insert statement's `NOT EXISTS` guard rather than a unique index — a partitioned table cannot carry a unique index that omits the partition key.++SQL lives in `core/generic_jobs.py`; the SDK wiring (`JobHandler`, `Outcome`, `GenericJobAdapter`, `JobConsumer`) in `sdk/jobs.py`. Nothing produces or consumes these tables yet; the run orchestrator lands on them in later phases.diff --git a/products/warehouse_sources_queue/backend/core/batch_consumer.py b/products/warehouse_sources_queue/backend/core/batch_consumer.pyindex 14e48255129c..bea94824d69f 100644--- a/products/warehouse_sources_queue/backend/core/batch_consumer.py+++ b/products/warehouse_sources_queue/backend/core/batch_consumer.py@@ -1340,6 +1340,7 @@ class BatchConsumer:run_uuid=batch.run_uuid,attempt=attempt,)+ await self._verify_ownership(lock_conn, batch)await self._fail_run(batch, reason=f"max retries exceeded (attempt {attempt})", conn=lock_conn)return False@@ -1471,6 +1472,7 @@ class BatchConsumer:attempt=attempt,)capture_exception(err)+ await self._verify_ownership(lock_conn, batch)await self._fail_run(batch, reason=reason, conn=lock_conn)elif attempt >= self._config.max_attempts:reason = f"max retries exceeded: {err}"@@ -1481,6 +1483,7 @@ class BatchConsumer:attempt=attempt,)capture_exception(err)+ await self._verify_ownership(lock_conn, batch)await self._fail_run(batch, reason=reason, conn=lock_conn)else:logger.warning(@@ -1489,6 +1492,7 @@ class BatchConsumer:attempt=attempt,error=str(err),)+ await self._verify_ownership(lock_conn, batch)await self._adapter.update_status(status_conn,batch_id=batch.id,@@ -1825,5 +1829,6 @@ ProcessBatchesFn = Callable[[list[PendingBatch]], Coroutine[Any, Any, None]]def _group_by_key(batches: list[PendingBatch]) -> dict[tuple[int, str], list[PendingBatch]]:groups: dict[tuple[int, str], list[PendingBatch]] = defaultdict(list)for batch in batches:- groups[(batch.team_id, batch.schema_id)].append(batch)+ key = getattr(batch, "consumer_group_key", (batch.team_id, batch.schema_id))+ groups[key].append(batch)return groupsdiff --git a/products/warehouse_sources_queue/backend/core/generic_jobs.py b/products/warehouse_sources_queue/backend/core/generic_jobs.pynew file mode 100644index 000000000000..84447180b29a--- /dev/null+++ b/products/warehouse_sources_queue/backend/core/generic_jobs.py@@ -0,0 +1,772 @@+"""Generic job queue: SQL and row types for the ``queuejob`` tables.++The generic layer carries heterogeneous work items (``kind``), grouped by an+opaque ``group_key`` and serialized per group within a ``lane``. It reuses the+``sourcebatch`` physics: denormalized state columns on the job row, an+append-only status log written in the same statement, lease-based group+ownership, and partial indexes that keep every query's cost tracking the+claimable set. All SQL lives here; the consumer engine (``batch_consumer.py``)+drives it through ``GenericJobAdapter`` in the SDK.++Nothing produces or consumes these tables yet — this layer lands ahead of the+run orchestrator so it can ship with tests and no production traffic.+"""++from __future__ import annotations++import json+from datetime import datetime+from typing import Any++import psycopg+from psycopg.rows import dict_row++from posthog.dataclasses import frozen++JOB_TABLE = "queuejob"+JOB_STATUS_TABLE = "queuejobstatus"+JOB_LEASE_TABLE = "queuejoblease"++# Claim eligibility must stay under the 7-day retention window (see+# jobs_db.CLAIM_ELIGIBILITY_INTERVAL for the reasoning); generic jobs carry+# their payload inline rather than in S3, but the partitions still drop at+# retention, so a job must not be claimable after its partition can vanish.+JOB_CLAIM_ELIGIBILITY_INTERVAL = "6 days 12 hours"+JOB_PARTITION_PRUNING_INTERVAL = "14 days"++JOB_LEASE_TTL_SECONDS = 300++TERMINAL_JOB_STATES = ("succeeded", "failed")+++@frozen+class Job:+ """One claimed generic job row.++ The consumer engine predates this layer and reads batch-shaped attribute+ names (it groups on ``(team_id, schema_id)`` and logs ``run_uuid`` /+ ``resource_name`` / ``batch_index``), so the engine-facing names below are+ aliases onto the generic fields. They exist only to satisfy the engine;+ handlers should read the generic fields.+ """++ id: str+ kind: str+ lane: str+ group_key: str+ team_id: int+ run_id: str | None+ sequence: int+ payload: dict[str, Any]+ priority: int+ dedup_key: str | None+ latest_state: str+ latest_attempt: int+ state_changed_at: datetime | None+ created_at: datetime++ # -- engine-facing aliases (see class docstring) -------------------------+ @property+ def schema_id(self) -> str:+ return self.group_key++ @property+ def consumer_group_key(self) -> tuple[int, str]:+ # One JobConsumer serves one lane, so group_key alone is the in-process+ # identity matching the queue lease's (lane, group_key) serialization.+ return (0, self.group_key)++ @property+ def run_uuid(self) -> str:+ return self.run_id or str(self.id)++ @property+ def job_id(self) -> str:+ return self.run_id or str(self.id)++ @property+ def batch_index(self) -> int:+ return self.sequence++ @property+ def resource_name(self) -> str:+ return self.kind++ @property+ def source_id(self) -> str:+ return self.lane++ @property+ def metadata(self) -> dict[str, Any]:+ return self.payload++ @property+ def is_final_batch(self) -> bool:+ return False+++def _job_status_dual_write_sql(*, with_job_created_at: bool) -> str:+ """Single-statement status INSERT + denormalized-state UPDATE.++ Same guards as ``jobs_db.build_status_dual_write_sql``: exact ``created_at``+ prunes to one partition when known, the ``IS DISTINCT FROM`` check makes+ heartbeat re-inserts a 0-row no-op, and the monotonic ``state_changed_at``+ check makes cross-connection races converge on the newest status row.+ """+ created_at_predicate = (+ "j.created_at = %(job_created_at)s"+ if with_job_created_at+ else f"j.created_at > now() - interval '{JOB_PARTITION_PRUNING_INTERVAL}'"+ )+ return f"""+ WITH ins AS (+ INSERT INTO {JOB_STATUS_TABLE} (job_id, job_state, attempt, exec_time, error_response, created_at)+ VALUES (%(job_id)s, %(job_state)s, %(attempt)s, now(), %(error_response)s, now())+ RETURNING job_id, job_state, attempt, created_at+ )+ UPDATE {JOB_TABLE} j+ SET latest_state = ins.job_state, latest_attempt = ins.attempt, state_changed_at = ins.created_at+ FROM ins+ WHERE j.id = ins.job_id+ AND {created_at_predicate}+ AND ((j.latest_state, j.latest_attempt) IS DISTINCT FROM (ins.job_state, ins.attempt)+ OR j.state_changed_at IS NULL)+ AND (j.state_changed_at IS NULL OR j.state_changed_at <= ins.created_at)+ """+++def _job_status_dual_write_guarded_sql(+ *,+ with_job_created_at: bool,+ with_expected_state_changed_at: bool,+ with_expected_state_and_attempt: bool,+) -> str:+ """Guarded twin that keeps terminal states absorbing and optionally applies+ a compare-and-swap fence for a specific observed state transition."""+ created_at_predicate = (+ "j.created_at = %(job_created_at)s"+ if with_job_created_at+ else f"j.created_at > now() - interval '{JOB_PARTITION_PRUNING_INTERVAL}'"+ )+ cas_predicate = (+ "\n AND j.state_changed_at IS NOT DISTINCT FROM %(expected_state_changed_at)s"+ if with_expected_state_changed_at+ else ""+ )+ state_attempt_predicate = (+ "\n AND (j.latest_state, j.latest_attempt) = (%(expected_state)s, %(expected_attempt)s)"+ if with_expected_state_and_attempt+ else ""+ )+ return f"""+ WITH target AS (+ SELECT j.id+ FROM {JOB_TABLE} j+ WHERE j.id = %(job_id)s+ AND {created_at_predicate}+ AND j.latest_state NOT IN ('succeeded', 'failed'){cas_predicate}{state_attempt_predicate}+ FOR UPDATE OF j+ ),+ ins AS (+ INSERT INTO {JOB_STATUS_TABLE} (job_id, job_state, attempt, exec_time, error_response, created_at)+ SELECT t.id, %(job_state)s, %(attempt)s, now(), %(error_response)s, now()+ FROM target t+ RETURNING job_id, job_state, attempt, created_at+ ),+ upd AS (+ UPDATE {JOB_TABLE} j+ SET latest_state = ins.job_state, latest_attempt = ins.attempt, state_changed_at = ins.created_at+ FROM ins+ WHERE j.id = ins.job_id+ AND {created_at_predicate}+ AND ((j.latest_state, j.latest_attempt) IS DISTINCT FROM (ins.job_state, ins.attempt)+ OR j.state_changed_at IS NULL)+ AND (j.state_changed_at IS NULL OR j.state_changed_at <= ins.created_at)+ RETURNING j.id+ )+ SELECT count(*) FROM ins+ """+++_JOB_COLUMNS = (+ "j.id, j.kind, j.lane, j.group_key, j.team_id, j.run_id, j.sequence, "+ "j.payload, j.priority, j.dedup_key, j.latest_state, j.latest_attempt, j.state_changed_at, j.created_at"+)++# The insert's dedup guard. A partitioned table cannot enforce a unique index+# that omits the partition key, so live-pair uniqueness is a NOT EXISTS in the+# same statement: correct under one enqueuer per key (the scheduler is+# single-flighted; followers are enqueued by the single run finalizer), and a+# rare concurrent duplicate is bounded — both rows share the dedup_key, so the+# loser is observable and the handler contract stays idempotent.+_INSERT_SQL = f"""+ INSERT INTO {JOB_TABLE} (+ id, kind, lane, group_key, team_id, run_id, sequence, payload,+ priority, dedup_key, created_at+ )+ SELECT+ gen_random_uuid(), %(kind)s::varchar, %(lane)s, %(group_key)s, %(team_id)s, %(run_id)s,+ %(sequence)s, %(payload)s::jsonb, %(priority)s, %(dedup_key)s::varchar, now()+ WHERE %(dedup_key)s::varchar IS NULL OR NOT EXISTS (+ SELECT 1 FROM {JOB_TABLE} d+ WHERE d.kind = %(kind)s::varchar+ AND d.dedup_key = %(dedup_key)s::varchar+ AND d.created_at > now() - interval '{JOB_PARTITION_PRUNING_INTERVAL}'+ AND d.latest_state != 'failed'+ AND NOT d.superseded+ )+ RETURNING id+"""++_INSERT_MANY_SQL = f"""+ WITH raw AS (+ SELECT value, ordinality+ FROM jsonb_array_elements(%(jobs)s::jsonb) WITH ORDINALITY+ ),+ input AS (+ SELECT+ value->>'kind' AS kind,+ value->>'lane' AS lane,+ value->>'group_key' AS group_key,+ (value->>'team_id')::bigint AS team_id,+ value->>'run_id' AS run_id,+ COALESCE((value->>'sequence')::int, 0) AS sequence,+ COALESCE(value->'payload', '{{}}'::jsonb) AS payload,+ COALESCE((value->>'priority')::smallint, 0) AS priority,+ value->>'dedup_key' AS dedup_key,+ ordinality,+ row_number() OVER (+ PARTITION BY value->>'kind', value->>'dedup_key'+ ORDER BY ordinality+ ) AS dedup_rank+ FROM raw+ )+ INSERT INTO {JOB_TABLE} (+ id, kind, lane, group_key, team_id, run_id, sequence, payload,+ priority, dedup_key, created_at+ )+ SELECT+ gen_random_uuid(), i.kind, i.lane, i.group_key, i.team_id, i.run_id,+ i.sequence, i.payload, i.priority, i.dedup_key, now()+ FROM input i+ WHERE i.dedup_key IS NULL OR (+ i.dedup_rank = 1+ AND NOT EXISTS (+ SELECT 1 FROM {JOB_TABLE} d+ WHERE d.kind = i.kind+ AND d.dedup_key = i.dedup_key+ AND d.created_at > now() - interval '{JOB_PARTITION_PRUNING_INTERVAL}'+ AND d.latest_state != 'failed'+ AND NOT d.superseded+ )+ )+ ORDER BY i.ordinality+ RETURNING id+"""+++def _claim_candidates_sql() -> str:+ """Claimable-job candidates from the denormalized state columns.++ Mirrors ``jobs_db._state_claim_candidates_sql``: answered by the partial+ indexes, narrow ``(id, created_at)`` output so the fairness sort never+ touches wide rows, and the gates deliberately ignore the kind filter — a+ group must stay serialized within its lane whatever kinds its jobs carry.++ Run gate: a job waits until every earlier ``sequence`` in the same+ ``run_id`` has succeeded. This includes pending and retryable predecessors;+ a failed step continues to park its followers.+ """+ return f"""+ SELECT j.id, j.created_at+ FROM {JOB_TABLE} j+ WHERE+ j.created_at > now() - interval '{JOB_CLAIM_ELIGIBILITY_INTERVAL}'+ AND j.lane = %(lane)s+ AND j.kind = ANY(%(kinds)s)+ AND NOT j.superseded+ AND (+ j.latest_state = 'pending'+ OR (+ j.latest_state = 'waiting_retry'+ AND j.state_changed_at <= now() - make_interval(+ secs => %(backoff)s * GREATEST(j.latest_attempt, 1)+ )+ )+ )+ AND (+ j.run_id IS NULL+ OR NOT EXISTS (+ SELECT 1+ FROM {JOB_TABLE} j_prev+ WHERE j_prev.run_id = j.run_id+ AND j_prev.sequence < j.sequence+ AND j_prev.created_at > now() - interval '{JOB_PARTITION_PRUNING_INTERVAL}'+ AND j_prev.latest_state IN ('pending', 'executing', 'waiting_retry', 'failed')+ )+ )+ AND NOT EXISTS (+ SELECT 1+ FROM {JOB_TABLE} j_busy+ WHERE j_busy.lane = j.lane+ AND j_busy.group_key = j.group_key+ AND j_busy.created_at > now() - interval '{JOB_PARTITION_PRUNING_INTERVAL}'+ AND j_busy.latest_state = 'executing'+ )+ """+++class JobsTable:+ """Raw SQL over the generic job tables (the ``BatchQueue`` idiom)."""++ # -- writes (producer side) ----------------------------------------------++ @staticmethod+ async def insert(+ conn: psycopg.AsyncConnection[Any],+ *,+ kind: str,+ lane: str,+ group_key: str,+ team_id: int,+ payload: dict[str, Any],+ run_id: str | None = None,+ sequence: int = 0,+ priority: int = 0,+ dedup_key: str | None = None,+ ) -> str | None:+ """Enqueue one job. Returns the new id, or None when the dedup guard refused it."""+ cursor = await conn.execute(+ _INSERT_SQL,+ {+ "kind": kind,+ "lane": lane,+ "group_key": group_key,+ "team_id": team_id,+ "run_id": run_id,+ "sequence": sequence,+ "payload": json.dumps(payload),+ "priority": priority,+ "dedup_key": dedup_key,+ },+ )+ row = await cursor.fetchone()+ return str(row[0]) if row else None++ @staticmethod+ async def insert_many(+ conn: psycopg.AsyncConnection[Any],+ jobs: list[dict[str, Any]],+ ) -> list[str]:+ """Enqueue several jobs in one transaction — the atomic follower primitive.++ Each entry takes the ``insert`` keyword arguments. Runs inside a single+ transaction even on an autocommit connection, so a crash mid-way+ enqueues nothing (the caller's dedup keys make the retry idempotent).+ """+ if not jobs:+ return []+ normalized = [+ {+ "run_id": None,+ "sequence": 0,+ "priority": 0,+ "dedup_key": None,+ **job,+ "payload": job.get("payload", {}),+ }+ for job in jobs+ ]+ async with conn.transaction():+ cursor = await conn.execute(_INSERT_MANY_SQL, {"jobs": json.dumps(normalized)})+ rows = await cursor.fetchall()+ return [str(row[0]) for row in rows]++ # -- reads (consumer side) -----------------------------------------------++ @staticmethod+ async def get_unprocessed_and_lock(+ conn: psycopg.AsyncConnection[Any],+ *,+ owner_token: str,+ lane: str,+ kinds: list[str],+ limit: int = 50,+ retry_backoff_base_seconds: int = 0,+ lease_ttl_seconds: int = JOB_LEASE_TTL_SECONDS,+ ) -> list[Job]:+ """Fetch claimable jobs whose (lane, group_key) lease is claimable by ``owner_token``.++ Same shape as ``BatchQueue.get_unprocessed_and_lock``: MATERIALIZED+ narrow candidates with per-team round-robin fairness (priority first+ within a team), join-back for the wide rows, and a claim-or-renew lease+ upsert in the same writable CTE. Groups live-leased by another owner+ are excluded from candidates so pods compute disjoint windows.+ """+ candidates_sql = _claim_candidates_sql()+ async with conn.cursor(row_factory=dict_row) as cur:+ await cur.execute(+ f"""+ WITH narrow AS MATERIALIZED (+ {candidates_sql}+ AND NOT EXISTS (+ SELECT 1+ FROM {JOB_LEASE_TABLE} l_live+ WHERE l_live.lane = j.lane+ AND l_live.group_key = j.group_key+ AND l_live.expires_at > now()+ AND l_live.owner_token != %(owner)s+ )+ ORDER BY+ row_number() OVER (+ PARTITION BY j.team_id+ ORDER BY j.priority DESC, j.created_at ASC, j.sequence ASC+ ) ASC,+ j.priority DESC,+ j.created_at ASC,+ j.sequence ASC+ LIMIT %(limit)s+ ),+ candidates AS MATERIALIZED (+ SELECT {_JOB_COLUMNS}+ FROM {JOB_TABLE} j+ JOIN narrow n ON n.id = j.id AND n.created_at = j.created_at+ ),+ candidate_groups AS (+ SELECT DISTINCT lane, group_key FROM candidates+ ),+ claimed AS (+ INSERT INTO {JOB_LEASE_TABLE} (lane, group_key, owner_token, expires_at, acquired_at, updated_at)+ SELECT lane, group_key, %(owner)s, now() + make_interval(secs => %(ttl)s), now(), now()+ FROM candidate_groups+ ON CONFLICT (lane, group_key) DO UPDATE+ SET owner_token = excluded.owner_token,+ expires_at = excluded.expires_at,+ acquired_at = CASE+ WHEN {JOB_LEASE_TABLE}.owner_token = excluded.owner_token+ THEN {JOB_LEASE_TABLE}.acquired_at+ ELSE now()+ END,+ updated_at = now()+ WHERE {JOB_LEASE_TABLE}.expires_at < now()+ OR {JOB_LEASE_TABLE}.owner_token = excluded.owner_token+ RETURNING lane, group_key+ )+ SELECT c.*+ FROM candidates c+ JOIN claimed USING (lane, group_key)+ ORDER BY c.priority DESC, c.created_at ASC, c.sequence ASC+ """,+ {+ "limit": limit,+ "backoff": retry_backoff_base_seconds,+ "owner": owner_token,+ "ttl": lease_ttl_seconds,+ "lane": lane,+ "kinds": kinds,+ },+ )+ rows = await cur.fetchall()+ return [Job(**{**row, "id": str(row["id"])}) for row in rows]++ # -- state transitions -----------------------------------------------------++ @staticmethod+ async def update_status(+ conn: psycopg.AsyncConnection[Any],+ *,+ job_id: str,+ job_state: str,+ attempt: int = 0,+ error_response: dict[str, Any] | None = None,+ job_created_at: datetime | None = None,+ ) -> None:+ params: dict[str, Any] = {+ "job_id": job_id,+ "job_state": job_state,+ "attempt": attempt,+ "error_response": json.dumps(error_response) if error_response else None,+ }+ if job_created_at is not None:+ params["job_created_at"] = job_created_at+ await conn.execute(+ _job_status_dual_write_sql(with_job_created_at=job_created_at is not None),+ params,+ )++ @staticmethod+ async def update_status_unless_failed(+ conn: psycopg.AsyncConnection[Any],+ *,+ job_id: str,+ job_state: str,+ attempt: int = 0,+ error_response: dict[str, Any] | None = None,+ job_created_at: datetime | None = None,+ expected_state_changed_at: datetime | None = None,+ arm_cas: bool = False,+ expected_state: str | None = None,+ expected_attempt: int | None = None,+ ) -> bool:+ """Guarded status write that never overwrites a terminal state.++ A caller may compare-and-swap either the observed timestamp (recovery)+ or the expected state and attempt (normal executing transitions).+ """+ params: dict[str, Any] = {+ "job_id": job_id,+ "job_state": job_state,+ "attempt": attempt,+ "error_response": json.dumps(error_response) if error_response else None,+ }+ if job_created_at is not None:+ params["job_created_at"] = job_created_at+ if arm_cas:+ params["expected_state_changed_at"] = expected_state_changed_at+ with_expected_state_and_attempt = expected_state is not None and expected_attempt is not None+ if with_expected_state_and_attempt:+ params["expected_state"] = expected_state+ params["expected_attempt"] = expected_attempt+ cursor = await conn.execute(+ _job_status_dual_write_guarded_sql(+ with_job_created_at=job_created_at is not None,+ with_expected_state_changed_at=arm_cas,+ with_expected_state_and_attempt=with_expected_state_and_attempt,+ ),+ params,+ )+ row = await cursor.fetchone()+ return bool(row and row[0])++ @staticmethod+ async def get_latest_state(+ conn: psycopg.AsyncConnection[Any],+ *,+ job_id: str,+ ) -> str | None:+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ SELECT latest_state FROM {JOB_TABLE}+ WHERE id = %(job_id)s+ AND created_at > now() - interval '{JOB_PARTITION_PRUNING_INTERVAL}'+ """,+ {"job_id": job_id},+ )+ row = await cur.fetchone()+ return str(row[0]) if row else None++ # -- leases ----------------------------------------------------------------++ @staticmethod+ async def renew_lease(+ conn: psycopg.AsyncConnection[Any],+ *,+ lane: str,+ group_key: str,+ owner_token: str,+ lease_ttl_seconds: int = JOB_LEASE_TTL_SECONDS,+ ) -> bool:+ """Extend a live lease; expiry is terminal (False = ownership gone for good)."""+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ UPDATE {JOB_LEASE_TABLE}+ SET expires_at = now() + make_interval(secs => %(ttl)s), updated_at = now()+ WHERE lane = %(lane)s AND group_key = %(group_key)s AND owner_token = %(owner)s+ AND expires_at > now()+ RETURNING 1+ """,+ {"lane": lane, "group_key": group_key, "owner": owner_token, "ttl": lease_ttl_seconds},+ )+ return (await cur.fetchone()) is not None++ @staticmethod+ async def verify_lease(+ conn: psycopg.AsyncConnection[Any],+ *,+ lane: str,+ group_key: str,+ owner_token: str,+ ) -> bool:+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ SELECT EXISTS (+ SELECT 1 FROM {JOB_LEASE_TABLE}+ WHERE lane = %(lane)s AND group_key = %(group_key)s+ AND owner_token = %(owner)s AND expires_at > now()+ )+ """,+ {"lane": lane, "group_key": group_key, "owner": owner_token},+ )+ row = await cur.fetchone()+ return bool(row and row[0])++ @staticmethod+ async def delete_expired_lease(+ conn: psycopg.AsyncConnection[Any],+ *,+ lane: str,+ group_key: str,+ ) -> None:+ """Delete the group's lease only if already expired; a live lease never matches."""+ await conn.execute(+ f"""+ DELETE FROM {JOB_LEASE_TABLE}+ WHERE lane = %(lane)s AND group_key = %(group_key)s AND expires_at <= now()+ """,+ {"lane": lane, "group_key": group_key},+ )++ @staticmethod+ async def unlock_groups(+ conn: psycopg.AsyncConnection[Any],+ *,+ lane: str,+ group_keys: list[str],+ owner_token: str,+ ) -> None:+ """Hand groups back when their work finishes (drop this owner's leases)."""+ if not group_keys:+ return+ await conn.execute(+ f"""+ DELETE FROM {JOB_LEASE_TABLE}+ WHERE lane = %(lane)s AND group_key = ANY(%(group_keys)s) AND owner_token = %(owner)s+ """,+ {"lane": lane, "group_keys": group_keys, "owner": owner_token},+ )++ @staticmethod+ async def release_all_owned(+ conn: psycopg.AsyncConnection[Any],+ *,+ owner_token: str,+ ) -> None:+ """Best-effort cleanup of everything this pod holds, on graceful shutdown."""+ await conn.execute(+ f"DELETE FROM {JOB_LEASE_TABLE} WHERE owner_token = %(owner)s",+ {"owner": owner_token},+ )++ # -- sweeps and gauges -------------------------------------------------------++ RECOVERY_SWEEP_GROUP_KEY = "__recovery-sweep__"+ RECOVERY_SWEEP_SLOT_TTL_SECONDS = 240++ @staticmethod+ async def get_stale_executing(+ conn: psycopg.AsyncConnection[Any],+ *,+ lane: str,+ kinds: list[str],+ grace_seconds: int = 0,+ limit: int = 100,+ ) -> list[Job]:+ """Claim one bounded stale-job recovery page for this lane.++ A sentinel lease single-flights sweeps across the fleet. It deliberately+ expires without an explicit release so a failed sweep cannot wedge the lane.+ """+ async with conn.cursor(row_factory=dict_row) as cur:+ await cur.execute(+ f"""+ INSERT INTO {JOB_LEASE_TABLE} (lane, group_key, owner_token, expires_at, acquired_at, updated_at)+ VALUES (+ %(lane)s,+ %(group_key)s,+ gen_random_uuid(),+ now() + make_interval(secs => %(ttl)s),+ now(),+ now()+ )+ ON CONFLICT (lane, group_key) DO UPDATE+ SET owner_token = excluded.owner_token,+ expires_at = excluded.expires_at,+ acquired_at = now(),+ updated_at = now()+ WHERE {JOB_LEASE_TABLE}.expires_at <= now()+ RETURNING 1+ """,+ {+ "lane": lane,+ "group_key": JobsTable.RECOVERY_SWEEP_GROUP_KEY,+ "ttl": JobsTable.RECOVERY_SWEEP_SLOT_TTL_SECONDS,+ },+ )+ if await cur.fetchone() is None:+ return []+ await cur.execute(+ f"""+ SELECT {_JOB_COLUMNS}+ FROM {JOB_TABLE} j+ WHERE j.created_at > now() - interval '{JOB_PARTITION_PRUNING_INTERVAL}'+ AND j.lane = %(lane)s+ AND j.kind = ANY(%(kinds)s)+ AND j.latest_state = 'executing'+ AND j.state_changed_at <= now() - make_interval(secs => %(grace)s)+ AND NOT EXISTS (+ SELECT 1 FROM {JOB_LEASE_TABLE} l+ WHERE l.lane = j.lane AND l.group_key = j.group_key+ AND l.expires_at > now()+ )+ ORDER BY j.state_changed_at ASC, j.created_at ASC, j.id ASC+ LIMIT %(limit)s+ """,+ {"lane": lane, "kinds": kinds, "grace": grace_seconds, "limit": limit},+ )+ rows = await cur.fetchall()+ return [Job(**{**row, "id": str(row["id"])}) for row in rows]++ @staticmethod+ async def get_claimable_count(+ conn: psycopg.AsyncConnection[Any],+ *,+ lane: str,+ kinds: list[str],+ retry_backoff_base_seconds: int = 0,+ ) -> int:+ """Depth gauge using the claim path's eligibility and gating predicates."""+ candidates_sql = _claim_candidates_sql()+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ SELECT count(*) FROM (+ {candidates_sql}+ AND NOT EXISTS (+ SELECT 1 FROM {JOB_LEASE_TABLE} l_live+ WHERE l_live.lane = j.lane+ AND l_live.group_key = j.group_key+ AND l_live.expires_at > now()+ )+ ) claimable+ """,+ {"lane": lane, "kinds": kinds, "backoff": retry_backoff_base_seconds},+ )+ row = await cur.fetchone()+ return int(row[0]) if row else 0++ @staticmethod+ async def get_oldest_unclaimed_age_seconds(+ conn: psycopg.AsyncConnection[Any],+ *,+ lane: str,+ kinds: list[str],+ ) -> float:+ """Freshness gauge: age of the oldest job no consumer has ever picked up."""+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ SELECT COALESCE(EXTRACT(EPOCH FROM (now() - min(j.created_at))), 0)+ FROM {JOB_TABLE} j+ WHERE j.created_at > now() - interval '{JOB_PARTITION_PRUNING_INTERVAL}'+ AND j.lane = %(lane)s+ AND j.kind = ANY(%(kinds)s)+ AND NOT j.superseded+ AND j.latest_state = 'pending'+ """,+ {"lane": lane, "kinds": kinds},+ )+ row = await cur.fetchone()+ return float(row[0]) if row else 0.0diff --git a/products/warehouse_sources_queue/backend/migrations/0011_generic_job_tables.py b/products/warehouse_sources_queue/backend/migrations/0011_generic_job_tables.pynew file mode 100644index 000000000000..031f4f6fb46d--- /dev/null+++ b/products/warehouse_sources_queue/backend/migrations/0011_generic_job_tables.py@@ -0,0 +1,257 @@+import datetime++from django.db import migrations, models++from posthog.models.utils import uuid7++# How many daily partitions to pre-create ahead of today.+PARTITIONS_AHEAD = 7+++def _precreate_daily_partitions(schema_editor, parent_table):+ """Pre-create one daily range partition per day for today + next N days.++ Same shape as 0001: individual ``CREATE TABLE ... PARTITION OF`` statements+ from Python so the DDL applies against Postgres-wire targets without+ PL/pgSQL support.+ """+ today = datetime.date.today()+ for offset in range(PARTITIONS_AHEAD + 1):+ day = today + datetime.timedelta(days=offset)+ next_day = day + datetime.timedelta(days=1)+ suffix = day.strftime("%Y%m%d")+ schema_editor.execute(+ f"CREATE TABLE IF NOT EXISTS {parent_table}_{suffix} "+ f"PARTITION OF {parent_table} "+ f"FOR VALUES FROM ('{day.isoformat()}') TO ('{next_day.isoformat()}')"+ )+++def _create_generic_job_tables(apps, schema_editor):+ # One statement per execute(): psycopg3 uses the extended query protocol,+ # which parses a single statement at a time.+ schema_editor.execute("""+ CREATE TABLE queuejob (+ id UUID NOT NULL DEFAULT gen_random_uuid(),+ kind VARCHAR(100) NOT NULL,+ lane VARCHAR(16) NOT NULL,+ group_key VARCHAR(400) NOT NULL,+ team_id BIGINT NOT NULL,+ run_id VARCHAR(200),+ sequence INT NOT NULL DEFAULT 0,+ payload JSONB NOT NULL DEFAULT '{}'::jsonb,+ priority SMALLINT NOT NULL DEFAULT 0,+ dedup_key VARCHAR(400),+ latest_state VARCHAR(32) NOT NULL DEFAULT 'pending',+ latest_attempt SMALLINT NOT NULL DEFAULT 0,+ state_changed_at TIMESTAMPTZ,+ superseded BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (id, created_at)+ ) PARTITION BY RANGE (created_at)+ """)+ # The claim scan and its gates, mirroring the sourcebatch partial-index+ # physics with lane/kind in the predicates so each fleet's poll cost tracks+ # its own claimable set.+ schema_editor.execute("""+ CREATE INDEX qj_claimable_idx ON queuejob (lane, kind, team_id, created_at, sequence)+ WHERE latest_state IN ('pending', 'waiting_retry')+ """)+ schema_editor.execute("""+ CREATE INDEX qj_run_gate_idx ON queuejob (run_id, latest_state, sequence)+ WHERE latest_state IN ('pending', 'executing', 'waiting_retry', 'failed')+ """)+ schema_editor.execute("""+ CREATE INDEX qj_group_busy_idx ON queuejob (lane, group_key)+ WHERE latest_state = 'executing'+ """)+ schema_editor.execute("""+ CREATE INDEX qj_failed_changed_idx ON queuejob (state_changed_at)+ WHERE latest_state = 'failed'+ """)+ # Dedup lookups. A partitioned table cannot carry a unique index that omits+ # the partition key, so uniqueness of live (kind, dedup_key) pairs is+ # enforced by the insert statement's NOT EXISTS guard; this index makes+ # that guard and the lookup cheap.+ schema_editor.execute("""+ CREATE INDEX qj_dedup_idx ON queuejob (kind, dedup_key)+ WHERE dedup_key IS NOT NULL+ """)+ schema_editor.execute("CREATE TABLE queuejob_default PARTITION OF queuejob DEFAULT")++ schema_editor.execute("""+ CREATE TABLE queuejobstatus (+ id UUID NOT NULL DEFAULT gen_random_uuid(),+ job_id UUID NOT NULL,+ job_state VARCHAR(32) NOT NULL,+ attempt SMALLINT NOT NULL DEFAULT 0,+ exec_time TIMESTAMPTZ,+ error_response JSONB,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (id, created_at)+ ) PARTITION BY RANGE (created_at)+ """)+ schema_editor.execute(+ "CREATE INDEX qjs_job_id_desc_state_idx ON queuejobstatus (job_id, created_at DESC, id DESC, job_state)"+ )+ schema_editor.execute("CREATE TABLE queuejobstatus_default PARTITION OF queuejobstatus DEFAULT")++ schema_editor.execute("""+ CREATE TABLE queuejoblease (+ id BIGSERIAL PRIMARY KEY,+ lane VARCHAR(16) NOT NULL,+ group_key VARCHAR(400) NOT NULL,+ owner_token VARCHAR(64) NOT NULL,+ expires_at TIMESTAMPTZ NOT NULL,+ acquired_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CONSTRAINT qjl_lane_group_uniq UNIQUE (lane, group_key)+ )+ """)+ schema_editor.execute("CREATE INDEX qjl_expires_at_idx ON queuejoblease (expires_at)")++ _precreate_daily_partitions(schema_editor, "queuejob")+ _precreate_daily_partitions(schema_editor, "queuejobstatus")+++def _drop_generic_job_tables(apps, schema_editor):+ schema_editor.execute("DROP TABLE IF EXISTS queuejoblease CASCADE")+ schema_editor.execute("DROP TABLE IF EXISTS queuejobstatus CASCADE")+ schema_editor.execute("DROP TABLE IF EXISTS queuejob CASCADE")+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources_queue", "0010_sourcebatch_destination_ids"),+ ]++ operations = [+ # Django state only: the DDL is RunPython below because Django cannot+ # express PARTITION BY RANGE (same pattern as 0001).+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.CreateModel(+ name="QueueJob",+ fields=[+ ("id", models.UUIDField(default=uuid7, editable=False, primary_key=True, serialize=False)),+ ("kind", models.CharField(max_length=100)),+ ("lane", models.CharField(max_length=16)),+ ("group_key", models.CharField(max_length=400)),+ ("team_id", models.BigIntegerField()),+ ("run_id", models.CharField(blank=True, max_length=200, null=True)),+ ("sequence", models.IntegerField(default=0)),+ ("payload", models.JSONField(blank=True, default=dict)),+ ("priority", models.SmallIntegerField(default=0)),+ ("dedup_key", models.CharField(blank=True, max_length=400, null=True)),+ ("latest_state", models.CharField(default="pending", max_length=32)),+ ("latest_attempt", models.SmallIntegerField(default=0)),+ ("state_changed_at", models.DateTimeField(blank=True, null=True)),+ ("superseded", models.BooleanField(default=False)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ],+ options={+ "db_table": "queuejob",+ "indexes": [+ models.Index(+ fields=["lane", "kind", "team_id", "created_at", "sequence"],+ name="qj_claimable_idx",+ condition=models.Q(latest_state__in=["pending", "waiting_retry"]),+ ),+ models.Index(+ fields=["run_id", "latest_state", "sequence"],+ name="qj_run_gate_idx",+ condition=models.Q(+ latest_state__in=["pending", "executing", "waiting_retry", "failed"]+ ),+ ),+ models.Index(+ fields=["lane", "group_key"],+ name="qj_group_busy_idx",+ condition=models.Q(latest_state="executing"),+ ),+ models.Index(+ fields=["state_changed_at"],+ name="qj_failed_changed_idx",+ condition=models.Q(latest_state="failed"),+ ),+ models.Index(+ fields=["kind", "dedup_key"],+ name="qj_dedup_idx",+ condition=models.Q(dedup_key__isnull=False),+ ),+ ],+ },+ ),+ migrations.CreateModel(+ name="QueueJobStatus",+ fields=[+ ("id", models.UUIDField(default=uuid7, editable=False, primary_key=True, serialize=False)),+ ("job_id", models.UUIDField()),+ (+ "job_state",+ models.CharField(+ choices=[+ ("waiting", "waiting"),+ ("executing", "executing"),+ ("succeeded", "succeeded"),+ ("waiting_retry", "waiting_retry"),+ ("failed", "failed"),+ ],+ max_length=32,+ ),+ ),+ ("attempt", models.SmallIntegerField(default=0)),+ ("exec_time", models.DateTimeField(blank=True, null=True)),+ ("error_response", models.JSONField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ],+ options={+ "db_table": "queuejobstatus",+ "indexes": [+ models.Index(+ fields=["job_id", "-created_at", "-id", "job_state"],+ name="qjs_job_id_desc_state_idx",+ ),+ ],+ },+ ),+ migrations.CreateModel(+ name="QueueJobLease",+ fields=[+ (+ "id",+ models.BigAutoField(+ auto_created=True, primary_key=True, serialize=False, verbose_name="ID"+ ),+ ),+ ("lane", models.CharField(max_length=16)),+ ("group_key", models.CharField(max_length=400)),+ (+ "owner_token",+ models.CharField(+ help_text="Per-pod identity (uuid4) of the current lease holder.",+ max_length=64,+ ),+ ),+ ("expires_at", models.DateTimeField()),+ ("acquired_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ],+ options={+ "db_table": "queuejoblease",+ "constraints": [+ models.UniqueConstraint(fields=("lane", "group_key"), name="qjl_lane_group_uniq")+ ],+ "indexes": [+ models.Index(fields=["expires_at"], name="qjl_expires_at_idx"),+ ],+ },+ ),+ ],+ database_operations=[],+ ),+ migrations.RunPython(+ _create_generic_job_tables,+ _drop_generic_job_tables,+ ),+ ]diff --git a/products/warehouse_sources_queue/backend/migrations/max_migration.txt b/products/warehouse_sources_queue/backend/migrations/max_migration.txtindex fba75b8ea0ec..4271773265b0 100644--- a/products/warehouse_sources_queue/backend/migrations/max_migration.txt+++ b/products/warehouse_sources_queue/backend/migrations/max_migration.txt@@ -1 +1 @@-0010_sourcebatch_destination_ids+0011_generic_job_tablesdiff --git a/products/warehouse_sources_queue/backend/models.py b/products/warehouse_sources_queue/backend/models.pyindex 69bd1df56f7a..16068721636a 100644--- a/products/warehouse_sources_queue/backend/models.py+++ b/products/warehouse_sources_queue/backend/models.py@@ -174,3 +174,127 @@ class SourceGroupLease(models.Model):indexes = [models.Index(fields=["expires_at"], name="sgl_expires_at_idx"),]+++class QueueJob(UUIDModel):+ """One unit of work on the generic job queue (phase 1 of the run orchestrator).++ ``kind`` names the work (``sync.extract``, ``post.table-size``, ...); ``lane``+ partitions leases so one ``group_key`` (e.g. ``team:schema``) can hold an+ extract-lane lease and a load-lane lease at the same time. All access is via+ raw SQL in ``core/generic_jobs.py`` — this model exists for migration and+ introspection. Nothing produces or consumes these rows yet.+ """++ class LatestState(models.TextChoices):+ # 'pending' means "no status row yet", mirroring SourceBatch semantics.+ PENDING = "pending", "pending"+ WAITING = "waiting", "waiting"+ EXECUTING = "executing", "executing"+ SUCCEEDED = "succeeded", "succeeded"+ WAITING_RETRY = "waiting_retry", "waiting_retry"+ FAILED = "failed", "failed"++ kind = models.CharField(max_length=100)+ lane = models.CharField(max_length=16)+ group_key = models.CharField(max_length=400)+ team_id = models.BigIntegerField()+ run_id = models.CharField(max_length=200, null=True, blank=True)+ sequence = models.IntegerField(default=0)+ payload = models.JSONField(default=dict, blank=True)+ priority = models.SmallIntegerField(default=0)+ dedup_key = models.CharField(max_length=400, null=True, blank=True)+ latest_state = models.CharField(max_length=32, default="pending")+ latest_attempt = models.SmallIntegerField(default=0)+ state_changed_at = models.DateTimeField(null=True, blank=True)+ superseded = models.BooleanField(default=False)+ created_at = models.DateTimeField(auto_now_add=True)++ __repr__ = sane_repr("kind", "lane", "group_key", "team_id", "latest_state")++ class Meta:+ db_table = "queuejob"+ indexes = [+ models.Index(+ fields=["lane", "kind", "team_id", "created_at", "sequence"],+ name="qj_claimable_idx",+ condition=models.Q(latest_state__in=["pending", "waiting_retry"]),+ ),+ models.Index(+ fields=["run_id", "latest_state", "sequence"],+ name="qj_run_gate_idx",+ condition=models.Q(latest_state__in=["pending", "executing", "waiting_retry", "failed"]),+ ),+ models.Index(+ fields=["lane", "group_key"],+ name="qj_group_busy_idx",+ condition=models.Q(latest_state="executing"),+ ),+ models.Index(+ fields=["state_changed_at"],+ name="qj_failed_changed_idx",+ condition=models.Q(latest_state="failed"),+ ),+ models.Index(+ fields=["kind", "dedup_key"],+ name="qj_dedup_idx",+ condition=models.Q(dedup_key__isnull=False),+ ),+ ]+++class QueueJobStatus(UUIDModel):+ """Append-only state log for QueueJob, mirroring SourceBatchStatus."""++ class State(models.TextChoices):+ WAITING = "waiting", "waiting"+ EXECUTING = "executing", "executing"+ SUCCEEDED = "succeeded", "succeeded"+ WAITING_RETRY = "waiting_retry", "waiting_retry"+ FAILED = "failed", "failed"++ job_id = models.UUIDField()+ job_state = models.CharField(max_length=32, choices=State.choices)+ attempt = models.SmallIntegerField(default=0)+ exec_time = models.DateTimeField(null=True, blank=True)+ error_response = models.JSONField(null=True, blank=True)+ created_at = models.DateTimeField(auto_now_add=True)++ __repr__ = sane_repr("job_id", "job_state", "attempt")++ class Meta:+ db_table = "queuejobstatus"+ indexes = [+ models.Index(+ fields=["job_id", "-created_at", "-id", "job_state"],+ name="qjs_job_id_desc_state_idx",+ ),+ ]+++class QueueJobLease(models.Model):+ """Lease-based mutual exclusion for a (lane, group_key) pair.++ The lane dimension is what lets extraction and loading run on separate pods+ for the same group without contending: each fleet leases its own lane. Same+ physics as SourceGroupLease — claimed by conditional upsert, renewed by+ heartbeat, reclaimable on expiry.+ """++ lane = models.CharField(max_length=16)+ group_key = models.CharField(max_length=400)+ owner_token = models.CharField(max_length=64, help_text="Per-pod identity (uuid4) of the current lease holder.")+ expires_at = models.DateTimeField()+ acquired_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ __repr__ = sane_repr("lane", "group_key", "owner_token", "expires_at")++ class Meta:+ db_table = "queuejoblease"+ constraints = [+ models.UniqueConstraint(fields=["lane", "group_key"], name="qjl_lane_group_uniq"),+ ]+ indexes = [+ models.Index(fields=["expires_at"], name="qjl_expires_at_idx"),+ ]diff --git a/products/warehouse_sources_queue/backend/sdk/__init__.py b/products/warehouse_sources_queue/backend/sdk/__init__.pyindex 0b72ec60e115..1687d4888805 100644--- a/products/warehouse_sources_queue/backend/sdk/__init__.py+++ b/products/warehouse_sources_queue/backend/sdk/__init__.py@@ -14,6 +14,7 @@ from products.warehouse_sources_queue.backend.core.batch_consumer import (OwnershipLostError,PermanentBatchApplyError,)+from products.warehouse_sources_queue.backend.core.generic_jobs import Job, JobsTablefrom products.warehouse_sources_queue.backend.core.health import HealthState, start_health_serverfrom products.warehouse_sources_queue.backend.core.jobs_db import (BATCH_TABLE,@@ -32,6 +33,17 @@ from products.warehouse_sources_queue.backend.core.metrics import (ConsumerMetrics,make_consumer_metrics,)+from products.warehouse_sources_queue.backend.sdk.jobs import (+ Fail,+ FollowerSpec,+ GenericJobAdapter,+ JobConsumer,+ JobContext,+ JobHandler,+ Outcome,+ Retry,+ Success,+)__all__ = ["BATCH_TABLE",@@ -48,11 +60,22 @@ __all__ = ["BatchConsumerConfig","BatchQueue","ConsumerMetrics",+ "Fail",+ "FollowerSpec",+ "GenericJobAdapter","HealthState",+ "Job",+ "JobConsumer",+ "JobContext",+ "JobHandler",+ "JobsTable",+ "Outcome","OwnershipLostError","PendingBatch","PermanentBatchApplyError",+ "Retry","RunActivitySummary",+ "Success","latest_status_lateral","make_consumer_metrics","start_health_server",diff --git a/products/warehouse_sources_queue/backend/sdk/jobs.py b/products/warehouse_sources_queue/backend/sdk/jobs.pynew file mode 100644index 000000000000..aa1969461964--- /dev/null+++ b/products/warehouse_sources_queue/backend/sdk/jobs.py@@ -0,0 +1,448 @@+"""SDK for the generic job queue: handlers, outcomes, and the consumer wiring.++A workload registers one ``JobHandler`` per kind and runs a ``JobConsumer``+for its lane. The consumer engine (``core.batch_consumer.BatchConsumer``)+supplies polling, lease heartbeats, retries with backoff, recovery sweeps, and+health/liveness; ``GenericJobAdapter`` maps its protocol onto the generic+tables. Followers returned by a successful handler are enqueued in the same+transaction as the terminal status write.+"""++from __future__ import annotations++import logging+from collections.abc import Callable+from contextvars import ContextVar+from datetime import datetime+from typing import TYPE_CHECKING, Any, Protocol, cast++import psycopg++from posthog.dataclasses import frozen++from products.warehouse_sources_queue.backend.core.batch_consumer import (+ BatchConsumer,+ BatchConsumerConfig,+ OwnershipLostError,+ PermanentBatchApplyError,+)+from products.warehouse_sources_queue.backend.core.generic_jobs import (+ JOB_LEASE_TTL_SECONDS,+ TERMINAL_JOB_STATES,+ Job,+ JobsTable,+)+from products.warehouse_sources_queue.backend.core.metrics import ConsumerMetrics, make_consumer_metrics++if TYPE_CHECKING:+ from products.warehouse_sources_queue.backend.core.batch_consumer import BatchConsumerAdapter, ProcessBatchFn++logger = logging.getLogger(__name__)+++@frozen+class FollowerSpec:+ """One job to enqueue when its parent succeeds."""++ kind: str+ group_key: str+ team_id: int+ payload: dict[str, Any]+ lane: str+ run_id: str | None = None+ sequence: int = 0+ priority: int = 0+ dedup_key: str | None = None+++@frozen+class Success:+ followers: tuple[FollowerSpec, ...] = ()+++@frozen+class Retry:+ reason: str+++@frozen+class Fail:+ reason: str+++Outcome = Success | Retry | Fail+++class JobRetryRequested(Exception):+ """Raised internally to route a ``Retry`` outcome into the engine's waiting_retry cycle."""+++@frozen(slots=False)+class JobContext:+ """What a handler gets besides the job itself."""++ logger: logging.Logger+++class JobHandler(Protocol):+ async def handle(self, job: Job, ctx: JobContext) -> Outcome: ...+++class GenericJobAdapter:+ """``BatchConsumerAdapter`` over the generic job tables.++ The engine's protocol speaks in batch vocabulary (``batch_id``,+ ``schema_id``); this adapter maps those onto jobs and (lane, group_key)+ leases — see ``Job``'s alias properties for the field mapping.+ """++ log_prefix = "generic_jobs"+ executing_state = "executing"+ succeeded_state = "succeeded"+ waiting_retry_state = "waiting_retry"+ # Lease ownership is token-based, so any connection works.+ per_group_connections = True+ # A skip means the row is already terminal. Do not regress it through an+ # executing write merely to record another success.+ record_skip_as_success = False++ def __init__(+ self,+ *,+ lane: str,+ kinds: list[str],+ is_retryable: Callable[[Exception], bool] | None = None,+ recovery_sweep_limit: int = 100,+ ) -> None:+ self._lane = lane+ self._kinds = kinds+ self._is_retryable = is_retryable+ self._recovery_sweep_limit = recovery_sweep_limit+ # Attempt-local state follows the engine's group task. It cannot leak+ # into a later attempt when ownership is lost and the task is abandoned.+ self._pending_followers: ContextVar[tuple[str, tuple[FollowerSpec, ...]] | None] = ContextVar(+ "generic_job_pending_followers", default=None+ )+ self._executing_attempt: ContextVar[tuple[str, int] | None] = ContextVar(+ "generic_job_executing_attempt", default=None+ )++ def stash_followers(self, job_id: str, followers: tuple[FollowerSpec, ...]) -> None:+ # An empty success deliberately replaces followers from any earlier+ # invocation in this task.+ self._pending_followers.set((job_id, followers))++ async def fetch_and_lock(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ limit: int,+ retry_backoff_base_seconds: int,+ owner_token: str,+ lease_ttl_seconds: int,+ ) -> list[Job]:+ return await JobsTable.get_unprocessed_and_lock(+ conn,+ owner_token=owner_token,+ lane=self._lane,+ kinds=self._kinds,+ limit=limit,+ retry_backoff_base_seconds=retry_backoff_base_seconds,+ lease_ttl_seconds=lease_ttl_seconds,+ )++ async def unlock(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ batches: list[Job],+ owner_token: str,+ ) -> None:+ await JobsTable.unlock_groups(+ conn,+ lane=self._lane,+ group_keys=sorted({job.group_key for job in batches}),+ owner_token=owner_token,+ )++ async def release_all_owned(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ owner_token: str,+ ) -> None:+ await JobsTable.release_all_owned(conn, owner_token=owner_token)++ async def update_status(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ batch_id: str,+ job_state: str,+ attempt: int,+ error_response: dict[str, Any] | None = None,+ batch_created_at: datetime | None = None,+ expected_state_changed_at: datetime | None = None,+ ) -> None:+ current = self._executing_attempt.get()+ expected_attempt = current[1] if current is not None and current[0] == batch_id else None+ expected_state = self.executing_state if expected_attempt is not None else None++ if job_state == self.succeeded_state:+ pending = self._pending_followers.get()+ followers = pending[1] if pending is not None and pending[0] == batch_id else ()+ # Terminal write and follower enqueue commit together: a crash+ # between them cannot complete a job without its followers.+ async with conn.transaction():+ wrote = await JobsTable.update_status_unless_failed(+ conn,+ job_id=batch_id,+ job_state=job_state,+ attempt=attempt,+ error_response=error_response,+ job_created_at=batch_created_at,+ expected_state=expected_state,+ expected_attempt=expected_attempt,+ )+ if not wrote:+ raise OwnershipLostError(f"job {batch_id} moved before its success transition")+ if followers:+ await JobsTable.insert_many(+ conn,+ [+ {+ "kind": f.kind,+ "lane": f.lane,+ "group_key": f.group_key,+ "team_id": f.team_id,+ "payload": f.payload,+ "run_id": f.run_id,+ "sequence": f.sequence,+ "priority": f.priority,+ "dedup_key": f.dedup_key,+ }+ for f in followers+ ],+ )+ self._pending_followers.set(None)+ self._executing_attempt.set(None)+ return++ # Recovery fences on its observed timestamp; transitions made by the+ # active handler fence on the executing state and current attempt.+ arm_cas = expected_state_changed_at is not None+ wrote = await JobsTable.update_status_unless_failed(+ conn,+ job_id=batch_id,+ job_state=job_state,+ attempt=attempt,+ error_response=error_response,+ job_created_at=batch_created_at,+ expected_state_changed_at=expected_state_changed_at,+ arm_cas=arm_cas,+ expected_state=expected_state,+ expected_attempt=expected_attempt,+ )+ if not wrote:+ raise OwnershipLostError(f"job {batch_id} moved under this writer; refusing to write '{job_state}' over it")+ if job_state == self.executing_state:+ self._executing_attempt.set((batch_id, attempt))++ async def fail_run(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ batch: Job,+ reason: str,+ ) -> None:+ # Must not raise (the engine calls this from error paths). No run-level+ # fan-out in phase 1: failing the one job is the whole action, and the+ # run gate parks any followers behind the failed sequence.+ try:+ self._pending_followers.set(None)+ current = self._executing_attempt.get()+ if current is not None and current[0] == batch.id:+ expected_state, expected_attempt = self.executing_state, current[1]+ else:+ expected_state, expected_attempt = batch.latest_state, batch.latest_attempt+ await JobsTable.update_status_unless_failed(+ conn,+ job_id=batch.id,+ job_state="failed",+ attempt=expected_attempt,+ error_response={"error": reason},+ job_created_at=batch.created_at,+ expected_state=expected_state,+ expected_attempt=expected_attempt,+ )+ self._executing_attempt.set(None)+ except Exception:+ logger.exception("generic_jobs_fail_run_write_failed", extra={"job_id": batch.id})++ async def verify_advisory_lock(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ team_id: int,+ schema_id: str,+ owner_token: str,+ ) -> bool:+ return await JobsTable.verify_lease(conn, lane=self._lane, group_key=schema_id, owner_token=owner_token)++ async def renew_lease(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ team_id: int,+ schema_id: str,+ owner_token: str,+ lease_ttl_seconds: int,+ ) -> bool:+ return await JobsTable.renew_lease(+ conn,+ lane=self._lane,+ group_key=schema_id,+ owner_token=owner_token,+ lease_ttl_seconds=lease_ttl_seconds or JOB_LEASE_TTL_SECONDS,+ )++ async def delete_expired_lease(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ team_id: int,+ schema_id: str,+ ) -> None:+ await JobsTable.delete_expired_lease(conn, lane=self._lane, group_key=schema_id)++ async def get_stale_executing(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ grace_seconds: int,+ keep_locks: bool = False,+ ) -> list[Job]:+ return await JobsTable.get_stale_executing(+ conn,+ lane=self._lane,+ kinds=self._kinds,+ grace_seconds=grace_seconds,+ limit=self._recovery_sweep_limit,+ )++ async def reconcile_failed_runs(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ grace_seconds: int,+ lookback_seconds: int,+ limit: int,+ ) -> None:+ # Nothing to reconcile: generic jobs have no external state machine to+ # repair (the batch queue's reconcile exists for ExternalDataJob rows).+ return++ async def should_process_batch(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ batch: Job,+ ) -> bool:+ state = await JobsTable.get_latest_state(conn, job_id=batch.id)+ return state not in TERMINAL_JOB_STATES++ def is_retryable_error(self, err: Exception) -> bool:+ if isinstance(err, JobRetryRequested):+ return True+ if isinstance(err, PermanentBatchApplyError):+ return False+ if self._is_retryable is not None:+ return self._is_retryable(err)+ return True++ def is_expected_user_error(self, err: Exception) -> bool:+ return False++ async def after_batch_processed(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ batch: Job,+ ) -> None:+ return+++# Module-level singleton: prometheus collectors register globally, so building+# them once keeps repeated JobConsumer construction (tests, reuse) safe.+GENERIC_JOB_METRICS: ConsumerMetrics | None = None+++def _generic_job_metrics() -> ConsumerMetrics:+ global GENERIC_JOB_METRICS+ if GENERIC_JOB_METRICS is None:+ GENERIC_JOB_METRICS = make_consumer_metrics("warehouse_jobs")+ return GENERIC_JOB_METRICS+++class JobConsumer:+ """Kind-dispatching consumer for one lane, on the shared engine.++ ``handlers`` maps kind -> ``JobHandler``; the consumer claims only those+ kinds. Handler outcomes: ``Success`` records the terminal state and+ enqueues followers atomically; ``Retry`` routes into the engine's+ waiting_retry cycle (attempt caps from ``config.max_attempts``); ``Fail``+ fails the job on first attempt.+ """++ def __init__(+ self,+ *,+ config: BatchConsumerConfig,+ lane: str,+ handlers: dict[str, JobHandler],+ health_reporter: Callable[[], None] | None = None,+ metrics: ConsumerMetrics | None = None,+ is_retryable: Callable[[Exception], bool] | None = None,+ recovery_sweep_limit: int = 100,+ ) -> None:+ self._handlers = handlers+ self._adapter = GenericJobAdapter(+ lane=lane,+ kinds=sorted(handlers),+ is_retryable=is_retryable,+ recovery_sweep_limit=recovery_sweep_limit,+ )+ self._ctx = JobContext(logger=logger)+ # The engine is typed against the batch item; Job satisfies its runtime+ # attribute contract through the documented aliases, so the casts bridge+ # the vocabulary until the engine is generic over its item type.+ self._consumer = BatchConsumer(+ config,+ cast("ProcessBatchFn", self._process),+ cast("BatchConsumerAdapter", self._adapter),+ health_reporter=health_reporter,+ metrics=metrics or _generic_job_metrics(),+ )++ async def _process(self, job: Job) -> None:+ handler = self._handlers.get(job.kind)+ if handler is None:+ raise PermanentBatchApplyError(f"no handler registered for kind {job.kind!r}")+ outcome = await handler.handle(job, self._ctx)+ match outcome:+ case Success(followers=followers):+ self._adapter.stash_followers(job.id, followers)+ case Retry(reason=reason):+ raise JobRetryRequested(reason)+ case Fail(reason=reason):+ raise PermanentBatchApplyError(reason)+ case _:+ raise PermanentBatchApplyError(f"handler for {job.kind!r} returned {outcome!r}, not an Outcome")++ async def run(self) -> None:+ await self._consumer.run()++ def request_shutdown(self) -> None:+ # The engine only arms shutdown from its own SIGTERM/SIGINT handlers;+ # tests and embedders need a programmatic trigger for the same event.+ self._consumer._shutdown.set()diff --git a/products/warehouse_sources_queue/backend/testing.py b/products/warehouse_sources_queue/backend/testing.pyindex 56011b9f0d46..2d6c78f84caf 100644--- a/products/warehouse_sources_queue/backend/testing.py+++ b/products/warehouse_sources_queue/backend/testing.py@@ -12,6 +12,7 @@ from django.db import connectionimport psycopg+from products.warehouse_sources_queue.backend.core.generic_jobs import JOB_LEASE_TABLE, JOB_STATUS_TABLE, JOB_TABLEfrom products.warehouse_sources_queue.backend.core.jobs_db import (BATCH_TABLE,LEASE_TABLE,@@ -149,3 +150,77 @@ BATCH_DEFAULTS: dict[str, Any] = {async def insert_batch(conn: psycopg.AsyncConnection[Any], **overrides: Any) -> str:params = {**BATCH_DEFAULTS, **overrides}return await BatchQueue.insert(conn, **params)+++def ensure_generic_job_tables(conn: psycopg.Connection[Any]) -> None:+ conn.execute(f"""+ CREATE TABLE IF NOT EXISTS {JOB_TABLE} (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ kind VARCHAR(100) NOT NULL,+ lane VARCHAR(16) NOT NULL,+ group_key VARCHAR(400) NOT NULL,+ team_id BIGINT NOT NULL,+ run_id VARCHAR(200),+ sequence INT NOT NULL DEFAULT 0,+ payload JSONB NOT NULL DEFAULT '{{}}'::jsonb,+ priority SMALLINT NOT NULL DEFAULT 0,+ dedup_key VARCHAR(400),+ latest_state VARCHAR(32) NOT NULL DEFAULT 'pending',+ latest_attempt SMALLINT NOT NULL DEFAULT 0,+ state_changed_at TIMESTAMPTZ,+ superseded BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+ )+ """)+ conn.execute(f"""+ CREATE INDEX IF NOT EXISTS qj_claimable_idx ON {JOB_TABLE} (lane, kind, team_id, created_at, sequence)+ WHERE latest_state IN ('pending', 'waiting_retry')+ """)+ conn.execute(f"""+ CREATE INDEX IF NOT EXISTS qj_run_gate_idx ON {JOB_TABLE} (run_id, latest_state, sequence)+ WHERE latest_state IN ('pending', 'executing', 'waiting_retry', 'failed')+ """)+ conn.execute(f"""+ CREATE INDEX IF NOT EXISTS qj_group_busy_idx ON {JOB_TABLE} (lane, group_key)+ WHERE latest_state = 'executing'+ """)+ conn.execute(f"""+ CREATE INDEX IF NOT EXISTS qj_dedup_idx ON {JOB_TABLE} (kind, dedup_key)+ WHERE dedup_key IS NOT NULL+ """)+ conn.execute(f"""+ CREATE TABLE IF NOT EXISTS {JOB_STATUS_TABLE} (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ job_id UUID NOT NULL,+ job_state VARCHAR(32) NOT NULL,+ attempt SMALLINT NOT NULL DEFAULT 0,+ exec_time TIMESTAMPTZ,+ error_response JSONB,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+ )+ """)+ conn.execute(f"""+ CREATE TABLE IF NOT EXISTS {JOB_LEASE_TABLE} (+ id BIGSERIAL PRIMARY KEY,+ lane VARCHAR(16) NOT NULL,+ group_key VARCHAR(400) NOT NULL,+ owner_token VARCHAR(64) NOT NULL,+ expires_at TIMESTAMPTZ NOT NULL,+ acquired_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CONSTRAINT qjl_lane_group_uniq UNIQUE (lane, group_key)+ )+ """)+++def truncate_generic_job_tables(conn: psycopg.Connection[Any]) -> None:+ conn.execute(f"TRUNCATE {JOB_STATUS_TABLE}, {JOB_TABLE}, {JOB_LEASE_TABLE} RESTART IDENTITY CASCADE")+++JOB_DEFAULTS: dict[str, Any] = {+ "kind": "test.kind",+ "lane": "test",+ "group_key": "1:group-1",+ "team_id": 1,+ "payload": {},+}diff --git a/products/warehouse_sources_queue/backend/tests/test_generic_jobs.py b/products/warehouse_sources_queue/backend/tests/test_generic_jobs.pynew file mode 100644index 000000000000..ffe3023352ce--- /dev/null+++ b/products/warehouse_sources_queue/backend/tests/test_generic_jobs.py@@ -0,0 +1,407 @@+import asyncio+from typing import Any, cast+from uuid import uuid4++import pytest++import psycopg++from products.warehouse_sources_queue.backend.core.batch_consumer import BatchConsumerConfig, _group_by_key+from products.warehouse_sources_queue.backend.core.generic_jobs import JOB_LEASE_TABLE, JOB_TABLE, Job, JobsTable+from products.warehouse_sources_queue.backend.core.jobs_db import PendingBatch+from products.warehouse_sources_queue.backend.sdk.jobs import (+ Fail,+ FollowerSpec,+ GenericJobAdapter,+ JobConsumer,+ JobContext,+ JobRetryRequested,+ Outcome,+ Success,+)+from products.warehouse_sources_queue.backend.testing import (+ JOB_DEFAULTS,+ ensure_generic_job_tables,+ get_test_database_url,+ truncate_generic_job_tables,+)++OWNER_A = str(uuid4())+OWNER_B = str(uuid4())++LANE = "test"+KIND = "test.kind"+++async def _try_insert(conn: psycopg.AsyncConnection[Any], **overrides: Any) -> str | None:+ return await JobsTable.insert(conn, **{**JOB_DEFAULTS, **overrides})+++async def _insert(conn: psycopg.AsyncConnection[Any], **overrides: Any) -> str:+ job_id = await _try_insert(conn, **overrides)+ assert job_id is not None+ return job_id+++async def _claim(+ conn: psycopg.AsyncConnection[Any],+ owner: str = OWNER_A,+ *,+ lane: str = LANE,+ kinds: list[str] | None = None,+ **kwargs: Any,+) -> list[Job]:+ return await JobsTable.get_unprocessed_and_lock(conn, owner_token=owner, lane=lane, kinds=kinds or [KIND], **kwargs)++[email protected](scope="package")+def _db_url(django_db_setup: None) -> str:+ return get_test_database_url()++[email protected](scope="package", autouse=True)+def _create_tables(_db_url: str) -> None:+ with psycopg.Connection.connect(_db_url, autocommit=True) as conn:+ ensure_generic_job_tables(conn)++[email protected](autouse=True)+def _clean_tables(_db_url: str) -> None:+ with psycopg.Connection.connect(_db_url, autocommit=True) as conn:+ truncate_generic_job_tables(conn)+++async def conn(_db_url: str):+ async with await psycopg.AsyncConnection.connect(_db_url, autocommit=True) as c:+ yield c+++async def conn_b(_db_url: str):+ async with await psycopg.AsyncConnection.connect(_db_url, autocommit=True) as c:+ yield c++[email protected]_db(transaction=True)+class TestEnqueueDedup:+ @pytest.mark.asyncio+ async def test_dedup_refuses_live_duplicate_and_frees_on_failure(self, conn):+ first = await _insert(conn, dedup_key="k1")+ assert await _try_insert(conn, dedup_key="k1") is None++ await JobsTable.update_status(conn, job_id=first, job_state="failed")+ assert await _try_insert(conn, dedup_key="k1") is not None++ @pytest.mark.parametrize(+ "overrides",+ [+ pytest.param({"kind": "test.other", "dedup_key": "k1"}, id="other_kind"),+ pytest.param({"dedup_key": None}, id="no_dedup_key"),+ ],+ )+ @pytest.mark.asyncio+ async def test_dedup_scopes_to_kind_and_key(self, overrides, conn):+ assert await _try_insert(conn, dedup_key="k1") is not None+ assert await _try_insert(conn, **overrides) is not None++ @pytest.mark.asyncio+ async def test_insert_many_enqueues_all_in_one_call(self, conn):+ ids = await JobsTable.insert_many(+ conn,+ [+ {**JOB_DEFAULTS, "dedup_key": "a"},+ {**JOB_DEFAULTS, "group_key": "1:group-2", "dedup_key": "b"},+ ],+ )+ assert len(ids) == 2+ assert await JobsTable.get_claimable_count(conn, lane=LANE, kinds=[KIND]) == 2++[email protected]_db(transaction=True)+class TestClaim:+ @pytest.mark.asyncio+ async def test_claims_pending_job_and_leases_its_group(self, conn):+ job_id = await _insert(conn)+ claimed = await _claim(conn)+ assert [j.id for j in claimed] == [job_id]++ async with conn.cursor() as cur:+ await cur.execute(f"SELECT lane, group_key, owner_token FROM {JOB_LEASE_TABLE}")+ leases = await cur.fetchall()+ assert leases == [(LANE, JOB_DEFAULTS["group_key"], OWNER_A)]++ @pytest.mark.parametrize(+ "insert_overrides",+ [+ pytest.param({"lane": "other"}, id="wrong_lane"),+ pytest.param({"kind": "test.other"}, id="wrong_kind"),+ ],+ )+ @pytest.mark.asyncio+ async def test_claim_filters_by_lane_and_kind(self, insert_overrides, conn):+ await _insert(conn, **insert_overrides)+ assert await _claim(conn) == []++ @pytest.mark.asyncio+ async def test_live_lease_by_other_owner_blocks_claim(self, conn, conn_b):+ await _insert(conn)+ assert len(await _claim(conn, OWNER_A)) == 1+ await _insert(conn, dedup_key="second")+ assert await _claim(conn_b, OWNER_B) == []+ # The holder itself can keep draining the group.+ assert len(await _claim(conn, OWNER_A)) == 2++ @pytest.mark.asyncio+ async def test_lanes_lease_independently_for_one_group(self, conn, conn_b):+ await _insert(conn)+ await _insert(conn, lane="load", kind="load.kind")+ extract = await _claim(conn, OWNER_A)+ load = await _claim(conn_b, OWNER_B, lane="load", kinds=["load.kind"])+ assert len(extract) == 1+ assert len(load) == 1++ @pytest.mark.asyncio+ async def test_executing_group_is_not_reclaimable(self, conn, conn_b):+ job_id = await _insert(conn)+ await _claim(conn, OWNER_A)+ await JobsTable.update_status(conn, job_id=job_id, job_state="executing")+ await _insert(conn, dedup_key="second")+ # Even after the lease lapses, the executing row keeps the group busy+ # for everyone (the recovery sweep, not the claim path, handles it).+ async with conn.cursor() as cur:+ await cur.execute(f"UPDATE {JOB_LEASE_TABLE} SET expires_at = now() - interval '1 minute'")+ assert await _claim(conn_b, OWNER_B) == []++ @pytest.mark.asyncio+ async def test_run_gate_holds_followers_behind_every_unsucceeded_step(self, conn):+ run_id = "run-1"+ first = await _insert(conn, run_id=run_id, sequence=0, dedup_key="s0", priority=0)+ second = await _insert(conn, run_id=run_id, sequence=1, dedup_key="s1", priority=10)++ # A higher-priority later step must not be returned alongside its pending prerequisite.+ assert [job.id for job in await _claim(conn)] == [first]++ await JobsTable.update_status(conn, job_id=first, job_state="executing")+ assert await _claim(conn) == []++ await JobsTable.update_status(conn, job_id=first, job_state="waiting_retry", attempt=1)+ async with conn.cursor() as cur:+ await cur.execute(f"DELETE FROM {JOB_LEASE_TABLE}")+ assert [job.id for job in await _claim(conn, retry_backoff_base_seconds=0)] == [first]++ await JobsTable.update_status(conn, job_id=first, job_state="failed", attempt=1)+ assert await _claim(conn) == []+ assert await JobsTable.get_latest_state(conn, job_id=second) == "pending"++ @pytest.mark.asyncio+ async def test_engine_groups_jobs_by_the_lease_key_not_team(self, conn):+ await _insert(conn, team_id=1, dedup_key="team-1")+ await _insert(conn, team_id=2, dedup_key="team-2")++ claimed = await _claim(conn)+ assert {job.team_id for job in claimed} == {1, 2}+ assert len(_group_by_key(cast("list[PendingBatch]", claimed))) == 1++ @pytest.mark.asyncio+ async def test_waiting_retry_respects_backoff(self, conn):+ job_id = await _insert(conn)+ await JobsTable.update_status(conn, job_id=job_id, job_state="waiting_retry", attempt=1)+ async with conn.cursor() as cur:+ await cur.execute(f"UPDATE {JOB_LEASE_TABLE} SET expires_at = now() - interval '1 minute'")++ assert await _claim(conn, retry_backoff_base_seconds=3600) == []+ claimed = await _claim(conn, retry_backoff_base_seconds=0)+ assert [j.id for j in claimed] == [job_id]+ assert claimed[0].latest_attempt == 1++[email protected]_db(transaction=True)+class TestStatusWrites:+ @pytest.mark.parametrize("terminal_state", ["failed", "succeeded"])+ @pytest.mark.asyncio+ async def test_terminal_states_are_absorbing_for_guarded_writes(self, terminal_state, conn):+ job_id = await _insert(conn)+ await JobsTable.update_status(conn, job_id=job_id, job_state=terminal_state)++ wrote = await JobsTable.update_status_unless_failed(conn, job_id=job_id, job_state="executing")+ assert wrote is False+ assert await JobsTable.get_latest_state(conn, job_id=job_id) == terminal_state++ @pytest.mark.asyncio+ async def test_failure_transition_requires_the_current_executing_attempt(self, conn):+ job_id = await _insert(conn)+ [job] = await _claim(conn)+ adapter = GenericJobAdapter(lane=LANE, kinds=[KIND])++ await adapter.update_status(conn, batch_id=job_id, job_state="executing", attempt=1)+ await adapter.fail_run(conn, batch=job, reason="failed")++ async with conn.cursor() as cur:+ await cur.execute(f"SELECT latest_state, latest_attempt FROM {JOB_TABLE} WHERE id = %s", (job_id,))+ assert await cur.fetchone() == ("failed", 1)++ # A stale attempt cannot overwrite a later owner's terminal result.+ other_id = await _insert(conn, dedup_key="other", group_key="other")+ [other] = await _claim(conn)+ await adapter.update_status(conn, batch_id=other_id, job_state="executing", attempt=1)+ await JobsTable.update_status(conn, job_id=other_id, job_state="succeeded", attempt=2)+ await adapter.fail_run(conn, batch=other, reason="stale")+ assert await JobsTable.get_latest_state(conn, job_id=other_id) == "succeeded"++ @pytest.mark.asyncio+ async def test_guarded_cas_refuses_stale_writer(self, conn):+ job_id = await _insert(conn)+ await JobsTable.update_status(conn, job_id=job_id, job_state="executing")++ # A writer that observed the pre-executing state (None) loses the CAS.+ wrote = await JobsTable.update_status_unless_failed(+ conn, job_id=job_id, job_state="waiting_retry", expected_state_changed_at=None, arm_cas=True+ )+ assert wrote is False+ assert await JobsTable.get_latest_state(conn, job_id=job_id) == "executing"++[email protected]_db(transaction=True)+class TestRecoverySweep:+ @pytest.mark.asyncio+ async def test_stale_executing_needs_expired_lease(self, conn):+ job_id = await _insert(conn)+ await _claim(conn, OWNER_A)+ await JobsTable.update_status(conn, job_id=job_id, job_state="executing")+ async with conn.cursor() as cur:+ await cur.execute(f"UPDATE {JOB_TABLE} SET state_changed_at = now() - interval '1 hour'")++ assert await JobsTable.get_stale_executing(conn, lane=LANE, kinds=[KIND], grace_seconds=60) == []++ async with conn.cursor() as cur:+ await cur.execute(f"UPDATE {JOB_LEASE_TABLE} SET expires_at = now() - interval '1 minute'")+ stale = await JobsTable.get_stale_executing(conn, lane=LANE, kinds=[KIND], grace_seconds=60)+ assert [j.id for j in stale] == [job_id]++ @pytest.mark.asyncio+ async def test_recovery_is_bounded_and_single_flight(self, conn, conn_b):+ for index in range(2):+ job_id = await _insert(conn, group_key=f"group-{index}", dedup_key=f"job-{index}")+ await JobsTable.update_status(conn, job_id=job_id, job_state="executing", attempt=1)+ async with conn.cursor() as cur:+ await cur.execute(f"UPDATE {JOB_TABLE} SET state_changed_at = now() - interval '1 hour'")++ stale = await JobsTable.get_stale_executing(conn, lane=LANE, kinds=[KIND], limit=1)+ assert len(stale) == 1+ assert await JobsTable.get_stale_executing(conn_b, lane=LANE, kinds=[KIND], limit=1) == []++ async with conn.cursor() as cur:+ await cur.execute(+ f"UPDATE {JOB_LEASE_TABLE} SET expires_at = now() - interval '1 minute' WHERE group_key = %s",+ (JobsTable.RECOVERY_SWEEP_GROUP_KEY,),+ )+ assert len(await JobsTable.get_stale_executing(conn_b, lane=LANE, kinds=[KIND], limit=1)) == 1++[email protected]_db(transaction=True)+class TestClaimableGauge:+ @pytest.mark.asyncio+ async def test_count_uses_run_backoff_and_lease_gates(self, conn):+ run_id = "run-depth"+ first = await _insert(conn, run_id=run_id, sequence=0, dedup_key="first")+ await _insert(conn, run_id=run_id, sequence=1, dedup_key="second")+ assert await JobsTable.get_claimable_count(conn, lane=LANE, kinds=[KIND]) == 1++ await JobsTable.update_status(conn, job_id=first, job_state="waiting_retry", attempt=1)+ assert await JobsTable.get_claimable_count(conn, lane=LANE, kinds=[KIND], retry_backoff_base_seconds=3600) == 0++ await JobsTable.update_status(conn, job_id=first, job_state="pending", attempt=1)+ await _claim(conn)+ assert await JobsTable.get_claimable_count(conn, lane=LANE, kinds=[KIND]) == 0+++def test_explicit_retry_bypasses_custom_exception_classifier():+ adapter = GenericJobAdapter(lane=LANE, kinds=[KIND], is_retryable=lambda _: False)+ assert adapter.is_retryable_error(JobRetryRequested("again")) is True+ assert adapter.is_retryable_error(Exception("no")) is False+++async def test_follower_state_is_replaced_and_scoped_to_one_group_task():+ adapter = GenericJobAdapter(lane=LANE, kinds=[KIND])+ follower = FollowerSpec(kind=KIND, lane=LANE, group_key="follower", team_id=1, payload={})++ async def attempt() -> None:+ adapter.stash_followers("job", (follower,))+ adapter.stash_followers("job", ())+ assert adapter._pending_followers.get() == ("job", ())++ await asyncio.create_task(attempt())+ assert adapter._pending_followers.get() is None+++class _RecordingHandler:+ def __init__(self, outcome: Outcome) -> None:+ self.outcome = outcome+ self.seen: list[str] = []++ async def handle(self, job: Job, ctx: JobContext) -> Outcome:+ self.seen.append(job.id)+ return self.outcome++[email protected]_db(transaction=True)+class TestJobConsumerEndToEnd:+ @pytest.mark.asyncio+ async def test_consumer_runs_handlers_enqueues_followers_and_fails_failures(self, conn, _db_url):+ follower = FollowerSpec(+ kind="test.follower",+ lane=LANE,+ group_key=JOB_DEFAULTS["group_key"],+ team_id=1,+ payload={"from": "parent"},+ dedup_key="follower-1",+ )+ ok_handler = _RecordingHandler(Success(followers=(follower,)))+ fail_handler = _RecordingHandler(Fail(reason="configured to fail"))+ follower_handler = _RecordingHandler(Success())++ ok_id = await _insert(conn, dedup_key="ok")+ fail_id = await _insert(conn, kind="test.failing", group_key="1:group-2", dedup_key="fails")++ consumer = JobConsumer(+ config=BatchConsumerConfig(+ database_url=_db_url,+ max_concurrency=2,+ poll_interval_seconds=0.05,+ recovery_interval_seconds=3600,+ reconcile_interval_seconds=3600,+ retry_backoff_base_seconds=0,+ ),+ lane=LANE,+ handlers={+ KIND: ok_handler,+ "test.failing": fail_handler,+ "test.follower": follower_handler,+ },+ )+ run_task = asyncio.create_task(consumer.run())++ async def _settled() -> bool:+ return (+ await JobsTable.get_latest_state(conn, job_id=ok_id) == "succeeded"+ and await JobsTable.get_latest_state(conn, job_id=fail_id) == "failed"+ and follower_handler.seen != []+ )++ try:+ async with asyncio.timeout(30):+ while not await _settled():+ await asyncio.sleep(0.05)+ finally:+ consumer.request_shutdown()+ await run_task++ assert ok_handler.seen == [ok_id]+ assert fail_handler.seen == [fail_id]+ # The follower the successful handler returned was enqueued and processed.+ async with conn.cursor() as cur:+ await cur.execute(f"SELECT latest_state, payload->>'from' FROM {JOB_TABLE} WHERE kind = 'test.follower'")+ rows = await cur.fetchall()+ assert rows == [("succeeded", "parent")]