: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(warehouse-sources): make duckgres eligibility team filter sargable (#73918)
Eric Duonge3a0e76dedd7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.pyindex 1e8aa24cf1c0..6931b100cb65 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py@@ -145,9 +145,10 @@ BLOCKED_LIVE_BATCH_CONDITION = f"""())"""+# Shared CTE prelude for eligibility queries (note the trailing comma — callers-# append their own CTEs/SELECT). Expects a %(team_ids)s bigint[] parameter-# (NULL = no team filter).+# append their own CTEs/SELECT). Callers pass scoped=True when team_ids is a+# concrete list; see _team_scope.## - cand_runs: runs with pending duckgres work — a delta-succeeded batch that is# not yet duckgres-succeeded. This is the driving set: every run the gate or@@ -161,7 +162,25 @@ BLOCKED_LIVE_BATCH_CONDITION = f"""(# Duckgres-failed (including superseded).# - incomplete_runs: non-failed runs that still owe unapplied data batches;# these block newer runs of the same schema (cross-run head-of-line).-ELIGIBILITY_CTES = f"""cand_runs AS MATERIALIZED (+def _team_scope(alias: str, *, scoped: bool) -> str:+ """Sargable per-team filter for the eligibility scans.++ In prod ``team_ids`` is always the concrete enabled-team list, so emit a+ plain ``= ANY(%(team_ids)s)``: the planner prunes to those teams via the+ ``(team_id, ...)`` index and never reads a non-enabled team's rows. The old+ ``%(team_ids)s IS NULL OR ...`` form existed only to also serve the+ dev/ungated case (team_ids IS NULL), but with a bound parameter Postgres+ builds a generic plan that cannot fold the NULL check — so it cannot use the+ index and seq-scans the whole shared partition window. A single non-enabled+ team with a high-volume (e.g. failing) source then dominates that scan and+ can push the eligibility/supersede queries past their statement timeout,+ even though none of those rows is ever sinked. Unscoped (dev) = match all.+ """+ return f"AND {alias}.team_id = ANY(%(team_ids)s)" if scoped else ""+++def _eligibility_ctes(scoped: bool) -> str:+ return f"""cand_runs AS MATERIALIZED (-- Runs with pending duckgres work: a delta-succeeded batch that is not yet-- duckgres-succeeded. Superset of every run the gate/supersede compares;-- run_starts/failed_runs scope to it so the work is bounded by the backlog.@@ -170,14 +189,14 @@ ELIGIBILITY_CTES = f"""cand_runs AS MATERIALIZED (JOIN {_latest_status_lateral(STATUS_TABLE, "cb")} cds ON cds.job_state = 'succeeded'LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "cb")} cdgs ON trueWHERE cb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND (%(team_ids)s::bigint[] IS NULL OR cb.team_id = ANY(%(team_ids)s))+ {_team_scope("cb", scoped=scoped)}AND (cdgs.job_state IS NULL OR cdgs.job_state <> 'succeeded')),run_starts AS MATERIALIZED (SELECT b_rs.run_uuid, min(b_rs.created_at) AS started_atFROM {BATCH_TABLE} b_rsWHERE b_rs.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND (%(team_ids)s::bigint[] IS NULL OR b_rs.team_id = ANY(%(team_ids)s))+ {_team_scope("b_rs", scoped=scoped)}AND b_rs.run_uuid IN (SELECT run_uuid FROM cand_runs)GROUP BY b_rs.run_uuid),@@ -188,7 +207,7 @@ ELIGIBILITY_CTES = f"""cand_runs AS MATERIALIZED (JOIN {_latest_status_lateral(STATUS_TABLE, "fb")} fds ON trueWHERE fb.run_uuid = cr.run_uuidAND fb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND (%(team_ids)s::bigint[] IS NULL OR fb.team_id = ANY(%(team_ids)s))+ {_team_scope("fb", scoped=scoped)}AND fds.job_state = 'failed')OR EXISTS (@@ -196,7 +215,7 @@ ELIGIBILITY_CTES = f"""cand_runs AS MATERIALIZED (JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "fb")} fdgs ON trueWHERE fb.run_uuid = cr.run_uuidAND fb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND (%(team_ids)s::bigint[] IS NULL OR fb.team_id = ANY(%(team_ids)s))+ {_team_scope("fb", scoped=scoped)}AND fdgs.job_state = 'failed')),@@ -212,7 +231,7 @@ ELIGIBILITY_CTES = f"""cand_runs AS MATERIALIZED (AND oa.run_uuid = old.run_uuidAND oa.batch_index = old.batch_indexWHERE old.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND (%(team_ids)s::bigint[] IS NULL OR old.team_id = ANY(%(team_ids)s))+ {_team_scope("old", scoped=scoped)}AND old.is_final_batch = falseAND oa.id IS NULLAND old.run_uuid NOT IN (SELECT run_uuid FROM failed_runs)@@ -303,10 +322,11 @@ class DuckgresBatchQueue:Liveness: older runs either complete, fail (max attempts), or aresuperseded by ``supersede_replaced_runs`` — all three unblock the gate."""+ scoped = team_ids is not Noneasync with conn.cursor(row_factory=dict_row) as cur:await cur.execute(f"""- WITH {ELIGIBILITY_CTES}+ WITH {_eligibility_ctes(scoped)}team_org AS (-- Enabled-team -> (org, budget) mapping, passed in because the-- queue DB has no teams table. Empty when no caps apply.@@ -336,7 +356,7 @@ class DuckgresBatchQueue:LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON trueWHEREb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND (%(team_ids)s::bigint[] IS NULL OR b.team_id = ANY(%(team_ids)s))+ {_team_scope("b", scoped=scoped)}AND (%(eligible_schema_ids)s::varchar[] IS NULL OR b.schema_id = ANY(%(eligible_schema_ids)s))-- In-flight groups: re-claiming them burns the LIMIT and-- max_groups budget on work this pod can't start.@@ -595,10 +615,11 @@ class DuckgresBatchQueue:Skips batches currently 'executing' (their attempt resolves on its own)and anything already terminal. Returns the number of batches superseded."""+ scoped = team_ids is not Noneasync with _statement_timeout(conn, ELIGIBILITY_QUERY_STATEMENT_TIMEOUT_MS), conn.cursor() as cur:await cur.execute(f"""- WITH {ELIGIBILITY_CTES}+ WITH {_eligibility_ctes(scoped)}replace_heads AS MATERIALIZED (SELECT nb.team_id, nb.schema_id, nb.run_uuid, rs.started_atFROM {BATCH_TABLE} nb@@ -610,7 +631,7 @@ class DuckgresBatchQueue:AND na.run_uuid = nb.run_uuidAND na.batch_index = nb.batch_indexWHERE nb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND (%(team_ids)s::bigint[] IS NULL OR nb.team_id = ANY(%(team_ids)s))+ {_team_scope("nb", scoped=scoped)}AND nds.job_state = 'succeeded'AND nb.batch_index = 0AND nb.is_final_batch = false@@ -678,10 +699,11 @@ class DuckgresBatchQueue:the page. Durable per-schema failure tracking lives onDuckgresSinkSchemaState (this count ages out with queue retention)."""+ scoped = team_ids is not Noneasync with _statement_timeout(conn, ELIGIBILITY_QUERY_STATEMENT_TIMEOUT_MS), conn.cursor() as cur:await cur.execute(f"""- WITH {ELIGIBILITY_CTES}+ WITH {_eligibility_ctes(scoped)}backlog AS (SELECTb.created_at,@@ -698,7 +720,7 @@ class DuckgresBatchQueue:AND a.run_uuid = b.run_uuidAND a.batch_index = b.batch_indexWHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND (%(team_ids)s::bigint[] IS NULL OR b.team_id = ANY(%(team_ids)s))+ {_team_scope("b", scoped=scoped)}AND (%(eligible_schema_ids)s::varchar[] IS NULL OR b.schema_id = ANY(%(eligible_schema_ids)s))AND ds.job_state = 'succeeded'AND b.is_final_batch = falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.pyindex 0217ff501e2d..3ccbdc5d09e9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py@@ -18,6 +18,8 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineDUCKGRES_STATUS_TABLE,DUCKGRES_STATUS_VIEW,DuckgresBatchQueue,+ _eligibility_ctes,+ _team_scope,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (BATCH_TABLE,@@ -514,6 +516,50 @@ class TestDuckgresTeamFilterAndBacklog:assert oldest_age is None and blocked_age is None+class TestTeamScopeSargable:+ """The team filter must become a plain, sargable ``= ANY(...)`` when+ team_ids is a concrete (prod) list, and disappear entirely when unscoped+ (dev/tests) — never the old ``%(team_ids)s IS NULL OR ...`` form, which+ defeats index pruning under a bound parameter. See _team_scope's+ docstring in jobs_db.py."""++ def test_team_scope_scoped_emits_plain_any(self) -> None:+ assert _team_scope("cb", scoped=True) == "AND cb.team_id = ANY(%(team_ids)s)"++ def test_team_scope_unscoped_is_empty(self) -> None:+ assert _team_scope("cb", scoped=False) == ""++ def test_eligibility_ctes_scoped_has_no_is_null_or(self) -> None:+ # Other IS NULL OR predicates (e.g. the duckgres-status join) are+ # unrelated and must stay; only the old non-sargable team_ids form+ # must be gone.+ assert "team_ids)s::bigint[] IS NULL OR" not in _eligibility_ctes(True)++ def test_eligibility_ctes_unscoped_has_no_team_ids_param(self) -> None:+ assert "%(team_ids)s" not in _eligibility_ctes(False)++ def test_eligibility_ctes_scoped_uses_sargable_any(self) -> None:+ assert "team_id = ANY(%(team_ids)s)" in _eligibility_ctes(True)++ @pytest.mark.django_db(transaction=True)+ @pytest.mark.asyncio+ async def test_backlog_stats_team_scoping_preserves_semantics(self, conn: psycopg.AsyncConnection[Any]) -> None:+ """The sargable rewrite must count exactly the same batches as the old+ ``IS NULL OR`` form: scoped to [1] counts only team 1's batch, and+ unscoped (None) counts every team's batch."""+ team1_batch = await _insert_batch(conn, team_id=1, run_uuid="run-team-1", schema_id="schema-1")+ await BatchQueue.update_status(conn, batch_id=team1_batch, job_state="succeeded", attempt=1)++ team999_batch = await _insert_batch(conn, team_id=999, run_uuid="run-team-999", schema_id="schema-1")+ await BatchQueue.update_status(conn, batch_id=team999_batch, job_state="succeeded", attempt=1)++ count, _, blocked, _, failing = await DuckgresBatchQueue.get_backlog_stats(conn, team_ids=[1])+ assert (count, blocked, failing) == (1, 0, 0) # team 999 excluded++ count, _, blocked, _, failing = await DuckgresBatchQueue.get_backlog_stats(conn, team_ids=None)+ assert (count, blocked, failing) == (2, 0, 0) # unscoped = all teams++@pytest.mark.django_db(transaction=True)class TestBackfillGating:@pytest.mark.asyncio