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): keep the append load on a retry of a table rebuild (#113781)

Tom Owersf05beabab4d2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md b/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md
index 0f0ecc23d496..a9257e0f3218 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md
@@ -25,6 +25,16 @@ The first batch of the next fresh run restores the table to that version when th
A resumed attempt keeps the rows of the attempt before it.
The restore covers the PostHog warehouse table only, not an external destination.
+## Incremental runs that load a table from empty
+
+An incremental run merges each batch on the primary key.
+A first sync and a reset are different: the table is empty, so the first batch overwrites the table and the later batches append.
+A merge into such a table finds no row to update, but it must read the key columns of each file to prove that.
+An attempt that loads this way and reads the source from the start records itself in `sync_type_config["table_rebuild_run_uuid"]` (`pipeline_v3/table_rebuild.py`).
+A later attempt of the same workflow run that also reads from the start loads the same way, and the loader skips the batches of the attempt that it replaced.
+An attempt that continues from a cursor merges, because it can read a row again that an earlier attempt already queued.
+The append keeps one row for each key in a batch, not in the run: a key that the source holds in two batches stays twice until a later run merges that key.
+
## Destinations
A 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/pipeline_v3/load/append_rollback.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/append_rollback.py
index b56cc95c03f6..92c170481540 100644
--- 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.py
@@ -37,6 +37,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
APPEND_ROLLBACK_TOTAL,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import ExportSignalMessage
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.table_rebuild import attempt_of
logger = structlog.get_logger(__name__)
@@ -67,14 +68,6 @@ class AppendRunMarker:
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)
@@ -106,7 +99,7 @@ class UnfinishedAppendRuns:
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)
+ 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]
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 a29dc78742cc..d25b0473f957 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
@@ -110,6 +110,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.temporal.data_imports.pipelines.pipeline_v3.table_rebuild import TableRebuildRun
from products.warehouse_sources.backend.temporal.data_imports.row_tracking import finish_row_tracking
from products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import merge_cursor_payloads
@@ -1145,6 +1146,20 @@ def _process_message_reported(
)
return
+ if export_signal.sync_type == "incremental" and export_signal.cdc_write_mode is None:
+ rebuild = TableRebuildRun(schema.sync_type_config)
+ if any(rebuild.replaces(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(
+ "rebuild_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
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 50b14eae1d37..20cc64ac5d22 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
@@ -1645,6 +1645,122 @@ class TestBatchPhaseReports:
assert _post_load_summary(mock_logger)["phase_names"] == ["job_completion", "post_import_trigger"]
+_WORKFLOW_RUN = "0190aaaa-0000-7000-8000-000000000001"
+
+
+class TestTableRebuildLoad:
+ # Batches of 3 keys each. `_SOURCE_REPEATS_A_KEY` holds key 4 in two batches.
+ _SOURCE = [{"id": [1, 2, 3]}, {"id": [4, 5, 6]}, {"id": [7, 8, 9]}]
+ _SOURCE_REPEATS_A_KEY = [{"id": [1, 2, 3]}, {"id": [4, 5, 6]}, {"id": [4, 8, 9]}]
+
+ @staticmethod
+ def _rows(run_uuid: str, index: int, ids: list[int]) -> pa.Table:
+ return pa.table({"id": ids, "name": [f"{run_uuid[-2:]}_b{index}_{row_id}" for row_id in ids]})
+
+ @contextmanager
+ def _loader(self, table_path: str, batches: dict[str, pa.Table], config: dict[str, Any]) -> Iterator[None]:
+ def local_ref(**kwargs: Any) -> DeltaTableRef:
+ ref = make_local_table_ref(table_path)
+ ref._is_first_sync = kwargs["is_first_sync"]
+ return ref
+
+ with ExitStack() as stack:
+ stack.enter_context(patch(f"{_PROCESSOR}.posthoganalytics"))
+ stack.enter_context(patch(f"{_PROCESSOR}.mark_batch_as_processed"))
+ stack.enter_context(patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False))
+ stack.enter_context(patch(f"{_PROCESSOR}.read_parquet", side_effect=lambda path: batches[path]))
+ stack.enter_context(patch(f"{_PROCESSOR}.DeltaTableRef", side_effect=local_ref))
+ job_model = stack.enter_context(patch(f"{_PROCESSOR}.ExternalDataJob"))
+ job = MagicMock()
+ job.schema.sync_type_config = config
+ job_model.objects.prefetch_related.return_value.get.return_value = job
+ yield
+
+ def _load(
+ self,
+ table_path: str,
+ attempt: int,
+ source: list[dict[str, list[int]]],
+ *,
+ rebuild: bool,
+ indexes: list[int] | None = None,
+ config: dict[str, Any] | None = None,
+ ) -> None:
+ run_uuid = f"{_WORKFLOW_RUN}-a{attempt}"
+ batches = {
+ f"s3://bucket/{run_uuid}/{index}": self._rows(run_uuid, index, rows["id"])
+ for index, rows in enumerate(source)
+ }
+ with self._loader(table_path, batches, config if config is not None else {}):
+ for index in indexes if indexes is not None else range(len(source)):
+ process_message(
+ _message(
+ run_uuid=run_uuid,
+ batch_index=index,
+ s3_path=f"s3://bucket/{run_uuid}/{index}",
+ is_first_ever_sync=rebuild,
+ )
+ )
+
+ @staticmethod
+ def _table_rows(table_path: str) -> list[tuple[int, str]]:
+ rows = DeltaTable(table_path).to_pyarrow_table().to_pydict()
+ return sorted(zip(rows["id"], rows["name"]))
+
+ @parameterized.expand(
+ [
+ ("one_attempt", []),
+ ("an_attempt_replaced_after_two_batches", [0, 1]),
+ ("an_attempt_replaced_before_its_first_batch_loads", []),
+ ]
+ )
+ def test_a_rebuild_gives_the_table_that_a_merge_of_each_batch_gives(
+ self, case: str, first_attempt_batches: list[int]
+ ) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ rebuilt, merged = f"{tmp}/rebuilt", f"{tmp}/merged"
+ last_attempt = 1 if case == "one_attempt" else 2
+ config: dict[str, Any] = {}
+
+ if last_attempt == 2:
+ self._load(rebuilt, 1, self._SOURCE, rebuild=True, indexes=first_attempt_batches, config=config)
+ config["table_rebuild_run_uuid"] = f"{_WORKFLOW_RUN}-a2"
+ self._load(rebuilt, last_attempt, self._SOURCE, rebuild=True, indexes=[0, 1], config=config)
+ if last_attempt == 2:
+ # A batch of the first attempt that the loader takes after the second attempt started.
+ self._load(rebuilt, 1, self._SOURCE, rebuild=True, indexes=[2], config=config)
+ self._load(rebuilt, last_attempt, self._SOURCE, rebuild=True, indexes=[2], config=config)
+
+ self._load(merged, last_attempt, self._SOURCE, rebuild=False)
+
+ assert len(self._table_rows(rebuilt)) == 9
+ assert self._table_rows(rebuilt) == self._table_rows(merged)
+ operations = [commit["operation"] for commit in DeltaTable(rebuilt).history()]
+ assert "MERGE" not in operations
+
+ def test_a_run_after_the_rebuild_merges_on_the_key(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ self._load(tmp, 1, self._SOURCE, rebuild=True)
+ later = pa.table({"id": [9, 10], "name": ["later_9", "later_10"]})
+ with self._loader(tmp, {"s3://bucket/later/0": later}, {"table_rebuild_run_uuid": f"{_WORKFLOW_RUN}-a1"}):
+ process_message(_message(run_uuid="0190bbbb-a1", batch_index=0, s3_path="s3://bucket/later/0"))
+
+ rows = dict(self._table_rows(tmp))
+ assert len(self._table_rows(tmp)) == 10
+ assert (rows[9], rows[10]) == ("later_9", "later_10")
+
+ def test_a_key_that_the_source_holds_twice_stays_twice_until_a_later_run_merges_it(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ self._load(tmp, 1, self._SOURCE_REPEATS_A_KEY, rebuild=True)
+ assert [name for row_id, name in self._table_rows(tmp) if row_id == 4] == ["a1_b1_4", "a1_b2_4"]
+
+ later = pa.table({"id": [4], "name": ["later_4"]})
+ with self._loader(tmp, {"s3://bucket/later/0": later}, {}):
+ process_message(_message(run_uuid="0190bbbb-a1", batch_index=0, s3_path="s3://bucket/later/0"))
+
+ assert [name for row_id, name in self._table_rows(tmp) if row_id == 4] == ["later_4"]
+
+
def _batch_rows(index: int) -> pa.Table:
# Each batch updates one row of the batch before it and adds two rows.
ids = [index * 2, index * 2 + 1, index * 2 + 2]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index 29d98aab9059..ffadcce4ad0b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -89,6 +89,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
S3BatchWriter,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer import ParquetCompression
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.table_rebuild import TableRebuildRun
from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import SourceCursorManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import (
ResumableSourceManager,
@@ -437,6 +438,16 @@ class PipelineV3(Generic[ResumableData]):
def _mark_first_ever_sync(self) -> None:
self._pg_producer.is_first_ever_sync = True
+ async def _record_table_rebuild(self, run_uuid: str) -> None:
+ """Record that this attempt loads the table from empty (see `TableRebuildRun`).
+
+ A failure only costs speed: a later attempt of the run then merges each batch.
+ """
+ try:
+ await database_sync_to_async_pool(TableRebuildRun.record)(self._schema, run_uuid)
+ except Exception:
+ await self._logger.aexception("V3 Pipeline: Failed to record the table rebuild")
+
def _maintains_companion_table(self) -> bool:
"""Whether this run's own table is a `_cdc` history table, keyed under its own watermark.
@@ -623,6 +634,13 @@ class PipelineV3(Generic[ResumableData]):
)
is_fresh_sync = self._delta_table_ref.is_first_sync or self._schema.table is None
+ if not is_fresh_sync and self._attempt > 1 and not should_resume:
+ # Only the first attempt deletes the table for a reset, and only that attempt holds
+ # the flag the delete sets. This attempt reads the source from the start again, so
+ # it must load the way the first attempt did: its first batch overwrites the table
+ # and the later batches append. Without this, every batch is a merge into a table
+ # that holds no key of the batch, and that merge reads each file of the table.
+ is_fresh_sync = TableRebuildRun(self._schema.sync_type_config).started_in(self._job.workflow_run_id)
if is_fresh_sync:
self._mark_first_ever_sync()
# No pre-write maintenance runs, so nothing here reads the handle that the corruption
@@ -661,6 +679,17 @@ class PipelineV3(Generic[ResumableData]):
# attempt after this one never reads a value that describes rows which are gone.
await self._stage_handoff_resume_value(force=True)
+ # Not for a webhook schema: an attempt of it does not read again the events that an
+ # earlier attempt took, so the batches of the earlier attempt must still load.
+ if (
+ is_fresh_sync
+ and not should_resume
+ and sync_type == "incremental"
+ and not self._schema.is_webhook
+ and self._run_uuid is not None
+ ):
+ await self._record_table_rebuild(self._run_uuid)
+
items = self._resource.items()
safe_point_scope = self._activate_safe_point(items)
awaiting_source = True
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/table_rebuild.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/table_rebuild.py
new file mode 100644
index 000000000000..d1276b5e7fa2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/table_rebuild.py
@@ -0,0 +1,48 @@
+from typing import Any
+
+from products.warehouse_sources.backend.models.external_data_schema import (
+ ExternalDataSchema,
+ update_sync_type_config_keys,
+)
+
+TABLE_REBUILD_RUN_KEY = "table_rebuild_run_uuid"
+
+
+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)
+
+
+class TableRebuildRun:
+ """The newest attempt that loads an incremental table from empty.
+
+ Such an attempt reads the source from the start. Its first batch overwrites the table and its
+ later batches append, because no row of the table can hold a key that the attempt has not
+ written itself. The record lets a later attempt of the same workflow run load the same way, and
+ lets the loader drop the batches of an attempt that a later one replaced: those batches would
+ append rows that the newer attempt also appends.
+ """
+
+ def __init__(self, config: dict[str, Any] | None) -> None:
+ raw = (config or {}).get(TABLE_REBUILD_RUN_KEY)
+ self._attempt = attempt_of(raw) if isinstance(raw, str) else None
+
+ def started_in(self, workflow_run_id: str | None) -> bool:
+ """Whether an attempt of `workflow_run_id` started to rebuild the table."""
+ return self._attempt is not None and workflow_run_id is not None and self._attempt[0] == workflow_run_id
+
+ def replaces(self, run_uuid: str) -> bool:
+ """Whether `run_uuid` is an earlier attempt of the workflow run that rebuilds the table."""
+ candidate = attempt_of(run_uuid)
+ if self._attempt is None or candidate is None:
+ return False
+ return self._attempt[0] == candidate[0] and candidate[1] < self._attempt[1]
+
+ @staticmethod
+ def record(schema: ExternalDataSchema, run_uuid: str) -> None:
+ update_sync_type_config_keys(schema.id, schema.team_id, updates={TABLE_REBUILD_RUN_KEY: run_uuid})
+ # The run saves this copy of the config again later, and that save must keep the record.
+ schema.sync_type_config[TABLE_REBUILD_RUN_KEY] = run_uuid
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
index 514d50243d3e..c867f981a26e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
@@ -57,6 +57,7 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
from products.warehouse_sources.backend.types import IncrementalFieldType
_PIPELINE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline"
+_TABLE_REBUILD = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.table_rebuild"
_SAFE_POINT = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.safe_point"
_LANES = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.lanes"
_CONSUMER = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer"
@@ -232,6 +233,73 @@ class TestAttemptScopedRunUuid:
mock_reset.assert_not_called()
+class TestTableRebuildAcrossAttempts:
+ @pytest.mark.parametrize(
+ "attempt, table_was_deleted, recorded, continues, is_webhook, expected_first_sync, expected_record",
+ [
+ pytest.param(1, True, None, False, False, True, "run-abc-a1", id="the_attempt_that_deletes_the_table"),
+ pytest.param(
+ 2, False, "run-abc-a1", False, False, True, "run-abc-a2", id="a_retry_that_reads_from_the_start"
+ ),
+ pytest.param(2, False, "run-abc-a1", True, False, False, "run-abc-a1", id="a_retry_that_continues"),
+ pytest.param(
+ 2, False, "run-old-a1", False, False, False, "run-old-a1", id="a_retry_of_a_run_without_a_rebuild"
+ ),
+ pytest.param(2, False, None, False, False, False, None, id="a_retry_with_no_record"),
+ pytest.param(
+ 1, False, "run-abc-a1", False, False, False, "run-abc-a1", id="a_first_attempt_that_keeps_the_table"
+ ),
+ pytest.param(1, True, None, False, True, True, None, id="a_webhook_schema_keeps_no_record"),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_each_attempt_of_a_rebuild_tells_the_loader_to_load_from_empty(
+ self,
+ attempt: int,
+ table_was_deleted: bool,
+ recorded: str | None,
+ continues: bool,
+ is_webhook: bool,
+ expected_first_sync: bool,
+ expected_record: str | None,
+ ) -> None:
+ pipeline = _make_pipeline()
+ pipeline._attempt = attempt
+ pipeline._run_uuid = f"run-abc-a{attempt}"
+ pipeline._reset_pipeline = True
+ pipeline._is_incremental = True
+ pipeline._schema.table = MagicMock()
+ cast(Any, pipeline._schema).is_webhook = is_webhook
+ pipeline._schema.sync_type_config = {"table_rebuild_run_uuid": recorded} if recorded else {}
+ pipeline._delta_table_ref = MagicMock(is_first_sync=table_was_deleted)
+ producer = MagicMock(sync_type="incremental", is_first_ever_sync=False)
+ pipeline._pg_producer = producer
+ schema = pipeline._schema
+ pipeline._continues_incremental_handoff = continues
+ pipeline._resumed_incremental_run_uuid = "run-abc-a1" if continues else None
+
+ with ExitStack() as stack:
+ for name in (
+ "reset_rows_synced_if_needed",
+ "setup_row_tracking_with_billing_check",
+ "persist_primary_keys",
+ "handle_reset_or_full_refresh",
+ "handle_corrupted_delta_log",
+ ):
+ stack.enter_context(patch(f"{_PIPELINE}.{name}", new_callable=AsyncMock))
+ stack.enter_context(patch(f"{_PIPELINE}.validate_incremental_sync"))
+ stack.enter_context(patch(f"{_PIPELINE}.DeltaMaintenance")).return_value.run_scheduled = AsyncMock()
+ stack.enter_context(patch(f"{_PIPELINE}.activity")).in_activity.return_value = False
+ stack.enter_context(patch(f"{_TABLE_REBUILD}.update_sync_type_config_keys"))
+ pipeline._resource.items = MagicMock(return_value=iter([]))
+ pipeline._batcher.should_yield.return_value = False # type: ignore[attr-defined]
+
+ await pipeline.run()
+
+ assert producer.is_first_ever_sync is expected_first_sync
+ assert schema.sync_type_config.get("table_rebuild_run_uuid") == expected_record
+
+
class TestExtractionFailureDoesNotCleanupS3:
@pytest.mark.asyncio
async def test_s3_files_preserved_when_extraction_fails(self) -> None: