: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(warehouse-sources): keep settled rows when a retry cleans the cdc buffer (#102479)
Daniel RC252b2e493f9c
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.mdindex c3d475f1451f..0838e6a6dfe8 100644--- a/docs/internal/cdc-buffered-ingress-runbook.md+++ b/docs/internal/cdc-buffered-ingress-runbook.md@@ -276,6 +276,31 @@ The only fix is a full `reset_pipeline` re-snapshot for that schema.Watch the age of the oldest unconsumed file per schema, not the file count. A schema with few filesthat are all thirteen days old is in trouble; one with thousands of fresh files is fine.+## Retried capture attempts++Temporal retries a capture attempt that dies, and the retry re-reads the WAL from the slot's+confirmed position. Micro-batch boundaries are not stable across attempts, so the retry covers the+same positions with differently-shaped files. Before its first write per schema, it removes every+file that reaches the position it restarted from (`end_seq >= restart_seq`), because it is about to+re-emit all of those positions.++One file can straddle that position. A micro-flush is cut per event, so it can carry the head of a+transaction; the slot then advances only to the previous transaction's end, and the retry re-reads+the straddled transaction from its first row. That file holds settled positions the WAL no longer+has beside the head the retry re-emits. Deleting it loses the settled rows. Keeping it hands the+`_cdc` table a second copy of the head: the replay filter matches a batch row against what the+table already holds, and when both files are read in one run the table holds neither copy yet, so+both are appended. So the retry rewrites the file with its settled rows only, under the narrowed+range and the same index. The replacement is staged under a `.staging` suffix the consumer never+parses, the original is removed, and only then is the staged file promoted to its final name, so no+listing ever holds both. A crash anywhere in that sequence is finished by the next attempt's+cleanup: a staged file always holds settled rows, so it removes the original if it is still there+and promotes the staged file.++A cleanup failure fails the attempt. A superseded file that survives is a second copy of every+position it holds once the retry writes them again, so the run retries rather than write beside it.+`cdc_buffer_superseded_files_removed` in the capture logs carries `removed` and `trimmed` counts.+## Known gap: zombie-attempt file collisionA Temporal activity attempt declared dead by heartbeat timeout can still be running and writing.diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.pyindex d3adfc3ba562..cfe82175a164 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py@@ -1316,6 +1316,7 @@ class CDCExtractActivity:# (b) on crash-replay the already-flushed prefix of the in-flight# transaction is re-delivered — incremental_merge dedups by PK,# scd2_append may create duplicate history rows. Accepted vs. loss.+ # The buffer lane trims that prefix in cleanup_superseded_files.if (self.last_complete_txn_end_lsn is not Noneand self.last_complete_txn_end_lsn != self.last_confirmed_lsndiff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.pyindex 63fd88a745eb..630ddd87839d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py@@ -18,9 +18,11 @@ Replay semantics: micro-batch boundaries are NOT deterministic across activityattempts (the flush budget spans tables, the slot micro-advances mid-run, and asoft deadline cuts runs on wall clock), so a retried attempt may cover the samepositions with differently-shaped files. Writers therefore call-`cleanup_superseded_files` before their first write per schema: anything at or-past the position the retry re-reads from is superseded and removed. A schema-reset (TRUNCATE / lost slot) invalidates the whole prefix — `purge_buffer_prefix`.+`cleanup_superseded_files` before their first write per schema: every file that+reaches the position the retry re-reads from is superseded and removed, and a file+that straddles that position first has its settled rows rewritten under a narrower+range. A schema reset (TRUNCATE / lost slot) invalidates the whole prefix —+`purge_buffer_prefix`.Two lanes write here. Shadow (the `dwh-cdc-buffer-shadow` feature flag, per team,evaluated once per extraction run and fail-closed) writes a validation copy while@@ -71,6 +73,9 @@ _INDEX_WIDTH = 6# ASCII digits only: int() also accepts "+", "_", whitespace, and Unicode digits,# any of which would break "lexicographic order equals numeric order"._FILE_NAME_RE = re.compile(rf"([0-9]{{{_SEQ_WIDTH}}})-([0-9]{{{_SEQ_WIDTH}}})-([0-9]{{{_INDEX_WIDTH}}})\.parquet")+# A trimmed replacement is written under this suffix first. The consumer parses names, so it+# never reads a staged file, and the original can be removed before the replacement appears.+_STAGING_SUFFIX = ".staging"def is_shadow_write_enabled(team_id: int, logger: FilteringBoundLogger) -> bool:@@ -220,13 +225,12 @@ class CDCBufferWriter:)def cleanup_superseded_files(self, *, team_id: int, schema_id: str, restart_seq: int) -> int:- """Remove files a retried attempt is about to regenerate.+ """Remove every file that reaches `restart_seq`, the position a retry re-reads from.- Called before the first write per schema in a run: every file whose- start_seq >= the position this run reads from (`restart_seq`) belongs to- a superseded attempt whose batch boundaries may differ. Files strictly- below restart_seq are settled — their WAL was released and will never be- re-produced. Returns the number of files removed.+ A file that straddles it holds settled rows the WAL no longer has beside a+ transaction head the retry re-emits, so its settled rows are rewritten first.+ A surviving superseded file means a second copy of every position the retry+ writes, so failures propagate and the attempt retries. Returns files removed."""prefix = strip_s3_protocol(get_buffer_prefix(team_id, schema_id))try:@@ -236,24 +240,93 @@ class CDCBufferWriter:except FileNotFoundError:return 0+ keys = self._promote_staged_files(keys)removed = 0+ trimmed = 0for key in keys:parsed = parse_buffer_file_name(key.rsplit("/", 1)[-1])- if parsed is None:+ if parsed is None or parsed.end_seq < restart_seq:continue- if parsed.start_seq >= restart_seq:- with suppress(Exception):- self._s3.rm(key)- removed += 1+ staged = None+ if parsed.start_seq < restart_seq:+ staged = self._stage_settled_rows(key, file_index=parsed.file_index, restart_seq=restart_seq)+ if staged is not None:+ trimmed += 1+ # The consumer may already have deleted an applied file.+ with suppress(FileNotFoundError):+ self._s3.rm(key)+ removed += 1+ if staged is not None:+ self._promote(staged)if removed:self._logger.info("cdc_buffer_superseded_files_removed",schema_id=schema_id,restart_seq=restart_seq,removed=removed,+ trimmed=trimmed,)return removed+ def _stage_settled_rows(self, key: str, *, file_index: int, restart_seq: int) -> str | None:+ """Write a straddling file's rows below `restart_seq` to a staged file, and return its key.++ The final name keeps the original's start and index under a narrowed range, so it sorts+ where the original did. Staged first because a listing that saw both the original and+ the replacement would hand the history table the settled rows twice.+ """+ try:+ with self._s3.open(key, "rb") as f:+ table = pq.read_table(f)+ except FileNotFoundError:+ return None+ settled = table.filter(pc.less(table.column(CDC_SEQ_COLUMN), pa.scalar(restart_seq, type=pa.int64())))+ if settled.num_rows == 0:+ return None+ start_seq = pc.min(settled.column(CDC_SEQ_COLUMN)).as_py()+ end_seq = pc.max(settled.column(CDC_SEQ_COLUMN)).as_py()+ final_key = f"{key.rsplit('/', 1)[0]}/{build_buffer_file_name(start_seq, end_seq, file_index)}"+ staged_key = final_key + _STAGING_SUFFIX+ with self._s3.open(staged_key, "wb") as f:+ pq.write_table(settled, f, compression="zstd")+ return staged_key++ def _promote(self, staged_key: str) -> None:+ with self._s3.open(staged_key, "rb") as f:+ table = pq.read_table(f)+ with self._s3.open(staged_key.removesuffix(_STAGING_SUFFIX), "wb") as f:+ pq.write_table(table, f, compression="zstd")+ with suppress(FileNotFoundError):+ self._s3.rm(staged_key)++ def _promote_staged_files(self, keys: list[str]) -> list[str]:+ """Finish a cleanup a crash interrupted: a staged file always holds settled rows.++ If its original is still there, the crash came before the delete, so the original goes+ first. Returns the listing without the staged names and their originals.+ """+ remaining = list(keys)+ for key in keys:+ if not key.endswith(_STAGING_SUFFIX):+ continue+ final_key = key.removesuffix(_STAGING_SUFFIX)+ final = parse_buffer_file_name(final_key.rsplit("/", 1)[-1])+ if final is None:+ continue+ for other in keys:+ span = parse_buffer_file_name(other.rsplit("/", 1)[-1])+ if span is None or span == final:+ continue+ if span.start_seq == final.start_seq and span.file_index == final.file_index:+ with suppress(FileNotFoundError):+ self._s3.rm(other)+ if other in remaining:+ remaining.remove(other)+ self._promote(key)+ remaining.remove(key)+ remaining.append(final_key)+ return remaining+def purge_buffer_prefix(team_id: int, schema_id: str, logger: FilteringBoundLogger, *, strict: bool = False) -> None:"""Remove a schema's entire buffer prefix.diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.pyindex 690e78b0cda5..82338642f3c8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.py@@ -1,12 +1,14 @@import ioimport randomfrom contextlib import contextmanager+from typing import castimport pytestfrom unittest.mock import MagicMock, patchimport pyarrow as paimport pyarrow.parquet as pq+from parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMNfrom products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import (@@ -16,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer importget_buffer_prefix,parse_buffer_file_name,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common import strip_s3_protocolclass TestBufferFileName:@@ -109,6 +112,11 @@ class TestCDCBufferWriter:@contextmanagerdef fake_open(path, mode):+ if mode == "rb":+ if path not in files:+ raise FileNotFoundError(path)+ yield io.BytesIO(files[path].getvalue())+ returnbuf = io.BytesIO()files[path] = bufyield buf@@ -125,6 +133,11 @@ class TestCDCBufferWriter:writer = CDCBufferWriter(MagicMock())return writer, files+ def _seed_file(self, files: dict[str, io.BytesIO], key: str, seqs: list[int]) -> None:+ buf = io.BytesIO()+ pq.write_table(self._table(seqs), buf)+ files[key] = buf+def _table(self, seqs: list[int]) -> pa.Table:return pa.table({@@ -223,6 +236,114 @@ class TestCDCBufferWriter:removed_keys = [c.args[0] for c in writer._s3.rm.call_args_list]assert removed_keys == keys[1:3]+ def test_cleanup_keeps_the_settled_rows_of_a_file_straddling_restart(self):+ writer, files = self._writer_with_captured_files()+ prefix = strip_s3_protocol(get_buffer_prefix(1, "abc"))+ settled = f"{prefix}/{build_buffer_file_name(100, 200, 0)}"+ straddling = f"{prefix}/{build_buffer_file_name(200, 300, 1)}"+ superseded = f"{prefix}/{build_buffer_file_name(300, 300, 2)}"+ self._seed_file(files, settled, [100, 200])+ self._seed_file(files, straddling, [200, 250, 300, 300])+ self._seed_file(files, superseded, [300, 300])+ writer._s3.ls = MagicMock(return_value=[settled, straddling, superseded])+ writer._s3.rm = MagicMock(side_effect=files.pop)++ removed = writer.cleanup_superseded_files(team_id=1, schema_id="abc", restart_seq=300)++ assert removed == 2+ trimmed = f"{prefix}/{build_buffer_file_name(200, 250, 1)}"+ assert set(files) == {settled, trimmed}+ assert pq.read_table(io.BytesIO(files[trimmed].getvalue())).column(CDC_SEQ_COLUMN).to_pylist() == [200, 250]+ assert [c.args[0] for c in writer._s3.rm.call_args_list] == [straddling, f"{trimmed}.staging", superseded]++ def test_no_listing_ever_holds_both_a_straddling_file_and_its_replacement(self):+ writer, files = self._writer_with_captured_files()+ prefix = strip_s3_protocol(get_buffer_prefix(1, "abc"))+ straddling = f"{prefix}/{build_buffer_file_name(200, 300, 1)}"+ trimmed = f"{prefix}/{build_buffer_file_name(200, 250, 1)}"+ self._seed_file(files, straddling, [200, 250, 300])+ listings: list[set[str]] = []+ real_open = writer._s3.open++ @contextmanager+ def observed_open(path, mode):+ with real_open(path, mode) as f:+ yield f+ listings.append({k for k in files if parse_buffer_file_name(k.rsplit("/", 1)[-1]) is not None})++ def observed_rm(key):+ files.pop(key)+ listings.append({k for k in files if parse_buffer_file_name(k.rsplit("/", 1)[-1]) is not None})++ writer._s3.open = observed_open+ writer._s3.ls = MagicMock(return_value=[straddling])+ writer._s3.rm = MagicMock(side_effect=observed_rm)++ writer.cleanup_superseded_files(team_id=1, schema_id="abc", restart_seq=300)++ assert all(not {straddling, trimmed} <= seen for seen in listings)+ assert set(files) == {trimmed}++ @parameterized.expand([("original_still_there", True), ("original_already_gone", False)])+ def test_cleanup_finishes_a_trim_a_crash_interrupted(self, _name, original_present):+ writer, files = self._writer_with_captured_files()+ prefix = strip_s3_protocol(get_buffer_prefix(1, "abc"))+ straddling = f"{prefix}/{build_buffer_file_name(200, 300, 1)}"+ trimmed = f"{prefix}/{build_buffer_file_name(200, 250, 1)}"+ staged = f"{trimmed}.staging"+ self._seed_file(files, staged, [200, 250])+ if original_present:+ self._seed_file(files, straddling, [200, 250, 300])+ writer._s3.ls = MagicMock(return_value=sorted(files))+ writer._s3.rm = MagicMock(side_effect=files.pop)++ writer.cleanup_superseded_files(team_id=1, schema_id="abc", restart_seq=400)++ assert set(files) == {trimmed}+ assert pq.read_table(io.BytesIO(files[trimmed].getvalue())).column(CDC_SEQ_COLUMN).to_pylist() == [200, 250]++ def test_cleanup_keeps_a_straddling_file_it_could_not_rewrite(self):+ writer, files = self._writer_with_captured_files()+ prefix = strip_s3_protocol(get_buffer_prefix(1, "abc"))+ straddling = f"{prefix}/{build_buffer_file_name(200, 300, 1)}"+ self._seed_file(files, straddling, [200, 300])+ writer._s3.ls = MagicMock(return_value=[straddling])+ writer._s3.rm = MagicMock()++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.cdc.buffer.pq.write_table",+ side_effect=OSError("s3 down"),+ ),+ pytest.raises(OSError),+ ):+ writer.cleanup_superseded_files(team_id=1, schema_id="abc", restart_seq=300)++ assert straddling not in [c.args[0] for c in writer._s3.rm.call_args_list]++ def test_cleanup_fails_when_a_superseded_file_survives(self):+ writer, _files = self._writer_with_captured_files()+ prefix = strip_s3_protocol(get_buffer_prefix(1, "abc"))+ writer._s3.ls = MagicMock(return_value=[f"{prefix}/{build_buffer_file_name(300, 400, 0)}"])+ writer._s3.rm = MagicMock(side_effect=OSError("s3 down"))++ with pytest.raises(OSError):+ writer.cleanup_superseded_files(team_id=1, schema_id="abc", restart_seq=300)++ def test_cleanup_tolerates_a_file_the_consumer_already_deleted(self):+ writer, _files = self._writer_with_captured_files()+ prefix = strip_s3_protocol(get_buffer_prefix(1, "abc"))+ writer._s3.ls = MagicMock(+ return_value=[+ f"{prefix}/{build_buffer_file_name(200, 300, 0)}",+ f"{prefix}/{build_buffer_file_name(300, 400, 1)}",+ ]+ )+ writer._s3.rm = MagicMock(side_effect=FileNotFoundError)++ assert writer.cleanup_superseded_files(team_id=1, schema_id="abc", restart_seq=300) == 2+ assert cast(MagicMock, writer._logger).info.call_args.kwargs["trimmed"] == 0+def test_cleanup_handles_missing_prefix(self):writer, _files = self._writer_with_captured_files()writer._s3.ls = MagicMock(side_effect=FileNotFoundError)diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.pyindex 00d8d9c83870..386f355745ab 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py@@ -3737,6 +3737,48 @@ class TestBufferedIngressCapture:captured["reader_ref"].confirm_position.assert_not_called()+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")+ def test_a_crash_mid_transaction_leaves_a_file_straddling_the_restart(self, MockBufferWriter):+ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (+ ChangeEventBatcher as RealBatcher,+ )++ class _DyingStream:+ def __init__(self, events):+ self._events = events++ def __len__(self):+ return len(self._events)++ def __iter__(self):+ yield from self._events+ raise RuntimeError("pod killed mid-transaction")++ source = _make_source()+ schema = _make_schema("users", cdc_mode="streaming", source=source)+ events = [+ _make_event(op="I", position="0/100", columns={"id": 1}),+ _make_event(op="I", position="0/100", columns={"id": 2}),+ _make_event(op="I", position="0/200", columns={"id": 3}),+ _make_event(op="I", position="0/200", columns={"id": 4}),+ ]+ captured: dict = {}++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ChangeEventBatcher",+ side_effect=lambda **kwargs: RealBatcher(max_events=4, **kwargs),+ ),+ pytest.raises(RuntimeError, match="pod killed mid-transaction"),+ ):+ self._run(MockBufferWriter, _DyingStream(events), [schema], source, capture=captured)++ written = MockBufferWriter.return_value.write_batch.call_args.kwargs["table"]+ assert written.column(CDC_SEQ_COLUMN).to_pylist() == [0x100, 0x100, 0x200, 0x200]+ captured["reader_ref"].confirm_position.assert_called_once_with("0/100")+ cleanup = MockBufferWriter.return_value.cleanup_superseded_files+ cleanup.assert_called_once_with(team_id=schema.team_id, schema_id=str(schema.id), restart_seq=0x100)+@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")def test_a_source_column_named_like_seq_fails_the_buffered_run(self, MockBufferWriter):# The batcher skips its append on the collision, so the file's name, ordering, and retry