: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): make the state claim path the only v3 queue reader (#69678)
estefania145c3e1f3294
diff --git a/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py b/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.pyindex d8b2ef120a20..519276184594 100644--- a/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py+++ b/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py@@ -49,8 +49,6 @@ def build_consumer_config(options: dict) -> ConsumerConfig:kwargs["recovery_grace_seconds"] = options["recovery_grace"]if options.get("poll_failure_liveness_threshold") is not None:kwargs["poll_failure_liveness_threshold"] = options["poll_failure_liveness_threshold"] or None- if options.get("claim_path") is not None:- kwargs["claim_path"] = options["claim_path"]return ConsumerConfig(**kwargs)@@ -160,15 +158,13 @@ class Command(BaseCommand):"0 disables the trip"),)+ # Deprecated no-op kept so deploys still passing the flag don't crash;+ # the legacy status-log claim path was removed and 'state' is the only reader.parser.add_argument("--claim-path",choices=["legacy", "state"],default=None,- help=(- "Queue reader source: 'legacy' derives batch state from the status log per poll; "- "'state' reads the denormalized columns (requires migration 0006 + backfill). "- "Writes always dual-write, so flipping back is a complete rollback"- ),+ help="Deprecated, ignored: readers always use the denormalized state columns",)def handle(self, *args, **options):@@ -177,6 +173,11 @@ class Command(BaseCommand):config = build_consumer_config(options)+ if options.get("claim_path") == "legacy":+ logger.warning(+ "claim_path_legacy_removed", note="--claim-path is ignored; the legacy claim path no longer exists"+ )+logger.info("warehouse_sources_load_starting",max_concurrency=config.max_concurrency,@@ -190,7 +191,6 @@ class Command(BaseCommand):connect_timeout=config.connect_timeout_seconds,lease_ttl=config.lease_ttl_seconds,recovery_grace=config.recovery_grace_seconds,- claim_path=config.claim_path,poll_failure_liveness_threshold=config.poll_failure_liveness_threshold,)diff --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 d0522ac8cd97..95d22b63ff2f 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@@ -100,10 +100,6 @@ class BatchConsumerConfig:# Withhold liveness after this many consecutive failed polls: a pod that# cannot poll does no work but would otherwise pass liveness forever.poll_failure_liveness_threshold: int | None = 10- # Which source the delta sink's queue readers use: the legacy status-log- # laterals or the denormalized state columns. Readers only — writes always- # dual-write, which is what makes flipping back a complete rollback.- claim_path: str = "legacy"def __post_init__(self) -> None:if self.recovery_grace_seconds is None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.pyindex 1a1847b5f4a9..7d0c4ea6e908 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py@@ -73,11 +73,6 @@ class DeltaBatchConsumerAdapter:waiting_retry_state: str = SourceBatchStatus.State.WAITING_RETRY.valueper_group_connections: bool = True- def __init__(self, *, use_state: bool = False) -> None:- # Readers only: True routes the claim, sweep, freshness, and reconcile- # queries through the denormalized state columns.- self._use_state = use_state-async def fetch_and_lock(self,conn: psycopg.AsyncConnection[Any],@@ -93,7 +88,6 @@ class DeltaBatchConsumerAdapter:limit=limit,retry_backoff_base_seconds=retry_backoff_base_seconds,lease_ttl_seconds=lease_ttl_seconds,- use_state=self._use_state,)async def unlock(@@ -215,7 +209,7 @@ class DeltaBatchConsumerAdapter:) -> list[PendingBatch]:# keep_locks is meaningless for the lease sink: get_stale_executing holds# no locks and the lease LEFT JOIN already excludes live groups.- return await BatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds, use_state=self._use_state)+ return await BatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds)async def reconcile_failed_runs(self,@@ -235,7 +229,6 @@ class DeltaBatchConsumerAdapter:grace_seconds=grace_seconds,lookback_seconds=lookback_seconds,limit=limit,- use_state=self._use_state,)for ref in refs:try:@@ -291,7 +284,7 @@ class DeltaBatchConsumerAdapter:"""try:async with asyncio.timeout(FRESHNESS_PROBE_TIMEOUT_SECONDS):- age = await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn, use_state=self._use_state)+ age = await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn)except TimeoutError:logger.error( # noqa: TRY400 — designed degraded path, traceback is noise"queue_freshness_probe_timed_out",@@ -336,7 +329,7 @@ class BatchConsumer(SharedBatchConsumer):super().__init__(config=config,process_batch=process_batch,- adapter=DeltaBatchConsumerAdapter(use_state=config.claim_path == "state"),+ adapter=DeltaBatchConsumerAdapter(),health_reporter=health_reporter,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.pyindex c711e0da0230..ab4a3ba869ae 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py@@ -167,74 +167,13 @@ def _bulk_fail_dual_write_sql(where_sql: str) -> str:FAIL_RUN_SQL = _bulk_fail_dual_write_sql("b.run_uuid = %(run_uuid)s")-def _legacy_claim_candidates_sql() -> str:- """Claimable-batch candidates derived from the status log (lateral probes).-- Cost scales with every batch retained in the window; kept as the rollback- path while the state-column variant proves itself in production.- """- return f"""- SELECT- {pending_batch_select_columns("s")}- FROM {BATCH_TABLE} b- {latest_status_lateral("b", "s")}- WHERE- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND (- s.batch_id IS NULL- OR (- s.job_state = 'waiting_retry'- AND s.created_at <= now() - make_interval(- secs => %(backoff)s * GREATEST(COALESCE(s.attempt, 1), 1)- )- )- )- AND NOT EXISTS (- SELECT 1- FROM {BATCH_TABLE} b_prev- {latest_status_lateral("b_prev", "s_prev")}- WHERE b_prev.run_uuid = b.run_uuid- AND b_prev.batch_index < b.batch_index- AND b_prev.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND (- s_prev.job_state = 'executing'- OR (- s_prev.job_state = 'waiting_retry'- AND s_prev.created_at > now() - make_interval(- secs => %(backoff)s * GREATEST(COALESCE(s_prev.attempt, 1), 1)- )- )- )- )- AND NOT EXISTS (- SELECT 1- FROM {BATCH_TABLE} b2- {latest_status_lateral("b2", "s2", join="INNER")}- WHERE b2.run_uuid = b.run_uuid- AND b2.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND s2.job_state = 'failed'- )- AND NOT EXISTS (- SELECT 1- FROM {BATCH_TABLE} b_busy- {latest_status_lateral("b_busy", "s_busy", join="INNER")}- WHERE b_busy.team_id = b.team_id- AND b_busy.schema_id = b.schema_id- AND b_busy.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND s_busy.job_state = 'executing'- )- """--def _state_claim_candidates_sql() -> str:"""Claimable-batch candidates read from the denormalized state columns.- Semantics mirror the legacy variant gate for gate; the difference is cost:- the claimable scan and every NOT EXISTS gate are answered by the partial+ The claimable scan and every NOT EXISTS gate are answered by the partialindexes (sb_claimable_idx, sb_run_gate_idx, sb_schema_busy_idx), so thework tracks the claimable set instead of everything retained. 'pending'- means no status row yet; 'waiting' is deliberately not claimable, matching- the legacy predicate.+ means no status row yet; 'waiting' is deliberately not claimable."""return f"""SELECT@@ -291,15 +230,14 @@ def _state_claim_candidates_sql() -> str:"""-def _stale_executing_sql(scope_sql: str = "", *, use_state: bool = False) -> str:+def _stale_executing_sql(scope_sql: str = "") -> str:"""Shared body of the stale-executing sweep (async consumer and its sync ops twin).- ``use_state`` pre-filters on the denormalized column so the lateral probes- only currently-executing batches instead of everything retained. The- lateral stays either way: heartbeats refresh the status log, not the- column, so the grace clock must come from ``s.created_at``.+ The denormalized-column pre-filter keeps the lateral probing only+ currently-executing batches. The lateral itself must stay: heartbeats+ refresh the status log, deliberately not the column, so the grace clock+ comes from ``s.created_at``."""- state_filter = "AND b.latest_state = 'executing'" if use_state else ""return f"""SELECT{pending_batch_select_columns("s")}@@ -308,7 +246,7 @@ def _stale_executing_sql(scope_sql: str = "", *, use_state: bool = False) -> strLEFT JOIN {LEASE_TABLE} l ON l.team_id = b.team_id AND l.schema_id = b.schema_idWHEREb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- {state_filter}+ AND b.latest_state = 'executing'AND s.job_state = 'executing'AND s.created_at <= now() - make_interval(secs => %(grace)s)AND (l.team_id IS NULL OR l.expires_at <= now())@@ -529,16 +467,12 @@ class BatchQueue:limit: int = 50,retry_backoff_base_seconds: int = 0,lease_ttl_seconds: int = LEASE_TTL_SECONDS,- use_state: bool = False,) -> list[PendingBatch]:"""Fetch unprocessed batches whose (team_id, schema_id) group lease is claimable by ``owner_token``.- ``use_state`` selects the candidate source: the denormalized state- columns (cost tracks the claimable set) or the legacy status-log- laterals (cost tracks everything retained). Both feed the identical- fairness sort and lease-claim CTE, and must return identical batches- for the same queue state — the equivalence test suite runs every claim- test through both.+ Candidates come from the denormalized state columns, so poll cost+ tracks the claimable set rather than everything retained in the+ 14-day window.Group ownership is a row in ``sourcegrouplease`` keyed by(team_id, schema_id). The outer query claims-or-renews the lease for@@ -555,15 +489,15 @@ class BatchQueue:affect the same (team_id, schema_id) row twice in one statement.``retry_backoff_base_seconds`` gates the ``waiting_retry`` branch on- the age of the latest status row: a batch is only eligible when- ``now() - s.created_at >= retry_backoff_base_seconds * GREATEST(s.attempt, 1)``+ ``state_changed_at``: a batch is only eligible when+ ``now() - state_changed_at >= retry_backoff_base_seconds * GREATEST(latest_attempt, 1)``(attempt is floored at 1 so that a zero-attempt row still waits at least onebase period).Head-of-line gating per run: a batch is excluded if any earlier``batch_index`` in the same ``run_uuid`` is currently ``executing`` orin ``waiting_retry`` whose backoff window has not yet elapsed. Earlier- batches that are unprocessed (NULL status) or ``waiting_retry`` with+ batches that are unprocessed (``pending``) or ``waiting_retry`` withbackoff met are treated as siblings that will be returned alongsidein the same poll and processed sequentially by the consumer.@@ -586,7 +520,7 @@ class BatchQueue:Own-leased groups stay in the window so a pod can keep draining a group italready holds."""- candidates_sql = _state_claim_candidates_sql() if use_state else _legacy_claim_candidates_sql()+ candidates_sql = _state_claim_candidates_sql()async with conn.cursor(row_factory=dict_row) as cur:await cur.execute(f"""@@ -722,7 +656,6 @@ class BatchQueue:conn: psycopg.AsyncConnection[Any],*,grace_seconds: int = 0,- use_state: bool = False,) -> list[PendingBatch]:"""Find batches stuck in 'executing' whose group lease is absent or expired (previous pod gone).@@ -737,7 +670,7 @@ class BatchQueue:this threshold before the batch is considered orphaned."""async with conn.cursor(row_factory=dict_row) as cur:- await cur.execute(_stale_executing_sql(use_state=use_state), {"grace": grace_seconds})+ await cur.execute(_stale_executing_sql(), {"grace": grace_seconds})rows = await cur.fetchall()return [PendingBatch(**row) for row in rows]@@ -823,17 +756,14 @@ class BatchQueue:grace_seconds: int,lookback_seconds: int,limit: int,- use_state: bool = False,) -> list[FailedRunRef]:"""Return one ref per run with a ``failed`` batch older than ``grace_seconds``, within ``lookback_seconds``.Ordered by latest failure first so fresh failures still land in the window when- already-reconciled runs outnumber ``limit`` within the lookback.- ``use_state`` pre-filters on the denormalized column so the lateral- (still needed for the failure timestamp and error payload) probes only- failed batches instead of everything retained.+ already-reconciled runs outnumber ``limit`` within the lookback. The+ denormalized-column pre-filter keeps the lateral (still needed for the+ failure timestamp and error payload) probing only failed batches."""- state_filter = "AND b.latest_state = 'failed'" if use_state else ""async with conn.cursor(row_factory=dict_row) as cur:await cur.execute(f"""@@ -846,7 +776,7 @@ class BatchQueue:{latest_status_lateral("b", "s", join="INNER")}WHEREb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- {state_filter}+ AND b.latest_state = 'failed'AND s.job_state = 'failed'AND s.created_at <= now() - make_interval(secs => %(grace)s)AND s.created_at >= now() - make_interval(secs => %(lookback)s)@@ -875,39 +805,24 @@ class BatchQueue:@staticmethodasync def get_oldest_unclaimed_batch_age_seconds(conn: psycopg.AsyncConnection[Any],- *,- use_state: bool = False,) -> float | None:"""Age in seconds of the oldest batch no consumer has ever picked up, or None when none are waiting.- A batch with no status row has never been claimed — this is the queue's- data-freshness signal, and it rises whenever loading stalls regardless- of the cause. Bounded to ``FRESHNESS_WINDOW`` so the probe stays cheap- on a healthy queue and the reported age saturates instead of scanning- unbounded history. ``use_state`` answers from the claimable partial- index ('pending' ⇔ no status row) instead of anti-joining the log.+ 'pending' means no status row yet — this is the queue's data-freshness+ signal, and it rises whenever loading stalls regardless of the cause.+ Answered from the claimable partial index; bounded to+ ``FRESHNESS_WINDOW`` so the reported age saturates instead of scanning+ unbounded history."""- if use_state:- sql = f"""+ async with conn.cursor() as cur:+ await cur.execute(+ f"""SELECT EXTRACT(EPOCH FROM (now() - min(b.created_at)))FROM {BATCH_TABLE} bWHERE b.created_at > now() - interval '{FRESHNESS_WINDOW}'AND b.latest_state = 'pending'- """- else:- sql = f"""- SELECT EXTRACT(EPOCH FROM (now() - min(b.created_at)))- FROM {BATCH_TABLE} b- WHERE b.created_at > now() - interval '{FRESHNESS_WINDOW}'- AND NOT EXISTS (- SELECT 1- FROM {STATUS_TABLE} s- WHERE s.batch_id = b.id- AND s.created_at > now() - interval '{FRESHNESS_WINDOW}'- )- """- async with conn.cursor() as cur:- await cur.execute(sql)+ """+ )row = await cur.fetchone()if row is None or row[0] is None:return Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.pyindex 0065d3f794ae..0e9137d350ac 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py@@ -14,7 +14,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer import (BatchConsumer,ConsumerConfig,- DeltaBatchConsumerAdapter,_group_by_key,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (@@ -1480,20 +1479,3 @@ class TestDispatchGroups:task.cancel()with pytest.raises(asyncio.CancelledError):await task---class TestClaimPathWiring:- def test_claim_path_config_reaches_the_adapter(self):- # A flag that parses but never reaches the adapter would leave the- # fleet silently on the legacy path after the flip.- state = BatchConsumer(- config=ConsumerConfig(database_url="postgres://unused:unused@localhost/unused", claim_path="state"),- process_batch=AsyncMock(),- )- legacy = BatchConsumer(- config=ConsumerConfig(database_url="postgres://unused:unused@localhost/unused"),- process_batch=AsyncMock(),- )-- assert cast(DeltaBatchConsumerAdapter, state._adapter)._use_state is True- assert cast(DeltaBatchConsumerAdapter, legacy._adapter)._use_state is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.pyindex 9d5262e73122..86020a0ae6b7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py@@ -18,21 +18,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineOWNER_A = str(uuid4())OWNER_B = str(uuid4())-# Claim-path under test for classes marked usefixtures("claim_path"): the legacy-# status-log laterals and the denormalized state columns must claim identically.-_CLAIM_USE_STATE = False--[email protected](params=[False, True], ids=["legacy", "state"])-def claim_path(request):- global _CLAIM_USE_STATE- _CLAIM_USE_STATE = request.param- yield request.param- _CLAIM_USE_STATE = False-async def _claim(conn: psycopg.AsyncConnection[Any], owner: str = OWNER_A, **kwargs: Any) -> list[PendingBatch]:- return await BatchQueue.get_unprocessed_and_lock(conn, owner_token=owner, use_state=_CLAIM_USE_STATE, **kwargs)+ return await BatchQueue.get_unprocessed_and_lock(conn, owner_token=owner, **kwargs)async def _release(conn: psycopg.AsyncConnection[Any], *, batches: list[PendingBatch], owner: str = OWNER_A) -> None:@@ -212,7 +200,6 @@ class TestBatchQueueInsert:@pytest.mark.django_db(transaction=True)[email protected]("claim_path")class TestBatchQueueGetUnprocessed:@pytest.mark.asyncioasync def test_returns_new_batches(self, conn):@@ -421,7 +408,6 @@ async def _insert_backdated_executing(@pytest.mark.django_db(transaction=True)[email protected]("claim_path")class TestBatchQueueGroupLease:@pytest.mark.asyncioasync def test_live_lease_excludes_other_owner(self, conn, conn_b):@@ -615,7 +601,6 @@ class TestGroupLeaseRecovery:@pytest.mark.django_db(transaction=True)[email protected]("claim_path")class TestBatchQueueRetryBackoff:@pytest.mark.asyncioasync def test_backoff_gates_fresh_waiting_retry(self, conn):@@ -634,8 +619,8 @@ class TestBatchQueueRetryBackoff:async def test_backoff_scales_with_attempt(self, conn):bid = await _insert_batch(conn)await BatchQueue.update_status(conn, batch_id=bid, job_state="waiting_retry", attempt=3)- # Backdate both backoff clocks by 10 seconds: the status log drives the- # legacy path, the state column drives the state path.+ # Backdate both the status log (audit trail) and the state column+ # (the backoff clock the claim reads) by 10 seconds.await conn.execute(f"UPDATE {STATUS_TABLE} SET created_at = created_at - interval '10 seconds' WHERE batch_id = %s",[bid],@@ -821,7 +806,6 @@ class TestGetRunActivitySummary:@pytest.mark.django_db(transaction=True)[email protected]("claim_path")class TestClaimWindowSkipsForeignLeasedGroups:@pytest.mark.asyncioasync def test_foreign_leased_group_does_not_occupy_the_window(self, conn, conn_b):@@ -969,9 +953,9 @@ class TestStateDualWrite:@pytest.mark.django_db(transaction=True)-class TestClaimPathEquivalence:- """Direct legacy-vs-state comparisons; divergence here means the A2 flip- would silently claim different work than today."""+class TestClaimGates:+ """Every claim gate exercised in one scenario; a predicate edit that breaks+ a gate shows up as a wrong claim set here."""async def _seed_rich_scenario(self, conn) -> None:# Claimable: fresh pending batches on two teams.@@ -992,59 +976,24 @@ class TestClaimPathEquivalence:# waiting_retry with backoff already elapsed (backoff=0 in the claim call).retry = await _insert_batch(conn, team_id=6, schema_id="s-f", run_uuid="run-f", batch_index=0)await BatchQueue.update_status(conn, batch_id=retry, job_state="waiting_retry", attempt=1)- # 'waiting' latest state is not claimable on either path.+ # 'waiting' latest state is not claimable.waiting = await _insert_batch(conn, team_id=7, schema_id="s-g", run_uuid="run-g", batch_index=0)await BatchQueue.update_status(conn, batch_id=waiting, job_state="waiting", attempt=0)@pytest.mark.asyncio- async def test_both_paths_claim_identical_batches_in_identical_order(self, conn):+ async def test_claim_applies_every_gate_at_once(self, conn):await self._seed_rich_scenario(conn)- legacy = await BatchQueue.get_unprocessed_and_lock(conn, owner_token=OWNER_A, limit=50, use_state=False)- await conn.execute(f"DELETE FROM {LEASE_TABLE}") # reset the claim's lease side effects- state = await BatchQueue.get_unprocessed_and_lock(conn, owner_token=OWNER_A, limit=50, use_state=True)-- assert [b.id for b in legacy] == [b.id for b in state]- assert [(b.latest_attempt, b.batch_index) for b in legacy] == [(b.latest_attempt, b.batch_index) for b in state]- # run-a (2) + run-b (1) + run-f retry (1); failed-run, busy-schema,- # 'waiting', and terminal batches are excluded on both paths.- assert len(legacy) == 4-- @pytest.mark.asyncio- async def test_freshness_probe_agrees_across_paths(self, conn):- await _insert_batch(conn, batch_index=0)- claimed = await _insert_batch(conn, batch_index=1)- await BatchQueue.update_status(conn, batch_id=claimed, job_state="executing", attempt=1)-- legacy_age = await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn, use_state=False)- state_age = await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn, use_state=True)-- assert legacy_age is not None and state_age is not None- assert abs(legacy_age - state_age) < 2.0-- @pytest.mark.asyncio- async def test_stale_executing_sweep_agrees_across_paths(self, conn):- orphan = await _insert_batch(conn, batch_index=0, run_uuid="run-orphan")- await BatchQueue.update_status(conn, batch_id=orphan, job_state="executing", attempt=1)- healthy = await _insert_batch(conn, batch_index=0, run_uuid="run-live", schema_id="schema-live")- await BatchQueue.update_status(conn, batch_id=healthy, job_state="succeeded", attempt=1)-- legacy = await BatchQueue.get_stale_executing(conn, grace_seconds=0, use_state=False)- state = await BatchQueue.get_stale_executing(conn, grace_seconds=0, use_state=True)-- assert [str(b.id) for b in legacy] == [str(b.id) for b in state] == [orphan]-- @pytest.mark.asyncio- async def test_failed_runs_reconcile_agrees_across_paths(self, conn):- failed = await _insert_batch(conn, run_uuid="run-fx", batch_index=0)- await BatchQueue.update_status(conn, batch_id=failed, job_state="failed", attempt=1)-- legacy = await BatchQueue.get_failed_runs(- conn, grace_seconds=0, lookback_seconds=3600, limit=10, use_state=False- )- state = await BatchQueue.get_failed_runs(conn, grace_seconds=0, lookback_seconds=3600, limit=10, use_state=True)+ claimed = await BatchQueue.get_unprocessed_and_lock(conn, owner_token=OWNER_A, limit=50)- assert [r.run_uuid for r in legacy] == [r.run_uuid for r in state] == ["run-fx"]+ # run-a (2) + run-b (1) + run-f retry (1); failed-run siblings, busy-schema+ # runs, 'waiting', and terminal batches are all excluded.+ assert sorted((b.run_uuid, b.batch_index) for b in claimed) == [+ ("run-a", 0),+ ("run-a", 1),+ ("run-b", 0),+ ("run-f", 0),+ ]@pytest.mark.asyncioasync def test_state_claim_candidates_can_use_the_claimable_index(self, conn):diff --git a/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.py b/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.pyindex c45ca3501f76..4d25b93ed587 100644--- a/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.py+++ b/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.py@@ -21,7 +21,6 @@ class TestBuildConsumerConfig:assert config.recovery_grace_seconds == 300assert config.lease_ttl_seconds == config.recovery_grace_secondsassert config.poll_failure_liveness_threshold == 10- assert config.claim_path == "legacy"@parameterized.expand([@@ -34,8 +33,6 @@ class TestBuildConsumerConfig:(["--recovery-grace", "900"], "recovery_grace_seconds", 900),(["--poll-failure-liveness-threshold", "5"], "poll_failure_liveness_threshold", 5),(["--poll-failure-liveness-threshold", "0"], "poll_failure_liveness_threshold", None),- (["--claim-path", "state"], "claim_path", "state"),- (["--claim-path", "legacy"], "claim_path", "legacy"),])def test_flag_overrides_reach_the_config(self, argv: list[str], field: str, expected):@@ -43,6 +40,14 @@ class TestBuildConsumerConfig:assert getattr(config, field) == expected+ @parameterized.expand([(["--claim-path", "state"],), (["--claim-path", "legacy"],)])+ def test_deprecated_claim_path_flag_is_still_accepted(self, argv: list[str]):+ # Deployed pods still pass --claim-path; dropping the arg would crash+ # the whole fleet at startup with "unrecognized arguments".+ config = build_consumer_config(_parse_options(argv))++ assert not hasattr(config, "claim_path")+def test_lease_ttl_follows_recovery_grace_when_not_set(self):config = build_consumer_config(_parse_options(["--recovery-grace", "900"]))