: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): bound duckgres eligibility queries with statement_timeout (#66915)
Eric Duongabc738fb6f33
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.pyindex c0b4d9548747..ec7ce79cfb85 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py@@ -137,21 +137,31 @@ class DuckgresBatchConsumerAdapter:returnself._last_maintenance_at = now- superseded = await DuckgresBatchQueue.supersede_replaced_runs(conn, team_ids=team_ids)- SINK_SUPERSEDED_BATCHES_TOTAL.set(superseded)- if superseded:- logger.info("duckgres_superseded_obsolete_batches", count=superseded)-- backlog, oldest_age, blocked, blocked_age = await DuckgresBatchQueue.get_backlog_stats(- conn,- team_ids=team_ids,- blocked_schema_ids=self._blocked_schema_ids,- eligible_schema_ids=self._eligible_schema_ids,- )- SINK_ELIGIBLE_BACKLOG.set(backlog)- SINK_OLDEST_ELIGIBLE_AGE_SECONDS.set(oldest_age or 0.0)- SINK_BLOCKED_BACKLOG.set(blocked)- SINK_BLOCKED_OLDEST_AGE_SECONDS.set(blocked_age or 0.0)+ try:+ # Eligibility-CTE queries scan the queue DB over the partition-pruning+ # window per enabled team; they are statement-timeout bounded (see+ # jobs_db). A timeout or transient queue-DB error must not wedge or+ # crash the poll loop — skip this tick and retry on the next one+ # rather than stacking long-running scans on the shared queue DB.+ superseded = await DuckgresBatchQueue.supersede_replaced_runs(conn, team_ids=team_ids)+ SINK_SUPERSEDED_BATCHES_TOTAL.set(superseded)+ if superseded:+ logger.info("duckgres_superseded_obsolete_batches", count=superseded)++ backlog, oldest_age, blocked, blocked_age = await DuckgresBatchQueue.get_backlog_stats(+ conn,+ team_ids=team_ids,+ blocked_schema_ids=self._blocked_schema_ids,+ eligible_schema_ids=self._eligible_schema_ids,+ )+ SINK_ELIGIBLE_BACKLOG.set(backlog)+ SINK_OLDEST_ELIGIBLE_AGE_SECONDS.set(oldest_age or 0.0)+ SINK_BLOCKED_BACKLOG.set(blocked)+ SINK_BLOCKED_OLDEST_AGE_SECONDS.set(blocked_age or 0.0)+ except Exception as e:+ logger.exception("duckgres_sink_maintenance_query_failed")+ capture_exception(e)+ returnblock_list_was_unset = self._blocked_schema_ids is Nonetry: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 a4cd16e54573..ce9f1a1c6719 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@@ -1,6 +1,8 @@from __future__ import annotationsimport json+from collections.abc import AsyncIterator+from contextlib import asynccontextmanagerfrom typing import Anyimport psycopg@@ -47,6 +49,28 @@ def _latest_status_lateral(status_table: str, batch_alias: str) -> str:)+# Server-side guard for the heavy eligibility-CTE maintenance queries (supersede+# + backlog): each scans PARTITION_PRUNING_INTERVAL of sourcebatch per enabled+# team, and on a high-volume org an unbounded run can saturate the shared queue+# DB. Worse, every ~30s poll starts another, so slow runs stack into many+# concurrent multi-hour scans that also starve the Delta consumer on the same+# DB. Cap each statement so a slow query fails fast and the poll loop retries on+# the next tick instead of wedging. Tune up if a legitimate run needs longer.+ELIGIBILITY_QUERY_STATEMENT_TIMEOUT_MS = 30_000+++@asynccontextmanager+async def _statement_timeout(conn: psycopg.AsyncConnection[Any], timeout_ms: int) -> AsyncIterator[None]:+ """Bound the wrapped query with a server-side ``statement_timeout``.++ The consumer connection is autocommit, so ``SET LOCAL`` needs an explicit+ transaction; it scopes the timeout to this block and resets it on exit.+ """+ async with conn.transaction():+ await conn.execute(f"SET LOCAL statement_timeout = {int(timeout_ms)}")+ yield++# Structured classification key written into duckgres status error_response by# every terminal-retire writer. Consumers (the backfill reconciler) dispatch on# this, not on error-message prose.@@ -415,7 +439,7 @@ class DuckgresBatchQueue:Skips batches currently 'executing' (their attempt resolves on its own)and anything already terminal. Returns the number of batches superseded."""- async with conn.cursor() as cur:+ async with _statement_timeout(conn, ELIGIBILITY_QUERY_STATEMENT_TIMEOUT_MS), conn.cursor() as cur:await cur.execute(f"""WITH {ELIGIBILITY_CTES}@@ -492,7 +516,7 @@ class DuckgresBatchQueue:by an unprimed schema; reported separately so weeks of backfill cannotpin the alert gauge while still being visible."""- async with conn.cursor() as cur:+ async with _statement_timeout(conn, ELIGIBILITY_QUERY_STATEMENT_TIMEOUT_MS), conn.cursor() as cur:await cur.execute(f"""WITH {ELIGIBILITY_CTES}diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.pyindex f45816c0a5aa..45edbc3b926d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py@@ -389,6 +389,39 @@ class TestDuckgresEnablementGating:assert batches == []mock_fetch.assert_not_called()+ @pytest.mark.asyncio+ async def test_fetch_swallows_maintenance_query_timeout_and_skips_planner(self):+ # The eligibility-CTE maintenance queries are statement-timeout bounded;+ # a timeout (or any transient queue-DB error) must be swallowed so the+ # poll loop is neither wedged nor crashed — the planner is skipped and+ # nothing is claimed this tick, and the next poll just retries.+ adapter = DuckgresBatchConsumerAdapter()+ adapter._team_ids = [1, 2]+ adapter._team_ids_fetched_at = time.monotonic()+ conn = _make_healthy_conn()++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_delta_succeeded_and_lock",+ new_callable=AsyncMock,+ ) as mock_fetch,+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.supersede_replaced_runs",+ new_callable=AsyncMock,+ side_effect=psycopg.errors.QueryCanceled("canceling statement due to statement timeout"),+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.run_backfill_planner",+ ) as mock_planner,+ ):+ batches = await adapter.fetch_and_lock(+ conn, limit=50, retry_backoff_base_seconds=0, owner_token="test-owner", lease_ttl_seconds=300+ )++ assert batches == []+ mock_planner.assert_not_called()+ mock_fetch.assert_not_called()+class TestMidClaimRetire:@pytest.mark.asyncio