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 claim window contention in the loader (#67775)

estefania3bb8efb205bb
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 3fe9301168d2..55694e13be5a 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
@@ -38,6 +38,12 @@ RECONCILE_LOOKBACK_SECONDS = 24 * 60 * 60 # wide enough to catch jobs orphaned
SHUTDOWN_DRAIN_TIMEOUT_SECONDS = 30.0
+# Per-poll fetch cap multiplier: fetch at most (free slots x this) batches so a poll
+# never leases far more groups than it can dispatch. Runs average ~2 batches per
+# group (batch 0 + final), so x3 gives headroom for multi-batch runs without
+# re-creating the over-claim problem.
+BATCHES_PER_GROUP_FETCH_FACTOR = 3
+
class OwnershipLostError(Exception):
"""Raised when the group lease for a (team_id, schema_id) is no longer held by this consumer."""
@@ -300,7 +306,7 @@ class BatchConsumer:
conn = await self._ensure_poll_conn()
batches = await self._adapter.fetch_and_lock(
conn,
- limit=self._config.poll_limit,
+ limit=self._fetch_limit(available),
retry_backoff_base_seconds=self._config.retry_backoff_base_seconds,
owner_token=self._owner_token,
lease_ttl_seconds=self._lease_ttl_seconds,
@@ -317,27 +323,58 @@ class BatchConsumer:
await self._wait_or_shutdown(self._config.poll_interval_seconds)
continue
- groups = _group_by_key(batches)
-
- logger.debug(
- self._event("poll_returned"),
- batch_count=len(batches),
- group_count=len(groups),
- )
-
- for key, group_batches in groups.items():
- if key in self._in_flight:
- continue
- if len(self._in_flight) >= self._config.max_concurrency:
- break
- task = asyncio.create_task(self._process_group_tracked(key, group_batches))
- self._in_flight[key] = task
- self._metrics.active_groups.inc()
+ await self._dispatch_groups(conn, batches)
await self._wait_or_shutdown(self._config.poll_interval_seconds)
finally:
await self._close()
+ def _fetch_limit(self, available: int) -> int:
+ """Cap the poll fetch so we never lease far more groups than we have free slots to run.
+
+ ``fetch_and_lock`` claims a lease for every group it returns, and a
+ leased-but-undispatched group is dark to the whole fleet until its TTL
+ expires.
+ """
+ return min(self._config.poll_limit, available * BATCHES_PER_GROUP_FETCH_FACTOR)
+
+ async def _dispatch_groups(self, conn: psycopg.AsyncConnection[Any], batches: list[PendingBatch]) -> None:
+ """Start a group task per fetched group, up to ``max_concurrency``; release the rest.
+
+ Groups the poll leased but we cannot dispatch are unlocked immediately —
+ holding their leases would leave them unclaimable fleet-wide until the
+ lease TTL expires. Groups already in flight keep their (just renewed) leases.
+ """
+ groups = _group_by_key(batches)
+
+ logger.debug(
+ self._event("poll_returned"),
+ batch_count=len(batches),
+ group_count=len(groups),
+ )
+
+ undispatched: list[PendingBatch] = []
+ for key, group_batches in groups.items():
+ if key in self._in_flight:
+ continue
+ if len(self._in_flight) >= self._config.max_concurrency:
+ undispatched.extend(group_batches)
+ continue
+ task = asyncio.create_task(self._process_group_tracked(key, group_batches))
+ self._in_flight[key] = task
+ self._metrics.active_groups.inc()
+
+ if undispatched:
+ logger.info(
+ self._event("released_undispatched_groups"),
+ batch_count=len(undispatched),
+ )
+ try:
+ await self._adapter.unlock(conn, batches=undispatched, owner_token=self._owner_token)
+ except Exception as e:
+ logger.exception(self._event("release_undispatched_failed"))
+ capture_exception(e)
+
def _reap_finished_tasks(self) -> None:
"""Remove completed group tasks from the in-flight registry."""
finished = [key for key, task in self._in_flight.items() if task.done()]
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 318d121c71c6..39c6ecb2fe0e 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
@@ -279,6 +279,15 @@ class BatchQueue:
Per-team fairness: candidates are interleaved round-robin across teams so one
team's deep backlog cannot monopolize the ``LIMIT`` window; within a team,
oldest-first order (and so per-run ``batch_index`` ordering) is preserved.
+
+ Disjoint windows across pods: groups live-leased by *another* owner are
+ excluded from candidates entirely, not merely dropped at the claim step.
+ Otherwise every pod computes the same top-``LIMIT`` window and groups
+ already owned elsewhere occupy window slots that losing pods can never
+ claim — with enough of them at the head of the queue the whole window is
+ dead weight and fleet concurrency collapses to roughly one window's worth.
+ Own-leased groups stay in the window so a pod can keep draining a group it
+ already holds.
"""
async with conn.cursor(row_factory=dict_row) as cur:
await cur.execute(
@@ -332,6 +341,14 @@ class BatchQueue:
AND b_busy.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
AND s_busy.job_state = 'executing'
)
+ AND NOT EXISTS (
+ SELECT 1
+ FROM {LEASE_TABLE} l_live
+ WHERE l_live.team_id = b.team_id
+ AND l_live.schema_id = b.schema_id
+ AND l_live.expires_at > now()
+ AND l_live.owner_token != %(owner)s
+ )
ORDER BY
row_number() OVER (
PARTITION BY b.team_id ORDER BY b.created_at ASC, b.batch_index ASC
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 fa9ee2e54e73..71caddc16571 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
@@ -1057,3 +1057,40 @@ class TestShutdown:
assert drained.is_set()
assert len(consumer._in_flight) == 0
+
+
+class TestDispatchGroups:
+ def test_fetch_limit_caps_to_free_slots_and_poll_limit(self):
+ consumer = _make_consumer(max_concurrency=16, poll_limit=50)
+ # 1 free slot must not lease a whole 50-batch window (orphaned-lease regression).
+ assert consumer._fetch_limit(1) == 3
+ assert consumer._fetch_limit(4) == 12
+ assert consumer._fetch_limit(16) == 48
+ wide = _make_consumer(max_concurrency=64, poll_limit=50)
+ assert wide._fetch_limit(64) == 50
+
+ @pytest.mark.asyncio
+ async def test_undispatched_groups_release_their_leases_in_the_same_cycle(self):
+ consumer = _make_consumer(max_concurrency=2)
+ consumer._in_flight[(1, "schema-0")] = AsyncMock()
+
+ dispatched = _make_batch(id="00000000-0000-0000-0000-00000000000a", schema_id="schema-1", run_uuid="run-1")
+ dropped_1 = _make_batch(id="00000000-0000-0000-0000-00000000000b", schema_id="schema-2", run_uuid="run-2")
+ dropped_2 = _make_batch(
+ id="00000000-0000-0000-0000-00000000000c", schema_id="schema-2", run_uuid="run-2", batch_index=1
+ )
+
+ with patch.object(consumer._adapter, "unlock", new=AsyncMock()) as mock_unlock:
+ await consumer._dispatch_groups(_make_healthy_conn(), [dispatched, dropped_1, dropped_2])
+
+ # One free slot: schema-1 dispatched; schema-2's lease must be released now,
+ # not left dark until the 300s TTL expires (the fleet-throughput regression).
+ assert (1, "schema-1") in consumer._in_flight
+ assert (1, "schema-2") not in consumer._in_flight
+ released = mock_unlock.call_args.kwargs["batches"]
+ assert {b.id for b in released} == {dropped_1.id, dropped_2.id}
+
+ task = consumer._in_flight.pop((1, "schema-1"))
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
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 784eb2ef226b..5448af3df61a 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
@@ -709,3 +709,31 @@ class TestGetRunActivitySummary:
assert summary.has_batches is False
assert summary.has_non_terminal is False
assert summary.is_stale is True
+
+
[email protected]_db(transaction=True)
+class TestClaimWindowSkipsForeignLeasedGroups:
+ @pytest.mark.asyncio
+ async def test_foreign_leased_group_does_not_occupy_the_window(self, conn, conn_b):
+ # Two claimable groups; A is older so it sits at the head of the window.
+ await _insert_batch(conn, team_id=1, schema_id="schema-A", job_id="job-A", run_uuid="run-A")
+ await _insert_batch(conn, team_id=2, schema_id="schema-B", job_id="job-B", run_uuid="run-B")
+
+ got_b = await _claim(conn_b, owner=OWNER_B, limit=1)
+ assert [b.schema_id for b in got_b] == ["schema-A"]
+
+ # OWNER_A polls with a window of 1. If foreign-leased groups occupied window
+ # slots (the pre-fix behavior), group A would fill the window, its lease claim
+ # would fail, and OWNER_A would get nothing while group B sat claimable —
+ # window starvation. The fix hands the slot to group B instead.
+ got_a = await _claim(conn, owner=OWNER_A, limit=1)
+ assert [b.schema_id for b in got_a] == ["schema-B"]
+
+ # A holder's own live lease keeps its group claimable (group continuation).
+ got_b_again = await _claim(conn_b, owner=OWNER_B, limit=2)
+ assert "schema-A" in {b.schema_id for b in got_b_again}
+
+ # Expired foreign leases stop shielding the group.
+ await conn.execute(f"UPDATE {LEASE_TABLE} SET expires_at = now() - interval '1 second'")
+ got_a_after_expiry = await _claim(conn, owner=OWNER_A, limit=2)
+ assert "schema-A" in {b.schema_id for b in got_a_after_expiry}