: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): keep the v3 batch claim fast under planner drift (#110610)
Tom Owersdb9efd4437ca
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 b96f052ac0c8..d15ef74ff5c4 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@@ -1475,16 +1475,25 @@ class TestPollFailureLiveness:consumer = BatchConsumer(config=config, process_batch=AsyncMock())succeeded = asyncio.Event()+ refailed = asyncio.Event()fetch_calls = 0+ jitter_windows: list[float] = []async def fetch(*args: Any, **kwargs: Any) -> list[PendingBatch]:nonlocal fetch_callsfetch_calls += 1- if fetch_calls <= 2:+ if fetch_calls in (1, 2, 4):await asyncio.sleep(3600) # times out- succeeded.set()+ if fetch_calls == 3:+ succeeded.set()+ if fetch_calls >= 5:+ refailed.set()return []+ def record_window(low: float, high: float) -> float:+ jitter_windows.append(high)+ return low+with (patch.object(consumer, "_connect", new_callable=AsyncMock, side_effect=lambda **kwargs: _make_healthy_conn()@@ -1503,13 +1512,18 @@ class TestPollFailureLiveness:"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.release_all_owned_leases",new_callable=AsyncMock,),+ patch(f"{batch_consumer_module.__name__}.random.uniform", side_effect=record_window),):run_task = asyncio.create_task(consumer.run())await asyncio.wait_for(succeeded.wait(), timeout=2.0)assert consumer._consecutive_poll_failures == 0+ await asyncio.wait_for(refailed.wait(), timeout=2.0)consumer._shutdown.set()await asyncio.wait_for(run_task, timeout=5.0)+ # The failure after the successful poll starts the backoff over at one interval.+ assert jitter_windows == [0.01, 0.02, 0.01]+class TestStatementTimeoutBackstop:@pytest.mark.parametrize(@@ -1545,35 +1559,36 @@ class TestStatementTimeoutBackstop:class TestPollBackoff:- def test_delay_grows_exponentially_and_caps(self):- # Losing the backoff means lockstep fleet retries; losing the cap means- # unbounded delays.- consumer = _make_consumer(poll_interval_seconds=2.0)- with patch(- "products.warehouse_sources_queue.backend.core.batch_consumer.random.uniform",- return_value=0.0,- ):- consumer._consecutive_poll_failures = 1- assert consumer._poll_retry_delay() == 2.0- consumer._consecutive_poll_failures = 2- assert consumer._poll_retry_delay() == 4.0- consumer._consecutive_poll_failures = 3- assert consumer._poll_retry_delay() == 8.0- consumer._consecutive_poll_failures = 20 # far past the cap- assert consumer._poll_retry_delay() == 30.0 # POLL_BACKOFF_MAX_SECONDS+ @pytest.mark.parametrize(+ "failures,window",+ [+ (0, 2.0), # defensive: a delay asked for before any failure uses the first step+ (1, 2.0),+ (2, 4.0),+ (3, 8.0),+ (5, 32.0),+ (6, 60.0), # POLL_BACKOFF_MAX_SECONDS+ (20, 60.0),# A prolonged outage grows the count without bound; 2 ** (failures - 1) used# to overflow float here and crash the consumer instead of returning the cap.- consumer._consecutive_poll_failures = 5000- assert consumer._poll_retry_delay() == 30.0-- def test_jitter_is_added_within_one_interval(self):+ (5000, 60.0),+ ],+ )+ @pytest.mark.parametrize("draw", ["low", "high"])+ def test_delay_is_the_interval_plus_full_jitter_over_a_doubling_capped_window(self, failures, window, draw):+ # Losing the doubling or the full jitter puts the fleet's retries back in+ # lockstep; losing the cap means unbounded delays; losing the floor lets a+ # failing pod poll faster than a healthy one.consumer = _make_consumer(poll_interval_seconds=2.0)- consumer._consecutive_poll_failures = 1+ consumer._consecutive_poll_failures = failureswith patch(- "products.warehouse_sources_queue.backend.core.batch_consumer.random.uniform",- return_value=1.5,- ):- assert consumer._poll_retry_delay() == 3.5 # 2.0 backoff + 1.5 jitter+ f"{batch_consumer_module.__name__}.random.uniform",+ side_effect=lambda low, high: low if draw == "low" else high,+ ) as mock_uniform:+ delay = consumer._poll_retry_delay()++ mock_uniform.assert_called_once_with(0, window)+ assert delay == (2.0 if draw == "low" else 2.0 + window)class TestFailRun: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.pyindex 2310a321ced8..d68c874e4d2c 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,4 +1,5 @@import re+import jsonimport timeimport asynciofrom collections.abc import Coroutine@@ -1735,6 +1736,80 @@ class TestClaimGates:("run-f", 0),]+ @pytest.mark.parametrize(+ "batches,backoff,expected",+ [+ pytest.param(+ [(0, "waiting_retry", "s"), (1, "pending", "s"), (2, "pending", "s")],+ 3600,+ [],+ id="earlier_retry_in_backoff_blocks_the_rest_of_the_run",+ ),+ pytest.param(+ [(0, "pending", "s"), (1, "waiting_retry", "s"), (2, "pending", "s")],+ 3600,+ [0],+ id="retry_in_backoff_blocks_only_later_batches",+ ),+ pytest.param(+ [(0, "pending", "s"), (1, "pending", "s"), (2, "waiting_retry", "s")],+ 3600,+ [0, 1],+ id="later_retry_in_backoff_does_not_block_earlier_batches",+ ),+ pytest.param(+ [(0, "waiting_retry", "s"), (1, "pending", "s"), (2, "pending", "s")],+ 0,+ [0, 1, 2],+ id="retry_with_elapsed_backoff_is_claimed_with_its_siblings",+ ),+ pytest.param(+ [(0, "executing", "other"), (1, "pending", "s")],+ 0,+ [],+ id="earlier_executing_batch_blocks_even_outside_the_busy_group",+ ),+ ],+ )+ @pytest.mark.asyncio+ async def test_head_of_line_gate_blocks_only_batches_after_the_blocker(self, conn, batches, backoff, expected):+ for batch_index, state, schema_id in batches:+ bid = await _insert_batch(conn, run_uuid="run-hol", schema_id=schema_id, batch_index=batch_index)+ if state != "pending":+ await BatchQueue.update_status(conn, batch_id=bid, job_state=state, attempt=1)++ claimed = await _claim(conn, retry_backoff_base_seconds=backoff)++ assert sorted(b.batch_index for b in claimed) == expected+ await _release(conn, batches=claimed)++ @pytest.mark.asyncio+ async def test_run_gate_probes_once_per_run_not_once_per_batch(self, conn):+ # A per-batch gate probe that the planner answers from a non-partial+ # run_uuid index reads the whole run for every candidate, so a backlog+ # of long runs grows quadratically. One probe per run bounds it.+ from products.warehouse_sources_queue.backend.core.jobs_db import _claim_window_sql++ for i in range(40):+ await _insert_batch(conn, run_uuid="long-run", schema_id="s-long", batch_index=i)+ await _insert_batch(conn, run_uuid="short-run", schema_id="s-short", batch_index=0)++ cur = await conn.execute(+ "EXPLAIN (ANALYZE, FORMAT JSON) WITH " + _claim_window_sql() + " SELECT * FROM narrow",+ {"backoff": 0, "owner": OWNER_A, "limit": 50},+ )+ row = await cur.fetchone()+ assert row is not None+ plan = row[0] if isinstance(row[0], list) else json.loads(row[0])++ def gate_loops(node: dict[str, Any]) -> list[int]:+ own = [node["Actual Loops"]] if str(node.get("Alias", "")).startswith("b_gate") else []+ return own + [loops for child in node.get("Plans", []) for loops in gate_loops(child)]++ loops = gate_loops(plan[0]["Plan"])+ assert loops, "the run gate must scan sourcebatch under the b_gate alias"+ assert max(loops) <= 2+@pytest.mark.asyncioasync def test_state_claim_candidates_can_use_the_claimable_index(self, conn):# The whole point of the state path is index-bound claiming; a predicatediff --git a/products/warehouse_sources_queue/backend/README.md b/products/warehouse_sources_queue/backend/README.mdindex 8c79c383fe7d..175e0ae8dbff 100644--- a/products/warehouse_sources_queue/backend/README.md+++ b/products/warehouse_sources_queue/backend/README.md@@ -77,8 +77,12 @@ Three changes in August 2026 restructured the hot queries after a production loa- [#83022](https://github.com/PostHog/posthog/pull/83022): the failed-run reconcile ran a per-batch latest-status probe for every failed batch in the lookback window, so a failure storm made each sweep take minutes. It now picks winners from the denormalized columns and probes status only for the LIMIT winners.- [#83067](https://github.com/PostHog/posthog/pull/83067): the stranded-run sweep gated raw batch rows, which the planner turned into a hash anti-join over every retained failed batch. It now aggregates into candidate runs first, so each gate is one index probe per run.+A fourth change followed an October 2026 claim stall, after an analyze of the current daily partition:++- The claim query's gates were correlated probes per candidate batch. On a hot partition the partial indexes churn and bloat, so the planner can answer a probe from `sb_run_uuid_idx`, `sb_run_uuid_bi_idx` or `sb_team_schema_idx` instead, and each probe then reads the whole run or group. A backlog of long runs made every poll quadratic. The gates now run once per group (`busy_groups`, `open_groups`) and once per run (`open_runs`), so a bad index choice costs at most one read of each candidate run. The loader also backs off failed polls with full jitter, so the fleet does not retry a struggling claim query in lockstep.+The shared lesson: every query on these tables must scale with the size of its answer (the claimable set, the candidate runs), never with retained failure history, because failure history is largest exactly when the fleet is least healthy.-The `core/jobs_db.py` docstrings on `_state_claim_candidates_sql`, `get_failed_runs` and `_stranded_candidate_runs_sql` carry the details, and plan-shape tests in `test_jobs_db.py` pin the query shapes.+The `core/jobs_db.py` docstrings on `_state_claim_candidates_sql`, `_claim_window_sql`, `get_failed_runs` and `_stranded_candidate_runs_sql` carry the details, and plan-shape tests in `test_jobs_db.py` pin the query shapes.### Adding a `sourcebatch` indexdiff --git a/products/warehouse_sources_queue/backend/core/batch_consumer.py b/products/warehouse_sources_queue/backend/core/batch_consumer.pyindex c97f1d69f02f..882f905e71c1 100644--- a/products/warehouse_sources_queue/backend/core/batch_consumer.py+++ b/products/warehouse_sources_queue/backend/core/batch_consumer.py@@ -45,9 +45,9 @@ RECONCILE_LOOKBACK_SECONDS = 24 * 60 * 60 # wide enough to catch jobs orphanedSHUTDOWN_DRAIN_TIMEOUT_SECONDS = 30.0-# Cap on the exponential backoff between failed polls — flat retries make the-# whole fleet hammer a degraded queue DB in lockstep.-POLL_BACKOFF_MAX_SECONDS = 30.0+# Cap on the jitter window between failed polls — flat retries make the whole+# fleet hammer a degraded queue DB in lockstep.+POLL_BACKOFF_MAX_SECONDS = 60.0# Ceiling on the backoff exponent. A prolonged queue-DB outage drives the failure# count into the thousands, and 2 ** (failures - 1) then overflows float when@@ -1635,13 +1635,19 @@ class BatchConsumer:self._metrics.poll_duration_seconds.observe(duration)def _poll_retry_delay(self) -> float:- """Capped, jittered backoff before retrying a failed poll: a degraded queue DB- gets exponentially less pressure and the fleet's retries desynchronize."""+ """Wait before the poll that follows a failed one: the normal poll interval+ plus full jitter over a window that doubles per consecutive failure.++ Full jitter, not a small offset on a fixed backoff: pods that time out+ together otherwise retry together, so a struggling queue DB gets the+ same expensive claim query from the whole fleet at once. The interval+ floor keeps a failing pod from polling faster than a healthy one.+ """base = self._config.poll_interval_secondsfailures = max(self._consecutive_poll_failures, 1)exponent = min(failures - 1, POLL_BACKOFF_MAX_DOUBLINGS)- backoff = min(base * 2**exponent, POLL_BACKOFF_MAX_SECONDS)- return backoff + random.uniform(0, base)+ window = min(base * 2**exponent, POLL_BACKOFF_MAX_SECONDS)+ return base + random.uniform(0, window)def _report_health(self) -> None:"""Report liveness, unless the stuck-batch watchdog or the poll-failure trip fired.diff --git a/products/warehouse_sources_queue/backend/core/jobs_db.py b/products/warehouse_sources_queue/backend/core/jobs_db.pyindex 00c7fb14170f..5b7731a61fd1 100644--- a/products/warehouse_sources_queue/backend/core/jobs_db.py+++ b/products/warehouse_sources_queue/backend/core/jobs_db.py@@ -327,33 +327,29 @@ FAIL_RUN_SCOPED_SQL = _bulk_fail_dual_write_sql(def _state_claim_candidates_sql(sync_type_scope: str = "") -> str:- """Claimable-batch candidates read from the denormalized state columns.-- The claimable scan and every NOT EXISTS gate are answered by the partial- indexes (sb_claimable_idx, sb_run_gate_idx, sb_schema_busy_idx), so the- work tracks the claimable set instead of everything retained. 'pending'- means no status row yet; 'waiting' is deliberately not claimable.-- ``sync_type_scope`` (from :func:`sync_type_scope_sql`) narrows only the outer- candidate set to this fleet's classes. It must never be applied inside the- NOT EXISTS gates below: they have to see other fleets' batches so one- schema's runs stay mutually exclusive across fleets.-- The outer candidate set is likewise bounded by- ``CLAIM_ELIGIBILITY_INTERVAL``: a batch older than that may already have- lost its parquet to retention, so it must never be claimed. The gates keep- ``PARTITION_PRUNING_INTERVAL`` for the same reason the sync-type scope- stays out of them — they must see every row that still exists.-- Selects only the join-back keys ``(id, created_at)``. The caller's fairness- ranking sorts the entire claimable set before its LIMIT can apply, so the- sort input must stay narrow: selecting the wide row here (``metadata``- alone is ~1 KB per batch) made every poll sort megabytes-to-gigabytes of- payload to keep ~50 rows, spilling past ``work_mem`` to disk once a backlog- built up and degrading the whole fleet's polls with it.+ """Claimable batches read from the denormalized state columns, before any gate.++ Answered by ``sb_claimable_idx``, so the scan tracks the claimable set+ instead of everything retained. 'pending' means no status row yet;+ 'waiting' is deliberately not claimable.++ ``sync_type_scope`` (from :func:`sync_type_scope_sql`) narrows only this+ candidate set to this fleet's classes. It must never be applied to the+ gates in :func:`_claim_window_sql`: they have to see other fleets' batches+ so one schema's runs stay mutually exclusive across fleets.++ The candidate set is likewise bounded by ``CLAIM_ELIGIBILITY_INTERVAL``: a+ batch older than that may already have lost its parquet to retention, so it+ must never be claimed. The gates keep ``PARTITION_PRUNING_INTERVAL`` for the+ same reason the sync-type scope stays out of them — they must see every row+ that still exists.++ Selects only the narrow keys that the gates and the fairness ranking need.+ Selecting the wide row here (``metadata`` alone is ~1 KB per batch) made+ every poll sort megabytes-to-gigabytes of payload to keep ~50 rows."""return f"""- SELECT b.id, b.created_at+ SELECT b.id, b.created_at, b.batch_index, b.team_id, b.schema_id, b.run_uuidFROM {BATCH_TABLE} bWHEREb.created_at > now() - interval '{CLAIM_ELIGIBILITY_INTERVAL}'@@ -367,37 +363,106 @@ def _state_claim_candidates_sql(sync_type_scope: str = "") -> str:)))- AND NOT EXISTS (- SELECT 1- FROM {BATCH_TABLE} b_prev- WHERE b_prev.run_uuid = b.run_uuid- AND b_prev.batch_index < b.batch_index- AND b_prev.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND (- b_prev.latest_state = 'executing'- OR (- b_prev.latest_state = 'waiting_retry'- AND b_prev.state_changed_at > now() - make_interval(- secs => %(backoff)s * GREATEST(b_prev.latest_attempt, 1)+ """+++def _claim_window_sql(sync_type_scope: str = "") -> str:+ """CTEs that end in ``narrow``: the gated, fairness-ranked ``(id, created_at)`` claim window.++ The gates are evaluated once per group and once per run, never once per+ candidate batch. A per-batch correlated probe is only cheap while the+ planner answers it from the partial indexes. On a hot daily partition+ those indexes churn and bloat, and after an analyze the planner can pick+ ``sb_run_uuid_idx``, ``sb_run_uuid_bi_idx`` or ``sb_team_schema_idx``+ instead. Each probe then reads every batch of its run or group, so a+ backlog of long runs costs (batches x run length) per poll. Here a bad+ index choice costs at most one run-length read per candidate run.++ Each gate keeps the semantics of the per-batch form:++ - ``busy_groups``: a group with an 'executing' batch is not claimable. It+ is one scan of the executing set, which only ``sb_schema_busy_idx``+ answers cheaply.+ - ``open_groups``: the busy gate, plus no live lease of another owner.+ - ``open_runs``: one ``sb_run_gate_idx`` probe per candidate run. A run+ with a 'failed' batch is not claimable. ``first_blocked_index`` is the+ lowest batch_index that is 'executing' or 'waiting_retry' inside its+ backoff. "No such batch earlier than mine" is the same as "my+ batch_index <= that minimum". The probe is an aggregate in a LATERAL,+ so the planner cannot flatten it into an anti-join whose hash side is+ every failed batch in the pruning window.++ The fairness ranking then runs over the gated rows only, which is the set+ the per-batch form ranked. Per team, oldest first; round-robin across+ teams; the LIMIT applies last.+ """+ return f"""+ claimable AS MATERIALIZED (+ {_state_claim_candidates_sql(sync_type_scope)}+ ),+ busy_groups AS MATERIALIZED (+ SELECT DISTINCT b_busy.team_id, b_busy.schema_id+ FROM {BATCH_TABLE} b_busy+ WHERE b_busy.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND b_busy.latest_state = 'executing'+ ),+ open_groups AS MATERIALIZED (+ SELECT g.team_id, g.schema_id+ FROM (SELECT DISTINCT c.team_id, c.schema_id FROM claimable c) g+ WHERE NOT EXISTS (+ SELECT 1+ FROM busy_groups x+ WHERE x.team_id = g.team_id AND x.schema_id = g.schema_id+ )+ AND NOT EXISTS (+ SELECT 1+ FROM {LEASE_TABLE} l_live+ WHERE l_live.team_id = g.team_id+ AND l_live.schema_id = g.schema_id+ AND l_live.expires_at > now()+ AND l_live.owner_token != %(owner)s+ )+ ),+ open_runs AS MATERIALIZED (+ SELECT r.run_uuid, gate.first_blocked_index+ FROM (+ SELECT DISTINCT c.run_uuid+ FROM claimable c+ JOIN open_groups g ON g.team_id = c.team_id AND g.schema_id = c.schema_id+ ) r+ CROSS JOIN LATERAL (+ SELECT+ bool_or(b_gate.latest_state = 'failed') AS has_failed,+ min(b_gate.batch_index) FILTER (+ WHERE b_gate.latest_state = 'executing'+ OR (+ b_gate.latest_state = 'waiting_retry'+ AND b_gate.state_changed_at > now() - make_interval(+ secs => %(backoff)s * GREATEST(b_gate.latest_attempt, 1)+ ))- )- )- )- AND NOT EXISTS (- SELECT 1- FROM {BATCH_TABLE} b2- WHERE b2.run_uuid = b.run_uuid- AND b2.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND b2.latest_state = 'failed'- )- AND NOT EXISTS (- SELECT 1- FROM {BATCH_TABLE} b_busy- WHERE b_busy.team_id = b.team_id- AND b_busy.schema_id = b.schema_id- AND b_busy.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND b_busy.latest_state = 'executing'- )+ ) AS first_blocked_index+ FROM {BATCH_TABLE} b_gate+ WHERE b_gate.run_uuid = r.run_uuid+ AND b_gate.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND b_gate.latest_state IN ('executing', 'waiting_retry', 'failed')+ ) gate+ WHERE gate.has_failed IS NOT TRUE+ ),+ narrow AS MATERIALIZED (+ SELECT c.id, c.created_at+ FROM claimable c+ JOIN open_groups g ON g.team_id = c.team_id AND g.schema_id = c.schema_id+ JOIN open_runs r ON r.run_uuid = c.run_uuid+ WHERE r.first_blocked_index IS NULL OR c.batch_index <= r.first_blocked_index+ ORDER BY+ row_number() OVER (+ PARTITION BY c.team_id ORDER BY c.created_at ASC, c.batch_index ASC+ ) ASC,+ c.created_at ASC,+ c.batch_index ASC+ LIMIT %(limit)s+ )"""@@ -1019,7 +1084,9 @@ class BatchQueue:join-back, ~LIMIT primary-key probes): the fairness sort has to processthe whole claimable set, so its input must stay narrow or a backlogturns every poll into a disk-spilling sort of full rows (see- :func:`_state_claim_candidates_sql`).+ :func:`_state_claim_candidates_sql`). The gates below run once per+ group and once per run, not once per candidate batch (see+ :func:`_claim_window_sql`).Uses a MATERIALIZED CTE so that candidate selection (with LIMIT) isfully resolved before the lease claim runs. ``candidate_groups`` is@@ -1067,28 +1134,11 @@ class BatchQueue:sync_type_scope, scope_params = sync_type_scope_sql(sync_types=sync_types, exclude_sync_types=exclude_sync_types)- candidates_sql = _state_claim_candidates_sql(sync_type_scope)+ window_sql = _claim_window_sql(sync_type_scope)async with conn.cursor(row_factory=dict_row) as cur:await cur.execute(f"""- WITH narrow AS MATERIALIZED (- {candidates_sql}- 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- ) ASC,- b.created_at ASC,- b.batch_index ASC- LIMIT %(limit)s- ),+ WITH {window_sql},candidates AS MATERIALIZED (SELECTb.id, b.team_id, b.schema_id, b.source_id, b.job_id,