: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): renew v3 group lease at each batch entry (#72850)
estefania0a466f7a84cb
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 67d01aa41bb4..aebc6773ad61 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@@ -619,7 +619,12 @@ class BatchConsumer:return await self._ensure_poll_conn()async def _verify_ownership(self, lock_conn: psycopg.AsyncConnection[Any] | None, batch: PendingBatch) -> None:- """Raise OwnershipLostError if this consumer no longer holds the group lease."""+ """Raise OwnershipLostError if this consumer no longer holds the group lease.++ A pure fail-closed verify: it never extends the lease. Used post-process+ and pre-commit, where an expired lease must stop the write rather than+ revive it. The batch-*entry* check is ``_renew_ownership`` instead.+ """if lock_conn is None:returntry:@@ -631,6 +636,38 @@ class BatchConsumer:if not owns:raise OwnershipLostError(f"group lease lost for ({batch.team_id}, {batch.schema_id})")+ async def _renew_ownership(self, lock_conn: psycopg.AsyncConnection[Any] | None, batch: PendingBatch) -> None:+ """Renew the group lease at batch entry, doubling as the ownership check.++ Without this, a group of many batches each shorter than the heartbeat's+ first tick (grace/3) renews only once — at group dispatch — because the+ per-batch heartbeat is cancelled before it ever fires. The lease then+ expires at cumulative TTL mid-group and the group is abandoned+ (OwnershipLostError) even though this pod is healthily draining it;+ the abandoned backlog then churns between pods at ~50% duty cycle.+ Renewing on entry keeps the lease alive for as long as we keep+ processing. ``renew_lease`` extends a lease that is still live *and*+ still ours, so it never resurrects one that lapsed (the recovery sweep+ may already have re-queued the group) and never steals one another pod+ reclaimed — both raise. Must run before the executing-status write; the+ post-process and pre-commit checks stay pure fail-closed verifies+ (``_verify_ownership``).+ """+ if lock_conn is None:+ return+ try:+ renewed = await self._adapter.renew_lease(+ lock_conn,+ team_id=batch.team_id,+ schema_id=batch.schema_id,+ owner_token=self._owner_token,+ lease_ttl_seconds=self._lease_ttl_seconds,+ )+ except Exception as e:+ raise OwnershipLostError("lease renewal query failed") from e+ if not renewed:+ raise OwnershipLostError(f"group lease lost for ({batch.team_id}, {batch.schema_id})")+async def _batch_heartbeat(self,lock_conn: psycopg.AsyncConnection[Any],@@ -745,7 +782,11 @@ class BatchConsumer:)self._inflight_started[batch.id] = time.monotonic()try:- await self._verify_ownership(lock_conn, batch)+ # Renew-or-abandon at entry (not a pure verify): re-ups the lease on+ # every batch so a long run of short batches can't expire it at+ # cumulative TTL and get abandoned mid-group. The pre-commit check in+ # _process_single_inner stays a fail-closed verify.+ await self._renew_ownership(lock_conn, batch)return await self._process_single_inner(batch, attempt, team_id, schema_id, lock_conn)finally:self._inflight_started.pop(batch.id, 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.pyindex fa9e2ab269ee..2c33444d26d5 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@@ -361,6 +361,66 @@ class TestProcessGroup:process_mock.assert_not_called()mock_unlock.assert_called_once()+ @pytest.mark.asyncio+ async def test_renews_lease_each_batch_so_short_batch_backlog_drains(self):+ # Regression for the between-batch renewal gap: a group of batches each+ # shorter than the heartbeat's first tick (grace/3) renews only once, at+ # dispatch, so the lease expires at cumulative TTL and the group is+ # abandoned mid-drain even while this pod owns it. Entry renewal keeps it+ # alive. Modeled against the real lease semantics + a logical clock the+ # per-batch work advances; a pure-verify entry check drops the tail.+ consumer = _make_consumer(recovery_grace_seconds=300, lease_ttl_seconds=300)+ clock = {"now": 0.0}+ # The claim that produced these batches already leased the group to this pod.+ lease: dict[str, Any] = {"owner": consumer._owner_token, "expires_at": 300.0}+ order: list[int] = []++ async def fake_renew(conn, *, team_id, schema_id, owner_token, lease_ttl_seconds):+ # Mirrors "UPDATE ... WHERE owner_token = ours AND expires_at > now()":+ # extends a live lease we still hold, fails once it lapses or another+ # pod reclaims it (an expired lease is never resurrected here).+ if lease["owner"] == owner_token and lease["expires_at"] > clock["now"]:+ lease["expires_at"] = clock["now"] + lease_ttl_seconds+ return True+ return False++ async def fake_verify(conn, *, team_id, schema_id, owner_token):+ return lease["owner"] == owner_token and lease["expires_at"] > clock["now"]++ async def process(batch):+ order.append(batch.batch_index)+ clock["now"] += 80.0 # each batch < grace/3 (100s); 5 x 80 = 400 > 300s TTL++ consumer._process_batch = process+ batches = [_make_batch(batch_index=i, id=f"00000000-0000-0000-0000-{i + 1:012d}") for i in range(5)]++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.renew_lease",+ side_effect=fake_renew,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.verify_advisory_lock",+ side_effect=fake_verify,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",+ new_callable=AsyncMock,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",+ new_callable=AsyncMock,+ ),+ patch.object(DeltaBatchConsumerAdapter, "should_process_batch", 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"), batches)++ # Whole group drains. With a pure-verify entry check the lease (renewed+ # only at dispatch) expires once cumulative work passes 300s and the group+ # is abandoned, leaving the tail unprocessed.+ assert order == [0, 1, 2, 3, 4]+class TestRecoverySweep:@pytest.mark.asyncio@@ -1547,11 +1607,20 @@ class TestOwnershipVerification:consumer = _make_consumer()processed: list[int] = []+ # Another pod reclaims the lease during batch 0. The batch-entry renewal is+ # the ownership check now, so batch 1's entry renewal fails and the group is+ # abandoned instead of processing the rest.+ owned = {"held": True}+async def track_and_lose_lock(batch):processed.append(batch.batch_index)+ owned["held"] = Falseconsumer._process_batch = track_and_lose_lock+ async def fake_renew(conn, *, team_id, schema_id, owner_token, lease_ttl_seconds):+ return owned["held"]+batches = [_make_batch(batch_index=i, id=f"00000000-0000-0000-0000-{i + 1:012d}") for i in range(3)]with (@@ -1563,18 +1632,21 @@ class TestOwnershipVerification:"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.renew_lease",+ side_effect=fake_renew,+ ),patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.verify_advisory_lock",new_callable=AsyncMock,- side_effect=[True, True, False],+ return_value=True,),patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),):await consumer._process_group((1, "schema-1"), batches)- # Batch 0 processes (verify returns True before batch 0, True before succeeded write),- # batch 1 fails on verify (returns False) and the group is abandoned.- assert len(processed) <= 2+ # Only batch 0 runs; batch 1's entry renewal sees the lease gone and abandons.+ assert processed == [0]mock_unlock.assert_called_once()@pytest.mark.asyncio