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.

fix(data-warehouse): stop v3 engine overwriting failed batches after dead-job skip (#72308)

estefania9a03febc17ab
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 4c35802b07b9..47a82e1c7d1f 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
@@ -127,6 +127,9 @@ class BatchConsumerAdapter(Protocol):
# Advisory-lock-based adapters set False (lock is session-scoped, must stay
# on the poll connection that acquired it).
per_group_connections: bool
+ # True: a should_process_batch skip means "already done" — still record succeeded.
+ # False: the adapter already wrote a terminal state; the engine must write nothing.
+ record_skip_as_success: bool
async def fetch_and_lock(
self,
@@ -769,6 +772,19 @@ class BatchConsumer:
# status written while the batch waited in this claim.
should_process = await self._adapter.should_process_batch(status_conn, batch=batch)
+ if not should_process and not self._adapter.record_skip_as_success:
+ # The adapter already wrote a terminal state (e.g. fail_run); an
+ # executing/succeeded write here would supersede it as the newer row.
+ logger.info(
+ self._event("batch_skipped_no_status_written"),
+ batch_id=batch.id,
+ run_uuid=batch.run_uuid,
+ )
+ self._metrics.batches_processed_total.labels(
+ team_id=team_id, schema_id=schema_id, status="skipped"
+ ).inc()
+ return False
+
# Pre-increment: if we OOM during processing, recovery sees attempt=N+1
# and knows this attempt was consumed.
await self._adapter.update_status(
@@ -1074,14 +1090,19 @@ class BatchConsumer:
await self._fail_run(batch, reason="max retries exceeded (likely OOM)", conn=conn)
else:
logger.warning(self._event("batch_recovered_for_retry"), attempt=batch.latest_attempt)
- await self._adapter.update_status(
- conn,
- batch_id=batch.id,
- job_state=self._adapter.waiting_retry_state,
- attempt=batch.latest_attempt,
- error_response={"error": "executing timed out - pod restart or OOM"},
- batch_created_at=batch.created_at,
- )
+ try:
+ await self._adapter.update_status(
+ conn,
+ batch_id=batch.id,
+ job_state=self._adapter.waiting_retry_state,
+ attempt=batch.latest_attempt,
+ error_response={"error": "executing timed out - pod restart or OOM"},
+ batch_created_at=batch.created_at,
+ )
+ except OwnershipLostError:
+ # Batch went terminal between the scan and this requeue;
+ # skip it without aborting the rest of the sweep.
+ logger.info(self._event("batch_recovery_skipped_terminal"), batch_id=batch.id)
finally:
structlog.contextvars.unbind_contextvars(*recovery_bound_keys)
finally:
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.py
index beb9690e34d1..1f1a6db0d75b 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
@@ -124,6 +124,9 @@ class DuckgresBatchConsumerAdapter:
# 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
+ # A skip means "already applied": the engine's succeeded record is what
+ # retires the batch (terminal retirement raises OwnershipLostError instead).
+ record_skip_as_success: bool = True
def __init__(self, lease_ttl_seconds: int = LEASE_TTL_SECONDS) -> None:
# TTL for verify_advisory_lock's boundary renewals (the consumer's
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 bbe57fafd177..c9b13eba5458 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
@@ -95,6 +95,9 @@ class DeltaBatchConsumerAdapter:
succeeded_state: str = SourceBatchStatus.State.SUCCEEDED.value
waiting_retry_state: str = SourceBatchStatus.State.WAITING_RETRY.value
per_group_connections: bool = True
+ # A skip means the job is dead and fail_run already failed the run's batches;
+ # the engine must record nothing over them.
+ record_skip_as_success: bool = False
def __init__(
self,
@@ -155,14 +158,20 @@ class DeltaBatchConsumerAdapter:
error_response: dict[str, Any] | None = None,
batch_created_at: datetime | None = None,
) -> None:
- await BatchQueue.update_status(
+ # 'failed' is absorbing: fail_run can retire a claimed batch mid-flight, and a
+ # newer write would supersede it — un-failing a cancelled run. Takeover-sentinel
+ # failures stay supersedable (see _is_job_dead's matching exemption).
+ inserted = await BatchQueue.update_status_unless_failed(
conn,
batch_id=batch_id,
job_state=job_state,
attempt=attempt,
error_response=error_response,
batch_created_at=batch_created_at,
+ supersedable_failed_error=LOCK_TAKEOVER_LATEST_ERROR,
)
+ if not inserted:
+ raise OwnershipLostError(f"batch {batch_id} is already failed; refusing to write '{job_state}' over it")
async def fail_run(
self,
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 0790ef416695..be0866e713f7 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
@@ -165,6 +165,54 @@ def build_status_dual_write_sql(*, with_batch_created_at: bool) -> str:
"""
+def build_status_dual_write_unless_failed_sql(*, with_batch_created_at: bool) -> str:
+ """Guarded twin of :func:`build_status_dual_write_sql`: inserts nothing over a
+ terminal 'failed', so a consumer's newer executing/succeeded rows can't
+ un-retire a batch fail_run already failed. A 'failed' carrying
+ ``%(supersedable_failed_error)s`` (the lock-takeover sentinel) stays writable —
+ takeover deliberately lets an in-flight batch finish. Returns the INSERT count
+ (0 = refused); the column UPDATE is a designed no-op for heartbeat re-inserts,
+ so its rowcount can't be the signal.
+ """
+ created_at_predicate = (
+ "b.created_at = %(batch_created_at)s"
+ if with_batch_created_at
+ else f"b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'"
+ )
+ return f"""
+ WITH target AS (
+ SELECT b.id
+ FROM {BATCH_TABLE} b
+ {latest_status_lateral("b", "s")}
+ WHERE b.id = %(batch_id)s
+ AND {created_at_predicate}
+ AND (
+ b.latest_state IS DISTINCT FROM 'failed'
+ OR s.error_response->>'error' = %(supersedable_failed_error)s
+ )
+ FOR UPDATE OF b
+ ),
+ ins AS (
+ INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)
+ SELECT t.id, %(job_state)s, %(attempt)s, now(), %(error_response)s, now()
+ FROM target t
+ RETURNING batch_id, job_state, attempt, created_at
+ ),
+ upd AS (
+ UPDATE {BATCH_TABLE} b
+ SET latest_state = ins.job_state, latest_attempt = ins.attempt, state_changed_at = ins.created_at
+ FROM ins
+ WHERE b.id = ins.batch_id
+ AND {created_at_predicate}
+ AND ((b.latest_state, b.latest_attempt) IS DISTINCT FROM (ins.job_state, ins.attempt)
+ OR b.state_changed_at IS NULL)
+ AND (b.state_changed_at IS NULL OR b.state_changed_at <= ins.created_at)
+ RETURNING b.id
+ )
+ SELECT count(*) FROM ins
+ """
+
+
def _bulk_fail_dual_write_sql(where_sql: str) -> str:
"""Bulk 'failed' status inserts plus the denormalized-state UPDATE, one statement.
@@ -673,6 +721,35 @@ class BatchQueue:
params,
)
+ @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,
+ batch_created_at: datetime | None = None,
+ supersedable_failed_error: str | None = None,
+ ) -> bool:
+ """Guarded twin of :meth:`update_status`: returns False (writing nothing) over
+ a terminal 'failed' — see :func:`build_status_dual_write_unless_failed_sql`."""
+ params: dict[str, Any] = {
+ "batch_id": batch_id,
+ "job_state": job_state,
+ "attempt": attempt,
+ "error_response": json.dumps(error_response) if error_response else None,
+ "supersedable_failed_error": supersedable_failed_error,
+ }
+ if batch_created_at is not None:
+ params["batch_created_at"] = batch_created_at
+ cursor = await conn.execute(
+ build_status_dual_write_unless_failed_sql(with_batch_created_at=batch_created_at is not None),
+ params,
+ )
+ row = await cursor.fetchone()
+ return bool(row and row[0])
+
@staticmethod
async def renew_lease(
conn: psycopg.AsyncConnection[Any],
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 eba9763c5732..7c4bf21e0eb1 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
@@ -112,12 +112,13 @@ class TestProcessSingle:
batch = _make_batch(latest_attempt=0)
states: list[str] = []
- async def track_status(conn, *, batch_id, job_state, attempt, error_response=None, batch_created_at=None):
+ async def track_status(conn, *, batch_id, job_state, attempt, **kwargs):
states.append(job_state)
+ return True
consumer._process_batch = AsyncMock()
with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
side_effect=track_status,
):
await consumer._process_single(batch)
@@ -130,12 +131,13 @@ class TestProcessSingle:
batch = _make_batch(latest_attempt=0)
states: list[str] = []
- async def track_status(conn, *, batch_id, job_state, attempt, error_response=None, batch_created_at=None):
+ async def track_status(conn, *, batch_id, job_state, attempt, **kwargs):
states.append(job_state)
+ return True
consumer._process_batch = AsyncMock(side_effect=ValueError("boom"))
with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
side_effect=track_status,
):
await consumer._process_single(batch)
@@ -160,7 +162,7 @@ class TestProcessSingle:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
) as mock_status,
patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail,
@@ -191,7 +193,7 @@ class TestProcessSingle:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
),
patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail,
@@ -216,7 +218,7 @@ class TestProcessGroup:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
),
patch(
@@ -244,7 +246,7 @@ class TestProcessGroup:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
),
patch(
@@ -279,7 +281,7 @@ class TestProcessGroup:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
),
patch(
@@ -314,7 +316,7 @@ class TestProcessGroup:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
),
patch(
@@ -371,7 +373,7 @@ class TestRecoverySweep:
return_value=[stale_batch],
),
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
) as mock_status,
patch(
@@ -388,6 +390,7 @@ class TestRecoverySweep:
attempt=1,
error_response={"error": "executing timed out - pod restart or OOM"},
batch_created_at=stale_batch.created_at,
+ supersedable_failed_error=LOCK_TAKEOVER_LATEST_ERROR,
)
mock_unlock.assert_called_once_with(
consumer._recovery_conn, batches=[stale_batch], owner_token=consumer._owner_token
@@ -416,6 +419,35 @@ class TestRecoverySweep:
assert "max retries exceeded" in mock_fail.call_args[1]["reason"]
mock_unlock.assert_called_once()
+ @pytest.mark.asyncio
+ async def test_sweep_continues_past_terminally_retired_batch(self):
+ # A batch failed between the stale scan and the requeue must be skipped,
+ # not abort recovery for the rest of the stale list.
+ consumer = _make_consumer(max_attempts=3)
+ stale_a = _make_batch(id="00000000-0000-0000-0000-00000000000a", latest_attempt=1)
+ stale_b = _make_batch(id="00000000-0000-0000-0000-00000000000b", schema_id="schema-2", latest_attempt=1)
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",
+ new_callable=AsyncMock,
+ return_value=[stale_a, stale_b],
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
+ new_callable=AsyncMock,
+ side_effect=[False, True], # first batch was retired mid-sweep
+ ) as mock_status,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",
+ new_callable=AsyncMock,
+ ) as mock_unlock,
+ ):
+ await consumer._recovery_sweep()
+
+ assert mock_status.await_count == 2 # the second batch still gets requeued
+ mock_unlock.assert_called_once()
+
@pytest.mark.asyncio
async def test_recovery_sweep_unlocks_on_error(self):
consumer = _make_consumer(max_attempts=3)
@@ -428,7 +460,7 @@ class TestRecoverySweep:
return_value=[stale_batch],
),
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
side_effect=Exception("db gone"),
),
@@ -833,6 +865,73 @@ class TestShouldProcessBatch:
mock_queue_fail.assert_not_called()
+class TestDeadJobSkip:
+ @pytest.mark.asyncio
+ async def test_dead_job_claim_writes_no_status_and_halts_group(self):
+ # Regression: the engine wrote 'executing' + 'succeeded' after a dead-job skip,
+ # superseding fail_run's 'failed' rows — un-failing a cancelled run.
+ consumer = _make_consumer()
+ process_mock = AsyncMock()
+ consumer._process_batch = process_mock
+ batch = _make_batch()
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._get_job_status_and_error",
+ return_value=("Failed", "connection lost"),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.fail_run",
+ new_callable=AsyncMock,
+ ) as mock_fail_run,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._update_job_status_to_failed",
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
+ new_callable=AsyncMock,
+ ) as mock_status,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",
+ new_callable=AsyncMock,
+ ) as mock_unlock,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.verify_advisory_lock",
+ new_callable=AsyncMock,
+ return_value=True,
+ ),
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
+ ):
+ await consumer._process_group((1, "schema-1"), [batch])
+
+ mock_fail_run.assert_awaited_once()
+ process_mock.assert_not_awaited() # no delta write for a dead job
+ mock_status.assert_not_called() # never 'executing', never 'succeeded'
+ mock_unlock.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_refused_status_write_abandons_batch_instead_of_reporting_success(self):
+ # A fail_run landing mid-apply must surface as an abandoned batch,
+ # never as succeeded.
+ consumer = _make_consumer()
+ consumer._process_batch = AsyncMock()
+ batch = _make_batch()
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._get_job_status_and_error",
+ return_value=("Running", None),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
+ new_callable=AsyncMock,
+ side_effect=[True, False], # executing lands, succeeded is refused
+ ),
+ pytest.raises(OwnershipLostError),
+ ):
+ await consumer._process_single(batch)
+
+
class TestReconcileFailedRuns:
@pytest.mark.asyncio
async def test_reconcile_reports_queue_freshness_gauge(self):
@@ -1068,7 +1167,7 @@ class TestConnectionRecovery:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
),
patch(
@@ -1143,7 +1242,7 @@ class TestPerGroupConnectionIsolation:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
),
patch(
@@ -1183,7 +1282,7 @@ class TestPerGroupConnectionIsolation:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
),
patch(
@@ -1219,7 +1318,7 @@ class TestPerGroupConnectionIsolation:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
),
patch(
@@ -1293,7 +1392,7 @@ class TestLogContextBinding:
consumer._process_batch = capture_context
with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
):
await consumer._process_single(batch)
@@ -1328,7 +1427,7 @@ class TestLogContextBinding:
consumer._process_batch = capture_context
with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
):
await consumer._process_single(batch)
@@ -1342,7 +1441,7 @@ class TestLogContextBinding:
consumer._process_batch = AsyncMock()
with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
):
await consumer._process_single(_make_batch(latest_attempt=0, metadata={}))
@@ -1355,7 +1454,7 @@ class TestLogContextBinding:
consumer._process_batch = AsyncMock(side_effect=ValueError("boom"))
with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
):
await consumer._process_single(_make_batch(latest_attempt=0))
@@ -1419,7 +1518,7 @@ class TestOwnershipVerification:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
),
patch(
@@ -1449,7 +1548,7 @@ class TestOwnershipVerification:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
),
pytest.raises(OwnershipLostError),
@@ -1464,7 +1563,7 @@ class TestOwnershipVerification:
with (
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
),
patch(
@@ -1534,7 +1633,7 @@ class TestOwnershipVerification:
return_value=False,
) as mock_renew,
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
) as mock_status,
patch("asyncio.sleep", new_callable=AsyncMock), # don't wait the real interval
@@ -1562,7 +1661,7 @@ class TestOwnershipVerification:
side_effect=[True, False],
) as mock_renew,
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",
new_callable=AsyncMock,
) as mock_status,
patch("asyncio.sleep", new_callable=AsyncMock),
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 ddd444ce8134..63b1287d6d8e 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
@@ -7,6 +7,7 @@ import pytest
import psycopg
+from products.warehouse_sources.backend.temporal.data_imports.metrics import LOCK_TAKEOVER_LATEST_ERROR
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
BATCH_TABLE,
CLAIM_ELIGIBILITY_INTERVAL,
@@ -1046,6 +1047,79 @@ class TestStateDualWrite:
assert (await _batch_state(conn, second))[0] == "failed"
[email protected]_db(transaction=True)
+class TestUpdateStatusUnlessFailed:
+ """'failed' must be absorbing: a consumer's newer executing/succeeded rows
+ would otherwise win the monotonic dual-write over a fail_run."""
+
+ @pytest.mark.parametrize("job_state", ["executing", "succeeded", "waiting_retry"])
+ @pytest.mark.asyncio
+ async def test_refuses_lifecycle_writes_over_failed(self, conn, job_state):
+ bid = await _insert_batch(conn, run_uuid="run-guard")
+ await BatchQueue.fail_run(conn, run_uuid="run-guard", team_id=1, schema_id="schema-1", reason="cancelled")
+
+ written = await BatchQueue.update_status_unless_failed(
+ conn,
+ batch_id=bid,
+ job_state=job_state,
+ attempt=1,
+ supersedable_failed_error=LOCK_TAKEOVER_LATEST_ERROR,
+ )
+
+ assert written is False
+ assert (await _batch_state(conn, bid))[0] == "failed"
+ cur = await conn.execute(f"SELECT count(*) FROM {STATUS_TABLE} WHERE batch_id = %s", (bid,))
+ row = await cur.fetchone()
+ assert row is not None and row[0] == 1 # only fail_run's row; nothing appended over it
+
+ @pytest.mark.asyncio
+ async def test_normal_lifecycle_writes_pass_and_dual_write(self, conn):
+ bid = await _insert_batch(conn)
+ cur = await conn.execute(f"SELECT created_at FROM {BATCH_TABLE} WHERE id = %s", (bid,))
+ row = await cur.fetchone()
+ assert row is not None
+
+ assert await BatchQueue.update_status_unless_failed(conn, batch_id=bid, job_state="executing", attempt=1)
+ assert await BatchQueue.update_status_unless_failed(
+ conn, batch_id=bid, job_state="succeeded", attempt=1, batch_created_at=row[0]
+ )
+
+ state, attempt, _ = await _batch_state(conn, bid)
+ assert (state, attempt) == ("succeeded", 1)
+
+ @pytest.mark.asyncio
+ async def test_takeover_failed_batch_stays_supersedable(self, conn, sync_conn):
+ # Takeover deliberately lets an in-flight consumer finish: only its exact
+ # sentinel error stays writable (twin of the _is_job_dead exemption).
+ bid = await _insert_batch(conn, job_id="job-tko")
+ await BatchQueue.update_status(conn, batch_id=bid, job_state="executing", attempt=1)
+ BatchQueue.fail_batches_for_job_sync(sync_conn, job_id="job-tko", reason=LOCK_TAKEOVER_LATEST_ERROR)
+
+ written = await BatchQueue.update_status_unless_failed(
+ conn,
+ batch_id=bid,
+ job_state="succeeded",
+ attempt=1,
+ supersedable_failed_error=LOCK_TAKEOVER_LATEST_ERROR,
+ )
+
+ assert written is True
+ assert (await _batch_state(conn, bid))[0] == "succeeded"
+
+ @pytest.mark.asyncio
+ async def test_heartbeat_reinsert_reports_written_not_refused(self, conn):
+ # A heartbeat re-insert (designed 0-row column no-op) must not read as a
+ # refusal, or every long batch would be abandoned mid-apply.
+ bid = await _insert_batch(conn)
+ assert await BatchQueue.update_status_unless_failed(conn, batch_id=bid, job_state="executing", attempt=1)
+
+ assert await BatchQueue.update_status_unless_failed(conn, batch_id=bid, job_state="executing", attempt=1)
+
+ cur = await conn.execute(f"SELECT count(*) FROM {STATUS_TABLE} WHERE batch_id = %s", (bid,))
+ row = await cur.fetchone()
+ assert row is not None and row[0] == 2 # the log still grows
+
+
@pytest.mark.django_db(transaction=True)
class TestClaimGates:
"""Every claim gate exercised in one scenario; a predicate edit that breaks