: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
fix(data-warehouse): fence v3 recovery sweep against live batch owners (#72358)
estefania12b000cfd4da
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 47a82e1c7d1f..67d01aa41bb4 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@@ -167,7 +167,11 @@ class BatchConsumerAdapter(Protocol):attempt: int,error_response: dict[str, Any] | None = None,batch_created_at: datetime | None = None,- ) -> None: ...+ expected_state_changed_at: datetime | None = None,+ ) -> None:+ """Write the batch's status. ``expected_state_changed_at`` arms a compare-and-swap+ where supported; a sink may signal a lost race by raising ``OwnershipLostError``."""+ ...async def fail_run(self,@@ -196,6 +200,17 @@ class BatchConsumerAdapter(Protocol):lease_ttl_seconds: int,) -> bool: ...+ async def delete_expired_lease(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ team_id: int,+ schema_id: str,+ ) -> None:+ """Remove the group's lease iff already expired, fencing a resurrecting owner+ before the recovery sweep re-queues its batches. No-op for non-lease sinks."""+ ...+async def get_stale_executing(self,conn: psycopg.AsyncConnection[Any],@@ -627,8 +642,10 @@ class BatchConsumer:Renewing the lease and refreshing the executing-status grace window onthe same cadence keeps the two reclaim signals consistent: a pod thatstops heartbeating loses its lease and ages out of the grace window at- the same time. ``renew_lease`` returning False means another pod- reclaimed the group, so we stop heartbeating immediately.+ the same time. ``renew_lease`` returning False means ownership is gone+ for good (reclaimed, sweep-deleted, or expired — expiry is terminal), so+ we stop heartbeating immediately; the pre-success ownership check then+ abandons the in-flight batch instead of writing ``succeeded``."""interval = max((self._config.recovery_grace_seconds or RECOVERY_GRACE_SECONDS) / 3, 10.0)while True:@@ -658,8 +675,8 @@ class BatchConsumer:)continueif not renewed:- # Another pod reclaimed the group: stop heartbeating so the- # in-flight apply is fenced by the per-batch ownership checks.+ # Ownership is gone (reclaimed or expired) — never transient: stop+ # heartbeating so the per-batch ownership checks fence the apply.logger.warning(self._event("batch_heartbeat_lease_lost"),batch_id=batch.id,@@ -1083,13 +1100,17 @@ class BatchConsumer:attempt=batch.latest_attempt,)try:+ # Claim the corpse first: once the expired lease is gone, a resurrecting+ # owner's renew matches nothing, so it can't finish over the re-queue.+ await self._adapter.delete_expired_lease(conn, team_id=batch.team_id, schema_id=batch.schema_id)if batch.latest_attempt >= self._config.max_attempts:logger.warning(self._event("batch_recovered_max_retries_exceeded"), attempt=batch.latest_attempt)+ # fail_run's bulk write re-reads each batch's latest status in-statement and+ # targets only non-terminal ones, so it can't flip a meanwhile-succeeded batch.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)try:await self._adapter.update_status(conn,@@ -1098,11 +1119,14 @@ class BatchConsumer:attempt=batch.latest_attempt,error_response={"error": "executing timed out - pod restart or OOM"},batch_created_at=batch.created_at,+ expected_state_changed_at=batch.state_changed_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)+ # The state moved after the stale scan (owner finished, or the batch+ # went terminal): leave it, without aborting the rest of the sweep.+ logger.info(self._event("batch_recovery_skipped_state_moved"), batch_id=batch.id)+ else:+ logger.warning(self._event("batch_recovered_for_retry"), attempt=batch.latest_attempt)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.pyindex 1f1a6db0d75b..0d1d0bc17a6e 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@@ -328,6 +328,7 @@ class DuckgresBatchConsumerAdapter:attempt: int,error_response: dict[str, Any] | None = None,batch_created_at: datetime | None = None, # delta-sink denormalization only; unused here+ expected_state_changed_at: datetime | None = None, # delta-sink recovery CAS only; unused here) -> None:# Invariant: never write ANY status over a terminal 'failed' — statuses# are latest-row-wins, so an unconditional write would un-retire a batch@@ -398,6 +399,17 @@ class DuckgresBatchConsumerAdapter:lease_ttl_seconds=lease_ttl_seconds,)+ async def delete_expired_lease(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ team_id: int,+ schema_id: str,+ ) -> None:+ # Protocol conformance only: its sole caller is the base engine's recovery+ # sweep, which never runs here — DuckgresBatchConsumer overrides _recovery_sweep.+ return None+async def get_stale_executing(self,conn: psycopg.AsyncConnection[Any],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 7e96aa0cc28b..74d63a414858 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@@ -40,9 +40,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_group_by_key,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (+ _UNSET,FRESHNESS_WINDOW_SECONDS,BatchQueue,PendingBatch,+ _Unset,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.metrics import (OLDEST_UNCLAIMED_BATCH_SECONDS,@@ -157,10 +159,13 @@ class DeltaBatchConsumerAdapter:attempt: int,error_response: dict[str, Any] | None = None,batch_created_at: datetime | None = None,+ expected_state_changed_at: datetime | None | _Unset = _UNSET,) -> None:# '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).+ # expected_state_changed_at additionally fences the recovery re-queue against a+ # live owner that completed the batch after the stale scan (see the sweep).inserted = await BatchQueue.update_status_unless_failed(conn,batch_id=batch_id,@@ -169,9 +174,13 @@ class DeltaBatchConsumerAdapter:error_response=error_response,batch_created_at=batch_created_at,supersedable_failed_error=LOCK_TAKEOVER_LATEST_ERROR,+ expected_state_changed_at=expected_state_changed_at,)if not inserted:- raise OwnershipLostError(f"batch {batch_id} is already failed; refusing to write '{job_state}' over it")+ raise OwnershipLostError(+ f"batch {batch_id} moved under this writer (already failed or state advanced); "+ f"refusing to write '{job_state}' over it"+ )async def fail_run(self,@@ -249,6 +258,15 @@ class DeltaBatchConsumerAdapter:lease_ttl_seconds=lease_ttl_seconds,)+ async def delete_expired_lease(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ team_id: int,+ schema_id: str,+ ) -> None:+ await BatchQueue.delete_expired_lease(conn, team_id=team_id, schema_id=schema_id)+async def get_stale_executing(self,conn: psycopg.AsyncConnection[Any],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 be0866e713f7..11bc231b412d 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@@ -64,6 +64,18 @@ FRESHNESS_WINDOW_SECONDS = 48 * 60 * 60FRESHNESS_WINDOW = f"{FRESHNESS_WINDOW_SECONDS} seconds"+class _Unset:+ """Sentinel for ``update_status_unless_failed(expected_state_changed_at=...)``.++ ``state_changed_at`` is nullable, so ``None`` is a legitimate value to arm the+ compare-and-swap against. ``_UNSET`` is the only signal for "no CAS wanted",+ keeping an ordinary write and a CAS against a genuinely-null observation apart.+ """+++_UNSET = _Unset()++def pending_batch_select_columns(status_alias: str) -> str:return f"""b.id, b.team_id, b.schema_id, b.source_id, b.job_id,@@ -165,7 +177,9 @@ 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:+def build_status_dual_write_unless_failed_sql(+ *, with_batch_created_at: bool, with_expected_state_changed_at: bool = False+) -> str:"""Guarded twin of :func:`build_status_dual_write_sql`: inserts nothing over aterminal 'failed', so a consumer's newer executing/succeeded rows can'tun-retire a batch fail_run already failed. A 'failed' carrying@@ -173,12 +187,24 @@ def build_status_dual_write_unless_failed_sql(*, with_batch_created_at: bool) ->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.++ ``with_expected_state_changed_at`` arms a compare-and-swap on the caller's+ observed ``state_changed_at`` — the recovery sweep's fence against a live owner+ that completed the batch between the stale scan and the re-queue. The predicate+ rides the ``target`` CTE, so it is evaluated under the same ``FOR UPDATE OF b``+ row lock that already serializes this write: a stale requeue matches no target,+ inserts nothing, and reports 0 without racing the owner's denormalized write."""created_at_predicate = ("b.created_at = %(batch_created_at)s"if with_batch_created_atelse f"b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'")+ cas_predicate = (+ "\n AND b.state_changed_at IS NOT DISTINCT FROM %(expected_state_changed_at)s"+ if with_expected_state_changed_at+ else ""+ )return f"""WITH target AS (SELECT b.id@@ -189,7 +215,7 @@ def build_status_dual_write_unless_failed_sql(*, with_batch_created_at: bool) ->AND (b.latest_state IS DISTINCT FROM 'failed'OR s.error_response->>'error' = %(supersedable_failed_error)s- )+ ){cas_predicate}FOR UPDATE OF b),ins AS (@@ -339,14 +365,16 @@ def _stale_executing_sql(scope_sql: str = "") -> str:The denormalized-column pre-filter keeps the lateral probing onlycurrently-executing batches. The lateral itself must stay: heartbeatsrefresh the status log, deliberately not the column, so the grace clock- comes from ``s.created_at``.+ comes from ``s.created_at``. The observed ``state_changed_at`` rides along+ so the recovery sweep can compare-and-swap its re-queue against it.Bounded by ``CLAIM_ELIGIBILITY_INTERVAL``, matching the claim path: arecovered batch gets re-processed, which needs its parquet to still exist."""return f"""SELECT- {pending_batch_select_columns("s")}+ {pending_batch_select_columns("s")},+ b.state_changed_atFROM {BATCH_TABLE} b{latest_status_lateral("b", "s", join="INNER")}LEFT JOIN {LEASE_TABLE} l ON l.team_id = b.team_id AND l.schema_id = b.schema_id@@ -401,6 +429,8 @@ class PendingBatch:metadata: dict[str, Any]latest_attempt: intcreated_at: datetime | None = None+ # Observed denormalized state clock at read time; None for sinks that don't surface it.+ state_changed_at: datetime | None = Nonedef to_export_signal(self) -> dict[str, Any]:"""Temporary bridge: convert a PendingBatch into an ExportSignalMessage dict@@ -731,9 +761,16 @@ class BatchQueue:error_response: dict[str, Any] | None = None,batch_created_at: datetime | None = None,supersedable_failed_error: str | None = None,+ expected_state_changed_at: datetime | None | _Unset = _UNSET,) -> bool:"""Guarded twin of :meth:`update_status`: returns False (writing nothing) over- a terminal 'failed' — see :func:`build_status_dual_write_unless_failed_sql`."""+ a terminal 'failed' — see :func:`build_status_dual_write_unless_failed_sql`.++ ``expected_state_changed_at`` additionally arms a compare-and-swap on the+ observed ``state_changed_at`` (pass it, including a genuine ``None``, to+ require the state to be unchanged; leave it unset for an ordinary write): a+ stale requeue then writes nothing and returns False, same as a refused one."""+ arm_cas = not isinstance(expected_state_changed_at, _Unset)params: dict[str, Any] = {"batch_id": batch_id,"job_state": job_state,@@ -743,8 +780,13 @@ class BatchQueue:}if batch_created_at is not None:params["batch_created_at"] = batch_created_at+ if arm_cas:+ params["expected_state_changed_at"] = expected_state_changed_atcursor = await conn.execute(- build_status_dual_write_unless_failed_sql(with_batch_created_at=batch_created_at is not None),+ build_status_dual_write_unless_failed_sql(+ with_batch_created_at=batch_created_at is not None,+ with_expected_state_changed_at=arm_cas,+ ),params,)row = await cursor.fetchone()@@ -759,19 +801,46 @@ class BatchQueue:owner_token: str,lease_ttl_seconds: int = LEASE_TTL_SECONDS,) -> bool:- """Extend this owner's group lease. Returns False if the lease was lost (row gone or reclaimed)."""+ """Extend this owner's live group lease. Expiry is terminal: False means ownership+ is gone for good (row deleted, reclaimed, or expired) and the owner must abandon.++ The ``expires_at > now()`` predicate makes a lapsed lease unrenewable, so an owner+ whose lease expired (e.g. a >TTL queue-DB blip during a long write) can't resurrect+ it and finish over a batch the recovery sweep has already re-queued."""async with conn.cursor() as cur:await cur.execute(f"""UPDATE {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+ @staticmethod+ async def delete_expired_lease(+ conn: psycopg.AsyncConnection[Any],+ *,+ team_id: int,+ schema_id: str,+ ) -> None:+ """Delete the group's lease only if it has already expired; a live lease never matches.++ The recovery sweep claims a corpse with this before re-queueing its batches, so a+ resurrecting owner's renew matches nothing even on pods still running the permissive+ (pre-expiry-fence) renew during a rollout.+ """+ await conn.execute(+ f"""+ DELETE FROM {LEASE_TABLE}+ WHERE team_id = %(team_id)s AND schema_id = %(schema_id)s AND expires_at <= now()+ """,+ {"team_id": team_id, "schema_id": schema_id},+ )+@staticmethodasync def verify_advisory_lock(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.pyindex a0c37e7e3448..fa9e2ab269ee 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@@ -1,4 +1,5 @@import asyncio+from datetime import UTC, datetimefrom typing import Anyimport pytest@@ -365,7 +366,8 @@ class TestRecoverySweep:@pytest.mark.asyncioasync def test_retries_stale_below_max(self):consumer = _make_consumer(max_attempts=3)- stale_batch = _make_batch(latest_attempt=1)+ # The observed state clock must ride into the re-queue as its CAS guard.+ stale_batch = _make_batch(latest_attempt=1, state_changed_at=datetime(2026, 1, 1, tzinfo=UTC))with (patch(@@ -392,6 +394,7 @@ class TestRecoverySweep:error_response={"error": "executing timed out - pod restart or OOM"},batch_created_at=stale_batch.created_at,supersedable_failed_error=LOCK_TAKEOVER_LATEST_ERROR,+ expected_state_changed_at=stale_batch.state_changed_at,)mock_unlock.assert_called_once_with(consumer._recovery_conn, batches=[stale_batch], owner_token=consumer._owner_tokendiff --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 63b1287d6d8e..05924f1f77ec 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@@ -1,13 +1,21 @@import re+import time+import asynciofrom datetime import timedeltafrom typing import Anyfrom uuid import uuid4import pytest+from unittest.mock import AsyncMock, patchimport psycopgfrom 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.consumer import (+ BatchConsumer,+ ConsumerConfig,+ DeltaBatchConsumerAdapter,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (BATCH_TABLE,CLAIM_ELIGIBILITY_INTERVAL,@@ -16,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineSTATUS_VIEW,BatchQueue,PendingBatch,+ build_status_dual_write_sql,)# Distinct per-pod identities for the group-lease tests.@@ -413,6 +422,18 @@ async def _insert_backdated_executing()+async def _wait_until_a_backend_blocks_on_lock(probe: psycopg.AsyncConnection[Any], *, timeout: float = 5.0) -> None:+ """Poll until some backend is parked waiting on a lock (the isolated test DB+ has no other traffic, so this is the requeue blocking behind the owner)."""+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ cur = await probe.execute("SELECT 1 FROM pg_stat_activity WHERE wait_event_type = 'Lock' LIMIT 1")+ if await cur.fetchone() is not None:+ return+ await asyncio.sleep(0.02)+ raise AssertionError("no backend ever blocked on a lock")++@pytest.mark.django_db(transaction=True)class TestBatchQueueGroupLease:@pytest.mark.asyncio@@ -523,6 +544,31 @@ class TestBatchQueueLeaseRenewal:assert renewed is False+ @pytest.mark.asyncio+ async def test_renew_of_expired_lease_returns_false(self, conn):+ # Expiry is terminal: an owner whose lease lapsed (e.g. a >TTL connectivity+ # blip) must not resurrect it and finish over a recovery re-queue.+ await _insert_lease(conn, team_id=1, schema_id="s1", owner=OWNER_A, expires_in_seconds=-1)++ renewed = await BatchQueue.renew_lease(+ conn, team_id=1, schema_id="s1", owner_token=OWNER_A, lease_ttl_seconds=300+ )++ assert renewed is False, "the owner of an expired lease must abandon, not renew"++ @pytest.mark.parametrize("expires_in_seconds,deleted", [(-1, True), (300, False)])+ @pytest.mark.asyncio+ async def test_sweep_delete_removes_only_the_expired_corpse(self, conn, expires_in_seconds, deleted):+ await _insert_lease(conn, team_id=1, schema_id="s1", owner=OWNER_A, expires_in_seconds=expires_in_seconds)++ await BatchQueue.delete_expired_lease(conn, team_id=1, schema_id="s1")++ assert (await _lease_count(conn, schema_id="s1") == 0) is deleted+ renewed = await BatchQueue.renew_lease(+ conn, team_id=1, schema_id="s1", owner_token=OWNER_A, lease_ttl_seconds=300+ )+ assert renewed is (not deleted), "delete must fence the old owner without touching live leases"+@pytest.mark.django_db(transaction=True)class TestVerifyGroupLeaseSync:@@ -1119,6 +1165,96 @@ class TestUpdateStatusUnlessFailed:row = await cur.fetchone()assert row is not None and row[0] == 2 # the log still grows+ @pytest.mark.parametrize(+ "expected_kind,requeue_lands",+ [("stale", False), ("current", True), ("omitted", True)],+ )+ @pytest.mark.asyncio+ async def test_cas_requeue_yields_to_states_written_after_the_read(self, conn, expected_kind, requeue_lands):+ # The recovery-sweep race: the sweep reads an executing batch, the owner+ # completes it, then the sweep re-queues off its now-stale read. The CAS+ # rides the FOR UPDATE OF b target, so a stale read writes nothing at all.+ bid = await _insert_batch(conn)+ await _insert_backdated_executing(conn, batch_id=bid, age_seconds=120, attempt=1)+ _, _, observed = await _batch_state(conn, bid)+ await BatchQueue.update_status(conn, batch_id=bid, job_state="succeeded", attempt=1)+ _, _, current = await _batch_state(conn, bid)++ cas_kwargs: dict[str, Any] = {}+ if expected_kind == "stale":+ cas_kwargs["expected_state_changed_at"] = observed+ elif expected_kind == "current":+ cas_kwargs["expected_state_changed_at"] = current+ landed = await BatchQueue.update_status_unless_failed(+ conn, batch_id=bid, job_state="waiting_retry", attempt=1, **cas_kwargs+ )++ state, _, _ = await _batch_state(conn, bid)+ if requeue_lands:+ assert (landed, state) == (True, "waiting_retry")+ else:+ assert (landed, state) == (False, "succeeded")+ 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, "a CAS miss must not even append a status row"++ @pytest.mark.asyncio+ async def test_cas_armed_against_null_observation_still_yields(self, conn):+ # state_changed_at is nullable, so the stale scan can observe None. Passing+ # None must arm the CAS (not fall through to an unconditional write): a write+ # that landed after the read still has to lose.+ bid = await _insert_batch(conn)+ await BatchQueue.update_status(conn, batch_id=bid, job_state="executing", attempt=1)+ await conn.execute(f"UPDATE {BATCH_TABLE} SET state_changed_at = NULL WHERE id = %s", (bid,))+ await BatchQueue.update_status(conn, batch_id=bid, job_state="succeeded", attempt=1)++ landed = await BatchQueue.update_status_unless_failed(+ conn, batch_id=bid, job_state="waiting_retry", attempt=1, expected_state_changed_at=None+ )++ state, _, _ = await _batch_state(conn, bid)+ assert (landed, state) == (False, "succeeded")+ 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, "a CAS miss against a null observation must not append a status row"++ @pytest.mark.asyncio+ async def test_requeue_appends_no_status_when_owner_commits_mid_write(self, conn, conn_b, _db_url):+ # True concurrency: the owner's completion commits *while* the CAS requeue is+ # already running. The requeue's target rides FOR UPDATE OF b, so it blocks on+ # the owner's row lock and re-reads the moved state — appending no stray status.+ bid = await _insert_batch(conn)+ await _insert_backdated_executing(conn, batch_id=bid, age_seconds=120, attempt=1)+ _, _, observed = await _batch_state(conn, bid)++ async with await psycopg.AsyncConnection.connect(_db_url, autocommit=False) as owner_conn:+ async with owner_conn.transaction():+ # Owner completes the batch but holds the row lock (uncommitted).+ await owner_conn.execute(+ build_status_dual_write_sql(with_batch_created_at=False),+ {"batch_id": bid, "job_state": "succeeded", "attempt": 1, "error_response": None},+ )+ requeue = asyncio.create_task(+ BatchQueue.update_status_unless_failed(+ conn,+ batch_id=bid,+ job_state="waiting_retry",+ attempt=1,+ expected_state_changed_at=observed,+ )+ )+ await _wait_until_a_backend_blocks_on_lock(conn_b)+ # Leaving the transaction commits the owner's succeeded write.+ landed = await requeue++ state, _, _ = await _batch_state(conn, bid)+ assert (landed, state) == (False, "succeeded")+ cur = await conn.execute(+ f"SELECT count(*) FROM {STATUS_TABLE} WHERE batch_id = %s AND job_state = 'waiting_retry'", (bid,)+ )+ row = await cur.fetchone()+ assert row is not None and row[0] == 0, "a requeue that loses the race must leave no waiting_retry status row"+@pytest.mark.django_db(transaction=True)class TestClaimGates:@@ -1299,3 +1435,33 @@ class TestSyncTypeFleetPartition:assert [str(b.id) for b in cdc_stale] == [cdc_bid]assert {str(b.id) for b in all_stale} == {cdc_bid, fr_bid}++[email protected]_db(transaction=True)+class TestRecoverySweepVsLiveOwner:+ @pytest.mark.asyncio+ async def test_owner_completion_between_scan_and_requeue_stays_succeeded(self, conn, _db_url):+ # The headline race: the sweep scans a stale executing batch, a resurrected+ # owner completes it, then the sweep's re-queue must yield instead of landing.+ bid = await _insert_batch(conn)+ await _insert_backdated_executing(conn, batch_id=bid, age_seconds=120, attempt=1)++ consumer = BatchConsumer(+ config=ConsumerConfig(database_url=_db_url, recovery_grace_seconds=60),+ process_batch=AsyncMock(),+ )+ consumer._recovery_conn = conn++ real_get_stale = DeltaBatchConsumerAdapter.get_stale_executing++ async def scan_then_owner_completes(adapter, c, **kwargs):+ stale = await real_get_stale(adapter, c, **kwargs)+ await BatchQueue.update_status(conn, batch_id=bid, job_state="succeeded", attempt=1)+ return stale++ with patch.object(DeltaBatchConsumerAdapter, "get_stale_executing", scan_then_owner_completes):+ await consumer._recovery_sweep()++ cur = await conn.execute(f"SELECT latest_state FROM {BATCH_TABLE} WHERE id = %s", (bid,))+ row = await cur.fetchone()+ assert row is not None and row[0] == "succeeded", "the sweep must not re-queue a batch its owner finished"