: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): stop the v3 reconcile sweep from starving the claim path (#80285)
James Greenhillaebdd25a2169
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 f12fa588b777..bd4a721441a7 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@@ -12,6 +12,7 @@ import asynciofrom collections.abc import Callable, Coroutinefrom datetime import datetimefrom typing import Any+from uuid import uuid4from django.db import close_old_connections@@ -319,6 +320,20 @@ class DeltaBatchConsumerAdapter:# connection, same periodicity, and isolated so it can't break the sweep.await self._observe_queue_freshness(conn)+ # Single-flight everything below fleet-wide: the sweeps reconcile global+ # queue state, so N pods running them do N times the work of one for zero+ # extra correctness — and their cost scales with the failure backlog,+ # which is exactly when concurrent copies on every pod can saturate the+ # queue DB and starve the claim path (the 2026-08-09 loader stall: 36+ # concurrent sweep queries, claim polls timing out fleet-wide). The+ # freshness probe above deliberately stays outside the slot: every pod+ # must keep its own gauge current, or max() across the fleet pins stale+ # values. The token is throwaway — the slot is never verified or+ # released, it just expires into the next pod's hands.+ if not await BatchQueue.try_acquire_reconcile_sweep_slot(conn, owner_token=str(uuid4())):+ logger.debug("reconcile_sweep_slot_held_elsewhere")+ return+refs = await BatchQueue.get_failed_runs(conn,grace_seconds=grace_seconds,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 ba9932a8807a..bb1e6c704ceb 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@@ -36,6 +36,16 @@ LEASE_TABLE = "sourcegrouplease"# sweep fire together.LEASE_TTL_SECONDS = 300+# Sentinel lease row that single-flights the reconcile sweep across the fleet.+# Real groups have team_id >= 1 and UUID schema ids, so this key can never+# collide with (or be claimed/unlocked as) an actual group. The slot TTL sits+# just under the engine's 300s reconcile interval so single-flighting never+# makes reconcile latency worse than the old every-pod cadence: the first pod+# whose timer fires after expiry wins the next sweep.+RECONCILE_SWEEP_LEASE_TEAM_ID = 0+RECONCILE_SWEEP_LEASE_SCHEMA_ID = "__reconcile-sweep__"+RECONCILE_SWEEP_SLOT_TTL_SECONDS = 240+# Partition pruning hint: only scan partitions within this window.# Set to 2x the retention period so the planner can skip dropped# partitions. Not a correctness filter -- older partitions are already@@ -793,6 +803,46 @@ class BatchQueue:row = await cursor.fetchone()return bool(row and row[0])+ @staticmethod+ async def try_acquire_reconcile_sweep_slot(+ conn: psycopg.AsyncConnection[Any],+ *,+ owner_token: str,+ ttl_seconds: int = RECONCILE_SWEEP_SLOT_TTL_SECONDS,+ ) -> bool:+ """Claim the fleet-wide reconcile-sweep slot; True means this pod runs the sweep.++ A sentinel row in the group-lease table, CAS-acquired only when expired.+ There is deliberately no release and no same-owner re-entrancy clause:+ the TTL *is* the fleet-wide sweep cadence, so at most one sweep starts+ per TTL no matter how many pods (or how many startup sweeps after a+ restart wave) race for it. A lease row rather than a session advisory+ lock for the same reason as group claiming: a lingering pgbouncer+ session must not be able to hold the slot forever — a crashed winner's+ slot frees itself at expiry.+ """+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ INSERT INTO {LEASE_TABLE} (team_id, schema_id, owner_token, expires_at, acquired_at, updated_at)+ VALUES (%(team_id)s, %(schema_id)s, %(owner)s, now() + make_interval(secs => %(ttl)s), now(), now())+ ON CONFLICT (team_id, schema_id) DO UPDATE+ SET owner_token = excluded.owner_token,+ expires_at = excluded.expires_at,+ acquired_at = now(),+ updated_at = now()+ WHERE {LEASE_TABLE}.expires_at <= now()+ RETURNING id+ """,+ {+ "team_id": RECONCILE_SWEEP_LEASE_TEAM_ID,+ "schema_id": RECONCILE_SWEEP_LEASE_SCHEMA_ID,+ "owner": owner_token,+ "ttl": ttl_seconds,+ },+ )+ return await cur.fetchone() is not None+@staticmethodasync def renew_lease(conn: psycopg.AsyncConnection[Any],@@ -1039,6 +1089,20 @@ class BatchQueue:WHEREb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'AND b.latest_state = 'failed'+ -- Implied by the s.created_at lower bound (the denormalizing+ -- status CTEs set state_changed_at to exactly the terminal+ -- status row's created_at), so it changes no semantics: it+ -- exists purely to prune the outer scan BEFORE the DISTINCT ON+ -- sort and the per-row lateral probes. Without it the sort+ -- input is every failed batch in the pruning window — 1.36M+ -- rows during the 2026-08 failure storm, a minutes-long disk+ -- spill at work_mem=4MB that, run by every pod concurrently,+ -- starved the claim path (the 2026-08-09 loader stall).+ -- state_changed_at is nullable; NULL rows must stay visible or a+ -- failed run could strand until the retention prune (the stranded+ -- sweep skips runs that have a failed batch).+ AND (b.state_changed_at IS NULL+ OR b.state_changed_at >= now() - make_interval(secs => %(lookback)s))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)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 29ed5fdc1e29..16640b9df02b 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@@ -1291,6 +1291,43 @@ class TestDeadJobSkip:class TestReconcileFailedRuns:+ @pytest.fixture(autouse=True)+ def _hold_sweep_slot(self):+ """Grant the fleet-wide sweep slot by default — these tests exercise the sweep body, not the slot."""+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.try_acquire_reconcile_sweep_slot",+ new_callable=AsyncMock,+ return_value=True,+ ):+ yield++ @pytest.mark.asyncio+ async def test_slot_held_elsewhere_skips_sweep_but_still_probes_freshness(self):+ # Single-flighting must never silence the freshness gauge: every pod+ # reports it, only the slot winner runs the sweep body.+ consumer = _make_consumer()++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.try_acquire_reconcile_sweep_slot",+ new_callable=AsyncMock,+ return_value=False,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_oldest_unclaimed_batch_age_seconds",+ new_callable=AsyncMock,+ return_value=42.0,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_failed_runs",+ new_callable=AsyncMock,+ ) as mock_failed_runs,+ ):+ await consumer._reconcile_failed_runs()++ assert OLDEST_UNCLAIMED_BATCH_SECONDS._value.get() == 42.0+ mock_failed_runs.assert_not_called()+@pytest.mark.asyncioasync def test_reconcile_reports_queue_freshness_gauge(self):# The gauge feeds the loader's data-freshness alert; if a reconcilediff --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 743edbc7cd40..07e86fb0f1d8 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@@ -195,6 +195,23 @@ def sync_conn(_db_url: str):yield c[email protected]_db(transaction=True)+class TestReconcileSweepSlot:+ @pytest.mark.asyncio+ async def test_first_acquire_wins_and_slot_is_not_reentrant(self, conn, conn_b):+ assert await BatchQueue.try_acquire_reconcile_sweep_slot(conn, owner_token="pod-a") is True+ assert await BatchQueue.try_acquire_reconcile_sweep_slot(conn_b, owner_token="pod-b") is False+ # Same owner is refused too: the slot paces the fleet-wide cadence, it+ # is not an ownership lock — re-entrancy would let one pod sweep in a+ # tight loop, which is exactly the stampede the slot exists to prevent.+ assert await BatchQueue.try_acquire_reconcile_sweep_slot(conn, owner_token="pod-a") is False++ @pytest.mark.asyncio+ async def test_expired_slot_is_reacquirable(self, conn, conn_b):+ assert await BatchQueue.try_acquire_reconcile_sweep_slot(conn, owner_token="pod-a", ttl_seconds=0) is True+ assert await BatchQueue.try_acquire_reconcile_sweep_slot(conn_b, owner_token="pod-b") is True++@pytest.mark.django_db(transaction=True)class TestBatchQueueInsert:@pytest.mark.asyncio