Skip to content

: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.

feat(data-warehouse): claim-path flag reading v3 queue state from columns (A2) (#69170)

estefaniae727ac035041
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.py
index 620ca67dfa97..d8b2ef120a20 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,6 +49,8 @@ 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)
@@ -158,6 +160,16 @@ class Command(BaseCommand):
"0 disables the trip"
),
)
+ 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"
+ ),
+ )
def handle(self, *args, **options):
health_port = options["health_port"]
@@ -178,6 +190,7 @@ 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.py
index 8bc6a5d0bec5..b67ec349696e 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
@@ -93,6 +93,10 @@ 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.py
index 7d0c4ea6e908..1a1847b5f4a9 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,6 +73,11 @@ class DeltaBatchConsumerAdapter:
waiting_retry_state: str = SourceBatchStatus.State.WAITING_RETRY.value
per_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],
@@ -88,6 +93,7 @@ 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(
@@ -209,7 +215,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)
+ return await BatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds, use_state=self._use_state)
async def reconcile_failed_runs(
self,
@@ -229,6 +235,7 @@ class DeltaBatchConsumerAdapter:
grace_seconds=grace_seconds,
lookback_seconds=lookback_seconds,
limit=limit,
+ use_state=self._use_state,
)
for ref in refs:
try:
@@ -284,7 +291,7 @@ class DeltaBatchConsumerAdapter:
"""
try:
async with asyncio.timeout(FRESHNESS_PROBE_TIMEOUT_SECONDS):
- age = await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn)
+ age = await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn, use_state=self._use_state)
except TimeoutError:
logger.error( # noqa: TRY400 — designed degraded path, traceback is noise
"queue_freshness_probe_timed_out",
@@ -329,7 +336,7 @@ class BatchConsumer(SharedBatchConsumer):
super().__init__(
config=config,
process_batch=process_batch,
- adapter=DeltaBatchConsumerAdapter(),
+ adapter=DeltaBatchConsumerAdapter(use_state=config.claim_path == "state"),
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.py
index 2121a416b79d..c711e0da0230 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,8 +167,139 @@ 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 _stale_executing_sql(scope_sql: str = "") -> str:
- """Shared body of the stale-executing sweep (async consumer and its sync ops twin)."""
+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
+ indexes (sb_claimable_idx, sb_run_gate_idx, sb_schema_busy_idx), so the
+ work tracks the claimable set instead of everything retained. 'pending'
+ means no status row yet; 'waiting' is deliberately not claimable, matching
+ the legacy predicate.
+ """
+ return f"""
+ SELECT
+ b.id, b.team_id, b.schema_id, b.source_id, b.job_id,
+ b.run_uuid, b.batch_index, b.s3_path, b.row_count, b.byte_size,
+ b.is_final_batch, b.total_batches, b.total_rows, b.sync_type,
+ b.cumulative_row_count, b.resource_name, b.is_resume,
+ b.is_first_ever_sync, b.metadata,
+ b.latest_attempt,
+ b.created_at
+ FROM {BATCH_TABLE} b
+ WHERE
+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND (
+ b.latest_state = 'pending'
+ OR (
+ b.latest_state = 'waiting_retry'
+ AND b.state_changed_at <= now() - make_interval(
+ secs => %(backoff)s * GREATEST(b.latest_attempt, 1)
+ )
+ )
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM {BATCH_TABLE} b_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 (
+ b_prev.latest_state = 'executing'
+ OR (
+ b_prev.latest_state = 'waiting_retry'
+ AND b_prev.state_changed_at > now() - make_interval(
+ secs => %(backoff)s * GREATEST(b_prev.latest_attempt, 1)
+ )
+ )
+ )
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM {BATCH_TABLE} b2
+ WHERE b2.run_uuid = b.run_uuid
+ AND b2.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND b2.latest_state = 'failed'
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM {BATCH_TABLE} b_busy
+ 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 b_busy.latest_state = 'executing'
+ )
+ """
+
+
+def _stale_executing_sql(scope_sql: str = "", *, use_state: bool = False) -> 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``.
+ """
+ state_filter = "AND b.latest_state = 'executing'" if use_state else ""
return f"""
SELECT
{pending_batch_select_columns("s")}
@@ -177,6 +308,7 @@ def _stale_executing_sql(scope_sql: str = "") -> str:
LEFT JOIN {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}'
+ {state_filter}
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())
@@ -397,9 +529,17 @@ 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.
+
Group ownership is a row in ``sourcegrouplease`` keyed by
(team_id, schema_id). The outer query claims-or-renews the lease for
each candidate group in a single writable CTE: a group is returned only
@@ -446,59 +586,12 @@ class BatchQueue:
Own-leased groups stay in the window so a pod can keep draining a group it
already holds.
"""
+ candidates_sql = _state_claim_candidates_sql() if use_state else _legacy_claim_candidates_sql()
async with conn.cursor(row_factory=dict_row) as cur:
await cur.execute(
f"""
WITH candidates AS MATERIALIZED (
- 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'
- )
+ {candidates_sql}
AND NOT EXISTS (
SELECT 1
FROM {LEASE_TABLE} l_live
@@ -629,6 +722,7 @@ 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).
@@ -643,7 +737,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(), {"grace": grace_seconds})
+ await cur.execute(_stale_executing_sql(use_state=use_state), {"grace": grace_seconds})
rows = await cur.fetchall()
return [PendingBatch(**row) for row in rows]
@@ -729,12 +823,17 @@ 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.
"""
+ 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"""
@@ -747,6 +846,7 @@ class BatchQueue:
{latest_status_lateral("b", "s", join="INNER")}
WHERE
b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ {state_filter}
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)
@@ -775,6 +875,8 @@ class BatchQueue:
@staticmethod
async 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.
@@ -782,11 +884,18 @@ class BatchQueue:
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.
+ unbounded history. ``use_state`` answers from the claimable partial
+ index ('pending' ⇔ no status row) instead of anti-joining the log.
"""
- async with conn.cursor() as cur:
- await cur.execute(
- f"""
+ if use_state:
+ sql = f"""
+ SELECT EXTRACT(EPOCH FROM (now() - min(b.created_at)))
+ FROM {BATCH_TABLE} b
+ WHERE 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}'
@@ -796,8 +905,9 @@ class BatchQueue:
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 None
diff --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.py
index 0e9137d350ac..0065d3f794ae 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,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from 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 (
@@ -1479,3 +1480,20 @@ 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 False
diff --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.py
index 114882fcaca4..9d5262e73122 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,9 +18,21 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
OWNER_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, **kwargs)
+ return await BatchQueue.get_unprocessed_and_lock(conn, owner_token=owner, use_state=_CLAIM_USE_STATE, **kwargs)
async def _release(conn: psycopg.AsyncConnection[Any], *, batches: list[PendingBatch], owner: str = OWNER_A) -> None:
@@ -200,6 +212,7 @@ class TestBatchQueueInsert:
@pytest.mark.django_db(transaction=True)
[email protected]("claim_path")
class TestBatchQueueGetUnprocessed:
@pytest.mark.asyncio
async def test_returns_new_batches(self, conn):
@@ -297,19 +310,17 @@ class TestBatchQueueGetUnprocessed:
# queued batches become selectable again.
exec_bid = await _insert_batch(conn, schema_id="S", run_uuid="run-1", batch_index=0)
await _insert_batch(conn, schema_id="S", run_uuid="run-2", batch_index=0)
- # Explicit timestamps so the latest-status view is deterministic (ids are random uuids).
+ await BatchQueue.update_status(conn, batch_id=exec_bid, job_state="executing", attempt=1)
+ # Backdate the executing row so the succeeded row below is unambiguously
+ # the latest for the view's (created_at DESC, id DESC) tie-break.
await conn.execute(
- f"INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, created_at) "
- f"VALUES (%s, 'executing', 1, now() - interval '5 seconds')",
+ f"UPDATE {STATUS_TABLE} SET created_at = created_at - interval '5 seconds' WHERE batch_id = %s",
[exec_bid],
)
assert await _claim(conn) == []
- await conn.execute(
- f"INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, created_at) VALUES (%s, 'succeeded', 1, now())",
- [exec_bid],
- )
+ await BatchQueue.update_status(conn, batch_id=exec_bid, job_state="succeeded", attempt=1)
batches = await _claim(conn)
@@ -396,14 +407,21 @@ async def _lease_count(conn: psycopg.AsyncConnection[Any], *, team_id: int = 1,
async def _insert_backdated_executing(
conn: psycopg.AsyncConnection[Any], *, batch_id: str, age_seconds: int = 120, attempt: int = 1
) -> None:
+ # Seed through the dual-write, then backdate both clocks, so the log and
+ # the state columns stay consistent like they do under real writers.
+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="executing", attempt=attempt)
+ await conn.execute(
+ f"UPDATE {STATUS_TABLE} SET created_at = created_at - make_interval(secs => %s) WHERE batch_id = %s",
+ [age_seconds, batch_id],
+ )
await conn.execute(
- f"INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, created_at) "
- f"VALUES (%s, 'executing', %s, now() - make_interval(secs => %s))",
- [batch_id, attempt, age_seconds],
+ f"UPDATE {BATCH_TABLE} SET state_changed_at = state_changed_at - make_interval(secs => %s) WHERE id = %s",
+ [age_seconds, batch_id],
)
@pytest.mark.django_db(transaction=True)
[email protected]("claim_path")
class TestBatchQueueGroupLease:
@pytest.mark.asyncio
async def test_live_lease_excludes_other_owner(self, conn, conn_b):
@@ -597,6 +615,7 @@ class TestGroupLeaseRecovery:
@pytest.mark.django_db(transaction=True)
[email protected]("claim_path")
class TestBatchQueueRetryBackoff:
@pytest.mark.asyncio
async def test_backoff_gates_fresh_waiting_retry(self, conn):
@@ -614,10 +633,15 @@ class TestBatchQueueRetryBackoff:
@pytest.mark.asyncio
async def test_backoff_scales_with_attempt(self, conn):
bid = await _insert_batch(conn)
- # Backdate the status row by 10 seconds with attempt=3.
+ 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.
await conn.execute(
- f"INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, created_at) "
- f"VALUES (%s, 'waiting_retry', 3, now() - interval '10 seconds')",
+ f"UPDATE {STATUS_TABLE} SET created_at = created_at - interval '10 seconds' WHERE batch_id = %s",
+ [bid],
+ )
+ await conn.execute(
+ f"UPDATE {BATCH_TABLE} SET state_changed_at = state_changed_at - interval '10 seconds' WHERE id = %s",
[bid],
)
@@ -797,6 +821,7 @@ class TestGetRunActivitySummary:
@pytest.mark.django_db(transaction=True)
[email protected]("claim_path")
class TestClaimWindowSkipsForeignLeasedGroups:
@pytest.mark.asyncio
async def test_foreign_leased_group_does_not_occupy_the_window(self, conn, conn_b):
@@ -941,3 +966,102 @@ class TestStateDualWrite:
assert failed == 2
assert (await _batch_state(conn, first))[0] == "failed"
assert (await _batch_state(conn, second))[0] == "failed"
+
+
[email protected]_db(transaction=True)
+class TestClaimPathEquivalence:
+ """Direct legacy-vs-state comparisons; divergence here means the A2 flip
+ would silently claim different work than today."""
+
+ async def _seed_rich_scenario(self, conn) -> None:
+ # Claimable: fresh pending batches on two teams.
+ await _insert_batch(conn, team_id=1, schema_id="s-a", run_uuid="run-a", batch_index=0)
+ await _insert_batch(conn, team_id=1, schema_id="s-a", run_uuid="run-a", batch_index=1)
+ await _insert_batch(conn, team_id=2, schema_id="s-b", run_uuid="run-b", batch_index=0)
+ # Terminal: succeeded batch must not appear.
+ done = await _insert_batch(conn, team_id=3, schema_id="s-c", run_uuid="run-c", batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=done, job_state="succeeded", attempt=1)
+ # Failed run: sibling pending batch must be excluded.
+ failed = await _insert_batch(conn, team_id=4, schema_id="s-d", run_uuid="run-d", batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=failed, job_state="failed", attempt=1)
+ await _insert_batch(conn, team_id=4, schema_id="s-d", run_uuid="run-d", batch_index=1)
+ # Busy schema: executing batch gates its sibling run.
+ busy = await _insert_batch(conn, team_id=5, schema_id="s-e", run_uuid="run-e1", batch_index=0)
+ await BatchQueue.update_status(conn, batch_id=busy, job_state="executing", attempt=1)
+ await _insert_batch(conn, team_id=5, schema_id="s-e", run_uuid="run-e2", batch_index=0)
+ # 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 = 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):
+ 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)
+
+ assert [r.run_uuid for r in legacy] == [r.run_uuid for r in state] == ["run-fx"]
+
+ @pytest.mark.asyncio
+ async def test_state_claim_candidates_can_use_the_claimable_index(self, conn):
+ # The whole point of the state path is index-bound claiming; a predicate
+ # edit that breaks the partial-index match silently reverts to O(retained).
+ await _insert_batch(conn)
+ await conn.execute("SET enable_seqscan = off")
+ try:
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
+ _state_claim_candidates_sql,
+ )
+
+ cur = await conn.execute(
+ "EXPLAIN (FORMAT TEXT) " + _state_claim_candidates_sql() + " LIMIT 50",
+ {"backoff": 0},
+ )
+ plan = "\n".join(row[0] for row in await cur.fetchall())
+ finally:
+ await conn.execute("SET enable_seqscan = on")
+ assert "sb_claimable_idx" in plan
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.py
index 5adc0a3d17d8..c45ca3501f76 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,6 +21,7 @@ class TestBuildConsumerConfig:
assert config.recovery_grace_seconds == 300
assert config.lease_ttl_seconds == config.recovery_grace_seconds
assert config.poll_failure_liveness_threshold == 10
+ assert config.claim_path == "legacy"
@parameterized.expand(
[
@@ -33,6 +34,8 @@ 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):