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.

feat(data-warehouse): fail fast on permanent apply errors and surface live-run divergence (#69025)

Eric Duong90c2744be842
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 b67ec349696e..d0522ac8cd97 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
@@ -55,6 +55,13 @@ class OwnershipLostError(Exception):
"""Raised when the group lease for a (team_id, schema_id) is no longer held by this consumer."""
+class PermanentBatchApplyError(Exception):
+ """Raise from process_batch for errors retries cannot fix (unsupported batch
+ kind, missing primary keys, malformed batch metadata). The consumer skips
+ the waiting_retry cycle and fails the run on the first attempt — retrying a
+ permanent error only delays the terminal state and burns sink throughput."""
+
+
@dataclass
class BatchConsumerConfig:
"""Tuning knobs for the batch consumer."""
@@ -813,8 +820,8 @@ class BatchConsumer:
) -> None:
"""Write the retry/terminal state after a processing error."""
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.
+ # Deterministic failures do not benefit from retrying. Preserve their
+ # messages, except for explicitly classified permanent apply errors.
logger.exception(
self._event("batch_failed_non_retryable"),
batch_id=batch.id,
@@ -822,8 +829,10 @@ class BatchConsumer:
attempt=attempt,
)
capture_exception(err)
- await self._fail_run(batch, reason=str(err), conn=lock_conn)
+ reason = f"permanent apply error: {err}" if isinstance(err, PermanentBatchApplyError) else str(err)
+ await self._fail_run(batch, reason=reason, conn=lock_conn)
elif attempt >= self._config.max_attempts:
+ reason = f"max retries exceeded: {err}"
logger.exception(
self._event("batch_failed_no_retries_left"),
batch_id=batch.id,
@@ -831,7 +840,7 @@ class BatchConsumer:
attempt=attempt,
)
capture_exception(err)
- await self._fail_run(batch, reason=f"max retries exceeded: {err}", conn=lock_conn)
+ await self._fail_run(batch, reason=reason, conn=lock_conn)
else:
logger.warning(
self._event("batch_failed_will_retry"),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py
index 922d01144c41..52bff919f6cc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py
@@ -130,6 +130,7 @@ __all__ = [
"blocked_schema_ids",
"failing_schema_ids",
"mark_primed",
+ "mark_schema_diverged",
"replan_backfill",
"run_backfill_planner",
"sink_eligible_schema_ids",
@@ -273,6 +274,40 @@ def mark_primed(schema_id: str, *, run_uuid: str, chunks_applied: int | None = N
).update(**updates)
+def mark_schema_diverged(schema_id: str, *, run_uuid: str, error: str) -> None:
+ """A LIVE run hard-failed in the sink: some of its batches applied and the
+ rest never will, so the duckgres table is durably behind Delta. Park the
+ schema in NEEDS_RESYNC — that blocks further live batches from compounding
+ the gap, classifies the schema failing (streak jumped to threshold: a
+ terminally failed run has no retry loop to ride out), and routes healing
+ through the existing path: the next fully-applied replace-head run
+ (full-refresh resync, or the schema's own next full_refresh sync) flips it
+ back to PRIMED.
+
+ CAS from PRIMED only: a BACKFILLING schema's failures are the reconciler's
+ to escalate, and an already-parked schema must not have its streak anchor
+ or error overwritten.
+ """
+ close_old_connections()
+ now = timezone.now()
+ flipped = DuckgresSinkSchemaState.objects.filter(
+ schema_id=schema_id, state=DuckgresSinkSchemaState.State.PRIMED
+ ).update(
+ state=DuckgresSinkSchemaState.State.NEEDS_RESYNC,
+ last_error=f"live run {run_uuid} failed in the duckgres sink: {error}"[:2000],
+ updated_at=now,
+ consecutive_failures=Greatest(F("consecutive_failures"), Value(FAILING_THRESHOLD)),
+ first_failed_at=Coalesce(F("first_failed_at"), Value(now)),
+ )
+ if flipped:
+ logger.warning(
+ "duckgres_sink_schema_diverged",
+ schema_id=schema_id,
+ run_uuid=run_uuid,
+ error=error[:500],
+ )
+
+
def replan_backfill(schema_id: str) -> None:
"""Operator entrypoint: retire the current backfill run and re-enter planning.
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 5cef94c921e9..4987ca73f6bb 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
@@ -19,15 +19,20 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
BatchConsumer as SharedBatchConsumer,
BatchConsumerConfig,
OwnershipLostError,
+ PermanentBatchApplyError,
ProcessBatchFn,
_group_by_key,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (
blocked_schema_ids as compute_blocked_schema_ids,
failing_schema_ids as compute_failing_schema_ids,
+ mark_schema_diverged,
run_backfill_planner,
sink_eligible_schema_ids as compute_eligible_schema_ids,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.batch_kind import (
+ is_backfill_metadata,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.enablement import (
duckgres_sink_enablement,
)
@@ -427,8 +432,7 @@ class DuckgresBatchConsumerAdapter:
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
+ return not isinstance(err, PermanentBatchApplyError)
class DuckgresBatchConsumer(SharedBatchConsumer):
@@ -525,6 +529,17 @@ class DuckgresBatchConsumer(SharedBatchConsumer):
)
raise
await super()._handle_batch_failure(batch, attempt, err, lock_conn=lock_conn, status_conn=status_conn)
+ if (attempt >= self._config.max_attempts or isinstance(err, PermanentBatchApplyError)) and not (
+ is_backfill_metadata(batch.metadata)
+ ):
+ # Terminal failure of a LIVE run: earlier batches applied, the rest
+ # never will — the duckgres table is durably behind Delta. Park the
+ # schema so the gap stops compounding and shows up as failing
+ # instead of silently diverging. Backfill chunks are excluded: the
+ # reconciler escalates those against the BACKFILLING state.
+ await sync_to_async(mark_schema_diverged, thread_sensitive=False)(
+ batch.schema_id, run_uuid=batch.run_uuid, error=str(err)
+ )
async def _recovery_sweep(self) -> None:
conn = await self._ensure_recovery_conn()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py
index 443185b555bf..f8bcfd5419a9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py
@@ -20,6 +20,9 @@ from posthog.models import Team
from products.warehouse_sources.backend.models import ExternalDataJob, ExternalDataSchema
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (
+ PermanentBatchApplyError,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import batch_kind
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
PendingBatch,
@@ -230,7 +233,7 @@ def _backfill_chunk_paths(batch: PendingBatch) -> list[str]:
except ValueError as e:
# Falling back to s3_path would silently apply only the chunk's first
# file; a malformed synthetic row must fail loudly instead.
- raise ValueError(f"backfill batch {batch.id}: {e}") from e
+ raise PermanentBatchApplyError(f"backfill batch {batch.id}: {e}") from e
def _read_parquet_expr(paths: list[str], *, union_by_name: bool = False) -> sql.Composable:
@@ -266,7 +269,7 @@ def _process_batch(
)
if batch.sync_type == "cdc":
- raise ValueError("Duckgres batch sink does not support CDC batches yet")
+ raise PermanentBatchApplyError("Duckgres batch sink does not support CDC batches yet")
_ensure_duckgres_apply_table(conn, duckgres_schema)
if batch.batch_index == 0 and not batch.is_final_batch:
@@ -478,13 +481,13 @@ def _plan_batch_operation(
primary_keys = _primary_keys(batch)
if not primary_keys:
- raise ValueError("Duckgres incremental batches require primary keys")
+ raise PermanentBatchApplyError("Duckgres incremental batches require primary keys")
return BatchApplyOperation(kind="merge", ensure_target_columns=True, primary_keys=primary_keys)
if batch.sync_type in ("full_refresh", "append"):
return BatchApplyOperation(kind="insert", ensure_target_columns=True)
- raise ValueError(f"Unsupported Duckgres sync type: {batch.sync_type}")
+ raise PermanentBatchApplyError(f"Unsupported Duckgres sync type: {batch.sync_type}")
def _table_exists(conn: psycopg.Connection[Any], duckgres_schema: str, duckgres_table: str) -> bool:
@@ -670,10 +673,10 @@ def _apply_batch_operation(
return
if operation.kind == "merge":
if operation.primary_keys is None:
- raise ValueError("Duckgres merge operation requires primary keys")
+ raise PermanentBatchApplyError("Duckgres merge operation requires primary keys")
_merge_batch(conn, duckgres_schema, duckgres_table, paths, columns, operation.primary_keys)
return
- raise ValueError(f"Unsupported Duckgres apply operation: {operation.kind}")
+ raise PermanentBatchApplyError(f"Unsupported Duckgres apply operation: {operation.kind}")
def _insert_batch(
@@ -709,7 +712,7 @@ def _merge_batch(
normalized_primary_keys = [NamingConvention.normalize_identifier(key) for key in primary_keys]
missing_keys = [key for key in normalized_primary_keys if key not in columns]
if missing_keys:
- raise ValueError(f"Duckgres incremental batch missing primary keys: {missing_keys}")
+ raise PermanentBatchApplyError(f"Duckgres incremental batch missing primary keys: {missing_keys}")
update_columns = [column for column in columns if column not in normalized_primary_keys]
if not update_columns:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py
index 4f4c58692634..52413cc0ed59 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py
@@ -599,3 +599,44 @@ class TestEnqueueLockTimeout:
assert any("SET lock_timeout" in query for query in executed)
assert any("RESET lock_timeout" in query for query in executed)
assert not any("INSERT INTO" in query for query in executed)
+
+
+# transaction=True: mark_schema_diverged does thread-entry close_old_connections
+# (it is called from the consumer via sync_to_async), which severs the
+# TestCase-style transaction-wrapped connection.
[email protected]_db(transaction=True)
+class TestMarkSchemaDiverged:
+ def _team(self) -> Team:
+ return Team.objects.create(organization=Organization.objects.create(name="org"), name="t")
+
+ def test_primed_schema_parks_as_failing_needs_resync(self):
+ row = _sink_state(self._team(), _State.PRIMED)
+
+ backfill_module.mark_schema_diverged(str(row.schema_id), run_uuid="run-x", error="poison batch")
+
+ row.refresh_from_db()
+ assert row.state == _State.NEEDS_RESYNC
+ assert row.consecutive_failures >= backfill_module.FAILING_THRESHOLD
+ assert row.first_failed_at is not None
+ assert "run-x" in (row.last_error or "")
+
+ # Second terminal failure must not clobber the streak anchor or error:
+ # the CAS is PRIMED-only.
+ anchor = row.first_failed_at
+ backfill_module.mark_schema_diverged(str(row.schema_id), run_uuid="run-y", error="later failure")
+ row.refresh_from_db()
+ assert row.first_failed_at == anchor
+ assert "run-x" in (row.last_error or "")
+
+ def test_non_primed_states_are_untouched(self):
+ # BACKFILLING failures are the reconciler's to escalate; a pending
+ # schema has no divergence to record.
+ team = self._team()
+ for state in (_State.BACKFILLING, _State.PENDING_BACKFILL):
+ row = _sink_state(team, state)
+
+ backfill_module.mark_schema_diverged(str(row.schema_id), run_uuid="run-x", error="boom")
+
+ row.refresh_from_db()
+ assert row.state == state
+ assert row.consecutive_failures == 0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py
index e78b26eb9cfa..aad7873575ac 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py
@@ -1,4 +1,5 @@
import time
+from contextlib import contextmanager
from typing import Any
import pytest
@@ -8,6 +9,7 @@ import psycopg
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (
OwnershipLostError,
+ PermanentBatchApplyError,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer import (
DuckgresBatchConsumer,
@@ -644,3 +646,105 @@ class TestStuckBatchWatchdog:
consumer._report_health()
assert reporter.call_count == 2
+
+
+class TestPermanentApplyErrors:
+ @contextmanager
+ def _sink_mocks(self, states):
+ async def track_status(conn, *, batch_id, job_state, attempt, error_response=None):
+ states.append(job_state)
+ return True
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",
+ side_effect=track_status,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.renew_lease",
+ new_callable=AsyncMock,
+ return_value=True,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.is_failed",
+ new_callable=AsyncMock,
+ return_value=False,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",
+ new_callable=AsyncMock,
+ return_value=False,
+ ),
+ ):
+ yield
+
+ @pytest.mark.asyncio
+ async def test_permanent_error_fails_run_on_first_attempt_and_marks_diverged(self):
+ # A permanent error must not burn max_attempts waiting_retry cycles,
+ # and the terminal live-run failure must park the schema (else the
+ # duckgres table silently diverges from Delta with no signal).
+ consumer = _make_consumer(max_attempts=3)
+ consumer._process_batch = AsyncMock(side_effect=PermanentBatchApplyError("unsupported sync type"))
+ states: list[str] = []
+
+ with (
+ self._sink_mocks(states),
+ patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.mark_schema_diverged"
+ ) as mock_diverged,
+ ):
+ await consumer._process_single(_make_batch(latest_attempt=0), lock_conn=_make_healthy_conn())
+
+ mock_fail.assert_called_once()
+ assert "permanent" in mock_fail.call_args.kwargs.get(
+ "reason", mock_fail.call_args.args[1] if len(mock_fail.call_args.args) > 1 else ""
+ )
+ assert SourceBatchDuckgresStatus.State.WAITING_RETRY not in states
+ mock_diverged.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_transient_error_still_retries_without_divergence_flip(self):
+ # Guards against over-eager classification: an ordinary error keeps the
+ # waiting_retry cycle and must not park the schema.
+ consumer = _make_consumer(max_attempts=3)
+ consumer._process_batch = AsyncMock(side_effect=ValueError("connection reset"))
+ states: list[str] = []
+
+ with (
+ self._sink_mocks(states),
+ patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.mark_schema_diverged"
+ ) as mock_diverged,
+ ):
+ await consumer._process_single(_make_batch(latest_attempt=0), lock_conn=_make_healthy_conn())
+
+ mock_fail.assert_not_called()
+ assert SourceBatchDuckgresStatus.State.WAITING_RETRY in states
+ mock_diverged.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_backfill_chunk_terminal_failure_does_not_mark_diverged(self):
+ # Backfill chunks fail against the BACKFILLING state; the reconciler
+ # escalates those. The divergence flip is for LIVE runs only.
+ consumer = _make_consumer(max_attempts=3)
+ consumer._process_batch = AsyncMock(side_effect=PermanentBatchApplyError("malformed chunk metadata"))
+ states: list[str] = []
+
+ with (
+ self._sink_mocks(states),
+ patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.mark_schema_diverged"
+ ) as mock_diverged,
+ ):
+ await consumer._process_single(
+ _make_batch(
+ latest_attempt=0, metadata={"duckgres_backfill": {"chunk_paths": ["s3://b/f"], "chunk_count": 1}}
+ ),
+ lock_conn=_make_healthy_conn(),
+ )
+
+ mock_fail.assert_called_once()
+ mock_diverged.assert_not_called()