: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): v3 loader queue freshness gauge and poll-duration visibility (#68595)
estefaniaede1ecf3c766
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 21c4a4d15062..58cbc38c2b05 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@@ -37,6 +37,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 (+ OLDEST_UNCLAIMED_BATCH_SECONDS,RUNS_RECONCILED_TOTAL,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (@@ -210,6 +211,10 @@ class DeltaBatchConsumerAdapter:limit: int,) -> None:"""Mark ExternalDataJobs Failed when their run has a failed queue batch but the app-DB write never landed."""+ # Piggyback the reconcile cadence for the queue-freshness gauge: same+ # connection, same periodicity, and isolated so it can't break the sweep.+ await self._observe_queue_freshness(conn)+refs = await BatchQueue.get_failed_runs(conn,grace_seconds=grace_seconds,@@ -257,6 +262,22 @@ class DeltaBatchConsumerAdapter:)capture_exception(e)+ async def _observe_queue_freshness(self, conn: psycopg.AsyncConnection[Any]) -> None:+ """Report the age of the oldest batch no consumer has picked up yet.++ This is the loader's data-freshness signal: it rises whenever loading+ stalls, no matter why — the alert on it fires even when every other+ health signal looks green. Failures are swallowed-with-capture so a+ broken probe can't take the reconcile sweep down with it.+ """+ try:+ age = await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn)+ except Exception as e:+ 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,conn: psycopg.AsyncConnection[Any],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 dfbe1a53aa48..f8234604072e 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@@ -46,6 +46,11 @@ PARTITION_PRUNING_INTERVAL = "14 days"# abandoned. Must exceed worst-case loader backlog latency — an unclaimed backlog is still live.TAKEOVER_STALE_THRESHOLD_SECONDS = 6 * 60 * 60+# Lookback for the queue-freshness probe. Bounds both the probe's cost and the+# reported age: an unclaimed batch older than this saturates the gauge at the+# window, which is already far past any sane alert threshold.+FRESHNESS_WINDOW = "48 hours"+def pending_batch_select_columns(status_alias: str) -> str:return f"""@@ -631,6 +636,37 @@ class BatchQueue:for row in rows]+ @staticmethod+ async def get_oldest_unclaimed_batch_age_seconds(+ conn: psycopg.AsyncConnection[Any],+ ) -> float | None:+ """Age in seconds of the oldest batch no consumer has ever picked up, or None when none are waiting.++ A batch with no status row has never been claimed — this is the queue's+ data-freshness signal, and it rises whenever loading stalls regardless+ of the cause. Bounded to ``FRESHNESS_WINDOW`` so the probe stays cheap+ on a healthy queue and the reported age saturates instead of scanning+ unbounded history.+ """+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ SELECT EXTRACT(EPOCH FROM (now() - min(b.created_at)))+ FROM {BATCH_TABLE} b+ WHERE b.created_at > now() - interval '{FRESHNESS_WINDOW}'+ AND NOT EXISTS (+ SELECT 1+ FROM {STATUS_TABLE} s+ WHERE s.batch_id = b.id+ AND s.created_at > now() - interval '{FRESHNESS_WINDOW}'+ )+ """+ )+ row = await cur.fetchone()+ if row is None or row[0] is None:+ return None+ return float(row[0])+@staticmethodasync def unlock_for_batches(conn: psycopg.AsyncConnection[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 4b9ad3f4da89..e0a44dc97ceb 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@@ -2,6 +2,12 @@ from dataclasses import dataclassfrom prometheus_client import Counter, Gauge, Histogram+# The claim query degrades with queue backlog, and its danger zone sits near the+# 300s group-lease TTL (a poll slower than TTL/2 hands groups over mostly+# expired). The old 5s ceiling made every degraded poll indistinguishable from a+# merely slow one — p95 sat "pinned at 5s" while real polls took minutes.+POLL_DURATION_BUCKETS = (0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 15.0, 60.0, 150.0, 300.0)+BATCHES_PROCESSED_TOTAL = Counter("warehouse_pg_consumer_batches_processed_total","Total batches processed by the Postgres consumer",@@ -29,7 +35,7 @@ RUNS_FAILED_TOTAL = Counter(POLL_DURATION_SECONDS = Histogram("warehouse_pg_consumer_poll_duration_seconds","Duration of Postgres poll queries",- buckets=(0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0),+ buckets=POLL_DURATION_BUCKETS,)POLL_BATCHES_FETCHED = Histogram(@@ -56,6 +62,18 @@ RUNS_RECONCILED_TOTAL = Counter("was reconciled to Failed by the reconcile sweep",)+# The loader's data-freshness signal: it rises whenever loading stalls,+# regardless of why (wedged consumers, claim-query degradation, crashloops).+# Every pod reports the same queue-wide value, so aggregate with max().+# livemax matches that: it stays accurate even if two consumer processes+# briefly co-exist in one pod, where livesum would double the age.+OLDEST_UNCLAIMED_BATCH_SECONDS = Gauge(+ "warehouse_pg_queue_oldest_unclaimed_batch_seconds",+ "Age of the oldest queue batch no consumer has picked up yet (0 = none waiting). "+ "Sampled on the reconcile cadence; saturates at the freshness probe window.",+ multiprocess_mode="livemax",+)+@dataclass(frozen=True)class ConsumerMetrics:@@ -121,7 +139,7 @@ def make_consumer_metrics(prefix: str) -> ConsumerMetrics:poll_duration_seconds=Histogram(f"{p}_poll_duration_seconds","Duration of Postgres poll queries",- buckets=(0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0),+ buckets=POLL_DURATION_BUCKETS,),poll_batches_fetched=Histogram(f"{p}_poll_batches_fetched",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 5b288cf7cbc5..f1cf1e8c0c26 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@@ -20,6 +20,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineFailedRunRef,PendingBatch,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.metrics import (+ OLDEST_UNCLAIMED_BATCH_SECONDS,+)from products.warehouse_sources_queue.backend.models import SourceBatchStatus@@ -569,6 +572,40 @@ class TestFailRun:class TestReconcileFailedRuns:+ @pytest.mark.asyncio+ async def test_reconcile_reports_queue_freshness_gauge(self):+ # The gauge feeds the loader's data-freshness alert; if a reconcile+ # refactor drops the probe, the alert goes silently blind.+ consumer = _make_consumer()++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_failed_runs",+ new_callable=AsyncMock,+ return_value=[],+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_oldest_unclaimed_batch_age_seconds",+ new_callable=AsyncMock,+ return_value=1234.5,+ ) as mock_probe,+ ):+ await consumer._reconcile_failed_runs()+ assert OLDEST_UNCLAIMED_BATCH_SECONDS._value.get() == 1234.5++ mock_probe.return_value = None # empty queue -> gauge resets to 0+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_failed_runs",+ 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,+ ):+ await consumer._reconcile_failed_runs()+ assert OLDEST_UNCLAIMED_BATCH_SECONDS._value.get() == 0.0+@pytest.mark.asyncioasync def test_marks_non_terminal_run_failed(self):consumer = _make_consumer()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 390cd91d4d77..d7d4e12eadbd 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@@ -492,6 +492,21 @@ class TestBatchQueueLeaseRenewal:assert renewed is False[email protected]_db(transaction=True)+class TestQueueFreshnessProbe:+ @pytest.mark.asyncio+ async def test_reports_only_batches_never_picked_up(self, conn):+ assert await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn) is None++ bid = await _insert_batch(conn)+ age = await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn)+ assert age is not None and age >= 0++ # Any status row means the batch was picked up — it must stop counting.+ await BatchQueue.update_status(conn, batch_id=bid, job_state="executing", attempt=1)+ assert await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn) is None++@pytest.mark.django_db(transaction=True)class TestGroupLeaseRecovery:@pytest.mark.asyncio