: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): remove rows of an unfinished append run before the next run loads (#113196)
Tom Owerse8630c90aa49
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex da578933692d..93a059ac4f47 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -275,6 +275,10 @@ DATA_WAREHOUSE_IMPORT_FREE_HANDOFFS_ENABLED: bool = get_from_env(DATA_WAREHOUSE_IMPORT_WATERMARK_CARRY_OVER_ENABLED: bool = get_from_env("DATA_WAREHOUSE_IMPORT_WATERMARK_CARRY_OVER_ENABLED", False, type_cast=str_to_bool)+# Restore unfinished append runs only after all extract and load workers have this implementation.+DATA_WAREHOUSE_APPEND_ROLLBACK_ENABLED: bool = get_from_env(+ "DATA_WAREHOUSE_APPEND_ROLLBACK_ENABLED", False, type_cast=str_to_bool+)MAX_AI_TASK_QUEUE = _set_temporal_task_queue("max-ai-task-queue")BATCH_EXPORTS_TASK_QUEUE = _set_temporal_task_queue("batch-exports-task-queue")DATA_MODELING_TASK_QUEUE = _set_temporal_task_queue("data-modeling-task-queue")diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex 4dfee057ff37..f6b297799405 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -221,6 +221,11 @@ STAGED_RESUME_VALUE_KEY = "resume_value"# holds the rows, not whichever attempt most recently restated the same value.STAGED_RESUME_OWNER_KEY = "resume_owner_run_uuid"+# The key for the append run that the loader started to write and has not completed. The loader+# owns the value (see `pipeline_v3/load/append_rollback.py`). A reset deletes the table, so it+# drops the key too.+APPEND_RUN_MARKER_KEY = "append_run_in_progress"+class ExternalDataSchemaQuerySet(models.QuerySet["ExternalDataSchema"]):def update(self, **kwargs: Any) -> int:@@ -1234,6 +1239,7 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djan"incremental_field_earliest_value","incremental_staged","incremental_staged_pending",+ APPEND_RUN_MARKER_KEY,"partitioning_enabled","partition_size","partition_count",diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md b/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.mdindex 358fa6dee70e..0f0ecc23d496 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md@@ -16,6 +16,15 @@ This page is the map; each package's own docstrings and READMEs carry the detailA run that fans out to several destinations finalizes differently - see [Destinations](#destinations).7. The post-import workflow (`../post_import_job.py`, `data-import-post-import`) runs the load-dependent step list (table size, DuckLake copy, signals, enrichment, statistics).+## Append runs that end early++An append run commits each batch to Delta, but its watermark moves only when the run completes.+A run that ends before its final batch (a cancel, a failure, a retried attempt) would leave rows that the next run reads again, and an append has no key to merge them on.+The loader records the table version at the first batch of each append run in `sync_type_config["append_run_in_progress"]`.+The first batch of the next fresh run restores the table to that version when the recorded run never completed (`pipeline_v3/load/append_rollback.py`).+A resumed attempt keeps the rows of the attempt before it.+The restore covers the PostHog warehouse table only, not an external destination.+## DestinationsA schema syncs to a set of destinations, of which the PostHog warehouse is one rather than a special case.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.pyindex 269ea67d30ec..8e30fa5c207e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.py@@ -114,6 +114,8 @@ async def execute_with_conflict_retry(operation_fn: Callable[[], T],operation_name: str,logger: FilteringBoundLogger,+ *,+ conflict_retries: int = DELTA_MERGE_CONFLICT_RETRIES,) -> T:"""Run a Delta operation that commits (merge, overwrite, append, optimize.compact, vacuum, ...),refreshing the table and re-running it on a commit conflict.@@ -150,12 +152,12 @@ async def execute_with_conflict_retry(raiseif not isinstance(e, deltalake.exceptions.CommitFailedError) and not is_invalid_version_race(e):raise- if attempt >= DELTA_MERGE_CONFLICT_RETRIES:+ if attempt >= conflict_retries:raiseattempt += 1await logger.awarning(f"{operation_name}: commit conflict, retrying with refreshed table "- f"(attempt {attempt}/{DELTA_MERGE_CONFLICT_RETRIES})"+ f"(attempt {attempt}/{conflict_retries})")await asyncio.to_thread(table.update_incremental)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.pyindex a88653ac13a7..6254811eb84d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.py@@ -79,6 +79,21 @@ class TestExecuteWithConflictRetry:assert operation_fn.call_count == 2table.update_incremental.assert_called_once()+ @pytest.mark.asyncio+ async def test_can_propagate_a_conflict_without_retrying(self):+ table = MagicMock()+ operation_fn = MagicMock(+ side_effect=deltalake.exceptions.CommitFailedError(+ "Commit failed: a concurrent transaction added new data."+ )+ )++ with pytest.raises(deltalake.exceptions.CommitFailedError):+ await execute_with_conflict_retry(table, operation_fn, "op", make_logger(), conflict_retries=0)++ operation_fn.assert_called_once()+ table.update_incremental.assert_not_called()+@pytest.mark.asyncioasync def test_retries_on_invalid_version_race_then_succeeds(self):# Two writers racing to commit the very first version of a brand-new table surface as adiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.pyindex 0c3857d0be21..0601dcaed0a1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py@@ -707,6 +707,31 @@ class DeltaWriter:return delta_table+ async def restore(self, version: int, commit_metadata: dict[str, str] | None = None) -> dict[str, Any]:+ """Put the table back to the data and schema it had at `version`.++ The restore is one commit that removes the files added after `version` and adds back the+ files removed after it. It reads and writes the log only. It fails when a file of `version`+ is gone, which a vacuum can cause.+ """+ delta_table = await self._table.get_delta_table()+ if delta_table is None:+ return {}+ commit_properties: deltalake.CommitProperties | None = (+ deltalake.CommitProperties(custom_metadata=commit_metadata) if commit_metadata else None+ )+ restore_target = delta_table+ restore_metrics = await execute_with_conflict_retry(+ delta_table,+ lambda: restore_target.restore(version, commit_properties=commit_properties),+ "restore",+ self._logger,+ conflict_retries=0,+ )+ # The deltalite handle of this table still describes the files that the restore removed.+ self._table.invalidate_cached_table()+ return restore_metrics+async def has_commit_with_metadata(self, match: dict[str, str], *, scan_limit: int = 50) -> bool:"""Check whether any recent delta commit has custom metadata matching all entries in `match`.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/append_rollback.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/append_rollback.pynew file mode 100644index 000000000000..b56cc95c03f6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/append_rollback.py@@ -0,0 +1,228 @@+"""Removes the rows of an append run that did not complete, before the next run loads.++An append run commits each batch to the table, but its watermark moves only when the whole run+completes. A run that ends early leaves its rows in the table and the watermark where it was, so the+next run reads the same rows again and an append has no key to merge them on. The loader therefore+records the table version at the first batch of each run. When the first batch of the next run finds+a recorded run that never completed, it restores the table to that version and then appends.+"""++from typing import Any++from django.conf import settings++import structlog+import deltalake.exceptions+from asgiref.sync import async_to_sync++from posthog.dataclasses import frozen+from posthog.exceptions_capture import capture_exception++from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob+from products.warehouse_sources.backend.models.external_data_schema import (+ APPEND_RUN_MARKER_KEY,+ ExternalDataSchema,+ update_sync_type_config_keys,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (+ TransientObjectStoreError,+ is_invalid_version_race,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import (+ ObjectStorePermissionDeniedError,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.writer import DeltaWriter+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (+ APPEND_ROLLBACK_TOTAL,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import ExportSignalMessage++logger = structlog.get_logger(__name__)+++@frozen+class AppendRunMarker:+ """The append run that the loader started to write, and the table as it was before that run."""++ job_id: str+ run_uuid: str+ # None when no table existed. The run then created the table, and version 0 of it is empty.+ table_id: str | None+ version: int | None++ @classmethod+ def from_config(cls, config: dict[str, Any] | None) -> "AppendRunMarker | None":+ raw = (config or {}).get(APPEND_RUN_MARKER_KEY)+ if not isinstance(raw, dict):+ return None+ job_id, run_uuid, table_id, version = (raw.get(key) for key in ("job_id", "run_uuid", "table_id", "version"))+ if not isinstance(job_id, str) or not isinstance(run_uuid, str):+ return None+ if not isinstance(table_id, str | None) or not isinstance(version, int | None):+ return None+ return cls(job_id=job_id, run_uuid=run_uuid, table_id=table_id, version=version)++ def to_config(self) -> dict[str, Any]:+ return {"job_id": self.job_id, "run_uuid": self.run_uuid, "table_id": self.table_id, "version": self.version}+++def _attempt_of(run_uuid: str) -> tuple[str, int] | None:+ """Split `<workflow run id>-a<attempt>`, the run id format of the extract pipeline."""+ workflow_run_id, separator, attempt = run_uuid.rpartition("-a")+ if not separator or not workflow_run_id or not attempt.isdigit():+ return None+ return workflow_run_id, int(attempt)+++def clear_append_run_marker(schema_id: str, team_id: int, job_id: str, run_uuid: str) -> None:+ def clear_if_owned(config: dict[str, Any]) -> None:+ marker = AppendRunMarker.from_config(config)+ if marker is not None and (marker.job_id == job_id or marker.run_uuid == run_uuid):+ config.pop(APPEND_RUN_MARKER_KEY, None)++ update_sync_type_config_keys(schema_id, team_id, mutate=clear_if_owned)+++class UnfinishedAppendRuns:+ """Tracks the append run in progress on one table, and removes the rows of a run that ended early."""++ def __init__(self, schema: ExternalDataSchema, delta_table_ref: DeltaTableRef) -> None:+ self._schema = schema+ self._delta_table_ref = delta_table_ref++ def _marker(self) -> AppendRunMarker | None:+ return AppendRunMarker.from_config(self._schema.sync_type_config)++ def is_replaced_attempt(self, run_uuid: str) -> bool:+ """Whether a later attempt of the same workflow run already started to load.++ That attempt reads the source again from the stored watermark, and its first batch removed+ the rows of the attempts before it. A batch of an earlier attempt that arrives afterwards+ would put those rows back.+ """+ if not settings.DATA_WAREHOUSE_APPEND_ROLLBACK_ENABLED:+ return False+ marker = self._marker()+ if marker is None or marker.run_uuid == run_uuid:+ return False+ current, candidate = _attempt_of(marker.run_uuid), _attempt_of(run_uuid)+ if current is None or candidate is None:+ return False+ return current[0] == candidate[0] and candidate[1] < current[1]++ def start_run(self, export_signal: ExportSignalMessage) -> None:+ """Call before the write of each append batch. Acts on the first batch of a new run only.++ A resumed attempt continues from the cursor of the attempt before it and keeps that+ attempt's rows, so it also keeps the recorded run.+ """+ if not settings.DATA_WAREHOUSE_APPEND_ROLLBACK_ENABLED or export_signal.batch_index != 0:+ return+ marker = self._marker()+ if marker is not None and (+ marker.run_uuid == export_signal.run_uuid+ or (export_signal.is_resume and marker.job_id == export_signal.job_id)+ ):+ return++ delta_table = async_to_sync(self._delta_table_ref.get_delta_table)()+ if (+ not export_signal.is_resume+ and marker is not None+ and delta_table is not None+ and self._never_completed(marker)+ ):+ self._roll_back(marker, export_signal)+ delta_table = async_to_sync(self._delta_table_ref.get_delta_table)()++ # Written before the batch, so a crash between the two leaves a version that is still the+ # table without this run.+ table_id: object = delta_table.metadata().id if delta_table is not None else None+ started = AppendRunMarker(+ job_id=export_signal.job_id,+ run_uuid=export_signal.run_uuid,+ table_id=table_id if isinstance(table_id, str) else None,+ version=self._delta_table_ref.latest_known_version(delta_table) if delta_table is not None else None,+ )+ self._schema.sync_type_config = update_sync_type_config_keys(+ self._schema.id, self._schema.team_id, updates={APPEND_RUN_MARKER_KEY: started.to_config()}+ )++ def _never_completed(self, marker: AppendRunMarker) -> bool:+ """Whether every row written after the recorded version belongs to a run that did not complete.++ The check reads the job rows and does not trust the marker alone. A loader that does not+ know the marker can complete a run and leave the marker in place, and a restore would then+ delete rows that the watermark already covers.+ """+ team_id = self._schema.team_id+ recorded_job_created_at = (+ ExternalDataJob.objects.filter(id=marker.job_id, team_id=team_id)+ .exclude(status=ExternalDataJob.Status.COMPLETED)+ .values_list("created_at", flat=True)+ .first()+ )+ if recorded_job_created_at is None:+ return False+ return not ExternalDataJob.objects.filter(+ schema_id=self._schema.id,+ team_id=team_id,+ status=ExternalDataJob.Status.COMPLETED,+ created_at__gt=recorded_job_created_at,+ rows_synced__gt=0,+ ).exists()++ def _roll_back(self, marker: AppendRunMarker, export_signal: ExportSignalMessage) -> None:+ delta_table = async_to_sync(self._delta_table_ref.get_delta_table)()+ if delta_table is None:+ return+ log = logger.bind(+ team_id=export_signal.team_id,+ external_data_schema_id=export_signal.schema_id,+ external_data_job_id=export_signal.job_id,+ run_uuid=export_signal.run_uuid,+ unfinished_job_id=marker.job_id,+ unfinished_run_uuid=marker.run_uuid,+ )+ current_table_id: object = delta_table.metadata().id+ if marker.table_id is not None and current_table_id != marker.table_id:+ # A repartition swap or a rebuild put a new table at this location. Its versions do not+ # relate to the recorded one.+ log.warning("append_rollback_skipped_table_replaced")+ return+ target_version = marker.version if marker.version is not None else 0+ current_version = self._delta_table_ref.latest_known_version(delta_table)+ if current_version <= target_version:+ return+ try:+ restore_metrics = async_to_sync(DeltaWriter(self._delta_table_ref).restore)(+ target_version,+ commit_metadata={"rolled_back_run_uuid": marker.run_uuid, "rolled_back_job_id": marker.job_id},+ )+ except (TransientObjectStoreError, ObjectStorePermissionDeniedError):+ APPEND_ROLLBACK_TOTAL.labels(outcome="retryable_failure").inc()+ raise+ except deltalake.exceptions.DeltaError as e:+ if isinstance(e, deltalake.exceptions.CommitFailedError) or is_invalid_version_race(e):+ APPEND_ROLLBACK_TOTAL.labels(outcome="retryable_failure").inc()+ raise+ APPEND_ROLLBACK_TOTAL.labels(outcome="permanent_failure").inc()+ log.exception("append_rollback_failed", target_version=target_version, current_version=current_version)+ capture_exception(e)+ return+ except Exception as e:+ APPEND_ROLLBACK_TOTAL.labels(outcome="permanent_failure").inc()+ # A retry cannot repair a missing baseline file. Continuing preserves the pre-rollout+ # behavior rather than permanently stopping every later sync of this table.+ log.exception("append_rollback_failed", target_version=target_version, current_version=current_version)+ capture_exception(e)+ return+ APPEND_ROLLBACK_TOTAL.labels(outcome="success").inc()+ log.info(+ "append_run_rolled_back",+ target_version=target_version,+ current_version=current_version,+ files_removed=restore_metrics.get("numRemovedFile"),+ files_restored=restore_metrics.get("numRestoredFile"),+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.pyindex 65c120140c42..0fe0225abe86 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py@@ -19,6 +19,12 @@ IDEMPOTENCY_HIT_TOTAL = Counter(labelnames=["team_id", "schema_id"],)+APPEND_ROLLBACK_TOTAL = Counter(+ "warehouse_load_append_rollback_total",+ "Append rollback attempts by outcome",+ labelnames=["outcome"],+)+PARQUET_READ_DURATION_SECONDS = Histogram("warehouse_load_parquet_read_duration_seconds","Duration of S3 parquet file reads",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.pyindex b4a86b2b531f..23aa1f810eeb 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@@ -77,6 +77,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineruns_in_order,set_violation,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.append_rollback import (+ UnfinishedAppendRuns,+ clear_append_run_marker,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.batch_steps import (BatchStepTimer,)@@ -541,6 +545,15 @@ def _mark_job_completed(export_signal: ExportSignalMessage) -> None:# 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 export_signal.sync_type == "append":+ # In the same transaction as the cursor, so a later run never finds the marker of+ # a run whose watermark already covers its rows.+ clear_append_run_marker(+ export_signal.schema_id,+ export_signal.team_id,+ export_signal.job_id,+ export_signal.run_uuid,+ )if job_completed:async_to_sync(finish_row_tracking)(export_signal.team_id, export_signal.schema_id)@@ -1122,6 +1135,23 @@ def _process_message_reported(_process_external_destinations_only(export_signal, verify_ownership)return+ append_runs = (+ UnfinishedAppendRuns(schema, delta_table_ref)+ if export_signal.sync_type == "append" and export_signal.cdc_write_mode is None+ else None+ )+ if append_runs is not None and any(append_runs.is_replaced_attempt(run_uuid) for run_uuid, _ in members):+ if constituents is not None:+ raise CoalescingDeclined("a batch belongs to an attempt that a later attempt replaced")+ logger.info(+ "append_batch_of_replaced_attempt_skipped",+ team_id=export_signal.team_id,+ external_data_schema_id=export_signal.schema_id,+ run_uuid=export_signal.run_uuid,+ batch_index=export_signal.batch_index,+ )+ return+with timer.step("idempotency_check"):if constituents is not None:# A set is all-or-nothing: a member that already landed means the others must be checked@@ -1186,6 +1216,12 @@ def _process_message_reported(_complete_run(export_signal, post_load_result)return+ if append_runs is not None:+ # Before the table is read, so the batch is fitted to the schema that the restore leaves.+ if verify_ownership is not None:+ verify_ownership()+ append_runs.start_run(export_signal)+logger.debug("message_received",team_id=export_signal.team_id,diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_append_rollback.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_append_rollback.pynew file mode 100644index 000000000000..cc41fdc1106f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_append_rollback.py@@ -0,0 +1,391 @@+import uuid+from collections.abc import Iterator+from contextlib import ExitStack+from pathlib import Path+from typing import Any, cast++import pytest+from unittest.mock import AsyncMock, patch++import pyarrow as pa+from deltalake import DeltaTable, write_deltalake+from deltalake.exceptions import CommitFailedError, DeltaError++from posthog.models import Team++from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob+from products.warehouse_sources.backend.models.external_data_schema import APPEND_RUN_MARKER_KEY, ExternalDataSchema+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import PostLoadResult+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.test.helpers import (+ make_local_table_ref,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.append_rollback import (+ clear_append_run_marker,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor import (+ process_message,+ process_messages,+)++_PROCESSOR = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor"++_SEED_IDS = [1, 2]+_SEED_WATERMARK = 2+# The window that every run after the seed reads, because no run before it moved the watermark.+_WINDOW = [[3, 4], [5, 6], [7, 8]]+_WINDOW_IDS = [3, 4, 5, 6, 7, 8]+++class _Loader:+ """Drives the load processor against a local Delta table and the test database."""++ def __init__(self, team: Team, table_path: str, sync_type: str = "append") -> None:+ self.team = team+ self.table_path = table_path+ self.sync_type = sync_type+ self.source = ExternalDataSource.objects.create(+ source_id=str(uuid.uuid4()), connection_id=str(uuid.uuid4()), team=team, source_type="Postgres"+ )+ self.schema = ExternalDataSchema.objects.create(+ name="events",+ team=team,+ source=self.source,+ sync_type=sync_type,+ sync_type_config={+ "incremental_field": "id",+ "incremental_field_type": "integer",+ "incremental_field_last_value": _SEED_WATERMARK,+ },+ )+ self._batches: dict[str, pa.Table] = {}++ def seed(self) -> None:+ write_deltalake(self.table_path, pa.table({"id": _SEED_IDS}))++ def new_job(self) -> ExternalDataJob:+ return ExternalDataJob.objects.create(+ team=self.team,+ pipeline=self.source,+ schema=self.schema,+ status=ExternalDataJob.Status.RUNNING,+ rows_synced=0,+ billable=True,+ workflow_run_id=str(uuid.uuid4()),+ )++ def messages(+ self,+ job: ExternalDataJob,+ batches: list[list[int]],+ *,+ attempt: int = 1,+ final: bool,+ is_resume: bool = False,+ ) -> list[dict[str, Any]]:+ """Stage the watermark like the extract side does, and return the queue messages of the run."""+ run_uuid = f"{job.workflow_run_id}-a{attempt}"+ self.schema.stage_incremental_field_value(run_uuid, max(max(ids) for ids in batches))+ ExternalDataJob.objects.filter(id=job.id).update(rows_synced=sum(len(ids) for ids in batches))+ messages = []+ for index, ids in enumerate(batches):+ path = f"s3://bucket/{run_uuid}/{index}.parquet"+ self._batches[path] = pa.table({"id": ids})+ last = final and index == len(batches) - 1+ messages.append(+ {+ "team_id": self.team.id,+ "job_id": str(job.id),+ "schema_id": str(self.schema.id),+ "source_id": str(self.source.id),+ "resource_name": "events",+ "run_uuid": run_uuid,+ "batch_index": index,+ "s3_path": path,+ "row_count": len(ids),+ "byte_size": 1,+ "is_final_batch": last,+ "total_batches": len(batches) if last else None,+ "total_rows": sum(len(b) for b in batches) if last else None,+ "sync_type": self.sync_type,+ "data_folder": None,+ "schema_path": None,+ "primary_keys": ["id"] if self.sync_type == "incremental" else None,+ "is_resume": is_resume,+ }+ )+ return messages++ def load(self, messages: list[dict[str, Any]]) -> None:+ for message in messages:+ process_message(message)++ def fail(self, job: ExternalDataJob, error: str) -> None:+ ExternalDataJob.objects.filter(id=job.id).update(status=ExternalDataJob.Status.FAILED, latest_error=error)++ def ids(self) -> list[int]:+ ids = cast(list[int], DeltaTable(self.table_path).to_pyarrow_table().column("id").to_pylist())+ return sorted(ids)++ def config(self) -> dict[str, Any]:+ return ExternalDataSchema.objects.get(id=self.schema.id).sync_type_config++ def operations(self) -> list[str]:+ return [commit["operation"] for commit in DeltaTable(self.table_path).history()]++[email protected](autouse=True)+def _boundaries(settings: Any) -> Iterator[None]:+ settings.DATA_WAREHOUSE_APPEND_ROLLBACK_ENABLED = True+ with ExitStack() as stack:+ for target in (+ "close_old_connections",+ "posthoganalytics",+ "mark_batch_as_processed",+ "release_v3_pipeline_lock",+ "_trigger_ducklake_register_data_imports",+ "_trigger_post_import_workflow",+ ):+ stack.enter_context(patch(f"{_PROCESSOR}.{target}"))+ stack.enter_context(patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False))+ stack.enter_context(patch(f"{_PROCESSOR}.finish_row_tracking", new_callable=AsyncMock))+ stack.enter_context(+ patch(+ f"{_PROCESSOR}.run_post_load_operations",+ new_callable=AsyncMock,+ return_value=PostLoadResult(queryable_folder=None),+ )+ )+ yield+++def loader(team: Team, tmp_path: Path) -> Iterator[_Loader]:+ instance = _Loader(team, str(tmp_path / "table"))+ with ExitStack() as stack:+ stack.enter_context(+ patch(f"{_PROCESSOR}.read_parquet", side_effect=lambda path: instance._batches[path]),+ )+ stack.enter_context(+ patch(f"{_PROCESSOR}.DeltaTableRef", side_effect=lambda **kwargs: make_local_table_ref(instance.table_path))+ )+ yield instance+++def _cancelled(loader: _Loader) -> None:+ job = loader.new_job()+ loader.load(loader.messages(job, _WINDOW[:2], final=False))+ loader.fail(job, "Sync cancelled by user")+++def _failed_mid_run(loader: _Loader) -> None:+ job = loader.new_job()+ loader.load(loader.messages(job, _WINDOW[:2], final=False))+ loader.fail(job, "connection to the source was lost")+++def _failed_twice(loader: _Loader) -> None:+ _cancelled(loader)+ _failed_mid_run(loader)+++def _failed_after_a_resumed_attempt(loader: _Loader) -> None:+ job = loader.new_job()+ loader.load(loader.messages(job, _WINDOW[:1], final=False))+ loader.load(loader.messages(job, _WINDOW[1:2], attempt=2, final=False, is_resume=True))+ loader.fail(job, "connection to the source was lost")+++class TestUnfinishedAppendRun:+ @pytest.mark.parametrize(+ "unfinished_run",+ [_cancelled, _failed_mid_run, _failed_twice, _failed_after_a_resumed_attempt],+ ids=lambda case: case.__name__,+ )+ @pytest.mark.parametrize("table_exists", [True, False], ids=["existing_table", "first_sync"])+ def test_the_next_run_loads_each_row_once(self, loader: _Loader, unfinished_run: Any, table_exists: bool) -> None:+ if table_exists:+ loader.seed()++ unfinished_run(loader)+ assert loader.config()["incremental_field_last_value"] == _SEED_WATERMARK++ next_job = loader.new_job()+ loader.load(loader.messages(next_job, _WINDOW, final=True))++ assert loader.ids() == (_SEED_IDS if table_exists else []) + _WINDOW_IDS+ config = loader.config()+ assert config["incremental_field_last_value"] == max(_WINDOW_IDS)+ assert APPEND_RUN_MARKER_KEY not in config+ assert ExternalDataJob.objects.get(id=next_job.id).status == ExternalDataJob.Status.COMPLETED++ def test_a_retried_attempt_of_one_job_replaces_the_attempt_before_it(self, loader: _Loader) -> None:+ loader.seed()+ job = loader.new_job()+ first_attempt = loader.messages(job, _WINDOW, final=False)+ second_attempt = loader.messages(job, _WINDOW, attempt=2, final=True)++ loader.load(first_attempt[:2])+ loader.load(second_attempt[:1])+ # A batch that the first attempt queued arrives after the second attempt started to load.+ loader.load(first_attempt[2:])+ loader.load(second_attempt[1:])++ assert loader.ids() == _SEED_IDS + _WINDOW_IDS+ assert loader.config()["incremental_field_last_value"] == max(_WINDOW_IDS)++ def test_a_set_with_the_first_batch_of_the_next_run_loads_each_row_once(self, loader: _Loader) -> None:+ loader.seed()+ _cancelled(loader)++ process_messages(loader.messages(loader.new_job(), _WINDOW, final=True))++ assert loader.ids() == _SEED_IDS + _WINDOW_IDS++ @pytest.mark.parametrize("marker_survives_completion", [False, True])+ def test_a_completed_run_keeps_its_rows(self, loader: _Loader, marker_survives_completion: bool) -> None:+ loader.seed()+ first_job = loader.new_job()+ loader.load(loader.messages(first_job, [[3, 4]], final=False))+ marker = loader.config().get(APPEND_RUN_MARKER_KEY)+ loader.load(loader.messages(first_job, [[5, 6]], attempt=2, final=True, is_resume=True))+ if not marker_survives_completion:+ assert APPEND_RUN_MARKER_KEY not in loader.config()+ if marker_survives_completion:+ # A loader from before the marker completes the run and does not remove the marker.+ assert marker is not None+ config = loader.config()+ config[APPEND_RUN_MARKER_KEY] = marker+ ExternalDataSchema.objects.filter(id=loader.schema.id).update(sync_type_config=config)++ loader.load(loader.messages(loader.new_job(), [[7, 8]], final=True))++ assert loader.ids() == _SEED_IDS + _WINDOW_IDS+ assert loader.config()["incremental_field_last_value"] == 8+ assert "RESTORE" not in loader.operations()++ def test_a_later_completed_job_makes_an_old_marker_inert(self, loader: _Loader) -> None:+ loader.seed()+ failed_job = loader.new_job()+ loader.load(loader.messages(failed_job, [[3, 4]], final=False))+ old_marker = loader.config()[APPEND_RUN_MARKER_KEY]+ loader.fail(failed_job, "failed")++ loader.load(loader.messages(loader.new_job(), [[5, 6]], final=True))+ restore_count = loader.operations().count("RESTORE")+ config = loader.config()+ config[APPEND_RUN_MARKER_KEY] = old_marker+ ExternalDataSchema.objects.filter(id=loader.schema.id).update(sync_type_config=config)++ loader.load(loader.messages(loader.new_job(), [[7, 8]], final=True))++ assert loader.ids() == [*_SEED_IDS, 5, 6, 7, 8]+ assert loader.operations().count("RESTORE") == restore_count++ def test_a_fresh_attempt_of_a_completed_job_does_not_restore(self, loader: _Loader) -> None:+ loader.seed()+ job = loader.new_job()+ loader.load(loader.messages(job, [[3, 4]], final=False))+ old_marker = loader.config()[APPEND_RUN_MARKER_KEY]+ loader.load(loader.messages(job, [[5, 6]], attempt=2, final=True, is_resume=True))+ config = loader.config()+ config[APPEND_RUN_MARKER_KEY] = old_marker+ ExternalDataSchema.objects.filter(id=loader.schema.id).update(sync_type_config=config)++ loader.load(loader.messages(job, [[7, 8]], attempt=3, final=False))++ assert loader.ids() == _SEED_IDS + _WINDOW_IDS+ assert "RESTORE" not in loader.operations()++ def test_a_first_resumed_batch_records_the_job(self, loader: _Loader) -> None:+ loader.seed()+ job = loader.new_job()++ loader.load(loader.messages(job, [[3, 4]], attempt=2, final=False, is_resume=True))++ marker = loader.config()[APPEND_RUN_MARKER_KEY]+ assert marker["job_id"] == str(job.id)+ assert marker["run_uuid"] == f"{job.workflow_run_id}-a2"++ def test_rollback_can_be_disabled(self, loader: _Loader, settings: Any) -> None:+ settings.DATA_WAREHOUSE_APPEND_ROLLBACK_ENABLED = False+ loader.seed()++ loader.load(loader.messages(loader.new_job(), [[3, 4]], final=False))++ assert APPEND_RUN_MARKER_KEY not in loader.config()++ def test_a_permanent_restore_failure_uses_a_new_baseline(self, loader: _Loader) -> None:+ loader.seed()+ _failed_mid_run(loader)++ with patch(f"{_PROCESSOR}.DeltaWriter.restore", new_callable=AsyncMock, side_effect=RuntimeError("gone")):+ loader.load(loader.messages(loader.new_job(), _WINDOW, final=True))++ assert loader.ids().count(3) == 2+ assert loader.ids().count(4) == 2+ assert loader.config()["incremental_field_last_value"] == 8+ assert APPEND_RUN_MARKER_KEY not in loader.config()++ @pytest.mark.parametrize(+ "error",+ [CommitFailedError("concurrent commit"), DeltaError("Invalid table version: 2")],+ ids=["commit_conflict", "invalid_version_race"],+ )+ def test_a_racy_restore_failure_retries_the_batch(self, loader: _Loader, error: Exception) -> None:+ loader.seed()+ _failed_mid_run(loader)+ marker = loader.config()[APPEND_RUN_MARKER_KEY]++ with (+ patch(f"{_PROCESSOR}.DeltaWriter.restore", new_callable=AsyncMock, side_effect=error),+ pytest.raises(type(error)),+ ):+ loader.load(loader.messages(loader.new_job(), _WINDOW, final=True))++ assert loader.config()[APPEND_RUN_MARKER_KEY] == marker++ def test_an_older_completion_does_not_clear_a_newer_runs_marker(self, loader: _Loader) -> None:+ older_job = loader.new_job()+ older_run = loader.messages(older_job, [[3]], final=False)[0]["run_uuid"]+ loader.load([loader.messages(loader.new_job(), [[4]], final=False)[0]])+ current_marker = loader.config()[APPEND_RUN_MARKER_KEY]++ clear_append_run_marker(str(loader.schema.id), loader.team.id, str(older_job.id), older_run)++ assert loader.config()[APPEND_RUN_MARKER_KEY] == current_marker++ def test_a_replaced_table_is_not_restored(self, loader: _Loader, tmp_path: Path) -> None:+ loader.seed()+ _cancelled(loader)+ # A repartition swap puts a rewritten table, with a new id and new versions, at the same location.+ rows = DeltaTable(loader.table_path).to_pyarrow_table()+ loader.table_path = str(tmp_path / "swapped")+ write_deltalake(loader.table_path, rows.slice(0, 2))+ write_deltalake(loader.table_path, rows.slice(2), mode="append")++ loader.load(loader.messages(loader.new_job(), [[9]], final=True))++ existing_ids = cast(list[int], rows.column("id").to_pylist())+ assert loader.ids() == sorted([*existing_ids, 9])+ assert "RESTORE" not in loader.operations()+++def test_an_incremental_run_after_a_failed_run_does_not_restore_the_table(team: Team, tmp_path: Path) -> None:+ loader = _Loader(team, str(tmp_path / "table"), sync_type="incremental")+ with (+ patch(f"{_PROCESSOR}.read_parquet", side_effect=lambda path: loader._batches[path]),+ patch(f"{_PROCESSOR}.DeltaTableRef", side_effect=lambda **kwargs: make_local_table_ref(loader.table_path)),+ ):+ loader.seed()+ failed_job = loader.new_job()+ loader.load(loader.messages(failed_job, _WINDOW[:2], final=False))+ loader.fail(failed_job, "connection to the source was lost")++ loader.load(loader.messages(loader.new_job(), _WINDOW, final=True))++ assert loader.ids() == _SEED_IDS + _WINDOW_IDS+ assert "RESTORE" not in loader.operations()+ assert APPEND_RUN_MARKER_KEY not in loader.config()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.pyindex d7dd484ce532..c3a5541f0cff 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py@@ -14,6 +14,8 @@ from collections.abc import Iteratorfrom contextlib import contextmanagerfrom typing import Any, Optional+from django.conf import settings+import psycopgimport structlogfrom structlog.types import FilteringBoundLogger@@ -259,12 +261,18 @@ class PostgresProducer:# A full_refresh is the exception: this run's batch 0 overwrites the table, so# an older attempt's loaded rows are gone either way and sparing it only leaves# its batches clogging the serial per-(team, schema) gate.+ #+ # An append is the same: the loader removes an older attempt's rows when this+ # run's batch 0 arrives (see `load/append_rollback.py`).with _queue_db_errors():superseded = BatchQueue.supersede_other_runs(self._conn,job_id=self._job_id,current_run_uuid=self._run_uuid,- spare_runs_with_progress=self._sync_type != "full_refresh",+ spare_runs_with_progress=(+ self._sync_type != "full_refresh"+ and not (self._sync_type == "append" and settings.DATA_WAREHOUSE_APPEND_ROLLBACK_ENABLED)+ ),)if superseded > 0:self._logger.info("superseded_old_run_batches", count=superseded)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.pyindex a02d878aa13e..244a0542b668 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py@@ -183,12 +183,16 @@ class TestPostgresProducerSupersede:@pytest.mark.parametrize("sync_type,spare",- [("full_refresh", False), ("incremental", True), ("append", True), ("cdc", True)],+ [("full_refresh", False), ("incremental", True), ("append", False), ("cdc", True)],)- def test_only_full_refresh_supersedes_a_run_that_is_still_loading(self, sync_type: str, spare: bool) -> None:- """A fresh full_refresh overwrites the table on batch 0, so an older attempt's loaded rows- are discarded either way and its queued batches are dead weight on the serial per-schema- gate. Every other sync type keeps the sparing rule, because partially merged work survives."""+ def test_only_full_refresh_and_append_supersede_a_run_that_is_still_loading(+ self, settings: Any, sync_type: str, spare: bool+ ) -> None:+ """A fresh full_refresh overwrites the table on batch 0, and the loader removes an older+ append attempt's rows on batch 0, so the loaded rows of an older attempt are discarded+ either way and its queued batches are dead weight on the serial per-schema gate. The other+ sync types keep the sparing rule, because partially merged work survives."""+ settings.DATA_WAREHOUSE_APPEND_ROLLBACK_ENABLED = Trueproducer = _make_producer(is_resume=False, sync_type=sync_type)batch_result = _make_batch_result(batch_index=0)@@ -200,6 +204,18 @@ class TestPostgresProducerSupersede:assert mock_supersede.call_args.kwargs["spare_runs_with_progress"] is spare+ def test_append_spares_a_loading_run_when_rollback_is_disabled(self, settings: Any) -> None:+ settings.DATA_WAREHOUSE_APPEND_ROLLBACK_ENABLED = False+ producer = _make_producer(is_resume=False, sync_type="append")++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer.BatchQueue.supersede_other_runs",+ return_value=0,+ ) as mock_supersede:+ producer.send_batch_notification(_make_batch_result(batch_index=0))++ assert mock_supersede.call_args.kwargs["spare_runs_with_progress"] is True+def test_does_not_supersede_on_non_zero_batch(self) -> None:producer = _make_producer(is_resume=False)batch_result = _make_batch_result(batch_index=1)