: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): lease coordination and whole-run chunk claiming for duckgres sink (#67537)
Eric Duong04e25bbb95ea
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 47c77c7de587..f0c995f003b4 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -234,6 +234,7 @@ rules:|SlackThreadTaskMapping|SourceBatch|SourceBatchDuckgresApply+ |SourceDuckgresGroupLease|SourceGroupLease|StreamlitApp|Subscription@@ -505,6 +506,7 @@ rules:|SlackThreadTaskMapping|SourceBatch|SourceBatchDuckgresApply+ |SourceDuckgresGroupLease|SourceGroupLease|StreamlitApp|Subscriptiondiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.pyindex 44cc6e80e35b..936a6dfe7c14 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py@@ -330,13 +330,7 @@ class BatchConsumer:try:conn = await self._ensure_poll_conn()async with asyncio.timeout(self._config.poll_timeout_seconds):- batches = await self._adapter.fetch_and_lock(- conn,- limit=self._fetch_limit(available),- retry_backoff_base_seconds=self._config.retry_backoff_base_seconds,- owner_token=self._owner_token,- lease_ttl_seconds=self._lease_ttl_seconds,- )+ batches = await self._fetch_batches(conn, available=available)except TimeoutError:# error, not exception: the timeout is the designed recovery# path and its traceback carries no diagnostic value.@@ -375,6 +369,17 @@ class BatchConsumer:finally:await self._close()+ async def _fetch_batches(self, conn: psycopg.AsyncConnection[Any], *, available: int) -> list[PendingBatch]:+ """Claim the next batches to process. ``available`` is the number of free+ group slots; subclasses may use it to bound how many groups they claim."""+ return await self._adapter.fetch_and_lock(+ conn,+ limit=self._fetch_limit(available),+ retry_backoff_base_seconds=self._config.retry_backoff_base_seconds,+ owner_token=self._owner_token,+ lease_ttl_seconds=self._lease_ttl_seconds,+ )+def _fetch_limit(self, available: int) -> int:"""Cap the poll fetch so we never lease far more groups than we have free slots to run.@@ -508,22 +513,35 @@ class BatchConsumer:)breakfinally:- if group_conn is not None:- try:- await self._adapter.unlock(group_conn, batches=batches, owner_token=self._owner_token)- except Exception as e:- logger.exception(- self._event("unlock_for_batches_failed"),- team_id=team_id,- external_data_schema_id=schema_id,- )- capture_exception(e)+ await self._unlock_group(group_conn, batches, team_id=team_id, schema_id=schema_id)if owns_conn and group_conn is not None:try:await group_conn.close()except Exception:pass+ async def _unlock_group(+ self,+ group_conn: psycopg.AsyncConnection[Any] | None,+ batches: list[PendingBatch],+ *,+ team_id: int,+ schema_id: str,+ ) -> None:+ """Release the group's claim after processing. ``group_conn`` is None when+ opening the per-group connection failed before processing started."""+ if group_conn is None:+ return+ try:+ await self._adapter.unlock(group_conn, batches=batches, owner_token=self._owner_token)+ except Exception as e:+ logger.exception(+ self._event("unlock_for_batches_failed"),+ team_id=team_id,+ external_data_schema_id=schema_id,+ )+ capture_exception(e)+async def _get_status_conn(self, lock_conn: psycopg.AsyncConnection[Any] | None) -> psycopg.AsyncConnection[Any]:"""Return the connection to use for status writes, preferring the lock session."""if lock_conn is not None:@@ -661,18 +679,23 @@ class BatchConsumer:resource_name=batch.resource_name,)- # Pre-increment: if we OOM here, recovery sees attempt=N+1 and knows this attempt was consumed.- await self._adapter.update_status(- status_conn,- batch_id=batch.id,- job_state=self._adapter.executing_state,- attempt=attempt,- )-heartbeat_task: asyncio.Task[None] | None = Nonetry:start = time.monotonic()+ # Before the executing write: adapters may read the batch's latest+ # status here, and our own 'executing' row would mask a terminal+ # status written while the batch waited in this claim.should_process = await self._adapter.should_process_batch(status_conn, batch=batch)++ # Pre-increment: if we OOM during processing, recovery sees attempt=N+1+ # and knows this attempt was consumed.+ await self._adapter.update_status(+ status_conn,+ batch_id=batch.id,+ job_state=self._adapter.executing_state,+ attempt=attempt,+ )+if should_process:if lock_conn is not None:heartbeat_task = asyncio.create_task(self._batch_heartbeat(lock_conn, batch, attempt))@@ -719,29 +742,7 @@ class BatchConsumer:self._metrics.batches_processed_total.labels(team_id=team_id, schema_id=schema_id, status="error").inc()self._metrics.batch_retry_total.labels(attempt=str(attempt), error_type=type(err).__name__).inc()- if attempt >= self._config.max_attempts:- logger.exception(- self._event("batch_failed_no_retries_left"),- batch_id=batch.id,- run_uuid=batch.run_uuid,- attempt=attempt,- )- capture_exception(err)- await self._fail_run(batch, reason=f"max retries exceeded: {err}", conn=lock_conn)- else:- logger.warning(- self._event("batch_failed_will_retry"),- batch_id=batch.id,- attempt=attempt,- error=str(err),- )- await self._adapter.update_status(- status_conn,- batch_id=batch.id,- job_state=self._adapter.waiting_retry_state,- attempt=attempt,- error_response={"error": str(err)[:1000]},- )+ await self._handle_batch_failure(batch, attempt, err, lock_conn=lock_conn, status_conn=status_conn)return Falsefinally:if heartbeat_task is not None:@@ -751,6 +752,40 @@ class BatchConsumer:except asyncio.CancelledError:pass+ async def _handle_batch_failure(+ self,+ batch: PendingBatch,+ attempt: int,+ err: Exception,+ *,+ lock_conn: psycopg.AsyncConnection[Any] | None,+ status_conn: psycopg.AsyncConnection[Any],+ ) -> None:+ """Write the retry/terminal state after a processing error."""+ if attempt >= self._config.max_attempts:+ logger.exception(+ self._event("batch_failed_no_retries_left"),+ batch_id=batch.id,+ run_uuid=batch.run_uuid,+ attempt=attempt,+ )+ capture_exception(err)+ await self._fail_run(batch, reason=f"max retries exceeded: {err}", conn=lock_conn)+ else:+ logger.warning(+ self._event("batch_failed_will_retry"),+ batch_id=batch.id,+ attempt=attempt,+ error=str(err),+ )+ await self._adapter.update_status(+ status_conn,+ batch_id=batch.id,+ job_state=self._adapter.waiting_retry_state,+ attempt=attempt,+ error_response={"error": str(err)[:1000]},+ )+async def _fail_run(self,batch: PendingBatch,diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.pyindex 6c8381a8cf56..9c8b0275b26b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py@@ -17,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineRECOVERY_INTERVAL_SECONDS,BatchConsumer as SharedBatchConsumer,BatchConsumerConfig,+ OwnershipLostError,ProcessBatchFn,_group_by_key,)@@ -32,6 +33,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineDuckgresBatchQueue,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (+ LEASE_TTL_SECONDS,PendingBatch,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.metrics import (@@ -81,12 +83,14 @@ class DuckgresBatchConsumerAdapter:executing_state: str = SourceBatchDuckgresStatus.State.EXECUTING.valuesucceeded_state: str = SourceBatchDuckgresStatus.State.SUCCEEDED.valuewaiting_retry_state: str = SourceBatchDuckgresStatus.State.WAITING_RETRY.value- # Advisory locks are session-scoped: the lock acquired during fetch_and_lock- # must be verified/released on the same connection, so groups share the poll- # connection. Migrating duckgres to leases is tracked separately.- per_group_connections: bool = False-- def __init__(self) -> None:+ # Lease ownership is token-based, so groups get their own connections and+ # the poll loop keeps claiming while groups run (no per-cycle barrier).+ per_group_connections: bool = True++ def __init__(self, lease_ttl_seconds: int = LEASE_TTL_SECONDS) -> None:+ # TTL for verify_advisory_lock's boundary renewals (the consumer's+ # configured group-lease TTL).+ self._lease_ttl_seconds = lease_ttl_secondsself._team_ids: list[int] | None = Noneself._team_ids_fetched_at: float | None = Noneself._last_maintenance_at = 0.0@@ -193,10 +197,9 @@ class DuckgresBatchConsumerAdapter:retry_backoff_base_seconds: int,owner_token: str,lease_ttl_seconds: int,+ max_groups: int | None = None,+ exclude_groups: list[tuple[int, str]] | None = None,) -> list[PendingBatch]:- # The duckgres sink coordinates via session advisory locks, not leases:- # owner_token / lease_ttl_seconds are part of the shared adapter contract- # but unused here.team_ids = await self._enabled_team_ids()if team_ids is not None and not team_ids:return []@@ -216,11 +219,15 @@ class DuckgresBatchConsumerAdapter:return await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn,+ owner_token=owner_token,limit=limit,retry_backoff_base_seconds=retry_backoff_base_seconds,team_ids=team_ids,blocked_schema_ids=self._blocked_schema_ids,eligible_schema_ids=self._eligible_schema_ids,+ lease_ttl_seconds=lease_ttl_seconds,+ max_groups=max_groups,+ exclude_groups=exclude_groups,)async def unlock(@@ -230,7 +237,7 @@ class DuckgresBatchConsumerAdapter:batches: list[PendingBatch],owner_token: str,) -> None:- await DuckgresBatchQueue.unlock_for_batches(conn, batches=batches)+ await DuckgresBatchQueue.unlock_for_batches(conn, batches=batches, owner_token=owner_token)async def release_all_owned(self,@@ -238,8 +245,7 @@ class DuckgresBatchConsumerAdapter:*,owner_token: str,) -> None:- # Duckgres holds session advisory locks; release them all on graceful shutdown.- await conn.execute("SELECT pg_advisory_unlock_all()")+ await DuckgresBatchQueue.release_all_owned_leases(conn, owner_token=owner_token)async def update_status(self,@@ -250,13 +256,19 @@ class DuckgresBatchConsumerAdapter:attempt: int,error_response: dict[str, Any] | None = None,) -> None:- await DuckgresBatchQueue.update_status(+ # Invariant: never write ANY status over a terminal 'failed' — statuses+ # are latest-row-wins, so an unconditional write would un-retire a batch+ # a supersede/replan/fail_run retired mid-claim. A blocked insert means+ # abort the group with no write (see update_status_unless_failed).+ inserted = await DuckgresBatchQueue.update_status_unless_failed(conn,batch_id=batch_id,job_state=job_state,attempt=attempt,error_response=error_response,)+ if not inserted:+ raise OwnershipLostError(f"batch {batch_id} was terminally retired while claimed")async def fail_run(self,@@ -284,7 +296,17 @@ class DuckgresBatchConsumerAdapter:schema_id: str,owner_token: str,) -> bool:- return await DuckgresBatchQueue.verify_advisory_lock(conn, team_id=team_id, schema_id=schema_id)+ # Verify-and-extend: a group of quick chunks can outlive the lease TTL+ # without any in-batch heartbeat firing, so the engine's per-batch+ # ownership check doubles as the renewal. Returns False exactly when+ # the lease was lost — a strict superset of a read-only verify.+ return await DuckgresBatchQueue.renew_lease(+ conn,+ team_id=team_id,+ schema_id=schema_id,+ owner_token=owner_token,+ lease_ttl_seconds=self._lease_ttl_seconds,+ )async def renew_lease(self,@@ -295,9 +317,13 @@ class DuckgresBatchConsumerAdapter:owner_token: str,lease_ttl_seconds: int,) -> bool:- # Duckgres ownership is the session advisory lock (checked by verify_advisory_lock),- # which has no TTL to renew; report ownership retained.- return True+ return await DuckgresBatchQueue.renew_lease(+ conn,+ team_id=team_id,+ schema_id=schema_id,+ owner_token=owner_token,+ lease_ttl_seconds=lease_ttl_seconds,+ )async def get_stale_executing(self,@@ -306,7 +332,10 @@ class DuckgresBatchConsumerAdapter:grace_seconds: int,keep_locks: bool = False,) -> list[PendingBatch]:- return await DuckgresBatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds, keep_locks=keep_locks)+ # keep_locks is meaningless for a lease sink (nothing is held), and the+ # base engine's keep-then-unlock sweep never runs for this adapter —+ # DuckgresBatchConsumer overrides _recovery_sweep.+ return await DuckgresBatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds)async def reconcile_failed_runs(self,@@ -327,6 +356,11 @@ class DuckgresBatchConsumerAdapter:*,batch: PendingBatch,) -> bool:+ # A batch retired mid-claim (supersede/replan) must abort the WHOLE+ # group with no status write: applying it could swap stale backfill data+ # over a rebuilt table, and its successors in this claim are retired too.+ if await DuckgresBatchQueue.is_failed(conn, batch_id=batch.id):+ raise OwnershipLostError(f"batch {batch.id} was terminally retired while claimed")already_applied = await DuckgresBatchQueue.has_applied(conn, batch=batch)if batch.is_final_batch:if not already_applied:@@ -345,19 +379,167 @@ class DuckgresBatchConsumerAdapter:class DuckgresBatchConsumer(SharedBatchConsumer):+ """The shared engine plus the sink's lease-safety overrides, kept out of the+ base engine so the delta consumer is unaffected: group-capped claiming+ (_fetch_batches), lease release on connect failure (_unlock_group),+ ownership-fenced error writes (_handle_batch_failure), and a fenced+ recovery sweep with no post-sweep lease release (_recovery_sweep).+ """+def __init__(self,config: DuckgresConsumerConfig,process_batch: ProcessBatchFn,health_reporter: Callable[[], None] | None = None,) -> None:+ # The adapter's boundary renewals must use the same TTL as the claim.+ adapter = DuckgresBatchConsumerAdapter(lease_ttl_seconds=config.lease_ttl_seconds or LEASE_TTL_SECONDS)super().__init__(config=config,process_batch=process_batch,- adapter=DuckgresBatchConsumerAdapter(),+ adapter=adapter,health_reporter=health_reporter,metrics=make_consumer_metrics("duckgres"),)+ self._duckgres_adapter = adapter++ async def _fetch_batches(self, conn: psycopg.AsyncConnection[Any], *, available: int) -> list[PendingBatch]:+ return await self._duckgres_adapter.fetch_and_lock(+ conn,+ # Full poll_limit, not the base _fetch_limit heuristic: one backfill+ # run legitimately co-claims many chunks, and max_groups below bounds+ # the over-claim by groups — the unit a lease covers.+ limit=self._config.poll_limit,+ retry_backoff_base_seconds=self._config.retry_backoff_base_seconds,+ owner_token=self._owner_token,+ lease_ttl_seconds=self._lease_ttl_seconds,+ # A leased-but-unstarted group is renewed by every poll and stays+ # dark to other pods, so never lease beyond our free slots.+ max_groups=available,+ # In-flight groups can't start again; re-claiming them starves+ # other schemas of the budget.+ exclude_groups=list(self._in_flight),+ )++ async def _unlock_group(+ self,+ group_conn: psycopg.AsyncConnection[Any] | None,+ batches: list[PendingBatch],+ *,+ team_id: int,+ schema_id: str,+ ) -> None:+ if group_conn is None:+ # Connect failed but the leases were claimed at fetch time. Release+ # them via the poll connection (release is token-scoped) or this+ # pod pins the groups — every poll renews its own leases.+ try:+ fallback_conn = await self._ensure_poll_conn()+ except Exception:+ return # queue DB fully unreachable; lease TTL is the backstop+ try:+ await self._duckgres_adapter.unlock(fallback_conn, batches=batches, owner_token=self._owner_token)+ except Exception as e:+ logger.exception(+ self._event("unlock_for_batches_failed"),+ team_id=team_id,+ external_data_schema_id=schema_id,+ )+ capture_exception(e)+ return+ await super()._unlock_group(group_conn, batches, team_id=team_id, schema_id=schema_id)++ async def _handle_batch_failure(+ self,+ batch: PendingBatch,+ attempt: int,+ err: Exception,+ *,+ lock_conn: psycopg.AsyncConnection[Any] | None,+ status_conn: psycopg.AsyncConnection[Any],+ ) -> None:+ # A worker can outlive its lease mid-batch; a stale writer must not+ # stamp waiting_retry — or fail the run — over the new owner's+ # lifecycle. Raising abandons the group with no status write.+ try:+ await self._verify_ownership(lock_conn, batch)+ except OwnershipLostError:+ logger.warning(+ self._event("ownership_lost_suppressing_error_status"),+ batch_id=batch.id,+ run_uuid=batch.run_uuid,+ error=str(err)[:500],+ )+ raise+ await super()._handle_batch_failure(batch, attempt, err, lock_conn=lock_conn, status_conn=status_conn)++ async def _recovery_sweep(self) -> None:+ conn = await self._ensure_recovery_conn()++ grace_seconds = self._config.recovery_grace_seconds+ assert grace_seconds is not None+ # Unlike the base sweep, no claims are released afterwards: the poll+ # loop can reclaim a just-requeued group (same owner token) mid-sweep,+ # and an owner-scoped delete would strip that fresh lease.+ stale = await self._duckgres_adapter.get_stale_executing(conn, grace_seconds=grace_seconds)+ if not stale:+ self._metrics.recovery_sweeps_total.labels(outcome="clean").inc()+ return++ self._metrics.recovery_sweeps_total.labels(outcome="orphans_found").inc()+ logger.info(self._event("recovery_sweep_found_stale_batches"), count=len(stale))++ recovery_bound_keys = (+ "team_id",+ "external_data_schema_id",+ "external_data_source_id",+ "external_data_job_id",+ "run_uuid",+ "batch_id",+ "resource_name",+ "log_source_id",+ "attempt",+ )+ for batch in stale:+ structlog.contextvars.bind_contextvars(+ team_id=batch.team_id,+ external_data_schema_id=batch.schema_id,+ external_data_source_id=batch.source_id,+ external_data_job_id=batch.job_id,+ run_uuid=batch.run_uuid,+ batch_id=batch.id,+ resource_name=batch.resource_name,+ log_source_id=batch.schema_id,+ attempt=batch.latest_attempt,+ )+ try:+ # Both writes are fenced inside the insert (still 'executing',+ # older than grace, no live lease): a batch that moved since+ # the unlocked scan is skipped, never clobbered.+ if batch.latest_attempt >= self._config.max_attempts:+ failed = await DuckgresBatchQueue.fail_run_if_stale(+ conn, batch=batch, reason="max retries exceeded (likely OOM)", grace_seconds=grace_seconds+ )+ if failed:+ logger.warning(+ self._event("batch_recovered_max_retries_exceeded"), attempt=batch.latest_attempt+ )+ self._metrics.runs_failed_total.inc()+ else:+ logger.info(self._event("batch_recovery_skipped_not_stale"), batch_id=batch.id)+ else:+ requeued = await DuckgresBatchQueue.requeue_stale_executing(+ conn,+ batch=batch,+ error_response={"error": "executing timed out - pod restart or OOM"},+ grace_seconds=grace_seconds,+ )+ if requeued:+ logger.warning(self._event("batch_recovered_for_retry"), attempt=batch.latest_attempt)+ else:+ logger.info(self._event("batch_recovery_skipped_not_stale"), batch_id=batch.id)+ finally:+ structlog.contextvars.unbind_contextvars(*recovery_bound_keys)__all__ = [diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.pyindex 140f3ec14fef..f78e52d4efa0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py@@ -11,11 +11,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (BATCH_TABLE,+ LEASE_TTL_SECONDS,PARTITION_PRUNING_INTERVAL,STATUS_TABLE,PendingBatch,pending_batch_select_columns,- unlock_advisory_locks,)DUCKGRES_STATUS_TABLE = "sourcebatchduckgresstatus"@@ -23,6 +23,9 @@ DUCKGRES_STATUS_TABLE = "sourcebatchduckgresstatus"# command. The eligibility queries here use per-batch LATERAL lookups instead.DUCKGRES_STATUS_VIEW = "v_latest_source_batch_duckgres_status"DUCKGRES_APPLY_TABLE = "sourcebatchduckgresapply"+# Twin of the delta queue's sourcegrouplease — separate table because both+# consumers process the same (team_id, schema_id) groups and must never contend.+DUCKGRES_LEASE_TABLE = "sourceduckgresgrouplease"def _latest_status_lateral(status_table: str, batch_alias: str) -> str:@@ -37,8 +40,6 @@ def _latest_status_lateral(status_table: str, batch_alias: str) -> str:)-DUCKGRES_ADVISORY_LOCK_NAMESPACE = 0x44475300 # "DGS\0" in hex-# Structured classification key written into duckgres status error_response by# every terminal-retire writer. Consumers (the backfill reconciler) dispatch on# this, not on error-message prose.@@ -148,17 +149,34 @@ class DuckgresBatchQueue:async def get_delta_succeeded_and_lock(conn: psycopg.AsyncConnection[Any],*,+ owner_token: str,limit: int = 50,retry_backoff_base_seconds: int = 0,team_ids: list[int] | None = None,blocked_schema_ids: list[str] | None = None,eligible_schema_ids: list[str] | None = None,+ lease_ttl_seconds: int = LEASE_TTL_SECONDS,+ max_groups: int | None = None,+ exclude_groups: list[tuple[int, str]] | None = None,) -> list[PendingBatch]:"""Fetch Duckgres-eligible batches whose Delta load has succeeded.Duckgres has its own sink state. A source batch is eligible only after theDelta consumer marks that exact batch row as succeeded.+ Group ownership is a ``sourceduckgresgrouplease`` row per+ (team_id, schema_id), claimed-or-renewed in the writable CTE like the+ delta queue's lease claim: free, own, or expired leases are claimable;+ another pod's live lease drops the group via ``JOIN claimed``. Unlike+ the old session advisory lock, an abandoned group simply expires.++ Mixed-version rollout is a single cutover (as with the delta queue's+ migration): the claim is pacing, not correctness — concurrent+ processors are arbitrated per batch by the duckgres-side apply marker+ (``DuckgresBatchAlreadyAppliedError``, a handled no-op). We deliberately+ do NOT probe the old advisory lock: a zombie session holding it would+ wedge the group indefinitely, the failure mode leases remove.+``retry_backoff_base_seconds`` gates the ``waiting_retry`` branch on the ageof the latest Duckgres status row, mirroring the Delta queue's backoff.@@ -178,6 +196,14 @@ class DuckgresBatchQueue:would apply them — including replace-head batches that bypass the unprimedblock. Computed by ``sink_eligible_schema_ids``.+ Intra-run head-of-line: LIVE batches stay strictly ordered (any+ unapplied lower batch_index blocks). Backfill CHUNKS relax this so a+ whole run drains in one claim: a pending predecessor blocks a chunk+ only when it cannot be returned AHEAD of it in this same fetch (see the+ gate's inline comments). Co-claimable predecessors sort earlier, land+ in the same group, and the group is processed strictly in order with a+ halt on first non-success — so chunk 0's CREATE still applies first.+Cross-run head-of-line: a batch is ineligible while an older run (by runstart time) of the same (team_id, schema_id) still has unapplied,non-failed data batches. Without this, a newer run's batch-0@@ -201,6 +227,24 @@ class DuckgresBatchQueue:b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'AND (%(team_ids)s::bigint[] IS NULL OR b.team_id = ANY(%(team_ids)s))AND (%(eligible_schema_ids)s::varchar[] IS NULL OR b.schema_id = ANY(%(eligible_schema_ids)s))+ -- In-flight groups: re-claiming them burns the LIMIT and+ -- max_groups budget on work this pod can't start.+ AND NOT (+ %(exclude_team_ids)s::bigint[] IS NOT NULL+ AND (b.team_id, b.schema_id) IN (+ SELECT * FROM unnest(%(exclude_team_ids)s::bigint[], %(exclude_schema_ids)s::varchar[])+ )+ )+ -- Other pods' live-leased groups are unclaimable; filter+ -- BEFORE the LIMIT or one leased backfill can fill the+ -- window and starve other schemas.+ AND NOT EXISTS (+ SELECT 1 FROM {DUCKGRES_LEASE_TABLE} bl+ WHERE bl.team_id = b.team_id+ AND bl.schema_id = b.schema_id+ AND bl.expires_at > now()+ AND bl.owner_token <> %(owner)s+ )AND NOT {BLOCKED_LIVE_BATCH_CONDITION}AND ds.job_state = 'succeeded'AND (@@ -239,6 +283,8 @@ class DuckgresBatchQueue:AND a.schema_id = prev.schema_idAND a.run_uuid = prev.run_uuidAND a.batch_index = prev.batch_index+ LEFT JOIN {_latest_status_lateral(STATUS_TABLE, "prev")} ds_prev ON true+ LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "prev")} dgs_prev ON trueWHERE prev.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'AND prev.team_id = b.team_idAND prev.schema_id = b.schema_id@@ -249,6 +295,27 @@ class DuckgresBatchQueue:OR (b.is_final_batch = true AND prev.batch_index <= b.batch_index))AND a.id IS NULL+ AND (+ -- LIVE batches: any unapplied predecessor blocks.+ {LIVE_BATCH_SQL_PREDICATE}+ -- Backfill chunks: block only on predecessors that+ -- cannot be co-claimed AHEAD of this chunk —+ -- not delta-succeeded (fail closed; enqueue_chunks+ -- writes chunks pre-succeeded atomically):+ OR ds_prev.job_state IS DISTINCT FROM 'succeeded'+ -- sorting later in the fetch order (a reconcile+ -- replay re-inserts dropped chunks with a fresh+ -- created_at):+ OR (prev.created_at, prev.batch_index) > (b.created_at, b.batch_index)+ OR dgs_prev.job_state = 'executing'+ OR dgs_prev.job_state = 'succeeded'+ OR (+ dgs_prev.job_state = 'waiting_retry'+ AND dgs_prev.created_at > now() - make_interval(+ secs => %(backoff)s * GREATEST(COALESCE(dgs_prev.attempt, 1), 1)+ )+ )+ ))AND (-- Cross-run head-of-line: an older non-failed run of this@@ -275,13 +342,36 @@ class DuckgresBatchQueue:)ORDER BY b.created_at ASC, b.batch_index ASC, b.is_final_batch ASCLIMIT %(limit)s+ ),+ candidate_groups AS (+ -- Cap leased groups to the consumer's free slots, oldest work+ -- first (NULL = no cap): a leased-but-unstarted group would be+ -- renewed by every poll and stay dark to other pods.+ SELECT c.team_id, c.schema_id+ FROM candidates c+ GROUP BY c.team_id, c.schema_id+ ORDER BY min(c.created_at) ASC, c.team_id ASC, c.schema_id ASC+ LIMIT COALESCE(%(max_groups)s, 2147483647)+ ),+ claimed AS (+ INSERT INTO {DUCKGRES_LEASE_TABLE} (team_id, schema_id, owner_token, expires_at, acquired_at, updated_at)+ SELECT team_id, schema_id, %(owner)s, now() + make_interval(secs => %(ttl)s), now(), now()+ FROM candidate_groups+ ON CONFLICT (team_id, schema_id) DO UPDATE+ SET owner_token = excluded.owner_token,+ expires_at = excluded.expires_at,+ acquired_at = CASE+ WHEN {DUCKGRES_LEASE_TABLE}.owner_token = excluded.owner_token THEN {DUCKGRES_LEASE_TABLE}.acquired_at+ ELSE now()+ END,+ updated_at = now()+ WHERE {DUCKGRES_LEASE_TABLE}.expires_at < now()+ OR {DUCKGRES_LEASE_TABLE}.owner_token = excluded.owner_token+ RETURNING team_id, schema_id)SELECT c.*FROM candidates c- WHERE pg_try_advisory_lock(- {DUCKGRES_ADVISORY_LOCK_NAMESPACE},- hashtext(c.team_id::text || ':' || c.schema_id)- )+ JOIN claimed USING (team_id, schema_id)ORDER BY c.created_at ASC, c.batch_index ASC, c.is_final_batch ASC""",{@@ -290,6 +380,11 @@ class DuckgresBatchQueue:"team_ids": team_ids,"blocked_schema_ids": blocked_schema_ids,"eligible_schema_ids": eligible_schema_ids,+ "owner": owner_token,+ "ttl": lease_ttl_seconds,+ "max_groups": max_groups,+ "exclude_team_ids": [team_id for team_id, _ in exclude_groups] if exclude_groups else None,+ "exclude_schema_ids": [schema_id for _, schema_id in exclude_groups] if exclude_groups else None,},)rows = await cur.fetchall()@@ -482,6 +577,181 @@ class DuckgresBatchQueue:},)+ @staticmethod+ async def update_status_unless_failed(+ conn: psycopg.AsyncConnection[Any],+ *,+ batch_id: str,+ job_state: str,+ attempt: int = 0,+ error_response: dict[str, Any] | None = None,+ ) -> bool:+ """Append a status row only if the batch's latest status is not terminal 'failed'.++ The consumer routes every status write through this so a terminal+ 'failed' (supersede/replan/fail_run can land at any point in a claimed+ batch's lifecycle) is never masked by a later row in the latest-status+ views. Guard and insert share one statement snapshot; returns False+ (writing nothing) when the batch is retired.++ Accepted residual: a failure writer whose statement overlaps this one+ can be mutually invisible. One statement wide, same class the supersede+ design accepts by skipping 'executing' victims, converges via the+ periodic sweeps — closing it needs a shared per-batch lock, not worth it.+ """+ cursor = await conn.execute(+ f"""+ INSERT INTO {DUCKGRES_STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)+ SELECT %(batch_id)s, %(job_state)s, %(attempt)s, now(), %(error_response)s, now()+ WHERE (+ SELECT cur.job_state+ FROM {DUCKGRES_STATUS_TABLE} cur+ WHERE cur.batch_id = %(batch_id)s+ ORDER BY cur.created_at DESC, cur.id DESC+ LIMIT 1+ ) IS DISTINCT FROM 'failed'+ """,+ {+ "batch_id": batch_id,+ "job_state": job_state,+ "attempt": attempt,+ "error_response": json.dumps(error_response) if error_response else None,+ },+ )+ return bool(cursor.rowcount)++ @staticmethod+ async def requeue_stale_executing(+ conn: psycopg.AsyncConnection[Any],+ *,+ batch: PendingBatch,+ error_response: dict[str, Any],+ grace_seconds: int,+ ) -> bool:+ """Flip a stale 'executing' batch to waiting_retry — fenced at write time.++ Between the unlocked stale scan and this write, the group can be+ reclaimed, a rival sweep can requeue first, or a leaseless live worker+ (old advisory-lock pod in the mixed-version window) can heartbeat a+ fresh 'executing'. The insert re-checks all of it in its own snapshot:+ latest status still 'executing', older than ``grace_seconds``, and no+ live lease. Returns False when skipped; a later sweep retries.+ """+ cursor = await conn.execute(+ f"""+ INSERT INTO {DUCKGRES_STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)+ SELECT %(batch_id)s, 'waiting_retry', %(attempt)s, now(), %(error_response)s, now()+ WHERE EXISTS (+ SELECT 1+ FROM (+ SELECT cur.job_state, cur.created_at+ FROM {DUCKGRES_STATUS_TABLE} cur+ WHERE cur.batch_id = %(batch_id)s+ ORDER BY cur.created_at DESC, cur.id DESC+ LIMIT 1+ ) latest+ WHERE latest.job_state = 'executing'+ AND latest.created_at <= now() - make_interval(secs => %(grace)s)+ )+ AND NOT EXISTS (+ SELECT 1 FROM {DUCKGRES_LEASE_TABLE} l+ WHERE l.team_id = %(team_id)s+ AND l.schema_id = %(schema_id)s+ AND l.expires_at > now()+ )+ """,+ {+ "batch_id": batch.id,+ "attempt": batch.latest_attempt,+ "error_response": json.dumps(error_response),+ "team_id": batch.team_id,+ "schema_id": batch.schema_id,+ "grace": grace_seconds,+ },+ )+ return bool(cursor.rowcount)++ @staticmethod+ async def fail_run_if_stale(+ conn: psycopg.AsyncConnection[Any],+ *,+ batch: PendingBatch,+ reason: str,+ grace_seconds: int,+ ) -> bool:+ """Terminally fail a run from recovery — fenced inside the insert itself.++ Same fence as ``requeue_stale_executing``, keyed on the anchor batch:+ the failure rows land only while its latest status is still 'executing',+ older than ``grace_seconds``, and the group has no live lease — all in+ this statement's snapshot. Returns False when the fence refuses. The+ group error path uses ``fail_run`` instead, since it legitimately fails+ runs while holding its own live lease.+ """+ cursor = await conn.execute(+ f"""+ INSERT INTO {DUCKGRES_STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)+ SELECT b.id, 'failed', 0, now(), %(error_response)s, now()+ FROM {BATCH_TABLE} b+ JOIN {_latest_status_lateral(STATUS_TABLE, "b")} ds ON true+ LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true+ WHERE+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND b.run_uuid = %(run_uuid)s+ AND ds.job_state = 'succeeded'+ AND (dgs.batch_id IS NULL OR dgs.job_state IN ('waiting_retry', 'executing'))+ AND EXISTS (+ SELECT 1+ FROM (+ SELECT anchor.job_state, anchor.created_at+ FROM {DUCKGRES_STATUS_TABLE} anchor+ WHERE anchor.batch_id = %(anchor_batch_id)s+ ORDER BY anchor.created_at DESC, anchor.id DESC+ LIMIT 1+ ) latest+ WHERE latest.job_state = 'executing'+ AND latest.created_at <= now() - make_interval(secs => %(grace)s)+ )+ AND NOT EXISTS (+ SELECT 1 FROM {DUCKGRES_LEASE_TABLE} l+ WHERE l.team_id = %(team_id)s+ AND l.schema_id = %(schema_id)s+ AND l.expires_at > now()+ )+ """,+ {+ "run_uuid": batch.run_uuid,+ "anchor_batch_id": batch.id,+ "team_id": batch.team_id,+ "schema_id": batch.schema_id,+ "error_response": json.dumps({"error": reason}),+ "grace": grace_seconds,+ },+ )+ return bool(cursor.rowcount)++ @staticmethod+ async def is_failed(+ conn: psycopg.AsyncConnection[Any],+ *,+ batch_id: str,+ ) -> bool:+ """Whether the batch's LATEST duckgres status is terminal 'failed' — the+ consumer's per-batch re-check for co-claimed batches retired mid-claim."""+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ SELECT job_state+ FROM {DUCKGRES_STATUS_TABLE}+ WHERE batch_id = %(batch_id)s+ ORDER BY created_at DESC, id DESC+ LIMIT 1+ """,+ {"batch_id": batch_id},+ )+ row = await cur.fetchone()+ return bool(row and row[0] == "failed")+@staticmethodasync def has_applied(conn: psycopg.AsyncConnection[Any],@@ -535,79 +805,122 @@ class DuckgresBatchQueue:return cursor.rowcount or 0@staticmethod- async def verify_advisory_lock(+ async def verify_lease(conn: psycopg.AsyncConnection[Any],*,team_id: int,schema_id: str,+ owner_token: str,) -> bool:- """Check if this session still holds the advisory lock for (team_id, schema_id)."""+ """Check whether ``owner_token`` still holds a live group lease for (team_id, schema_id)."""async with conn.cursor() as cur:await cur.execute(f"""SELECT EXISTS (- SELECT 1 FROM pg_locks- WHERE locktype = 'advisory'- AND classid = {DUCKGRES_ADVISORY_LOCK_NAMESPACE}- AND objid = hashtext(%(key)s)- AND pid = pg_backend_pid()- AND granted = true+ SELECT 1 FROM {DUCKGRES_LEASE_TABLE}+ WHERE team_id = %(team_id)s+ AND schema_id = %(schema_id)s+ AND owner_token = %(owner)s+ AND expires_at > now())""",- {"key": f"{team_id}:{schema_id}"},+ {"team_id": team_id, "schema_id": schema_id, "owner": owner_token},)row = await cur.fetchone()return bool(row and row[0])+ @staticmethod+ async def renew_lease(+ conn: psycopg.AsyncConnection[Any],+ *,+ team_id: int,+ schema_id: str,+ owner_token: str,+ lease_ttl_seconds: int = LEASE_TTL_SECONDS,+ ) -> bool:+ """Extend this owner's group lease. Returns False when lost (gone,+ reclaimed, or expired) — an expired lease must never be resurrected here+ (recovery may have re-queued the group); re-claiming goes through the+ fetch's claim CTE only.+ """+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ UPDATE {DUCKGRES_LEASE_TABLE}+ SET expires_at = now() + make_interval(secs => %(ttl)s), updated_at = now()+ WHERE team_id = %(team_id)s+ AND schema_id = %(schema_id)s+ AND owner_token = %(owner)s+ AND expires_at > now()+ RETURNING 1+ """,+ {"team_id": team_id, "schema_id": schema_id, "owner": owner_token, "ttl": lease_ttl_seconds},+ )+ return (await cur.fetchone()) is not None+@staticmethodasync def get_stale_executing(conn: psycopg.AsyncConnection[Any],*,grace_seconds: int = 0,- keep_locks: bool = False,) -> list[PendingBatch]:- """Find batches stuck in 'executing' whose advisory lock is not held (previous pod crashed).-- When ``keep_locks`` is True the caller is responsible for releasing the- probe locks after it has finished acting on the returned batches.- """+ """Find batches stuck in 'executing' whose group lease is absent or+ expired — unlike the old advisory-lock probe, an abandoned lease always+ expires, so orphaned groups are always reclaimable."""async with conn.cursor(row_factory=dict_row) as cur:await cur.execute(f"""- WITH candidates AS MATERIALIZED (- SELECT- {pending_batch_select_columns("dgs")}- FROM {BATCH_TABLE} b- JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true- WHERE- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND dgs.job_state = 'executing'- AND dgs.created_at <= now() - make_interval(secs => %(grace)s)- ORDER BY b.created_at ASC, b.batch_index ASC- )- SELECT c.*- FROM candidates c- WHERE pg_try_advisory_lock(- {DUCKGRES_ADVISORY_LOCK_NAMESPACE},- hashtext(c.team_id::text || ':' || c.schema_id)- )- ORDER BY c.created_at ASC, c.batch_index ASC+ SELECT+ {pending_batch_select_columns("dgs")}+ FROM {BATCH_TABLE} b+ JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true+ LEFT JOIN {DUCKGRES_LEASE_TABLE} l ON l.team_id = b.team_id AND l.schema_id = b.schema_id+ WHERE+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND dgs.job_state = 'executing'+ AND dgs.created_at <= now() - make_interval(secs => %(grace)s)+ AND (l.team_id IS NULL OR l.expires_at <= now())+ ORDER BY b.created_at ASC, b.batch_index ASC""",{"grace": grace_seconds},)rows = await cur.fetchall()- result = [PendingBatch(**row) for row in rows]-- if not keep_locks:- await DuckgresBatchQueue.unlock_for_batches(conn, batches=result)-- return result+ return [PendingBatch(**row) for row in rows]@staticmethodasync def unlock_for_batches(conn: psycopg.AsyncConnection[Any],*,batches: list[PendingBatch],+ owner_token: str,+ ) -> None:+ """Release the group leases for ``batches``' groups held by ``owner_token``+ — the owner predicate keeps this a no-op if another pod reclaimed the group."""+ pairs = list({(b.team_id, b.schema_id) for b in batches})+ if not pairs:+ return+ team_ids = [team_id for team_id, _ in pairs]+ schema_ids = [schema_id for _, schema_id in pairs]+ await conn.execute(+ f"""+ DELETE FROM {DUCKGRES_LEASE_TABLE}+ WHERE owner_token = %(owner)s+ AND (team_id, schema_id) IN (+ SELECT * FROM unnest(%(team_ids)s::bigint[], %(schema_ids)s::varchar[])+ )+ """,+ {"owner": owner_token, "team_ids": team_ids, "schema_ids": schema_ids},+ )++ @staticmethod+ async def release_all_owned_leases(+ conn: psycopg.AsyncConnection[Any],+ *,+ owner_token: str,) -> None:- await unlock_advisory_locks(conn, batches=batches, namespace=DUCKGRES_ADVISORY_LOCK_NAMESPACE)+ """Delete every group lease held by ``owner_token``. Best-effort cleanup on shutdown."""+ await conn.execute(+ f"DELETE FROM {DUCKGRES_LEASE_TABLE} WHERE owner_token = %(owner)s",+ {"owner": owner_token},+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.pyindex 3d3caddbea6e..f45816c0a5aa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py@@ -4,6 +4,11 @@ from typing import Anyimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch+import psycopg++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (+ OwnershipLostError,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer import (DuckgresBatchConsumer,DuckgresBatchConsumerAdapter,@@ -70,12 +75,22 @@ class TestDuckgresProcessSingle:async def track_status(conn, **kwargs):update_status_calls.append(kwargs)+ return Truewith (patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status",side_effect=track_status,),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",+ side_effect=track_status,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.is_failed",+ new_callable=AsyncMock,+ return_value=False,+ ),patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",new_callable=AsyncMock,@@ -94,12 +109,22 @@ class TestDuckgresProcessSingle:async def track_status(conn, *, batch_id, job_state, attempt, error_response=None):states.append(job_state)+ return Truewith (patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status",side_effect=track_status,),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",+ side_effect=track_status,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.is_failed",+ new_callable=AsyncMock,+ return_value=False,+ ),patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",new_callable=AsyncMock,@@ -125,6 +150,16 @@ class TestDuckgresProcessSingle:"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status",new_callable=AsyncMock,),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",+ new_callable=AsyncMock,+ return_value=True,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.is_failed",+ new_callable=AsyncMock,+ return_value=False,+ ),patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",new_callable=AsyncMock,@@ -148,12 +183,22 @@ class TestDuckgresProcessSingle:async def track_status(conn, *, batch_id, job_state, attempt, error_response=None):states.append(job_state)+ return Truewith (patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status",side_effect=track_status,),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",+ side_effect=track_status,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.is_failed",+ new_callable=AsyncMock,+ return_value=False,+ ),patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",new_callable=AsyncMock,@@ -187,7 +232,13 @@ class TestDuckgresEnablementGating:new_callable=AsyncMock,) as mock_fetch:batches = await adapter.fetch_and_lock(- conn, limit=50, retry_backoff_base_seconds=0, owner_token="test-owner", lease_ttl_seconds=300+ conn,+ limit=50,+ retry_backoff_base_seconds=0,+ owner_token="test-owner",+ lease_ttl_seconds=300,+ max_groups=16,+ exclude_groups=[],)assert batches == []@@ -229,13 +280,22 @@ class TestDuckgresEnablementGating:),):await adapter.fetch_and_lock(- conn, limit=50, retry_backoff_base_seconds=30, owner_token="test-owner", lease_ttl_seconds=300+ conn,+ limit=50,+ retry_backoff_base_seconds=30,+ owner_token="test-owner",+ lease_ttl_seconds=300,+ max_groups=16,+ exclude_groups=[],)assert mock_fetch.call_args[1]["team_ids"] == [1, 2]assert mock_fetch.call_args[1]["retry_backoff_base_seconds"] == 30assert mock_fetch.call_args[1]["blocked_schema_ids"] == ["blocked-schema"]assert mock_fetch.call_args[1]["eligible_schema_ids"] == ["eligible-schema"]+ assert mock_fetch.call_args[1]["owner_token"] == "test-owner"+ assert mock_fetch.call_args[1]["lease_ttl_seconds"] == 300+ assert mock_fetch.call_args[1]["max_groups"] == 16mock_supersede.assert_called_once()mock_backlog.assert_called_once()mock_planner.assert_called_once_with([1, 2])@@ -268,7 +328,13 @@ class TestDuckgresEnablementGating:),):batches = await adapter.fetch_and_lock(- conn, limit=50, retry_backoff_base_seconds=0, owner_token="test-owner", lease_ttl_seconds=300+ conn,+ limit=50,+ retry_backoff_base_seconds=0,+ owner_token="test-owner",+ lease_ttl_seconds=300,+ max_groups=16,+ exclude_groups=[],)assert batches == []@@ -311,13 +377,209 @@ class TestDuckgresEnablementGating:),):batches = await adapter.fetch_and_lock(- conn, limit=50, retry_backoff_base_seconds=0, owner_token="test-owner", lease_ttl_seconds=300+ conn,+ limit=50,+ retry_backoff_base_seconds=0,+ owner_token="test-owner",+ lease_ttl_seconds=300,+ max_groups=16,+ exclude_groups=[],)assert batches == []mock_fetch.assert_not_called()+class TestMidClaimRetire:+ @pytest.mark.asyncio+ async def test_terminally_retired_batch_aborts_group_without_any_status_write(self):+ # A chunk retired mid-claim must abort the whole group with NO status+ # write — even an 'executing' row would mask the terminal 'failed'.+ consumer = _make_consumer()+ consumer._process_batch = AsyncMock()++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.is_failed",+ new_callable=AsyncMock,+ return_value=True,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status",+ new_callable=AsyncMock,+ ) as mock_status,+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",+ new_callable=AsyncMock,+ ) as mock_status_unless_failed,+ pytest.raises(OwnershipLostError),+ ):+ await consumer._process_single(_make_batch())++ consumer._process_batch.assert_not_called()+ mock_status.assert_not_called()+ mock_status_unless_failed.assert_not_called()++ @pytest.mark.asyncio+ async def test_status_write_blocked_by_terminal_failed_aborts_group(self):+ # Any status write blocked by a terminal 'failed' means the batch was+ # retired while claimed; stamping a later status would un-retire it.+ adapter = DuckgresBatchConsumerAdapter()+ conn = _make_healthy_conn()++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",+ new_callable=AsyncMock,+ return_value=False,+ ):+ with pytest.raises(OwnershipLostError):+ await adapter.update_status(+ conn,+ batch_id="00000000-0000-0000-0000-000000000001",+ job_state=SourceBatchDuckgresStatus.State.SUCCEEDED.value,+ attempt=1,+ )+++class TestGroupLeaseRenewal:+ @pytest.mark.asyncio+ async def test_boundary_ownership_check_extends_the_lease(self):+ # Quick chunks never trigger in-batch heartbeats, so the per-batch+ # ownership check must renew the lease or a long group loses it mid-run.+ adapter = DuckgresBatchConsumerAdapter(lease_ttl_seconds=900)+ conn = _make_healthy_conn()++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.renew_lease",+ new_callable=AsyncMock,+ return_value=True,+ ) as mock_renew:+ owns = await adapter.verify_advisory_lock(conn, team_id=1, schema_id="schema-1", owner_token="owner-a")++ assert owns is True+ assert mock_renew.call_args[1]["lease_ttl_seconds"] == 900+++class TestErrorPathOwnershipFencing:+ @pytest.mark.asyncio+ async def test_error_status_suppressed_when_ownership_lost_mid_batch(self):+ # A worker that outlived its lease must abandon with no write, not+ # stamp waiting_retry (or fail the run) over the new owner's lifecycle.+ consumer = _make_consumer(max_attempts=3)+ consumer._process_batch = AsyncMock(side_effect=ValueError("boom"))+ lock_conn = _make_healthy_conn()+ states: list[str] = []++ async def track_status(conn, *, batch_id, job_state, attempt, error_response=None):+ states.append(job_state)+ return True++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",+ side_effect=track_status,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.renew_lease",+ new_callable=AsyncMock,+ side_effect=[True, False], # start-of-batch check passes; error-path check fails+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.is_failed",+ new_callable=AsyncMock,+ return_value=False,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",+ new_callable=AsyncMock,+ return_value=False,+ ),+ patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail,+ pytest.raises(OwnershipLostError),+ ):+ await consumer._process_single(_make_batch(), lock_conn=lock_conn)++ mock_fail.assert_not_called()+ assert SourceBatchDuckgresStatus.State.WAITING_RETRY not in states+++class TestGroupConnectionFailure:+ @pytest.mark.asyncio+ async def test_leases_released_when_group_connection_fails(self):+ # A failed group-connection open must still release the fetch-time+ # leases via the poll conn, or every poll renews them indefinitely.+ consumer = _make_consumer()+ batches = [_make_batch()]++ with (+ patch.object(consumer, "_connect", new_callable=AsyncMock, side_effect=psycopg.OperationalError("no conn")),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.unlock_for_batches",+ new_callable=AsyncMock,+ ) as mock_unlock,+ ):+ await consumer._process_group_tracked((1, "schema-1"), batches)++ mock_unlock.assert_called_once_with(consumer._poll_conn, batches=batches, owner_token=consumer._owner_token)+++class TestFencedRecoverySweep:+ @pytest.mark.asyncio+ @pytest.mark.parametrize("fenced_result", [True, False])+ async def test_stale_batch_requeued_only_through_the_fenced_write(self, fenced_result):+ # The sweep must requeue via the write-time fence and never release+ # leases afterwards (the poll loop can reclaim a group mid-sweep).+ consumer = _make_consumer(max_attempts=3)+ stale_batch = _make_batch(latest_attempt=1)++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_stale_executing",+ new_callable=AsyncMock,+ return_value=[stale_batch],+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.requeue_stale_executing",+ new_callable=AsyncMock,+ return_value=fenced_result,+ ) as mock_requeue,+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.unlock_for_batches",+ new_callable=AsyncMock,+ ) as mock_unlock,+ ):+ await consumer._recovery_sweep()++ mock_requeue.assert_called_once()+ assert mock_requeue.call_args[1]["grace_seconds"] == consumer._config.recovery_grace_seconds+ mock_unlock.assert_not_called()++ @pytest.mark.asyncio+ @pytest.mark.parametrize("fenced_result", [True, False])+ async def test_exhausted_stale_batch_failed_only_through_the_fenced_write(self, fenced_result):+ consumer = _make_consumer(max_attempts=3)+ stale_batch = _make_batch(latest_attempt=3)++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_stale_executing",+ new_callable=AsyncMock,+ return_value=[stale_batch],+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.fail_run_if_stale",+ new_callable=AsyncMock,+ return_value=fenced_result,+ ) as mock_fenced_fail,+ patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_unfenced,+ ):+ await consumer._recovery_sweep()++ mock_fenced_fail.assert_called_once()+ assert "max retries exceeded" in mock_fenced_fail.call_args[1]["reason"]+ mock_unfenced.assert_not_called()++class TestStuckBatchWatchdog:@pytest.mark.asyncioasync def test_health_withheld_while_a_batch_is_stuck(self):diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.pyindex abdfe441d9f6..889965a45ebd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py@@ -6,6 +6,7 @@ import psycopgfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.jobs_db import (DUCKGRES_APPLY_TABLE,+ DUCKGRES_LEASE_TABLE,DUCKGRES_STATUS_TABLE,DUCKGRES_STATUS_VIEW,DuckgresBatchQueue,@@ -115,11 +116,23 @@ def _ensure_tables(conn: psycopg.Connection[Any]) -> None:CONSTRAINT sgl_team_schema_uniq UNIQUE (team_id, schema_id))""")+ conn.execute(f"""+ CREATE TABLE IF NOT EXISTS {DUCKGRES_LEASE_TABLE} (+ id BIGSERIAL PRIMARY KEY,+ team_id BIGINT NOT NULL,+ schema_id VARCHAR(200) 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 sdgl_team_schema_uniq UNIQUE (team_id, schema_id)+ )+ """)def _truncate_tables(conn: psycopg.Connection[Any]) -> None:conn.execute(- f"TRUNCATE {DUCKGRES_APPLY_TABLE}, {DUCKGRES_STATUS_TABLE}, {STATUS_TABLE}, {BATCH_TABLE}, {LEASE_TABLE} RESTART IDENTITY CASCADE"+ f"TRUNCATE {DUCKGRES_APPLY_TABLE}, {DUCKGRES_STATUS_TABLE}, {STATUS_TABLE}, {BATCH_TABLE}, {LEASE_TABLE}, {DUCKGRES_LEASE_TABLE} RESTART IDENTITY CASCADE")@@ -179,7 +192,7 @@ class TestDuckgresBatchQueueEligibility:async def test_ignores_batches_until_delta_succeeds(self, conn):await _insert_batch(conn)- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert batches == []@@ -188,7 +201,7 @@ class TestDuckgresBatchQueueEligibility:batch_id = await _insert_batch(conn)await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert len(batches) == 1assert str(batches[0].id) == batch_id@@ -199,7 +212,7 @@ class TestDuckgresBatchQueueEligibility:await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)await DuckgresBatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert batches == []@@ -209,7 +222,7 @@ class TestDuckgresBatchQueueEligibility:await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)await DuckgresBatchQueue.update_status(conn, batch_id=batch_id, job_state="waiting_retry", attempt=1)- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert len(batches) == 1assert batches[0].latest_attempt == 1@@ -221,7 +234,7 @@ class TestDuckgresBatchQueueEligibility:await BatchQueue.update_status(conn, batch_id=first_id, job_state="succeeded", attempt=1)await BatchQueue.update_status(conn, batch_id=second_id, job_state="succeeded", attempt=1)- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert [batch.batch_index for batch in batches] == [0]@@ -232,13 +245,13 @@ class TestDuckgresBatchQueueEligibility:await BatchQueue.update_status(conn, batch_id=data_id, job_state="succeeded", attempt=1)await BatchQueue.update_status(conn, batch_id=final_id, job_state="succeeded", attempt=1)- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert [str(batch.id) for batch in batches] == [data_id]await DuckgresBatchQueue.mark_applied(conn, batch=batches[0])- await DuckgresBatchQueue.unlock_for_batches(conn, batches=batches)+ await DuckgresBatchQueue.unlock_for_batches(conn, batches=batches, owner_token="owner-a")- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert [str(batch.id) for batch in batches] == [final_id]@pytest.mark.asyncio@@ -248,7 +261,7 @@ class TestDuckgresBatchQueueEligibility:failed_id = await _insert_batch(conn, batch_index=1)await BatchQueue.update_status(conn, batch_id=failed_id, job_state="failed", attempt=1)- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert batches == []@@ -260,7 +273,7 @@ class TestDuckgresBatchQueueEligibility:await BatchQueue.update_status(conn, batch_id=failed_id, job_state="succeeded", attempt=1)await DuckgresBatchQueue.update_status(conn, batch_id=failed_id, job_state="failed", attempt=3)- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert batches == []@@ -298,7 +311,7 @@ class TestDuckgresCrossRunOrdering:new0 = await _insert_batch(conn, run_uuid="run-2", batch_index=0)await BatchQueue.update_status(conn, batch_id=new0, job_state="succeeded", attempt=1)- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")# Only the older run's next batch is eligible; run-2 waits behind it.assert [(b.run_uuid, b.batch_index) for b in batches] == [("run-1", 1)]@@ -312,7 +325,7 @@ class TestDuckgresCrossRunOrdering:new0 = await _insert_batch(conn, run_uuid="run-2", batch_index=0)await BatchQueue.update_status(conn, batch_id=new0, job_state="succeeded", attempt=1)- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert [(b.run_uuid, b.batch_index) for b in batches] == [("run-2", 0)]@@ -332,7 +345,7 @@ class TestDuckgresCrossRunOrdering:superseded = await DuckgresBatchQueue.supersede_replaced_runs(conn)assert superseded == 1 # run-1's pending batch 1- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert [(b.run_uuid, b.batch_index) for b in batches] == [("run-2", 0)]@pytest.mark.asyncio@@ -348,7 +361,7 @@ class TestDuckgresCrossRunOrdering:superseded = await DuckgresBatchQueue.supersede_replaced_runs(conn)assert superseded == 0- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert [(b.run_uuid, b.batch_index) for b in batches] == [("run-1", 0)]@@ -359,10 +372,15 @@ class TestDuckgresTeamFilterAndBacklog:batch_id = await _insert_batch(conn, team_id=1)await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- # Advisory locks are session-reentrant, so repeated fetches on one conn are fine.- assert await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, team_ids=[2]) == []- assert len(await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, team_ids=[1, 2])) == 1- assert len(await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, team_ids=None)) == 1+ # The same owner re-claims its own lease, so repeated fetches are fine.+ assert await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a", team_ids=[2]) == []+ assert (+ len(await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a", team_ids=[1, 2]))+ == 1+ )+ assert (+ len(await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a", team_ids=None)) == 1+ )@pytest.mark.asyncioasync def test_backlog_stats(self, conn):@@ -401,8 +419,20 @@ class TestBackfillGating:batch_id = await _insert_batch(conn, sync_type="incremental")await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- assert await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, blocked_schema_ids=["schema-1"]) == []- assert len(await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, blocked_schema_ids=["other"])) == 1+ assert (+ await DuckgresBatchQueue.get_delta_succeeded_and_lock(+ conn, owner_token="owner-a", blocked_schema_ids=["schema-1"]+ )+ == []+ )+ assert (+ len(+ await DuckgresBatchQueue.get_delta_succeeded_and_lock(+ conn, owner_token="owner-a", blocked_schema_ids=["other"]+ )+ )+ == 1+ )@pytest.mark.asyncioasync def test_backfill_batches_pass_the_block(self, conn):@@ -415,7 +445,9 @@ class TestBackfillGating:)await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, blocked_schema_ids=["schema-1"])+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(+ conn, owner_token="owner-a", blocked_schema_ids=["schema-1"]+ )assert [b.run_uuid for b in batches] == ["duckgres-backfill-schema-1-v7"]@@ -456,7 +488,7 @@ class TestBackfillQueueContracts:assert await BatchQueue.get_unprocessed_and_lock(conn, owner_token="test-owner") == []- duck = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ duck = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert [str(b.id) for b in duck] == [batch_id]@pytest.mark.asyncio@@ -476,7 +508,9 @@ class TestBackfillQueueContracts:)await BatchQueue.update_status(conn, batch_id=chunk, job_state="succeeded", attempt=1)- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, blocked_schema_ids=["schema-1"])+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(+ conn, owner_token="owner-a", blocked_schema_ids=["schema-1"]+ )assert [str(b.id) for b in batches] == [chunk]@pytest.mark.asyncio@@ -495,7 +529,7 @@ class TestBackfillQueueContracts:# Schema primed (not blocked) but the backfill run is older and# incomplete: the live batch must wait.- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert [str(b.id) for b in batches] == [chunk]@pytest.mark.asyncio@@ -534,7 +568,7 @@ class TestBackfillQueueContracts:# The straddling sibling is NOT lost: its head-of-line prev is satisfied# by the pre-apply marker, the run is not failed, and it remains the# schema's claimable work (post-swap it applies as a live batch).- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")assert [str(b.id) for b in batches] == [late_b]@pytest.mark.asyncio@@ -551,7 +585,9 @@ class TestBackfillQueueContracts:# Retire the plain run first so the cross-run gate isn't what hides it.await DuckgresBatchQueue.update_status(conn, batch_id=plain, job_state="failed", attempt=1)- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, blocked_schema_ids=["schema-1"])+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(+ conn, owner_token="owner-a", blocked_schema_ids=["schema-1"]+ )assert [str(b.id) for b in batches] == [head]@pytest.mark.asyncio@@ -565,7 +601,9 @@ class TestBackfillQueueContracts:await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)async def claim(eligible: list[str] | None) -> list[Any]:- return await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, eligible_schema_ids=eligible)+ return await DuckgresBatchQueue.get_delta_succeeded_and_lock(+ conn, owner_token="owner-a", eligible_schema_ids=eligible+ )assert len(await claim(None)) == 1assert len(await claim(["schema-1"])) == 1@@ -580,10 +618,312 @@ class TestBackfillQueueContracts:head = await _insert_batch(conn, run_uuid="run-refresh", sync_type="full_refresh", batch_index=0)await BatchQueue.update_status(conn, batch_id=head, job_state="succeeded", attempt=1)- bypasses = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, blocked_schema_ids=["schema-1"])+ bypasses = await DuckgresBatchQueue.get_delta_succeeded_and_lock(+ conn, owner_token="owner-a", blocked_schema_ids=["schema-1"]+ )assert [str(b.id) for b in bypasses] == [head]gated = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, blocked_schema_ids=["schema-1"], eligible_schema_ids=["other-schema"]+ conn, owner_token="owner-a", blocked_schema_ids=["schema-1"], eligible_schema_ids=["other-schema"])assert gated == []+++async def _insert_chunk(+ conn: psycopg.AsyncConnection[Any],+ *,+ batch_index: int,+ chunk_count: int = 3,+ run_uuid: str = "duckgres-backfill-schema-1-v1-g00000000",+ delta_succeeded: bool = True,+) -> str:+ batch_id = await _insert_batch(+ conn,+ run_uuid=run_uuid,+ job_id="duckgres-backfill",+ is_resume=True,+ batch_index=batch_index,+ metadata={+ "duckgres_backfill": True,+ "chunk_paths": [f"s3://b/c{batch_index}.parquet"],+ "chunk_count": chunk_count,+ },+ )+ if delta_succeeded:+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)+ return batch_id++[email protected]_db(transaction=True)+class TestBackfillChunkClaiming:+ @pytest.mark.asyncio+ async def test_whole_backfill_run_claimable_in_one_fetch(self, conn):+ for i in range(3):+ await _insert_chunk(conn, batch_index=i)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")++ # Chunks must come back in index order: the group loop applies them+ # sequentially, so chunk 0's CREATE always lands before the inserts.+ assert [b.batch_index for b in batches] == [0, 1, 2]++ @pytest.mark.asyncio+ async def test_chunks_blocked_behind_executing_predecessor(self, conn):+ chunk0 = await _insert_chunk(conn, batch_index=0)+ await _insert_chunk(conn, batch_index=1)+ await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="executing", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")++ assert batches == []++ @pytest.mark.asyncio+ async def test_replayed_predecessor_with_newer_created_at_blocks_successor(self, conn):+ # A reconcile replay re-inserts chunk 0 with a fresh created_at, so it+ # sorts AFTER chunk 1; chunk 1 must stay blocked until chunk 0 applies+ # (co-claiming it would apply before the CREATE — data loss).+ await _insert_chunk(conn, batch_index=1, chunk_count=2)+ chunk0 = await _insert_chunk(conn, batch_index=0, chunk_count=2)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")+ assert [b.batch_index for b in batches] == [0]++ await _mark_applied_raw(+ conn, batch_id=chunk0, run_uuid="duckgres-backfill-schema-1-v1-g00000000", batch_index=0+ )+ await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="succeeded", attempt=1)+ await DuckgresBatchQueue.unlock_for_batches(conn, batches=batches, owner_token="owner-a")++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")+ assert [b.batch_index for b in batches] == [1]++ @pytest.mark.asyncio+ async def test_chunks_blocked_behind_non_delta_succeeded_predecessor(self, conn):+ # enqueue_chunks writes chunks pre-succeeded atomically, so this state+ # shouldn't exist — the gate must fail closed anyway.+ await _insert_chunk(conn, batch_index=0, delta_succeeded=False)+ await _insert_chunk(conn, batch_index=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")++ assert batches == []++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "backoff_seconds,expected_indexes",+ [+ (3600, []), # predecessor inside its backoff window gates the run+ (0, [0, 1]), # backoff elapsed: predecessor and successor co-claim+ ],+ )+ async def test_retry_backoff_gates_successor_chunks(self, conn, backoff_seconds, expected_indexes):+ chunk0 = await _insert_chunk(conn, batch_index=0, chunk_count=2)+ await _insert_chunk(conn, batch_index=1, chunk_count=2)+ await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="waiting_retry", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(+ conn, owner_token="owner-a", retry_backoff_base_seconds=backoff_seconds+ )++ assert [b.batch_index for b in batches] == expected_indexes++ @pytest.mark.asyncio+ async def test_executing_insert_refuses_when_latest_status_is_failed(self, conn):+ # A supersede landing between the retire check and the executing write+ # must block the insert, or the new row masks the terminal 'failed'.+ chunk0 = await _insert_chunk(conn, batch_index=0)++ assert await DuckgresBatchQueue.update_status_unless_failed(conn, batch_id=chunk0, job_state="executing")+ await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="failed", attempt=0)++ assert not await DuckgresBatchQueue.update_status_unless_failed(conn, batch_id=chunk0, job_state="executing")+ assert await DuckgresBatchQueue.is_failed(conn, batch_id=chunk0)++ # A reset-style revive (fresh non-failed status) reopens the path.+ await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="waiting_retry", attempt=1)+ assert await DuckgresBatchQueue.update_status_unless_failed(conn, batch_id=chunk0, job_state="executing")++ @pytest.mark.asyncio+ async def test_is_failed_tracks_latest_status(self, conn):+ # The mid-claim retire check must see a 'failed' written under a+ # claimed chunk, and a later status must clear it (latest-row wins).+ chunk0 = await _insert_chunk(conn, batch_index=0)+ assert not await DuckgresBatchQueue.is_failed(conn, batch_id=chunk0)++ await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="failed", attempt=0)+ assert await DuckgresBatchQueue.is_failed(conn, batch_id=chunk0)++ await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="succeeded", attempt=1)+ assert not await DuckgresBatchQueue.is_failed(conn, batch_id=chunk0)++ @pytest.mark.asyncio+ async def test_applied_predecessor_does_not_block(self, conn):+ chunk0 = await _insert_chunk(conn, batch_index=0)+ await _insert_chunk(conn, batch_index=1)+ await _mark_applied_raw(+ conn, batch_id=chunk0, run_uuid="duckgres-backfill-schema-1-v1-g00000000", batch_index=0+ )+ await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="succeeded", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")++ assert [b.batch_index for b in batches] == [1]++[email protected]_db(transaction=True)+class TestDuckgresGroupLease:+ @pytest.mark.asyncio+ async def test_live_lease_blocks_other_owner_until_released(self, conn):+ batch_id = await _insert_batch(conn)+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)++ claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")+ assert len(claimed) == 1++ assert await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-b") == []++ # A non-owner's unlock must not release owner-a's lease.+ await DuckgresBatchQueue.unlock_for_batches(conn, batches=claimed, owner_token="owner-b")+ assert await DuckgresBatchQueue.verify_lease(conn, team_id=1, schema_id="schema-1", owner_token="owner-a")++ await DuckgresBatchQueue.unlock_for_batches(conn, batches=claimed, owner_token="owner-a")+ assert len(await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-b")) == 1++ @pytest.mark.asyncio+ async def test_max_groups_caps_leased_groups_leaving_the_rest_claimable(self, conn):+ # A pod must not lease groups it has no slot to start — every poll+ # renews them, blocking other pods.+ older = await _insert_batch(conn, schema_id="schema-1")+ await BatchQueue.update_status(conn, batch_id=older, job_state="succeeded", attempt=1)+ newer = await _insert_batch(conn, schema_id="schema-2")+ await BatchQueue.update_status(conn, batch_id=newer, job_state="succeeded", attempt=1)++ capped = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a", max_groups=1)+ assert [str(b.id) for b in capped] == [older]++ # The uncapped group carries no lease, so another owner claims it now.+ other = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-b", max_groups=1)+ assert [str(b.id) for b in other] == [newer]++ @pytest.mark.asyncio+ async def test_excluded_in_flight_groups_do_not_consume_the_claim_budget(self, conn):+ # Re-claiming an in-flight group burns the max_groups budget and+ # starves other schemas.+ mine = await _insert_batch(conn, schema_id="schema-1")+ await BatchQueue.update_status(conn, batch_id=mine, job_state="succeeded", attempt=1)+ other = await _insert_batch(conn, schema_id="schema-2")+ await BatchQueue.update_status(conn, batch_id=other, job_state="succeeded", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(+ conn, owner_token="owner-a", max_groups=1, exclude_groups=[(1, "schema-1")]+ )++ assert [str(b.id) for b in batches] == [other]++ @pytest.mark.asyncio+ async def test_other_owners_leased_group_cannot_flood_the_candidate_limit(self, conn):+ # Another pod's leased backfill must be filtered BEFORE the candidate+ # LIMIT, or its chunks fill the window and hide other schemas' work.+ for i in range(3):+ await _insert_chunk(conn, batch_index=i)+ claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-b")+ assert len(claimed) == 3 # owner-b holds the group's lease; chunks stay statusless++ live = await _insert_batch(conn, schema_id="schema-2")+ await BatchQueue.update_status(conn, batch_id=live, job_state="succeeded", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a", limit=3)++ assert [str(b.id) for b in batches] == [live]++ @pytest.mark.asyncio+ async def test_expired_lease_is_reclaimable_by_another_owner(self, conn):+ batch_id = await _insert_batch(conn)+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)+ await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")+ await conn.execute(f"UPDATE {DUCKGRES_LEASE_TABLE} SET expires_at = now() - interval '1 second'")++ # An expired lease is dead even for its original owner — the only way+ # back in is the fetch's claim CTE.+ assert not await DuckgresBatchQueue.renew_lease(conn, team_id=1, schema_id="schema-1", owner_token="owner-a")++ assert len(await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-b")) == 1+ assert not await DuckgresBatchQueue.renew_lease(conn, team_id=1, schema_id="schema-1", owner_token="owner-a")+ assert await DuckgresBatchQueue.renew_lease(conn, team_id=1, schema_id="schema-1", owner_token="owner-b")++ @pytest.mark.asyncio+ async def test_requeue_is_fenced_on_live_lease_and_current_status(self, conn):+ # The requeue write must re-check lease and status in its own snapshot,+ # or the scan-to-write gap stamps waiting_retry into an owned group.+ batch_id = await _insert_batch(conn)+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)+ claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")+ await DuckgresBatchQueue.update_status(conn, batch_id=batch_id, job_state="executing", attempt=1)++ # Live lease (owner-a) → requeue and terminal failure must refuse.+ assert not await DuckgresBatchQueue.requeue_stale_executing(+ conn, batch=claimed[0], error_response={"error": "timed out"}, grace_seconds=0+ )+ assert not await DuckgresBatchQueue.fail_run_if_stale(+ conn, batch=claimed[0], reason="timed out", grace_seconds=0+ )+ assert not await DuckgresBatchQueue.is_failed(conn, batch_id=batch_id)++ await conn.execute(f"UPDATE {DUCKGRES_LEASE_TABLE} SET expires_at = now() - interval '1 second'")+ assert await DuckgresBatchQueue.requeue_stale_executing(+ conn, batch=claimed[0], error_response={"error": "timed out"}, grace_seconds=0+ )++ # Latest is now waiting_retry: a rival sweep's second requeue is a+ # no-op, and the fenced terminal failure no longer fires either.+ assert not await DuckgresBatchQueue.requeue_stale_executing(+ conn, batch=claimed[0], error_response={"error": "timed out"}, grace_seconds=0+ )+ assert not await DuckgresBatchQueue.fail_run_if_stale(+ conn, batch=claimed[0], reason="timed out", grace_seconds=0+ )++ @pytest.mark.asyncio+ async def test_fresh_executing_heartbeat_blocks_recovery_writes(self, conn):+ # An old advisory-lock pod processes leaselessly, heartbeating fresh+ # 'executing' rows; recovery writes must re-check the status AGE or+ # they requeue/fail a batch that is demonstrably alive.+ batch_id = await _insert_batch(conn)+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)+ claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")+ await DuckgresBatchQueue.update_status(conn, batch_id=batch_id, job_state="executing", attempt=1)+ await conn.execute(f"UPDATE {DUCKGRES_LEASE_TABLE} SET expires_at = now() - interval '1 second'")++ assert not await DuckgresBatchQueue.requeue_stale_executing(+ conn, batch=claimed[0], error_response={"error": "timed out"}, grace_seconds=3600+ )+ assert not await DuckgresBatchQueue.fail_run_if_stale(+ conn, batch=claimed[0], reason="max retries exceeded", grace_seconds=3600+ )+ assert not await DuckgresBatchQueue.is_failed(conn, batch_id=batch_id)++ @pytest.mark.asyncio+ async def test_fenced_terminal_failure_fires_only_while_stale_and_unowned(self, conn):+ batch_id = await _insert_batch(conn)+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)+ claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")+ await DuckgresBatchQueue.update_status(conn, batch_id=batch_id, job_state="executing", attempt=3)+ await conn.execute(f"UPDATE {DUCKGRES_LEASE_TABLE} SET expires_at = now() - interval '1 second'")++ assert await DuckgresBatchQueue.fail_run_if_stale(+ conn, batch=claimed[0], reason="max retries exceeded", grace_seconds=0+ )+ assert await DuckgresBatchQueue.is_failed(conn, batch_id=batch_id)++ @pytest.mark.asyncio+ async def test_stale_executing_visible_only_after_lease_expiry(self, conn):+ batch_id = await _insert_batch(conn)+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)+ await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")+ await DuckgresBatchQueue.update_status(conn, batch_id=batch_id, job_state="executing", attempt=1)++ assert await DuckgresBatchQueue.get_stale_executing(conn, grace_seconds=0) == []++ await conn.execute(f"UPDATE {DUCKGRES_LEASE_TABLE} SET expires_at = now() - interval '1 second'")+ stale = await DuckgresBatchQueue.get_stale_executing(conn, grace_seconds=0)+ assert [str(b.id) for b in stale] == [batch_id]diff --git a/products/warehouse_sources_queue/backend/migrations/0005_duckgres_group_lease.py b/products/warehouse_sources_queue/backend/migrations/0005_duckgres_group_lease.pynew file mode 100644index 000000000000..fd2422e4bd84--- /dev/null+++ b/products/warehouse_sources_queue/backend/migrations/0005_duckgres_group_lease.py@@ -0,0 +1,75 @@+import django.db.models.manager+from django.db import migrations, models+++def _create_duckgres_group_lease_table(apps, schema_editor):+ schema_editor.execute("""+ CREATE TABLE sourceduckgresgrouplease (+ id BIGSERIAL PRIMARY KEY,+ team_id BIGINT NOT NULL,+ schema_id VARCHAR(200) 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 sdgl_team_schema_uniq UNIQUE (team_id, schema_id)+ )+ """)+ schema_editor.execute("""+ CREATE INDEX sdgl_expires_at_idx ON sourceduckgresgrouplease (expires_at)+ """)+ schema_editor.execute("""+ CREATE INDEX sdgl_team_id_idx ON sourceduckgresgrouplease (team_id)+ """)+++def _drop_duckgres_group_lease_table(apps, schema_editor):+ schema_editor.execute("DROP TABLE IF EXISTS sourceduckgresgrouplease CASCADE")+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources_queue", "0004_source_group_lease"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.CreateModel(+ name="SourceDuckgresGroupLease",+ fields=[+ (+ "id",+ models.BigAutoField(+ auto_created=True, primary_key=True, serialize=False, verbose_name="ID"+ ),+ ),+ ("team_id", models.BigIntegerField(db_index=True)),+ ("schema_id", models.CharField(max_length=200)),+ (+ "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": "sourceduckgresgrouplease",+ "indexes": [models.Index(fields=["expires_at"], name="sdgl_expires_at_idx")],+ "constraints": [+ models.UniqueConstraint(fields=("team_id", "schema_id"), name="sdgl_team_schema_uniq")+ ],+ },+ managers=[+ ("all_teams", django.db.models.manager.Manager()),+ ],+ ),+ ],+ database_operations=[],+ ),+ migrations.RunPython(_create_duckgres_group_lease_table, _drop_duckgres_group_lease_table),+ ]diff --git a/products/warehouse_sources_queue/backend/migrations/max_migration.txt b/products/warehouse_sources_queue/backend/migrations/max_migration.txtindex 6dd9cfaaa442..0daddc644d82 100644--- a/products/warehouse_sources_queue/backend/migrations/max_migration.txt+++ b/products/warehouse_sources_queue/backend/migrations/max_migration.txt@@ -1 +1 @@-0004_source_group_lease\ No newline at end of file+0005_duckgres_group_leasediff --git a/products/warehouse_sources_queue/backend/models.py b/products/warehouse_sources_queue/backend/models.pyindex e2f706e965b3..24815cab944a 100644--- a/products/warehouse_sources_queue/backend/models.py+++ b/products/warehouse_sources_queue/backend/models.py@@ -144,6 +144,35 @@ class SourceGroupLease(models.Model):]+class SourceDuckgresGroupLease(ProductTeamModel):+ """Lease-based mutual exclusion for the duckgres sink's (team_id, schema_id) groups.++ Same mechanics as [SourceGroupLease], but a separate table: both consumers+ process the same groups independently and must never contend for one lease+ row. Replaces the sink's session-scoped advisory lock, which could be+ orphaned indefinitely on SIGKILL or a lingering pgbouncer session. All+ access is raw SQL in ``duckgres/jobs_db.py``; this model exists for+ migration/introspection.+ """++ schema_id = models.CharField(max_length=200)+ 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("team_id", "schema_id", "owner_token", "expires_at")++ class Meta:+ db_table = "sourceduckgresgrouplease"+ constraints = [+ models.UniqueConstraint(fields=["team_id", "schema_id"], name="sdgl_team_schema_uniq"),+ ]+ indexes = [+ models.Index(fields=["expires_at"], name="sdgl_expires_at_idx"),+ ]++class SourceBatchDuckgresApply(ProductTeamModel, UUIDModel):schema_id = models.CharField(max_length=200)run_uuid = models.CharField(max_length=200)