: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
feat(data-warehouse): instrument the queue maintenance queries (#83703)
estefania4da84d15edc5
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 ab1accb1108d..d85e51febdf7 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@@ -49,9 +49,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_Unset,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.metrics import (+ CLAIMABLE_BATCHES,OLDEST_UNCLAIMED_BATCH_SECONDS,RUNS_RECONCILED_TOTAL,RUNS_TERMINALIZED_STALE_TOTAL,+ observe_queue_query,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (release_v3_pipeline_lock,@@ -305,12 +307,13 @@ class DeltaBatchConsumerAdapter:) -> list[PendingBatch]:# keep_locks is meaningless for the lease sink: get_stale_executing holds# no locks and the lease LEFT JOIN already excludes live groups.- return await BatchQueue.get_stale_executing(- conn,- grace_seconds=grace_seconds,- sync_types=self._claim_sync_types,- exclude_sync_types=self._claim_exclude_sync_types,- )+ with observe_queue_query("get_stale_executing"):+ return await BatchQueue.get_stale_executing(+ conn,+ grace_seconds=grace_seconds,+ sync_types=self._claim_sync_types,+ exclude_sync_types=self._claim_exclude_sync_types,+ )async def reconcile_failed_runs(self,@@ -339,12 +342,13 @@ class DeltaBatchConsumerAdapter:logger.debug("reconcile_sweep_slot_held_elsewhere")return- refs = await BatchQueue.get_failed_runs(- conn,- grace_seconds=grace_seconds,- lookback_seconds=lookback_seconds,- limit=limit,- )+ with observe_queue_query("get_failed_runs"):+ refs = await BatchQueue.get_failed_runs(+ conn,+ grace_seconds=grace_seconds,+ lookback_seconds=lookback_seconds,+ limit=limit,+ )for ref in refs:# A producer can enqueue a batch into a run after fail_run swept it (the# extraction is still in flight when a sibling batch exhausts retries).@@ -446,7 +450,8 @@ class DeltaBatchConsumerAdapter:batch. Failing batches first also self-heals a crash mid-sweep: the run then has a failed batch,so ``reconcile_failed_runs`` finalizes the job next cycle."""- refs = await BatchQueue.get_stale_stranded_runs(conn, stale_seconds=stale_seconds, limit=limit)+ with observe_queue_query("get_stale_stranded_runs"):+ refs = await BatchQueue.get_stale_stranded_runs(conn, stale_seconds=stale_seconds, limit=limit)for ref in refs:try:failed_batches = await BatchQueue.fail_run(@@ -520,7 +525,17 @@ class DeltaBatchConsumerAdapter:"""try:async with asyncio.timeout(FRESHNESS_PROBE_TIMEOUT_SECONDS):- age = await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn)+ with observe_queue_query("oldest_unclaimed_probe"):+ age = await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn)+ # Set immediately, so a failure in the depth probe below can never+ # blind the age gauge this alert hangs off.+ OLDEST_UNCLAIMED_BATCH_SECONDS.set(age or 0.0)+ # Depth rides the same probe and timeout: age says how stale the head+ # of the queue is, depth says how much sits behind it — a stall and a+ # burst are indistinguishable on age alone.+ with observe_queue_query("claimable_depth_probe"):+ depth = await BatchQueue.get_claimable_batch_count(conn)+ CLAIMABLE_BATCHES.set(depth)except TimeoutError:logger.error( # noqa: TRY400 — designed degraded path, traceback is noise"queue_freshness_probe_timed_out",@@ -532,7 +547,6 @@ class DeltaBatchConsumerAdapter:logger.exception("queue_freshness_probe_failed")capture_exception(e)return- OLDEST_UNCLAIMED_BATCH_SECONDS.set(age or 0.0)async def should_process_batch(self,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 f008891117b0..36c13a35f3c0 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@@ -1339,6 +1339,30 @@ class BatchQueue:return Nonereturn float(row[0])+ @staticmethod+ async def get_claimable_batch_count(conn: psycopg.AsyncConnection[Any]) -> int:+ """How many batches are state-eligible for claiming right now (queue depth).++ The depth companion to :meth:`get_oldest_unclaimed_batch_age_seconds`:+ the claim's per-run, schema-busy, and lease gates are deliberately not+ applied (they need per-row probes; this must stay one cheap partial-index+ scan), and neither is the retry-backoff gate (it needs the fleet's backoff+ config, and this probe stays parameter-free), so the count reads slightly+ high. Bounded by ``CLAIM_ELIGIBILITY_INTERVAL`` to match what the claim+ query can see.+ """+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ SELECT count(*)+ FROM {BATCH_TABLE} b+ WHERE b.created_at > now() - interval '{CLAIM_ELIGIBILITY_INTERVAL}'+ AND b.latest_state IN ('pending', 'waiting_retry')+ """+ )+ row = await cur.fetchone()+ return int(row[0]) if row else 0+@staticmethoddef get_oldest_non_terminal_batch_age_seconds(conn: psycopg.Connection[Any],diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.pyindex 228e8008b061..427b0b8cd7a5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py@@ -1,5 +1,10 @@+import time+import asyncio+from collections.abc import Iterator+from contextlib import contextmanagerfrom dataclasses import dataclass+import psycopgfrom prometheus_client import Counter, Gauge, Histogram# The claim query degrades with queue backlog, and its danger zone sits near the@@ -88,6 +93,75 @@ OLDEST_UNCLAIMED_BATCH_SECONDS = Gauge(multiprocess_mode="livemax",)+# Depth companion to the age gauge above: age says how stale the head of the queue+# is, depth says how much work is behind it — a stall and a burst look identical on+# age alone. Same probe, same cadence, same aggregation (max across pods).+CLAIMABLE_BATCHES = Gauge(+ "warehouse_pg_queue_claimable_batches",+ "Batches whose state makes them claimable right now (pending or waiting_retry, "+ "within the claim eligibility window; per-run and lease gates not applied). "+ "Sampled on the reconcile cadence.",+ multiprocess_mode="livemax",+)++# The maintenance queries (sweeps, reconcile passes, probes) shaped like the claim+# poll: cost scales with queue state, and the 2026-08 stall came from one that had+# no latency signal at all. Same bucket ceiling rationale as POLL_DURATION_BUCKETS.+QUEUE_QUERY_DURATION_SECONDS = Histogram(+ "warehouse_pg_queue_query_duration_seconds",+ "Duration of maintenance queries against the batch queue, by query name. "+ "Observed on success AND on failure/timeout, so degradation is never invisible.",+ labelnames=["query"],+ buckets=POLL_DURATION_BUCKETS,+)++QUEUE_QUERY_FAILURES_TOTAL = Counter(+ "warehouse_pg_queue_query_failures_total",+ "Maintenance queue queries that raised or timed out before returning. "+ "Probe timeouts count as reason=cancelled, not timeout: asyncio.timeout "+ "cancels the timed block and only converts to TimeoutError outside it. "+ "Worker-shutdown cancellations mid-query land under cancelled too, so "+ "expect a small rate during deploys.",+ labelnames=["query", "reason"],+)+++def _failure_reason(exc: BaseException) -> str:+ """Small, fixed label set: exception class names (psycopg has hundreds) would bloat cardinality."""+ # Fires only for a TimeoutError raised inside the timed block, which psycopg+ # never does (its timeouts are psycopg.Error subclasses, so reason=db).+ # Kept as defensive coverage; alert on cancelled, not this.+ if isinstance(exc, TimeoutError):+ return "timeout"+ # asyncio.timeout cancels the timed block; the CancelledError is what this code+ # sees. Worker-shutdown cancellation is indistinguishable and lands here too.+ if isinstance(exc, asyncio.CancelledError):+ return "cancelled"+ if isinstance(exc, psycopg.Error):+ return "db"+ return "other"+++@contextmanager+def observe_queue_query(query: str) -> Iterator[None]:+ """Time a maintenance queue query; failures still record their elapsed time.++ The duration is observed in ``finally``, deliberately including the failure+ and timeout paths: the poll histogram's original design only recorded+ successes, so a fleet whose queries all timed out looked *faster* on the+ histogram exactly when it was slowest, and only a separate counter told the+ truth. Here the histogram carries the whole story and the failure counter+ adds the why.+ """+ start = time.monotonic()+ try:+ yield+ except BaseException as e:+ QUEUE_QUERY_FAILURES_TOTAL.labels(query=query, reason=_failure_reason(e)).inc()+ raise+ finally:+ QUEUE_QUERY_DURATION_SECONDS.labels(query=query).observe(time.monotonic() - start)+@dataclass(frozen=True)class ConsumerMetrics: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 9268569db916..e4cc69302f1d 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@@ -34,6 +34,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinePendingBatch,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.metrics import (+ CLAIMABLE_BATCHES,OLDEST_UNCLAIMED_BATCH_SECONDS,RUNS_RECONCILED_TOTAL,)@@ -1578,6 +1579,11 @@ class TestReconcileFailedRuns:new_callable=AsyncMock,return_value=42.0,),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_claimable_batch_count",+ new_callable=AsyncMock,+ return_value=7,+ ),patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_failed_runs",new_callable=AsyncMock,@@ -1605,9 +1611,15 @@ class TestReconcileFailedRuns:new_callable=AsyncMock,return_value=1234.5,) as mock_probe,+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_claimable_batch_count",+ new_callable=AsyncMock,+ return_value=321,+ ) as mock_depth,):await consumer._reconcile_failed_runs()assert OLDEST_UNCLAIMED_BATCH_SECONDS._value.get() == 1234.5+ assert CLAIMABLE_BATCHES._value.get() == 321mock_probe.return_value = None # empty queue -> gauge resets to 0with patch(@@ -1615,9 +1627,15 @@ class TestReconcileFailedRuns:new_callable=AsyncMock,return_value=[],):- with patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_oldest_unclaimed_batch_age_seconds",- mock_probe,+ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_oldest_unclaimed_batch_age_seconds",+ mock_probe,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_claimable_batch_count",+ mock_depth,+ ),):await consumer._reconcile_failed_runs()assert OLDEST_UNCLAIMED_BATCH_SECONDS._value.get() == 0.0diff --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 292ca1c6275d..3cf27330d61e 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@@ -1063,8 +1063,12 @@ class TestGetStaleStrandedRuns:plan = "\n".join(row[0] for row in await cur.fetchall())finally:await conn.execute("SET enable_seqscan = on")+ # The fence must keep the failed-run gate a per-run SubPlan probing the+ # run-gate index. Asserting "no Hash Anti Join anywhere" instead is flaky:+ # the UNFENCED lease gate may legitimately plan as a hash anti-join, and a+ # flattened failed-gate can still show sb_run_gate_idx (as its hash build).assert "sb_run_gate_idx" in plan- assert "Hash Anti Join" not in plan+ assert "SubPlan" in plan@pytest.mark.django_db(transaction=True)@@ -1525,6 +1529,23 @@ class TestClaimGates:assert "sb_claimable_idx" in plan[email protected]_db(transaction=True)+class TestGetClaimableBatchCount:+ @pytest.mark.asyncio+ async def test_counts_claimable_states_within_eligibility_window(self, conn):+ # Feeds the queue-depth gauge; dropping a state or the window bound here+ # makes the backpressure signal lie.+ await _insert_batch(conn, batch_index=0, run_uuid="r-a")+ retry = await _insert_batch(conn, batch_index=1, run_uuid="r-a")+ await BatchQueue.update_status(conn, batch_id=retry, job_state="waiting_retry", attempt=1)+ done = await _insert_batch(conn, batch_index=2, run_uuid="r-a")+ await BatchQueue.update_status(conn, batch_id=done, job_state="succeeded", attempt=1)+ expired = await _insert_batch(conn, batch_index=0, run_uuid="r-old")+ await conn.execute(f"UPDATE {BATCH_TABLE} SET created_at = now() - interval '7 days' WHERE id = %s", (expired,))++ assert await BatchQueue.get_claimable_batch_count(conn) == 2++@pytest.mark.django_db(transaction=True)class TestClaimEligibilityWindow:"""Batches old enough to have lost their parquet to retention must never bediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_metrics.pynew file mode 100644index 000000000000..297457516244--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_metrics.py@@ -0,0 +1,48 @@+import asyncio++import pytest++import psycopg++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.metrics import (+ QUEUE_QUERY_DURATION_SECONDS,+ QUEUE_QUERY_FAILURES_TOTAL,+ observe_queue_query,+)+++def _duration_count(query: str) -> float:+ """Total observations for a query label (buckets are stored non-cumulative)."""+ return sum(b.get() for b in QUEUE_QUERY_DURATION_SECONDS.labels(query=query)._buckets)+++class TestObserveQueueQuery:+ def test_success_observes_duration(self):+ before = _duration_count("t-success")+ with observe_queue_query("t-success"):+ pass+ assert _duration_count("t-success") == before + 1++ @pytest.mark.parametrize(+ "exc,reason",+ [+ (TimeoutError(), "timeout"),+ (asyncio.CancelledError(), "cancelled"),+ (psycopg.OperationalError(), "db"),+ (ValueError("x"), "other"),+ ],+ )+ def test_failure_still_observes_duration_and_counts_reason(self, exc, reason):+ # The poll histogram's original blind spot: queries that timed out never+ # reached it, so a fleet at its slowest looked fastest. A raise inside+ # the block must land in BOTH the histogram and the failure counter.+ query = f"t-fail-{reason}"+ dur_before = _duration_count(query)+ fail_before = QUEUE_QUERY_FAILURES_TOTAL.labels(query=query, reason=reason)._value.get()++ with pytest.raises(type(exc)):+ with observe_queue_query(query):+ raise exc++ assert _duration_count(query) == dur_before + 1+ assert QUEUE_QUERY_FAILURES_TOTAL.labels(query=query, reason=reason)._value.get() == fail_before + 1