Skip to content

: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.

fix(data-warehouse): harden v3 loader against claim degradation and silent wedging (#68570)

estefaniab9adad569ad4
diff --git a/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py b/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py
index f6091d6e3691..f3a928acb2f5 100644
--- a/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py
+++ b/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py
@@ -76,10 +76,21 @@ class Command(BaseCommand):
default=60.0,
help="Health check timeout in seconds (default: 60.0)",
)
+ parser.add_argument(
+ "--stuck-batch-timeout",
+ type=float,
+ default=7200.0,
+ help=(
+ "Stop reporting liveness once any single batch has been executing longer than this many "
+ "seconds, so a wedged sink connection becomes a pod restart instead of an invisible stall. "
+ "0 disables the watchdog (default: 7200.0)"
+ ),
+ )
def handle(self, *args, **options):
health_port = options["health_port"]
health_timeout = options["health_timeout"]
+ stuck_batch_timeout = options["stuck_batch_timeout"] or None
config = ConsumerConfig(
database_url=WAREHOUSE_SOURCES_DATABASE_URL,
@@ -89,6 +100,7 @@ class Command(BaseCommand):
max_attempts=options["max_attempts"],
health_port=health_port,
health_timeout_seconds=health_timeout,
+ stuck_batch_timeout_seconds=stuck_batch_timeout,
)
logger.info(
@@ -98,6 +110,7 @@ class Command(BaseCommand):
poll_limit=config.poll_limit,
max_attempts=config.max_attempts,
health_port=health_port,
+ stuck_batch_timeout=stuck_batch_timeout,
)
health_state = HealthState(timeout_seconds=health_timeout)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py
index 55694e13be5a..44cc6e80e35b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py
@@ -71,6 +71,12 @@ class BatchConsumerConfig:
reconcile_grace_seconds: int = RECONCILE_GRACE_SECONDS
reconcile_lookback_seconds: int = RECONCILE_LOOKBACK_SECONDS
reconcile_limit: int = 100
+ # Ceilings on queue-DB operations. Without them a claim query or sweep that
+ # degrades past "slow" into "never returns" silently wedges the consumer:
+ # the awaiting task holds its slot forever, with no error and no log.
+ connect_timeout_seconds: int = 10
+ poll_timeout_seconds: float | None = 180.0
+ sweep_timeout_seconds: float | None = 300.0
# When set, the consumer stops reporting itself healthy once any single batch
# has been executing longer than this, so a wedged sink connection turns into
# a liveness-probe restart instead of an indefinite, invisible stall.
@@ -238,8 +244,24 @@ class BatchConsumer:
return await psycopg.AsyncConnection.connect(
self._config.database_url,
autocommit=True,
+ connect_timeout=self._config.connect_timeout_seconds,
)
+ async def _drop_conn(self, attr: str) -> None:
+ """Close and forget a connection after a timed-out operation.
+
+ A cancelled psycopg operation can leave the connection mid-protocol;
+ re-dialing on the next cycle is cheaper than reasoning about its state.
+ """
+ conn: psycopg.AsyncConnection[Any] | None = getattr(self, attr)
+ setattr(self, attr, None)
+ if conn is None:
+ return
+ try:
+ await asyncio.wait_for(conn.close(), timeout=5.0)
+ except Exception:
+ pass
+
async def _ensure_poll_conn(self) -> psycopg.AsyncConnection[Any]:
"""Return the poll connection, reconnecting if a failover/pgbouncer bounce dropped it."""
if self._poll_conn is not None and not self._poll_conn.closed and not self._poll_conn.broken:
@@ -282,9 +304,12 @@ class BatchConsumer:
)
try:
- await self._recovery_sweep()
- self._recovery_task = asyncio.create_task(self._recovery_loop())
+ # Liveness must be reporting before the startup sweep runs: the sweep
+ # scans the whole queue and can outlast the health server's startup
+ # grace window, and a pod liveness-killed mid-sweep can never boot.
self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())
+ await self._recovery_sweep_with_timeout()
+ self._recovery_task = asyncio.create_task(self._recovery_loop())
while not self._shutdown.is_set():
self._report_health()
@@ -304,20 +329,41 @@ class BatchConsumer:
poll_start = time.monotonic()
try:
conn = await self._ensure_poll_conn()
- batches = await self._adapter.fetch_and_lock(
- conn,
- limit=self._fetch_limit(available),
- retry_backoff_base_seconds=self._config.retry_backoff_base_seconds,
- owner_token=self._owner_token,
- lease_ttl_seconds=self._lease_ttl_seconds,
+ async with asyncio.timeout(self._config.poll_timeout_seconds):
+ batches = await self._adapter.fetch_and_lock(
+ conn,
+ limit=self._fetch_limit(available),
+ retry_backoff_base_seconds=self._config.retry_backoff_base_seconds,
+ owner_token=self._owner_token,
+ lease_ttl_seconds=self._lease_ttl_seconds,
+ )
+ except TimeoutError:
+ # error, not exception: the timeout is the designed recovery
+ # path and its traceback carries no diagnostic value.
+ logger.error( # noqa: TRY400
+ self._event("poll_timed_out"),
+ timeout_seconds=self._config.poll_timeout_seconds,
)
+ await self._drop_conn("_poll_conn")
+ await self._wait_or_shutdown(self._config.poll_interval_seconds)
+ continue
except psycopg.OperationalError as e:
logger.exception(self._event("poll_failed_queue_db_unreachable"))
capture_exception(e)
await self._wait_or_shutdown(self._config.poll_interval_seconds)
continue
- self._metrics.poll_duration_seconds.observe(time.monotonic() - poll_start)
+ poll_duration = time.monotonic() - poll_start
+ self._metrics.poll_duration_seconds.observe(poll_duration)
self._metrics.poll_batches_fetched.observe(len(batches))
+ if poll_duration > self._lease_ttl_seconds / 2:
+ # Leases are claimed at query start, so a poll this slow hands
+ # groups over with most of their TTL already burned — the
+ # leading indicator of fetch-expire-refetch churn fleet-wide.
+ logger.warning(
+ self._event("poll_duration_approaching_lease_ttl"),
+ poll_duration_seconds=round(poll_duration, 3),
+ lease_ttl_seconds=self._lease_ttl_seconds,
+ )
if not batches:
await self._wait_or_shutdown(self._config.poll_interval_seconds)
@@ -405,6 +451,25 @@ class BatchConsumer:
group_conn = self._poll_conn
assert group_conn is not None
+ # The lease was claimed when the poll query started; a slow poll can
+ # burn most of its TTL before the group task runs. Re-up it here so
+ # processing starts with a full window instead of expiring mid-batch
+ # and churning the group to another pod.
+ renewed = await self._adapter.renew_lease(
+ group_conn,
+ team_id=team_id,
+ schema_id=schema_id,
+ owner_token=self._owner_token,
+ lease_ttl_seconds=self._lease_ttl_seconds,
+ )
+ if not renewed:
+ logger.warning(
+ self._event("lease_lost_before_dispatch"),
+ team_id=team_id,
+ schema_id=schema_id,
+ )
+ return
+
for batch in batches:
if self._shutdown.is_set():
logger.info(
@@ -715,7 +780,7 @@ class BatchConsumer:
break
try:
- await self._recovery_sweep()
+ await self._recovery_sweep_with_timeout()
except Exception as e:
logger.exception(self._event("recovery_sweep_error"))
capture_exception(e)
@@ -724,11 +789,30 @@ class BatchConsumer:
if now - self._last_reconcile_monotonic >= self._config.reconcile_interval_seconds:
self._last_reconcile_monotonic = now
try:
- await self._reconcile_failed_runs()
+ async with asyncio.timeout(self._config.sweep_timeout_seconds):
+ await self._reconcile_failed_runs()
+ except TimeoutError:
+ logger.error( # noqa: TRY400 — designed recovery path, traceback is noise
+ self._event("reconcile_sweep_timed_out"),
+ timeout_seconds=self._config.sweep_timeout_seconds,
+ )
+ await self._drop_conn("_recovery_conn")
except Exception as e:
logger.exception(self._event("reconcile_sweep_error"))
capture_exception(e)
+ async def _recovery_sweep_with_timeout(self) -> None:
+ """Run the recovery sweep under the sweep timeout; a sweep that never returns must not stall the consumer."""
+ try:
+ async with asyncio.timeout(self._config.sweep_timeout_seconds):
+ await self._recovery_sweep()
+ except TimeoutError:
+ logger.error( # noqa: TRY400 — designed recovery path, traceback is noise
+ self._event("recovery_sweep_timed_out"),
+ timeout_seconds=self._config.sweep_timeout_seconds,
+ )
+ await self._drop_conn("_recovery_conn")
+
async def _reconcile_failed_runs(self) -> None:
"""Reconcile runs whose queue batch failed but whose terminal-state write never landed."""
conn = await self._ensure_recovery_conn()
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.py
index d5bb5af48a01..dfbe1a53aa48 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
@@ -59,6 +59,32 @@ def pending_batch_select_columns(status_alias: str) -> str:
"""
+def latest_status_lateral(batch_alias: str, status_alias: str, *, join: str = "LEFT") -> str:
+ """Per-batch latest-status lookup, driven by the (batch_id, created_at DESC, id DESC) index.
+
+ Replaces joins against the ``DISTINCT ON`` latest-status view: the view has
+ to reduce the *entire* status table before the planner can join it, so its
+ cost grows with total queue history no matter how few batches the outer
+ query touches — under backlog that made every poll and sweep degrade
+ together. A lateral LIMIT 1 probe costs one index descent per outer batch
+ instead.
+
+ ``join="LEFT"`` keeps outer batches with no status row (``status_alias``
+ columns come back NULL); ``join="INNER"`` drops them.
+ """
+ join_kw = "LEFT JOIN" if join == "LEFT" else "JOIN"
+ return f"""
+ {join_kw} LATERAL (
+ SELECT id, batch_id, job_state, attempt, exec_time, error_response, created_at
+ FROM {STATUS_TABLE}
+ WHERE batch_id = {batch_alias}.id
+ AND created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ ORDER BY created_at DESC, id DESC
+ LIMIT 1
+ ) {status_alias} ON true
+ """
+
+
# Retained for the duckgres sink, which still coordinates via session advisory
# locks (see duckgres/jobs_db.py). The delta queue now uses leases instead.
async def unlock_advisory_locks(
@@ -296,7 +322,7 @@ class BatchQueue:
SELECT
{pending_batch_select_columns("s")}
FROM {BATCH_TABLE} b
- LEFT JOIN {STATUS_VIEW} s ON b.id = s.batch_id
+ {latest_status_lateral("b", "s")}
WHERE
b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
AND (
@@ -311,7 +337,7 @@ class BatchQueue:
AND NOT EXISTS (
SELECT 1
FROM {BATCH_TABLE} b_prev
- LEFT JOIN {STATUS_VIEW} s_prev ON b_prev.id = s_prev.batch_id
+ {latest_status_lateral("b_prev", "s_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}'
@@ -325,17 +351,18 @@ class BatchQueue:
)
)
)
- AND b.run_uuid NOT IN (
- SELECT DISTINCT b2.run_uuid
+ AND NOT EXISTS (
+ SELECT 1
FROM {BATCH_TABLE} b2
- JOIN {STATUS_VIEW} s2 ON b2.id = s2.batch_id
- WHERE b2.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ {latest_status_lateral("b2", "s2", join="INNER")}
+ WHERE b2.run_uuid = b.run_uuid
+ AND b2.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
AND s2.job_state = 'failed'
)
AND NOT EXISTS (
SELECT 1
FROM {BATCH_TABLE} b_busy
- JOIN {STATUS_VIEW} s_busy ON b_busy.id = s_busy.batch_id
+ {latest_status_lateral("b_busy", "s_busy", join="INNER")}
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}'
@@ -485,7 +512,7 @@ class BatchQueue:
SELECT
{pending_batch_select_columns("s")}
FROM {BATCH_TABLE} b
- JOIN {STATUS_VIEW} s ON b.id = s.batch_id
+ {latest_status_lateral("b", "s", join="INNER")}
LEFT JOIN {LEASE_TABLE} l ON l.team_id = b.team_id AND l.schema_id = b.schema_id
WHERE
b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
@@ -513,7 +540,7 @@ class BatchQueue:
INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)
SELECT b.id, 'failed', 0, now(), %(error_response)s, now()
FROM {BATCH_TABLE} b
- LEFT JOIN {STATUS_VIEW} s ON b.id = s.batch_id
+ {latest_status_lateral("b", "s")}
WHERE
b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
AND b.run_uuid = %(run_uuid)s
@@ -539,7 +566,7 @@ class BatchQueue:
INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)
SELECT b.id, 'failed', 0, now(), %(error_response)s, now()
FROM {BATCH_TABLE} b
- LEFT JOIN {STATUS_VIEW} s ON b.id = s.batch_id
+ {latest_status_lateral("b", "s")}
WHERE
b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
AND b.job_id = %(job_id)s
@@ -576,7 +603,7 @@ class BatchQueue:
b.run_uuid, b.job_id, b.team_id, b.schema_id, b.metadata, s.error_response,
s.created_at AS failed_at
FROM {BATCH_TABLE} b
- JOIN {STATUS_VIEW} s ON b.id = s.batch_id
+ {latest_status_lateral("b", "s", join="INNER")}
WHERE
b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
AND s.job_state = 'failed'
@@ -670,7 +697,7 @@ class BatchQueue:
) AS non_terminal_count,
GREATEST(MAX(s.created_at), MAX(b.created_at)) AS latest_activity_at
FROM {BATCH_TABLE} b
- LEFT JOIN {STATUS_VIEW} s ON b.id = s.batch_id
+ {latest_status_lateral("b", "s")}
WHERE
b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
AND b.job_id = %(job_id)s
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.py
index 71caddc16571..5b288cf7cbc5 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
@@ -1,5 +1,5 @@
import asyncio
-from typing import Any
+from typing import Any, cast
import pytest
from unittest.mock import AsyncMock, patch
@@ -84,6 +84,18 @@ def _make_healthy_conn(closed: bool = False, broken: bool = False) -> AsyncMock:
return conn
[email protected](autouse=True)
+def _lease_renewal_succeeds():
+ # Group dispatch renews the lease before processing; the real SQL can't run
+ # against mock connections. Tests exercising renewal failure re-patch this.
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.renew_lease",
+ new_callable=AsyncMock,
+ return_value=True,
+ ):
+ yield
+
+
class TestProcessSingle:
@pytest.mark.asyncio
async def test_success_updates_status_to_executing_then_succeeded(self):
@@ -281,6 +293,29 @@ class TestProcessGroup:
assert processed == [0]
+ @pytest.mark.asyncio
+ async def test_abandons_group_when_lease_lost_before_dispatch(self):
+ consumer = _make_consumer()
+ batch = _make_batch()
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.renew_lease",
+ new_callable=AsyncMock,
+ return_value=False,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",
+ new_callable=AsyncMock,
+ ) as mock_unlock,
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
+ ):
+ await consumer._process_group((1, "schema-1"), [batch])
+
+ # Another pod owns the group now — processing it here would double-write.
+ cast(AsyncMock, consumer._process_batch).assert_not_called()
+ mock_unlock.assert_called_once()
+
class TestRecoverySweep:
@pytest.mark.asyncio
@@ -368,6 +403,128 @@ class TestRecoverySweep:
)
+class TestStartupLiveness:
+ @pytest.mark.asyncio
+ async def test_heartbeat_reports_liveness_while_startup_sweep_runs(self):
+ health_reported = asyncio.Event()
+ config = ConsumerConfig(
+ database_url="postgres://unused:unused@localhost/unused",
+ heartbeat_interval_seconds=0.01,
+ )
+ consumer = BatchConsumer(config=config, process_batch=AsyncMock(), health_reporter=health_reported.set)
+
+ release_sweep = asyncio.Event()
+
+ async def blocking_sweep(*args: Any, **kwargs: Any) -> list[PendingBatch]:
+ await release_sweep.wait()
+ return []
+
+ with (
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
+ patch.object(consumer, "_install_signal_handlers"),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",
+ side_effect=blocking_sweep,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.release_all_owned_leases",
+ new_callable=AsyncMock,
+ ),
+ ):
+ run_task = asyncio.create_task(consumer.run())
+ # With the sweep blocked indefinitely, liveness must still be reported.
+ await asyncio.wait_for(health_reported.wait(), timeout=1.0)
+ consumer._shutdown.set()
+ release_sweep.set()
+ await asyncio.wait_for(run_task, timeout=5.0)
+
+
+class TestQueueOperationTimeouts:
+ @pytest.mark.asyncio
+ async def test_hung_poll_times_out_and_consumer_keeps_polling(self):
+ config = ConsumerConfig(
+ database_url="postgres://unused:unused@localhost/unused",
+ poll_interval_seconds=0.01,
+ poll_timeout_seconds=0.05,
+ )
+ consumer = BatchConsumer(config=config, process_batch=AsyncMock())
+
+ second_poll_started = asyncio.Event()
+ fetch_calls = 0
+
+ async def hung_fetch(*args: Any, **kwargs: Any) -> list[PendingBatch]:
+ nonlocal fetch_calls
+ fetch_calls += 1
+ if fetch_calls >= 2:
+ second_poll_started.set()
+ await asyncio.sleep(3600)
+ return []
+
+ with (
+ patch.object(consumer, "_connect", new_callable=AsyncMock, side_effect=lambda: _make_healthy_conn()),
+ patch.object(consumer, "_install_signal_handlers"),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",
+ new_callable=AsyncMock,
+ return_value=[],
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_unprocessed_and_lock",
+ side_effect=hung_fetch,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.release_all_owned_leases",
+ new_callable=AsyncMock,
+ ),
+ ):
+ run_task = asyncio.create_task(consumer.run())
+ # A second poll can only start if the first hung one timed out instead of wedging.
+ await asyncio.wait_for(second_poll_started.wait(), timeout=2.0)
+ consumer._shutdown.set()
+ await asyncio.wait_for(run_task, timeout=5.0)
+
+ @pytest.mark.asyncio
+ async def test_hung_startup_sweep_times_out_and_polling_starts(self):
+ config = ConsumerConfig(
+ database_url="postgres://unused:unused@localhost/unused",
+ poll_interval_seconds=0.01,
+ sweep_timeout_seconds=0.05,
+ )
+ consumer = BatchConsumer(config=config, process_batch=AsyncMock())
+
+ polling_started = asyncio.Event()
+
+ async def hung_sweep(*args: Any, **kwargs: Any) -> list[PendingBatch]:
+ await asyncio.sleep(3600)
+ return []
+
+ async def fetch(*args: Any, **kwargs: Any) -> list[PendingBatch]:
+ polling_started.set()
+ return []
+
+ with (
+ patch.object(consumer, "_connect", new_callable=AsyncMock, side_effect=lambda: _make_healthy_conn()),
+ patch.object(consumer, "_install_signal_handlers"),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",
+ side_effect=hung_sweep,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_unprocessed_and_lock",
+ side_effect=fetch,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.release_all_owned_leases",
+ new_callable=AsyncMock,
+ ),
+ ):
+ run_task = asyncio.create_task(consumer.run())
+ # Polling can only begin if the hung startup sweep was abandoned by the timeout.
+ await asyncio.wait_for(polling_started.wait(), timeout=2.0)
+ consumer._shutdown.set()
+ await asyncio.wait_for(run_task, timeout=5.0)
+
+
class TestFailRun:
@pytest.mark.asyncio
async def test_does_not_raise_when_job_status_update_fails(self):