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 load completion and error classification (#70490)

estefania4287bf4866b9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
index fddb5010f0b1..9f65a86a25fc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
@@ -1,7 +1,7 @@
from collections.abc import Callable
from typing import Any, Literal
-from django.db import close_old_connections
+from django.db import close_old_connections, transaction
import s3fs
import pyarrow as pa
@@ -35,6 +35,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (
validate_schema_and_update_table,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (
+ OwnershipLostError,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.common import (
ExportSignalMessage,
SyncTypeLiteral,
@@ -300,20 +303,30 @@ def _release_pipeline_lock_for_job(export_signal: ExportSignalMessage) -> None:
def _mark_job_completed(export_signal: ExportSignalMessage) -> None:
- model = update_external_job_status(
- job_id=export_signal.job_id,
- team_id=export_signal.team_id,
- status=ExternalDataJob.Status.COMPLETED,
- logger=logger,
- latest_error=None,
- )
+ # Reconnect stale connections before the transaction; close_old_connections must never
+ # run inside an atomic block since it can drop the connection mid-transaction.
+ close_old_connections()
- if model.status == ExternalDataJob.Status.COMPLETED:
- # Promote only when the Completed write landed: if the job was cancelled (absorbing
- # Failed) after the final batch passed should_process_batch, the staged incremental
- # cursor must not advance past data that was never fully loaded.
- _promote_staged_cursor(export_signal)
+ # The Completed write and cursor promotion share one transaction so they commit together:
+ # if promotion raises, the completion rolls back and the batch retries, never stranding a
+ # terminal job with a stale cursor that a later append sync would re-extract past.
+ with transaction.atomic():
+ model = update_external_job_status(
+ job_id=export_signal.job_id,
+ team_id=export_signal.team_id,
+ status=ExternalDataJob.Status.COMPLETED,
+ logger=logger,
+ latest_error=None,
+ )
+ job_completed = model.status == ExternalDataJob.Status.COMPLETED
+ if job_completed:
+ # Promote only when the Completed write landed: if the job was cancelled (absorbing
+ # Failed) after the final batch passed should_process_batch, the staged incremental
+ # cursor must not advance past data that was never fully loaded.
+ _promote_staged_cursor(export_signal)
+
+ if job_completed:
async_to_sync(finish_row_tracking)(export_signal.team_id, export_signal.schema_id)
logger.info(
@@ -335,23 +348,15 @@ def _mark_job_completed(export_signal: ExportSignalMessage) -> None:
def _promote_staged_cursor(export_signal: ExportSignalMessage) -> None:
- close_old_connections()
- try:
- schema = ExternalDataSchema.objects.get(id=export_signal.schema_id, team_id=export_signal.team_id)
- promoted = schema.promote_staged_incremental_values(export_signal.run_uuid)
- if promoted:
- logger.info(
- "staged_cursor_promoted",
- run_uuid=export_signal.run_uuid,
- external_data_schema_id=export_signal.schema_id,
- )
- except Exception as e:
- logger.exception(
- "staged_cursor_promotion_failed",
+ # Runs inside the completion transaction; failures roll it back so the batch retries.
+ schema = ExternalDataSchema.objects.get(id=export_signal.schema_id, team_id=export_signal.team_id)
+ promoted = schema.promote_staged_incremental_values(export_signal.run_uuid)
+ if promoted:
+ logger.info(
+ "staged_cursor_promoted",
run_uuid=export_signal.run_uuid,
external_data_schema_id=export_signal.schema_id,
)
- capture_exception(e)
def _mark_job_failed(export_signal: ExportSignalMessage, error: Exception) -> None:
@@ -457,6 +462,10 @@ def process_message(
if verify_ownership is not None:
verify_ownership()
_run_post_load_for_already_processed_batch(export_signal)
+ # Post-load can run minutes (compaction, S3 prep) — re-check before
+ # completion promotes the cursor and releases the lock under a new owner.
+ if verify_ownership is not None:
+ verify_ownership()
_mark_job_completed(export_signal)
return
@@ -667,6 +676,11 @@ def process_message(
cdc_write_mode=export_signal.cdc_write_mode,
)
+ # Post-load can run minutes (compaction, S3 prep) — re-check before
+ # completion promotes the cursor and releases the lock under a new owner.
+ if verify_ownership is not None:
+ verify_ownership()
+
_mark_job_completed(export_signal)
logger.debug("post_load_operations_complete")
@@ -689,6 +703,10 @@ def process_message(
"total_rows": export_signal.total_rows,
},
)
+ except OwnershipLostError:
+ # Benign fencing abandon: the engine re-raises this without writing a
+ # failure status, so it must not count as a load failure in analytics either.
+ raise
except Exception as e:
posthoganalytics.capture(
distinct_id=get_machine_id(),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
index 0c2c4899cf2e..0d5570040a86 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
@@ -160,23 +160,29 @@ class TestPromoteStagedCursor:
@patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.ExternalDataSchema.objects"
)
- def test_does_not_raise_on_promotion_failure(self, mock_objects: MagicMock) -> None:
+ def test_promotion_failure_propagates(self, mock_objects: MagicMock) -> None:
+ # If the failure is swallowed, the job completes with a stale cursor and
+ # the next run re-extracts the same window — duplicate rows for append syncs.
schema = MagicMock()
schema.promote_staged_incremental_values.side_effect = RuntimeError("db error")
mock_objects.get.return_value = schema
signal = self._make_signal()
- _promote_staged_cursor(signal)
+ with pytest.raises(RuntimeError):
+ _promote_staged_cursor(signal)
@patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.ExternalDataSchema.objects"
)
- def test_does_not_raise_when_schema_missing(self, mock_objects: MagicMock) -> None:
+ def test_missing_schema_propagates(self, mock_objects: MagicMock) -> None:
+ # A deleted schema is permanent; the consumer's non-retryable patterns
+ # fail the run fast instead of completing a job for a schema that's gone.
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
mock_objects.get.side_effect = ExternalDataSchema.DoesNotExist()
signal = self._make_signal()
- _promote_staged_cursor(signal)
+ with pytest.raises(ExternalDataSchema.DoesNotExist):
+ _promote_staged_cursor(signal)
class _LeaseLost(Exception):
@@ -276,6 +282,74 @@ class TestProcessMessageOwnershipGate:
mock_post_load.assert_not_called()
mock_mark_completed.assert_not_called()
+ @patch(f"{_PROCESSOR}.posthoganalytics")
+ @patch(f"{_PROCESSOR}._mark_job_completed")
+ @patch(f"{_PROCESSOR}._run_post_load_for_already_processed_batch")
+ @patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=True)
+ @patch(f"{_PROCESSOR}.DeltaTableHelper")
+ @patch(f"{_PROCESSOR}.ExternalDataJob")
+ @patch(f"{_PROCESSOR}.s3fs")
+ @patch(f"{_PROCESSOR}.close_old_connections")
+ def test_ownership_lost_during_post_load_blocks_completion(
+ self,
+ _close: MagicMock,
+ _s3fs: MagicMock,
+ mock_job_model: MagicMock,
+ _helper_cls: MagicMock,
+ _already: MagicMock,
+ mock_post_load: MagicMock,
+ mock_mark_completed: MagicMock,
+ _analytics: MagicMock,
+ ) -> None:
+ # Post-load can run minutes; without the re-check a lease lost mid-post-load
+ # still promotes the cursor and marks the job COMPLETED under a new owner.
+ mock_job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()
+
+ calls = {"count": 0}
+
+ def verify_ownership() -> None:
+ calls["count"] += 1
+ if calls["count"] > 1:
+ raise _LeaseLost()
+
+ with pytest.raises(_LeaseLost):
+ process_message(_message(is_final_batch=True), verify_ownership=verify_ownership)
+
+ mock_post_load.assert_called_once()
+ mock_mark_completed.assert_not_called()
+
+ @patch(f"{_PROCESSOR}.posthoganalytics")
+ @patch(f"{_PROCESSOR}._run_post_load_for_already_processed_batch")
+ @patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=True)
+ @patch(f"{_PROCESSOR}.DeltaTableHelper")
+ @patch(f"{_PROCESSOR}.ExternalDataJob")
+ @patch(f"{_PROCESSOR}.s3fs")
+ @patch(f"{_PROCESSOR}.close_old_connections")
+ def test_ownership_loss_is_not_counted_as_load_failure(
+ self,
+ _close: MagicMock,
+ _s3fs: MagicMock,
+ mock_job_model: MagicMock,
+ _helper_cls: MagicMock,
+ _already: MagicMock,
+ _post_load: MagicMock,
+ mock_analytics: MagicMock,
+ ) -> None:
+ # Fencing abandons are benign; counting them as load failures pollutes the metric.
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (
+ OwnershipLostError,
+ )
+
+ mock_job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()
+
+ def verify_ownership() -> None:
+ raise OwnershipLostError("group lease lost")
+
+ with pytest.raises(OwnershipLostError):
+ process_message(_message(is_final_batch=True), verify_ownership=verify_ownership)
+
+ mock_analytics.capture.assert_not_called()
+
class TestMarkJobCompleted:
def _make_signal(self, **overrides: Any) -> MagicMock:
@@ -295,6 +369,7 @@ class TestMarkJobCompleted:
("completed_write_absorbed_by_failed", "Failed", False),
]
)
+ @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.transaction")
@patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.release_v3_pipeline_lock"
)
@@ -321,6 +396,7 @@ class TestMarkJobCompleted:
mock_finish_row_tracking: AsyncMock,
mock_job_objects: MagicMock,
mock_release: MagicMock,
+ mock_transaction: MagicMock,
) -> None:
model = MagicMock()
model.status = resulting_status
@@ -342,6 +418,44 @@ class TestMarkJobCompleted:
# The pipeline lock must be released either way, or the next sync is blocked.
mock_release.assert_called_once_with(team_id=1, schema_id="schema-1", token="wf-run-1")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.transaction")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.release_v3_pipeline_lock"
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.finish_row_tracking",
+ new_callable=AsyncMock,
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.ExternalDataSchema.objects"
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.update_external_job_status"
+ )
+ def test_promotion_failure_does_not_finalize_job(
+ self,
+ mock_update: MagicMock,
+ mock_schema_objects: MagicMock,
+ mock_finish_row_tracking: AsyncMock,
+ mock_release: MagicMock,
+ mock_transaction: MagicMock,
+ ) -> None:
+ # Promotion raising must propagate and skip finalization so the batch retries; otherwise the
+ # job stays Completed with a stale cursor and a later append sync re-extracts the same window.
+ model = MagicMock()
+ model.status = "Completed"
+ mock_update.return_value = model
+
+ schema = MagicMock()
+ schema.promote_staged_incremental_values.side_effect = RuntimeError("db error")
+ mock_schema_objects.get.return_value = schema
+
+ with pytest.raises(RuntimeError, match="db error"):
+ _mark_job_completed(self._make_signal())
+
+ mock_finish_row_tracking.assert_not_awaited()
+ mock_release.assert_not_called()
+
# Regression guard for #70476: pyarrow 21+ string_view broke delta pushdown on string PKs.
class TestReadExistingRowsByFirstPk:
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 c9474838f7eb..ed1ca276fd1b 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
@@ -76,6 +76,9 @@ NON_RETRYABLE_ERROR_PATTERNS: tuple[str, ...] = (
# incoming values no longer fit the stored Delta column type
# (SchemaColumnTypeChangedException) — only a reset and full re-sync can fix it
"Source column type changed",
+ # 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",
)
# How long an "alive" job-status lookup stays cached before re-checking the app DB.
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 485b3d4684ff..16863b2f07b6 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
@@ -38,7 +38,7 @@ LEASE_TTL_SECONDS = 300
# Partition pruning hint: only scan partitions within this window.
# Set to 2x the retention period so the planner can skip dropped
-# partitions. Not a correctness filter — older partitions are already
+# partitions. Not a correctness filter -- older partitions are already
# gone by the time this matters.
PARTITION_PRUNING_INTERVAL = "14 days"
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 ef1f7f19bdbb..eba9763c5732 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
@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer import (
BatchConsumer,
ConsumerConfig,
+ DeltaBatchConsumerAdapter,
_group_by_key,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
@@ -1683,3 +1684,21 @@ class TestBatchHeartbeat:
# blip -> continue; renewed -> status refresh; lease lost -> stop
assert renew.await_count == 3
refresh.assert_awaited_once()
+
+
+class TestIsRetryableError:
+ # A dropped pattern silently reverts a permanent error (deleted schema/job,
+ # data that can never fit) to burning all retry attempts before failing.
+
+ @pytest.mark.parametrize(
+ ("message", "retryable"),
+ [
+ ("value is too large to store in a Decimal128 of precision 24", False),
+ ("Primary key required for incremental syncs", False),
+ ("ExternalDataSchema matching query does not exist.", False),
+ ("ExternalDataJob matching query does not exist.", False),
+ ("connection reset by peer", True),
+ ],
+ )
+ def test_pattern_classification(self, message: str, retryable: bool):
+ assert DeltaBatchConsumerAdapter().is_retryable_error(Exception(message)) is retryable