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): stop discarding staged batches when a v3 extraction fails (#103963)

Tom Owersd2c586859d8f
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 f6b078975b66..be1fe368ca94 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
@@ -23,7 +23,12 @@ from asgiref.sync import sync_to_async
from posthog.exceptions_capture import capture_exception
from posthog.temporal.common.db_errors import is_transient_db_error
-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema, update_should_sync
+from products.warehouse_sources.backend.models.external_data_schema import (
+ SCHEMA_DELETED_JOB_ERROR,
+ SYNC_DISABLED_JOB_ERROR,
+ ExternalDataSchema,
+ update_should_sync,
+)
from products.warehouse_sources.backend.temporal.data_imports.metrics import (
LOCK_TAKEOVER_LATEST_ERROR,
TERMINAL_JOB_STATUSES,
@@ -56,6 +61,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
BACKLOGGED_GROUPS,
BLOCKED_BATCHES,
CLAIMABLE_BATCHES,
+ DRAINED_AFTER_FAILURE_TOTAL,
OLDEST_UNCLAIMED_BATCH_SECONDS,
ORPHANED_BATCHES_DRAINED_TOTAL,
RUNS_RECONCILED_TOTAL,
@@ -65,6 +71,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (
release_v3_pipeline_lock,
)
+from products.warehouse_sources.backend.types import ExternalDataJobStatus
from products.warehouse_sources_queue.backend.models import SourceBatchStatus
logger = structlog.get_logger(__name__)
@@ -100,6 +107,16 @@ STRANDED_RUN_ERROR = (
# already seen that failure on the job, so this text only has to explain the batch rows themselves.
ORPHANED_BATCH_ERROR = "left over from a run that had already failed (orphan drain)"
+# Failures that represent a decision to stop this run rather than something going wrong.
+# Their queued batches are discarded even where the sync type would otherwise drain:
+# finishing the load would override the person or the cleanup that asked it to stop.
+DELIBERATE_STOP_ERRORS: frozenset[str] = frozenset(
+ {
+ SYNC_DISABLED_JOB_ERROR,
+ SCHEMA_DELETED_JOB_ERROR,
+ }
+)
+
# Permanent failures the customer can fix. These stop the schedule as well as the run: the loader
# fails outside the workflow, so the finalization activity that would otherwise disable the schema
@@ -114,15 +131,20 @@ DISABLE_SCHEMA_ERROR_PATTERNS: tuple[str, ...] = (
"Source column type changed",
)
+# The schema or job row was deleted mid-sync — no retry can bring it back, and no more of that
+# run's queued batches should load into a destination whose schema record is gone.
+DELETION_ERROR_PATTERNS: tuple[str, ...] = (
+ "ExternalDataSchema matching query does not exist",
+ "ExternalDataJob matching query does not exist",
+)
+
# Errors that fail identically on every attempt. Substring-matched because they
# surface as generic exceptions; keep entries specific so transients can't match.
# The disable set above, plus the permanent failures that must not stop the schedule: a deleted row
# has nothing left to disable, and a full object store is an infrastructure fix, not a sync setting.
NON_RETRYABLE_ERROR_PATTERNS: tuple[str, ...] = (
*DISABLE_SCHEMA_ERROR_PATTERNS,
- # the schema or job row was deleted mid-sync — no retry can bring it back
- "ExternalDataSchema matching query does not exist",
- "ExternalDataJob matching query does not exist",
+ *DELETION_ERROR_PATTERNS,
# self-hosted object storage (MinIO) has hit its minimum free drive threshold and is
# refusing writes — every retry hits the same full disk until an operator frees space
"XMinioStorageFull",
@@ -138,8 +160,7 @@ EXPECTED_USER_ERROR_PATTERNS: tuple[str, ...] = (
"Source column type changed",
# the schema or job was deleted (e.g. the user removed the source) while a batch for it
# was still in flight — an upstream/customer action, not a pipeline bug
- "ExternalDataSchema matching query does not exist",
- "ExternalDataJob matching query does not exist",
+ *DELETION_ERROR_PATTERNS,
)
# How long an "alive" job-status lookup stays cached before re-checking the app DB.
@@ -182,6 +203,9 @@ class DeltaBatchConsumerAdapter:
self._claim_exclude_sync_types = claim_exclude_sync_types
# job_id -> (is_dead, checked_at via time.monotonic())
self._job_dead_cache: dict[str, tuple[bool, float]] = {}
+ # job_id -> (status, latest_error) for dead jobs only, so the drain decision in
+ # _drainable_after_failure reads the row _is_job_dead already fetched.
+ self._job_dead_cache_status: dict[str, tuple[str, str | None]] = {}
async def fetch_and_lock(
self,
@@ -748,6 +772,17 @@ class DeltaBatchConsumerAdapter:
if not job_dead:
return True
+ if self._drainable_after_failure(batch):
+ DRAINED_AFTER_FAILURE_TOTAL.inc()
+ logger.info(
+ "loading_batch_of_failed_run",
+ batch_id=batch.id,
+ job_id=batch.job_id,
+ run_uuid=batch.run_uuid,
+ sync_type=batch.sync_type,
+ )
+ return True
+
logger.warning(
"skipping_batch_for_dead_job",
batch_id=batch.id,
@@ -757,6 +792,52 @@ class DeltaBatchConsumerAdapter:
await self.fail_run(conn, batch=batch, reason="sync cancelled or job failed")
return False
+ def _drainable_after_failure(self, batch: PendingBatch) -> bool:
+ """Whether a dead job's queued batches should still be loaded rather than thrown away.
+
+ An extraction that dies mid-run leaves batches already read from the source, already
+ written to S3, and already billed. Wiping them throws that away and makes the next
+ attempt redo it, which is how one thrashing schema turned into six figures of failed
+ batches with ``latest_attempt = 0`` — rows no consumer ever tried.
+
+ Draining is only safe where a half-loaded run is a smaller run rather than a wrong
+ one, so each exclusion below is its own reason:
+
+ - ``full_refresh`` replaces the table, so a partial snapshot is a torn table.
+ - ``append`` has no primary key, so a re-extracted window duplicates rows.
+ - ``cdc`` resolves its position from consumed buffer files; that machinery decides
+ what a partial run means, not this check.
+ - A billing-limit status is exactly the case where loading more is the thing the
+ limit exists to prevent.
+ - A deliberate stop (syncing turned off, the table deleted) is a decision to make
+ this run stop, so finishing the load would override it.
+ - A permanent, unfixable failure (``DISABLE_SCHEMA_ERROR_PATTERNS``) already disabled
+ the schema because the data itself cannot land, and a deletion failure
+ (``DELETION_ERROR_PATTERNS``) means the schema or job row is gone; loading more in
+ either case writes into a destination the run has already given up on.
+
+ ``incremental`` is left because its next run continues from a staged cursor that
+ only promotes on a Completed job (``load/processor.py``). The job stays Failed here,
+ so the cursor does not advance, the next run re-extracts the same window, and its
+ primary key makes that merge idempotent. Loading is therefore strictly progress.
+ """
+ if batch.sync_type != "incremental":
+ return False
+
+ status_and_error = self._job_dead_cache_status.get(batch.job_id)
+ if status_and_error is None:
+ return False
+
+ status, error = status_and_error
+ error = error or ""
+ if error in DELIBERATE_STOP_ERRORS:
+ return False
+ if any(pattern in error for pattern in DISABLE_SCHEMA_ERROR_PATTERNS):
+ return False
+ if any(pattern in error for pattern in DELETION_ERROR_PATTERNS):
+ return False
+ return status == ExternalDataJobStatus.FAILED
+
async def _is_job_dead(self, batch: PendingBatch) -> bool:
"""Whether the batch's ExternalDataJob is in a terminal non-Completed state (e.g. cancelled)."""
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
@@ -778,14 +859,23 @@ class DeltaBatchConsumerAdapter:
# its batches here would close that deliberate recovery window.
and row[1] != LOCK_TAKEOVER_LATEST_ERROR
)
-
if len(self._job_dead_cache) >= JOB_STATUS_CACHE_MAX_ENTRIES:
# Evict alive entries first: dead verdicts are final, and re-deriving one
# costs an app-DB read per queued batch of that job.
self._job_dead_cache = {k: v for k, v in self._job_dead_cache.items() if v[0]}
if len(self._job_dead_cache) >= JOB_STATUS_CACHE_MAX_ENTRIES:
self._job_dead_cache.clear()
+ self._job_dead_cache_status = {
+ k: v for k, v in self._job_dead_cache_status.items() if k in self._job_dead_cache
+ }
+
self._job_dead_cache[batch.job_id] = (is_dead, now)
+ # Written after eviction, not before: an eviction on this very call prunes the status
+ # map against the dead-verdict map, and this job is not in that one until the line
+ # above. Writing first would drop the row the drain decision is about to read, and the
+ # batch would be discarded rather than loaded.
+ if is_dead and row is not None:
+ self._job_dead_cache_status[batch.job_id] = (row[0], row[1])
return is_dead
def is_retryable_error(self, err: Exception) -> bool:
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 8c92cfeaf506..8db3122ec0f6 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
@@ -84,6 +84,13 @@ ORPHANED_BATCHES_DRAINED_TOTAL = Counter(
"is the standing population, this counter is the drain rate.",
)
+DRAINED_AFTER_FAILURE_TOTAL = Counter(
+ "warehouse_pg_consumer_drained_after_failure_total",
+ "Batches loaded even though their job had already failed, because the run was incremental "
+ "and the rows were already extracted and staged. Rising here means work that used to be "
+ "discarded now lands.",
+)
+
RUNS_TERMINALIZED_STALE_TOTAL = Counter(
"warehouse_pg_consumer_runs_terminalized_stale_total",
"Runs the loader abandoned (non-terminal batches, no live lease, no progress past the "
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 bc86c7be1c87..138aef17e6e5 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
@@ -11,6 +11,10 @@ import psycopg
import structlog
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import (
+ SCHEMA_DELETED_JOB_ERROR,
+ SYNC_DISABLED_JOB_ERROR,
+)
from products.warehouse_sources.backend.temporal.data_imports.metrics import LOCK_TAKEOVER_LATEST_ERROR
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3 import (
batch_consumer as batch_consumer_module,
@@ -28,6 +32,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
consumer as consumer_module,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer import (
+ JOB_STATUS_CACHE_MAX_ENTRIES,
BatchConsumer,
ConsumerConfig,
DeltaBatchConsumerAdapter,
@@ -1671,6 +1676,90 @@ class TestShouldProcessBatch:
assert mock_queue_fail.call_args.kwargs["run_uuid"] == batch.run_uuid
mock_release.assert_called_once_with(team_id=batch.team_id, schema_id=batch.schema_id, token="wf-run-1")
+ @pytest.mark.parametrize(
+ "sync_type,job_status,latest_error,expect_drained",
+ [
+ # The case this exists for: extraction died, rows are already staged, and the next
+ # run continues from a cursor that only promotes on a Completed job.
+ ("incremental", "Failed", "connection lost", True),
+ # A decision to stop this run. Finishing the load would override it.
+ ("incremental", "Failed", SYNC_DISABLED_JOB_ERROR, False),
+ ("incremental", "Failed", SCHEMA_DELETED_JOB_ERROR, False),
+ # A permanent, unfixable failure already disabled the schema; loading more
+ # writes into a destination the run has already given up on.
+ ("incremental", "Failed", "delta-rs: is too large to store in a Decimal128", False),
+ ("incremental", "Failed", "Primary key required for incremental syncs", False),
+ ("incremental", "Failed", "SchemaColumnTypeChangedException: Source column type changed", False),
+ # The schema or job row is gone — nothing left to load into.
+ ("incremental", "Failed", "ExternalDataSchema matching query does not exist", False),
+ ("incremental", "Failed", "ExternalDataJob matching query does not exist", False),
+ # Loading more is the thing a billing limit exists to prevent.
+ ("incremental", "BillingLimitReached", "over limit", False),
+ ("incremental", "BillingLimitTooLow", "limit too low", False),
+ # A full refresh replaces the table, so a partial snapshot is a torn table.
+ ("full_refresh", "Failed", "connection lost", False),
+ # An append has no primary key, so a re-extracted window duplicates rows.
+ ("append", "Failed", "connection lost", False),
+ # CDC resolves its position from consumed buffer files; that machinery owns it.
+ ("cdc", "Failed", "connection lost", False),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_only_incremental_runs_drain_after_a_genuine_failure(
+ self, sync_type, job_status, latest_error, expect_drained
+ ):
+ consumer = _make_consumer()
+ conn = consumer._poll_conn
+ assert conn is not None
+ batch = _make_batch(sync_type=sync_type, metadata={"workflow_run_id": "wf-run-1"})
+
+ with (
+ patch(
+ f"{consumer_module.__name__}._get_job_status_and_error",
+ return_value=(job_status, latest_error),
+ ),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.fail_run",
+ new_callable=AsyncMock,
+ ) as mock_queue_fail,
+ patch(f"{consumer_module.__name__}._update_job_status_to_failed"),
+ patch(f"{consumer_module.__name__}.release_v3_pipeline_lock"),
+ ):
+ result = await consumer._adapter.should_process_batch(conn, batch=batch)
+
+ assert result is expect_drained
+ assert mock_queue_fail.await_count == (0 if expect_drained else 1)
+
+ @pytest.mark.asyncio
+ async def test_drain_survives_a_cache_eviction_on_the_same_call(self):
+ # The status map is pruned against the dead-verdict map. If this job's status were
+ # recorded before that prune it would be dropped on the way through, and the batch
+ # would be discarded rather than loaded - silently, and only once the cache is full.
+ consumer = _make_consumer()
+ conn = consumer._poll_conn
+ assert conn is not None
+ # _adapter is typed as the protocol, and the cache is a Delta-adapter detail.
+ adapter = cast(DeltaBatchConsumerAdapter, consumer._adapter)
+ adapter._job_dead_cache = {f"filler-{i}": (False, 0.0) for i in range(JOB_STATUS_CACHE_MAX_ENTRIES)}
+ batch = _make_batch(sync_type="incremental", metadata={"workflow_run_id": "wf-run-1"})
+
+ with (
+ patch(
+ f"{consumer_module.__name__}._get_job_status_and_error",
+ return_value=("Failed", "connection lost"),
+ ),
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.fail_run",
+ new_callable=AsyncMock,
+ ) as mock_queue_fail,
+ patch(f"{consumer_module.__name__}._update_job_status_to_failed"),
+ patch(f"{consumer_module.__name__}.release_v3_pipeline_lock"),
+ ):
+ result = await adapter.should_process_batch(conn, batch=batch)
+
+ assert result is True
+ mock_queue_fail.assert_not_awaited()
+
@pytest.mark.parametrize(
"status_row",
[