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): v3 loader outage hardening — visibility, concurrency, tunables, fail-fast (#68848)

estefania754120aea306
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 f3a928acb2f5..620ca67dfa97 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
@@ -22,6 +22,36 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
logger = structlog.get_logger(__name__)
+def build_consumer_config(options: dict) -> ConsumerConfig:
+ """Translate CLI options into a ConsumerConfig.
+
+ Ceiling flags map 0 to None (disabled); unset flags keep the dataclass defaults.
+ """
+ kwargs: dict = {
+ "database_url": WAREHOUSE_SOURCES_DATABASE_URL,
+ "max_concurrency": options["max_concurrency"],
+ "poll_interval_seconds": options["poll_interval"],
+ "poll_limit": options["poll_limit"],
+ "max_attempts": options["max_attempts"],
+ "health_port": options["health_port"],
+ "health_timeout_seconds": options["health_timeout"],
+ "stuck_batch_timeout_seconds": options["stuck_batch_timeout"] or None,
+ }
+ if options.get("poll_timeout") is not None:
+ kwargs["poll_timeout_seconds"] = options["poll_timeout"] or None
+ if options.get("sweep_timeout") is not None:
+ kwargs["sweep_timeout_seconds"] = options["sweep_timeout"] or None
+ if options.get("connect_timeout") is not None:
+ kwargs["connect_timeout_seconds"] = options["connect_timeout"]
+ if options.get("lease_ttl") is not None:
+ kwargs["lease_ttl_seconds"] = options["lease_ttl"]
+ if options.get("recovery_grace") is not None:
+ kwargs["recovery_grace_seconds"] = options["recovery_grace"]
+ if options.get("poll_failure_liveness_threshold") is not None:
+ kwargs["poll_failure_liveness_threshold"] = options["poll_failure_liveness_threshold"] or None
+ return ConsumerConfig(**kwargs)
+
+
async def _run_consumer(config: ConsumerConfig, health_reporter) -> None:
"""Configure the Temporal-style produce path then run the consumer.
@@ -86,22 +116,54 @@ class Command(BaseCommand):
"0 disables the watchdog (default: 7200.0)"
),
)
+ # Omitted flags keep the ConsumerConfig defaults (single source of truth);
+ # exposed so a degraded fleet can be retuned without a code deploy.
+ parser.add_argument(
+ "--poll-timeout",
+ type=float,
+ default=None,
+ help="Seconds before a claim poll is abandoned and retried on a fresh connection. 0 disables the ceiling",
+ )
+ parser.add_argument(
+ "--sweep-timeout",
+ type=float,
+ default=None,
+ help="Seconds before a recovery/reconcile sweep is abandoned. 0 disables the ceiling",
+ )
+ parser.add_argument(
+ "--connect-timeout",
+ type=int,
+ default=None,
+ help="Seconds before a queue-DB connection attempt fails",
+ )
+ parser.add_argument(
+ "--lease-ttl",
+ type=int,
+ default=None,
+ help="Group-lease validity window in seconds (defaults to --recovery-grace)",
+ )
+ parser.add_argument(
+ "--recovery-grace",
+ type=int,
+ default=None,
+ help="Seconds an executing batch may go without a heartbeat before the recovery sweep re-queues it",
+ )
+ parser.add_argument(
+ "--poll-failure-liveness-threshold",
+ type=int,
+ default=None,
+ help=(
+ "Stop reporting liveness after this many consecutive failed polls, so a pod that can no "
+ "longer claim work becomes a visible restart instead of a silent zero-throughput loop. "
+ "0 disables the trip"
+ ),
+ )
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,
- max_concurrency=options["max_concurrency"],
- poll_interval_seconds=options["poll_interval"],
- poll_limit=options["poll_limit"],
- max_attempts=options["max_attempts"],
- health_port=health_port,
- health_timeout_seconds=health_timeout,
- stuck_batch_timeout_seconds=stuck_batch_timeout,
- )
+
+ config = build_consumer_config(options)
logger.info(
"warehouse_sources_load_starting",
@@ -110,7 +172,13 @@ class Command(BaseCommand):
poll_limit=config.poll_limit,
max_attempts=config.max_attempts,
health_port=health_port,
- stuck_batch_timeout=stuck_batch_timeout,
+ stuck_batch_timeout=config.stuck_batch_timeout_seconds,
+ poll_timeout=config.poll_timeout_seconds,
+ sweep_timeout=config.sweep_timeout_seconds,
+ connect_timeout=config.connect_timeout_seconds,
+ lease_ttl=config.lease_ttl_seconds,
+ recovery_grace=config.recovery_grace_seconds,
+ poll_failure_liveness_threshold=config.poll_failure_liveness_threshold,
)
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 936a6dfe7c14..e98ce7026619 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
@@ -81,6 +81,9 @@ class BatchConsumerConfig:
# has been executing longer than this, so a wedged sink connection turns into
# a liveness-probe restart instead of an indefinite, invisible stall.
stuck_batch_timeout_seconds: float | None = None
+ # Withhold liveness after this many consecutive failed polls: a pod that
+ # cannot poll does no work but would otherwise pass liveness forever.
+ poll_failure_liveness_threshold: int | None = 10
def __post_init__(self) -> None:
if self.recovery_grace_seconds is None:
@@ -197,6 +200,12 @@ class BatchConsumerAdapter(Protocol):
batch: PendingBatch,
) -> bool: ...
+ def is_retryable_error(self, err: Exception) -> bool:
+ """Whether a processing error can plausibly succeed on retry — deterministic
+ data/config errors fail identically every attempt, so retrying only delays
+ the run's terminal state."""
+ ...
+
async def after_batch_processed(
self,
conn: psycopg.AsyncConnection[Any],
@@ -235,6 +244,9 @@ class BatchConsumer:
# batch_id -> monotonic start, for the stuck-batch watchdog.
self._inflight_started: dict[str, float] = {}
self._last_stuck_log_monotonic = 0.0
+ # Consecutive failed polls, for the poll-failure liveness trip.
+ self._consecutive_poll_failures = 0
+ self._last_poll_failure_log_monotonic = 0.0
@property
def _lease_ttl_seconds(self) -> int:
@@ -337,15 +349,19 @@ class BatchConsumer:
logger.error( # noqa: TRY400
self._event("poll_timed_out"),
timeout_seconds=self._config.poll_timeout_seconds,
+ consecutive_failures=self._consecutive_poll_failures + 1,
)
+ self._note_poll_failure("timeout", duration=time.monotonic() - poll_start)
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)
+ self._note_poll_failure("db_unreachable", duration=time.monotonic() - poll_start)
await self._wait_or_shutdown(self._config.poll_interval_seconds)
continue
+ self._consecutive_poll_failures = 0
poll_duration = time.monotonic() - poll_start
self._metrics.poll_duration_seconds.observe(poll_duration)
self._metrics.poll_batches_fetched.observe(len(batches))
@@ -762,7 +778,18 @@ class BatchConsumer:
status_conn: psycopg.AsyncConnection[Any],
) -> None:
"""Write the retry/terminal state after a processing error."""
- if attempt >= self._config.max_attempts:
+ if not self._adapter.is_retryable_error(err):
+ # Deterministic failure: retrying repeats the same outcome. The raw
+ # message is the customer-visible latest_error, so keep it unwrapped.
+ logger.exception(
+ self._event("batch_failed_non_retryable"),
+ batch_id=batch.id,
+ run_uuid=batch.run_uuid,
+ attempt=attempt,
+ )
+ capture_exception(err)
+ await self._fail_run(batch, reason=str(err), conn=lock_conn)
+ elif attempt >= self._config.max_attempts:
logger.exception(
self._event("batch_failed_no_retries_left"),
batch_id=batch.id,
@@ -859,16 +886,36 @@ class BatchConsumer:
limit=self._config.reconcile_limit,
)
+ def _note_poll_failure(self, reason: str, *, duration: float) -> None:
+ """Record a failed poll: the success path never reaches the poll histograms,
+ so without this a fleet whose polls all fail looks healthier than a slow one."""
+ self._consecutive_poll_failures += 1
+ self._metrics.poll_failures_total.labels(reason=reason).inc()
+ self._metrics.poll_duration_seconds.observe(duration)
+
def _report_health(self) -> None:
- """Report liveness, unless the stuck-batch watchdog has tripped.
+ """Report liveness, unless the stuck-batch watchdog or the poll-failure trip fired.
Withholding the report makes the health server's timeout fail the liveness
probe, so Kubernetes restarts the pod and the recovery sweep reassigns the
wedged batch -- a sync thread blocked on a dead sink connection cannot be
cancelled from the event loop, so a restart is the only real remedy.
+ Likewise for polling: a pod whose polls all fail does no work but would
+ otherwise report healthy forever.
"""
if self._health_reporter is None:
return
+ threshold = self._config.poll_failure_liveness_threshold
+ if threshold is not None and self._consecutive_poll_failures >= threshold:
+ now = time.monotonic()
+ if now - self._last_poll_failure_log_monotonic > 60:
+ self._last_poll_failure_log_monotonic = now
+ logger.error(
+ self._event("poll_failure_liveness_tripped"),
+ consecutive_failures=self._consecutive_poll_failures,
+ threshold=threshold,
+ )
+ return
timeout = self._config.stuck_batch_timeout_seconds
if timeout is not None and self._inflight_started:
now = time.monotonic()
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.py
index 9c8b0275b26b..e57dfdfb9a0d 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
@@ -377,6 +377,10 @@ class DuckgresBatchConsumerAdapter:
if not batch.is_final_batch:
await DuckgresBatchQueue.mark_applied(conn, batch=batch)
+ def is_retryable_error(self, err: Exception) -> bool:
+ # No known deterministic duckgres failure signatures yet; retry everything.
+ return True
+
class DuckgresBatchConsumer(SharedBatchConsumer):
"""The shared engine plus the sink's lease-safety overrides, kept out of the
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.py
index 868f8de4e759..6ccfcdc49ec2 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
@@ -7,6 +7,7 @@ polling, retry, and recovery mechanics to the v3 batch consumer engine.
from __future__ import annotations
+import asyncio
from collections.abc import Callable
from typing import Any
@@ -33,6 +34,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
_group_by_key,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
+ FRESHNESS_WINDOW_SECONDS,
BatchQueue,
PendingBatch,
)
@@ -49,6 +51,19 @@ logger = structlog.get_logger(__name__)
ConsumerConfig = BatchConsumerConfig
+# Ceiling for the queue-freshness probe, deliberately far below the sweep
+# timeout so a degraded probe can't starve the reconcile sweep it rides on.
+FRESHNESS_PROBE_TIMEOUT_SECONDS = 30.0
+
+# Errors that fail identically on every attempt. Substring-matched because they
+# surface as generic exceptions; keep entries specific so transients can't match.
+NON_RETRYABLE_ERROR_PATTERNS: tuple[str, ...] = (
+ # delta-rs decimal precision overflow — the batch's data cannot fit the column
+ "is too large to store in a Decimal128",
+ # schema configured as incremental without a primary key — config error
+ "Primary key required for incremental syncs",
+)
+
class DeltaBatchConsumerAdapter:
log_prefix: str = ""
@@ -267,11 +282,22 @@ class DeltaBatchConsumerAdapter:
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.
+ health signal looks green. The probe has its own timeout so it cannot
+ eat the reconcile sweep's budget; on timeout the gauge saturates, since
+ a queue DB too degraded to measure freshness must read as stale. Other
+ failures are swallowed-with-capture so a broken probe can't take the
+ sweep down.
"""
try:
- age = await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn)
+ async with asyncio.timeout(FRESHNESS_PROBE_TIMEOUT_SECONDS):
+ age = await BatchQueue.get_oldest_unclaimed_batch_age_seconds(conn)
+ except TimeoutError:
+ logger.error( # noqa: TRY400 — designed degraded path, traceback is noise
+ "queue_freshness_probe_timed_out",
+ timeout_seconds=FRESHNESS_PROBE_TIMEOUT_SECONDS,
+ )
+ OLDEST_UNCLAIMED_BATCH_SECONDS.set(FRESHNESS_WINDOW_SECONDS)
+ return
except Exception as e:
logger.exception("queue_freshness_probe_failed")
capture_exception(e)
@@ -286,6 +312,10 @@ class DeltaBatchConsumerAdapter:
) -> bool:
return True
+ def is_retryable_error(self, err: Exception) -> bool:
+ message = str(err)
+ return not any(pattern in message for pattern in NON_RETRYABLE_ERROR_PATTERNS)
+
async def after_batch_processed(
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.py
index 9d82c6046a75..5aa7d98789cb 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
@@ -49,7 +49,8 @@ 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"
+FRESHNESS_WINDOW_SECONDS = 48 * 60 * 60
+FRESHNESS_WINDOW = f"{FRESHNESS_WINDOW_SECONDS} seconds"
def pending_batch_select_columns(status_alias: str) -> str:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py
index d66fa70e59d9..61a77e4d2f4a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py
@@ -25,4 +25,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
async def process_batch(batch: PendingBatch) -> None:
"""Load a single batch into Delta Lake, reusing the existing processor."""
- await sync_to_async(process_message)(batch.to_export_signal())
+ # thread_sensitive=False: the default single-thread executor would cap the pod's
+ # real parallelism at 1; process_message is self-contained, so cross-thread is safe.
+ await sync_to_async(process_message, thread_sensitive=False)(batch.to_export_signal())
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.py
index e0a44dc97ceb..38fccff5b40d 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
@@ -38,6 +38,14 @@ POLL_DURATION_SECONDS = Histogram(
buckets=POLL_DURATION_BUCKETS,
)
+# Failed polls never reach the histograms above, so a fleet whose polls all
+# time out looks better on those — this counter is the alertable signal.
+POLL_FAILURES_TOTAL = Counter(
+ "warehouse_pg_consumer_poll_failures_total",
+ "Poll cycles that failed before returning batches",
+ labelnames=["reason"],
+)
+
POLL_BATCHES_FETCHED = Histogram(
"warehouse_pg_consumer_poll_batches_fetched",
"Number of batches returned per poll cycle",
@@ -90,6 +98,7 @@ class ConsumerMetrics:
runs_failed_total: Counter
poll_duration_seconds: Histogram
poll_batches_fetched: Histogram
+ poll_failures_total: Counter
active_groups: Gauge
recovery_sweeps_total: Counter
@@ -101,6 +110,7 @@ DELTA_CONSUMER_METRICS = ConsumerMetrics(
runs_failed_total=RUNS_FAILED_TOTAL,
poll_duration_seconds=POLL_DURATION_SECONDS,
poll_batches_fetched=POLL_BATCHES_FETCHED,
+ poll_failures_total=POLL_FAILURES_TOTAL,
active_groups=ACTIVE_GROUPS,
recovery_sweeps_total=RECOVERY_SWEEPS_TOTAL,
)
@@ -146,6 +156,11 @@ def make_consumer_metrics(prefix: str) -> ConsumerMetrics:
"Number of batches returned per poll cycle",
buckets=(0, 1, 5, 10, 25, 50, 100, 250, 500),
),
+ poll_failures_total=Counter(
+ f"{p}_poll_failures_total",
+ "Poll cycles that failed before returning batches",
+ labelnames=["reason"],
+ ),
active_groups=Gauge(
f"{p}_active_groups",
"Number of (team_id, schema_id) groups currently being processed",
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 ce7afea6f75d..355e4d9277f8 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
@@ -17,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
_group_by_key,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
+ FRESHNESS_WINDOW_SECONDS,
FailedRunRef,
PendingBatch,
)
@@ -136,6 +137,35 @@ class TestProcessSingle:
assert states == [SourceBatchStatus.State.EXECUTING, SourceBatchStatus.State.WAITING_RETRY]
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "20009.59457503306999908717 is too large to store in a Decimal128 of precision 24.",
+ "Primary key required for incremental syncs",
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_non_retryable_error_fails_run_on_first_attempt(self, message: str):
+ # Deterministic data/config errors fail identically every attempt;
+ # retrying them wastes all attempts on every scheduled run.
+ consumer = _make_consumer(max_attempts=3)
+ batch = _make_batch(latest_attempt=0)
+ consumer._process_batch = AsyncMock(side_effect=ValueError(message))
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ new_callable=AsyncMock,
+ ) as mock_status,
+ patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail,
+ ):
+ await consumer._process_single(batch)
+
+ mock_fail.assert_called_once()
+ assert mock_fail.call_args[1]["reason"] == message # customer-visible error stays actionable
+ states = [call[1]["job_state"] for call in mock_status.call_args_list]
+ assert SourceBatchStatus.State.WAITING_RETRY not in states
+
@pytest.mark.asyncio
async def test_max_attempts_exceeded_fails_run(self):
consumer = _make_consumer(max_attempts=3)
@@ -528,6 +558,69 @@ class TestQueueOperationTimeouts:
await asyncio.wait_for(run_task, timeout=5.0)
+class TestPollFailureLiveness:
+ def test_withholds_liveness_after_threshold_consecutive_failures(self):
+ # Without the trip, a pod whose every poll fails passes liveness forever.
+ calls: list[int] = []
+ consumer = _make_consumer(poll_failure_liveness_threshold=2)
+ consumer._health_reporter = lambda: calls.append(1)
+
+ consumer._report_health()
+ consumer._note_poll_failure("timeout", duration=1.0)
+ consumer._report_health()
+ assert len(calls) == 2 # one failure is below the threshold
+
+ consumer._note_poll_failure("timeout", duration=1.0)
+ consumer._report_health()
+ consumer._report_health()
+ assert len(calls) == 2 # tripped: heartbeat and poll-loop reports both withhold
+
+ @pytest.mark.asyncio
+ async def test_successful_poll_resets_the_failure_count(self):
+ # Only consecutive failures may trip the probe; without the reset a pod
+ # restarts after N failures spread across weeks of healthy operation.
+ 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())
+
+ succeeded = asyncio.Event()
+ fetch_calls = 0
+
+ async def fetch(*args: Any, **kwargs: Any) -> list[PendingBatch]:
+ nonlocal fetch_calls
+ fetch_calls += 1
+ if fetch_calls <= 2:
+ await asyncio.sleep(3600) # times out
+ succeeded.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",
+ 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=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())
+ await asyncio.wait_for(succeeded.wait(), timeout=2.0)
+ assert consumer._consecutive_poll_failures == 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):
@@ -606,6 +699,36 @@ class TestReconcileFailedRuns:
await consumer._reconcile_failed_runs()
assert OLDEST_UNCLAIMED_BATCH_SECONDS._value.get() == 0.0
+ @pytest.mark.asyncio
+ async def test_hung_freshness_probe_saturates_gauge_and_reconcile_still_runs(self):
+ # A queue DB too degraded to measure freshness must read as stale, not
+ # pin the last good value — and the probe must not eat the sweep's budget.
+ consumer = _make_consumer()
+
+ async def hung_probe(*args: Any, **kwargs: Any) -> float:
+ await asyncio.sleep(3600)
+ return 0.0
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.FRESHNESS_PROBE_TIMEOUT_SECONDS",
+ 0.05,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_oldest_unclaimed_batch_age_seconds",
+ side_effect=hung_probe,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_failed_runs",
+ new_callable=AsyncMock,
+ return_value=[],
+ ) as mock_failed_runs,
+ ):
+ await asyncio.wait_for(consumer._reconcile_failed_runs(), timeout=2.0)
+
+ assert OLDEST_UNCLAIMED_BATCH_SECONDS._value.get() == FRESHNESS_WINDOW_SECONDS
+ mock_failed_runs.assert_called_once()
+
@pytest.mark.asyncio
async def test_marks_non_terminal_run_failed(self):
consumer = _make_consumer()
diff --git a/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.py b/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.py
new file mode 100644
index 000000000000..5adc0a3d17d8
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.py
@@ -0,0 +1,46 @@
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.management.commands.run_warehouse_sources_load import (
+ Command,
+ build_consumer_config,
+)
+
+
+def _parse_options(argv: list[str]) -> dict:
+ parser = Command().create_parser("manage.py", "run_warehouse_sources_load")
+ return vars(parser.parse_args(argv))
+
+
+class TestBuildConsumerConfig:
+ def test_defaults_come_from_the_config_dataclass(self):
+ config = build_consumer_config(_parse_options([]))
+
+ assert config.poll_timeout_seconds == 180.0
+ assert config.sweep_timeout_seconds == 300.0
+ assert config.connect_timeout_seconds == 10
+ assert config.recovery_grace_seconds == 300
+ assert config.lease_ttl_seconds == config.recovery_grace_seconds
+ assert config.poll_failure_liveness_threshold == 10
+
+ @parameterized.expand(
+ [
+ (["--poll-timeout", "600"], "poll_timeout_seconds", 600.0),
+ (["--poll-timeout", "0"], "poll_timeout_seconds", None),
+ (["--sweep-timeout", "900"], "sweep_timeout_seconds", 900.0),
+ (["--sweep-timeout", "0"], "sweep_timeout_seconds", None),
+ (["--connect-timeout", "30"], "connect_timeout_seconds", 30),
+ (["--lease-ttl", "600"], "lease_ttl_seconds", 600),
+ (["--recovery-grace", "900"], "recovery_grace_seconds", 900),
+ (["--poll-failure-liveness-threshold", "5"], "poll_failure_liveness_threshold", 5),
+ (["--poll-failure-liveness-threshold", "0"], "poll_failure_liveness_threshold", None),
+ ]
+ )
+ def test_flag_overrides_reach_the_config(self, argv: list[str], field: str, expected):
+ config = build_consumer_config(_parse_options(argv))
+
+ assert getattr(config, field) == expected
+
+ def test_lease_ttl_follows_recovery_grace_when_not_set(self):
+ config = build_consumer_config(_parse_options(["--recovery-grace", "900"]))
+
+ assert config.lease_ttl_seconds == 900