: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): stop re-reading the last cdc buffer file every run (#108591)
Daniel RCff12a275929c
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.mdindex e8ad1b701f24..cbdcd73bdf7c 100644--- a/docs/internal/cdc-buffered-ingress-runbook.md+++ b/docs/internal/cdc-buffered-ingress-runbook.md@@ -67,11 +67,14 @@ A table whose data was deleted is still streaming but not seeded; its next sync**Buffer files are deleted at the start of the next run**, before they are read, so the run thatproves a file consumed is never the run that deletes it. A file goes when it is strictly below thefloor — the lowest position any of the schema's tables holds — or when it sits exactly at the floor-and predates a listing by a run that went on to complete every table it writes. The floor alone is+and a run that went on to complete every table it writes already read it. The floor alone isnot enough at its own boundary: capture flushes a transaction bigger than its budget across severalfiles that all carry that transaction's commit position, so a file at the floor may be the unreadtail of one. A completed listing is what proves otherwise. For a `both` run, both jobs have to havecompleted, or a file could be deleted while the history table still owed it.+Each listing records the name and ETag of the files at its highest position, and a file that still+carries a recorded ETag holds exactly what that run read, so the next run deletes it. A file the+listing did not record goes once its mtime predates the listing by a clock-skew margin.**A lane resumes from its own table.** A failed run can leave one table holding rows the other doesnot, so each reads back the highest commit position it holds. The merge lane drops only what is@@ -305,6 +308,7 @@ twice, so a `both` source's synced-row count roughly halved when it moved to the**The merge lane re-bills the rows at its position until the file holding them is deleted.** Itkeeps every row at its position deliberately, since dropping one would lose a later event for the-same key at that same commit, and a kept row is a staged row. That is one transaction's rows, for-the tick or two until the completed-listing proof clears the file. The history lane matches those-rows by content and bills none of them.+same key at that same commit, and a kept row is a staged row. That happens only when the file+changed after the last completed listing recorded it, or that listing never saw it; otherwise the+next run deletes the file before reading it. The history lane matches those rows by content and+bills none of them.diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/source_manager.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/source_manager.pyindex 4dc666c8ed9b..eb415cc62e3a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/source_manager.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/source_manager.py@@ -12,7 +12,7 @@ be in memory when the generator resumes.from __future__ import annotationsimport datetime as dt-from collections.abc import AsyncGenerator, Callable+from collections.abc import AsyncGenerator, Callable, Mappingfrom typing import TYPE_CHECKING, Any, Final, Literalfrom django.db import transaction@@ -23,6 +23,7 @@ import psycopgimport pyarrow as paimport pyarrow.compute as pcimport pyarrow.parquet as pq+from botocore.exceptions import ClientErrorfrom structlog.types import FilteringBoundLoggerfrom posthog.dataclasses import frozen@@ -174,11 +175,23 @@ _CONSUMED_MTIME_MARGIN = dt.timedelta(minutes=5)# When a run listed the buffer, kept on that run's own job. Proof only once the job completes.BUFFER_LISTED_AT_KEY = "cdc_buffer_listed_at"+# File name to ETag of the files at the highest position that listing saw, kept beside it.+BUFFER_LISTED_TAIL_KEY = "cdc_buffer_listed_tail"# When capture moved the table's legacy source onto the buffer, kept in the table's sync_type_config.LEGACY_CONVERTED_AT_KEY = "cdc_legacy_converted_at"-def read_completed_listing_proof(schema: ExternalDataSchema) -> dt.datetime | None:+@frozen+class ListingProof:+ """A buffer listing by a run that went on to complete every table it writes."""++ listed_at: dt.datetime+ # File name to ETag of the files at the highest position the listing saw. A file still carrying+ # that ETag holds exactly what the run read.+ tail: Mapping[str, str]+++def read_completed_listing_proof(schema: ExternalDataSchema) -> ListingProof | None:"""When the buffer was last listed by a run that went on to complete every table it writes.Completion is what proves consumption: it means the generator drained every listed file and@@ -219,11 +232,12 @@ def read_completed_listing_proof(schema: ExternalDataSchema) -> dt.datetime | Noif stamped.tzinfo is None:continueif _companions_completed((snapshot or {}).get(COMPANION_JOB_IDS_KEY) or []):- return stamped+ tail = (snapshot or {}).get(BUFFER_LISTED_TAIL_KEY)+ return ListingProof(listed_at=stamped, tail=tail if isinstance(tail, dict) else {})return None-async def completed_listing_proof(schema: ExternalDataSchema) -> dt.datetime | None:+async def completed_listing_proof(schema: ExternalDataSchema) -> ListingProof | None:"""`read_completed_listing_proof`, off the event loop."""return await database_sync_to_async_pool(db_read_with_retry)(lambda: read_completed_listing_proof(schema))@@ -299,7 +313,7 @@ def clear_listing(job_id: str, team_id: int) -> None:stamped = dict(job.schema_snapshot or {}) if job is not None else {}if job is None or not stamped.get(BUFFER_LISTED_AT_KEY):return- snapshot = {k: v for k, v in stamped.items() if k != BUFFER_LISTED_AT_KEY}+ snapshot = {k: v for k, v in stamped.items() if k not in (BUFFER_LISTED_AT_KEY, BUFFER_LISTED_TAIL_KEY)}ExternalDataJob.objects.filter(id=job.id).update(schema_snapshot=snapshot)@@ -456,6 +470,26 @@ class _BufferFile:span: BufferFileSpankey: strmodified: dt.datetime | None+ etag: str | None++ @property+ def name(self) -> str:+ return self.key.rsplit("/", 1)[-1]+++# Past this many files at one position the tail is not recorded, and those files go by the mtime+# rule a run later. A transaction split across that many files is rare, and the tail is stored on+# every job that lists it.+_MAX_TAIL_FILES = 100+++def _listing_tail(files: list[_BufferFile]) -> dict[str, str]:+ """Name to ETag of the files at the highest position listed, which the next run's floor sits on."""+ if not files:+ return {}+ top = max(file.span.end_seq for file in files)+ tail = {file.name: file.etag for file in files if file.span.end_seq == top and file.etag}+ return tail if len(tail) <= _MAX_TAIL_FILES else {}class ReplayFilter:@@ -645,14 +679,14 @@ class CDCSourceManager:logger: FilteringBoundLogger,*,deletion_floor: int | None = None,- proof_time: dt.datetime | None = None,+ proof: ListingProof | None = None,) -> None:self._inputs = inputsself._logger = loggerself._deletion_floor = deletion_floor- self._proof_time = proof_time+ self._proof = proof- def _is_consumed(self, end_seq: int, modified: dt.datetime | None) -> bool:+ def _is_consumed(self, file: _BufferFile) -> bool:"""Whether every table this schema feeds already holds this file's rows.Strictly below the floor is position-proof: the lowest-placed lane holds a commit above it,@@ -661,18 +695,58 @@ class CDCSourceManager:AT the floor, position alone cannot tell a consumed file from the unread tail of atransaction split across files — they all carry one commit position. A file that alreadyexisted when a run listed the buffer, and that run then COMPLETED, was read and written by- it. The margin absorbs clock skew between S3 and our own clock.+ it. The listing's ETag proves that at once. Without one, the file's mtime has to predate the+ listing by a margin that absorbs clock skew between S3 and our own clock, which a file written+ just before a frequent run's listing does not meet until a later run."""floor = self._deletion_floor+ end_seq = file.span.end_seqif floor is None or end_seq > floor:return Falseif end_seq < floor:return True- if modified is None or modified.tzinfo is None or self._proof_time is None:+ proof = self._proof+ if proof is None:+ return False+ if file.name in proof.tail:+ # A different ETag means capture rewrote the file after that listing, so the run never read it.+ return file.etag is not None and proof.tail[file.name] == file.etag+ modified = file.modified+ if modified is None or modified.tzinfo is None:return False- return modified < self._proof_time - _CONSUMED_MTIME_MARGIN+ return modified < proof.listed_at - _CONSUMED_MTIME_MARGIN- async def stamp_listing(self, listed_at: dt.datetime) -> None:+ async def _delete_unless_replaced(self, s3: Any, file: _BufferFile) -> bool:+ """Delete a consumed file unless capture replaced it after the listing. Returns whether it went.++ Below the floor any content is settled, because a capture retry only re-emits changes every lane+ already holds. At the floor the proof covers the listed bytes, and a retry can replace them with+ unread rows of the same transaction while this run reads earlier files. So the delete is+ conditioned on the listed ETag, and a file that no longer matches is kept and read.+ S3 and SeaweedFS list every object with its ETag, so a listing without one keeps the file.+ """+ if self._deletion_floor is None or file.span.end_seq < self._deletion_floor:+ await s3._rm(file.key)+ return True+ if file.etag is None:+ return False+ bucket, key, _ = s3.split_path(file.key)+ s3.invalidate_cache(file.key)+ client = await s3.get_s3(bucket)+ try:+ await client.delete_object(Bucket=bucket, Key=key, IfMatch=f'"{file.etag}"')+ except ClientError as error:+ # 409 means a write to the same key was in flight, so the file is read like any other replacement.+ if error.response.get("Error", {}).get("Code") in (+ "PreconditionFailed",+ "ConditionalRequestConflict",+ "NoSuchKey",+ ):+ return False+ raise+ return True++ async def stamp_listing(self, listed_at: dt.datetime, tail: Mapping[str, str]) -> None:"""Record on this run's own job that it listed the buffer, before any file is read.Kept on the job rather than beside the schema's settings: it describes one run, and it is@@ -690,6 +764,7 @@ class CDCSourceManager:)snapshot = dict(job.schema_snapshot or {})snapshot[BUFFER_LISTED_AT_KEY] = listed_at.isoformat()+ snapshot[BUFFER_LISTED_TAIL_KEY] = dict(tail)ExternalDataJob.objects.filter(id=job.id).update(schema_snapshot=snapshot)await database_sync_to_async_pool(db_read_with_retry)(_stamp)@@ -723,8 +798,14 @@ class CDCSourceManager:if parsed is None:continuemodified = entry.get("LastModified")+ etag = entry.get("ETag")files.append(- _BufferFile(span=parsed, key=key, modified=modified if isinstance(modified, dt.datetime) else None)+ _BufferFile(+ span=parsed,+ key=key,+ modified=modified if isinstance(modified, dt.datetime) else None,+ etag=etag.strip('"') if isinstance(etag, str) and etag else None,+ ))files.sort(key=lambda f: (f.span.start_seq, f.span.end_seq, f.span.file_index))@@ -748,14 +829,14 @@ class CDCSourceManager:"""listed_at = dt.datetime.now(tz=dt.UTC)files = await self._list_buffer_files()- await self.stamp_listing(listed_at)+ tail = _listing_tail(files)+ await self.stamp_listing(listed_at, tail)batch: TableBatcher[str] = TableBatcher(row_limit=batch_row_limit, byte_limit=batch_byte_limit)async with aget_s3_client() as s3:for file in files:# The only place a buffer file is deleted — see `_is_consumed` for the proof.- if self._is_consumed(file.span.end_seq, file.modified):- await s3._rm(file.key)+ if self._is_consumed(file) and await self._delete_unless_replaced(s3, file):continuetry:@@ -766,6 +847,10 @@ class CDCSourceManager:# A concurrent run, or a retry of this activity, can have deleted the file# between the listing and this open — the listing is a snapshot, not a lease.await self._logger.adebug("cdc_buffer_file_already_consumed", key=file.key)+ # This run never read the file, and a capture retry can write the same bytes+ # under the same name, so its ETag must not prove the rewrite read.+ if tail.pop(file.name, None) is not None:+ await self.stamp_listing(listed_at, tail)continueif table.num_rows == 0:diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.pyindex 7ee3d613b62b..270a76db23b2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py@@ -5,6 +5,7 @@ from unittest.mock import ANY, AsyncMock, MagicMock, call, patchfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.temporal.data_imports.cdc.lane_position import LanePosition+from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import ListingProoffrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputsfrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSource@@ -52,8 +53,10 @@ def _inputs(reset_pipeline: bool = False) -> SourceInputs:)-def _days_ago(days: int | None) -> dt.datetime | None:- return None if days is None else dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=days)+def _proof_days_ago(days: int | None) -> ListingProof | None:+ if days is None:+ return None+ return ListingProof(listed_at=dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=days), tail={})def _delta_ref() -> MagicMock:@@ -69,7 +72,7 @@ def _dispatch(job_version: str | None = ExternalDataJob.PipelineVersion.V3,clear_listing: MagicMock | None = None,retire_orphans: MagicMock | None = None,- proof_time: dt.datetime | None = None,+ proof: ListingProof | None = None,hand_reset: MagicMock | None = None,expired: AsyncMock | None = None,):@@ -83,7 +86,7 @@ def _dispatch(patch(f"{_MANAGER}.DeltaTableRef", _delta_ref()),patch(f"{_MANAGER}.read_lane_position", AsyncMock(return_value=LanePosition(position=None, applied={}))),patch(f"{_MANAGER}.ensure_position_stats", AsyncMock()),- patch(f"{_MANAGER}.completed_listing_proof", AsyncMock(return_value=proof_time)),+ patch(f"{_MANAGER}.completed_listing_proof", AsyncMock(return_value=proof)),patch(f"{_MANAGER}.buffer_expired_unread", expired or AsyncMock(return_value=False)),patch(f"{_SNAPSHOT_LANE}.hand_reset_to_capture", hand_reset or MagicMock()),patch.object(PostgresSource, "make_ssh_tunnel_func", return_value=MagicMock()),@@ -187,7 +190,7 @@ class TestBufferedDispatch:schema = _schema(cdc_table_mode="both")response = _dispatch(- schema, _inputs(), proof_time=_days_ago(proof_days_ago), hand_reset=hand_reset, expired=expired_check+ schema, _inputs(), proof=_proof_days_ago(proof_days_ago), hand_reset=hand_reset, expired=expired_check)assert hand_reset.call_args_list == ([call(schema, ANY, start_capture=False)] if reset else [])diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_listing_proof.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_listing_proof.pyindex 01da74aeb77f..75aa94c41e97 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_listing_proof.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_listing_proof.py@@ -1,3 +1,4 @@+import uuidimport datetime as dtfrom posthog.test.base import BaseTest@@ -14,7 +15,9 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.companion_jobs)from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (BUFFER_LISTED_AT_KEY,+ BUFFER_LISTED_TAIL_KEY,LEGACY_CONVERTED_AT_KEY,+ ListingProof,buffer_may_have_expired_unread,clear_listing,read_completed_listing_proof,@@ -34,10 +37,21 @@ class TestCompletedListingProof(BaseTest):)return ExternalDataSchema.objects.create(team=self.team, source=source, name="users")- def _job(self, schema, *, status, listed_at=None, companion_of=None, billable=True) -> ExternalDataJob:+ def _job(+ self,+ schema: ExternalDataSchema,+ *,+ status: str,+ listed_at: dt.datetime | None = None,+ companion_of: uuid.UUID | None = None,+ billable: bool = True,+ tail: dict[str, str] | None = None,+ ) -> ExternalDataJob:snapshot: dict = {}if listed_at is not None:snapshot[BUFFER_LISTED_AT_KEY] = listed_at.isoformat()+ if tail is not None:+ snapshot[BUFFER_LISTED_TAIL_KEY] = tailif companion_of is not None:snapshot["companion_of"] = str(companion_of)job = ExternalDataJob.objects.create(@@ -58,9 +72,9 @@ class TestCompletedListingProof(BaseTest):# leave no companion row. An empty companion set has to count as proof.schema = self._schema()listed = dt.datetime(2026, 1, 1, 12, 0, tzinfo=dt.UTC)- self._job(schema, status=ExternalDataJob.Status.COMPLETED, listed_at=listed)+ self._job(schema, status=ExternalDataJob.Status.COMPLETED, listed_at=listed, tail={"f.parquet": "etag-1"})- assert self._proof(schema) == listed+ assert self._proof(schema) == ListingProof(listed_at=listed, tail={"f.parquet": "etag-1"})def test_a_run_still_going_proves_nothing(self):schema = self._schema()@@ -88,7 +102,7 @@ class TestCompletedListingProof(BaseTest):)self._job(schema, status=ExternalDataJob.Status.FAILED, companion_of=newer.id, billable=False)- assert self._proof(schema) == older+ assert self._proof(schema) == ListingProof(listed_at=older, tail={})def test_a_run_that_never_listed_proves_nothing(self):# The in-flight no-op tick returns an empty response without listing, so it must not count.@@ -234,7 +248,10 @@ class TestClearListing(BaseTest):def test_only_the_stamp_comes_off(self):schema = self._schema()- job = self._job(schema, {BUFFER_LISTED_AT_KEY: "2026-01-01T00:00:00+00:00", "name": "users"})+ job = self._job(+ schema,+ {BUFFER_LISTED_AT_KEY: "2026-01-01T00:00:00+00:00", BUFFER_LISTED_TAIL_KEY: {"f": "e"}, "name": "users"},+ )clear_listing(str(job.id), self.team.id)diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.pyindex eb2942cdadb4..ad7049fb707f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py@@ -2,10 +2,11 @@ import datetime as dtimport contextlibimport pytest-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import ANY, AsyncMock, MagicMock, patchimport pyarrow as paimport pyarrow.parquet as pq+from botocore.exceptions import ClientErrorfrom parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (@@ -25,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.source_managerCONSOLIDATED_WRITE_MODE,CDCLane,CDCSourceManager,+ ListingProof,ReplayFilter,build_output_lanes,captures_to_buffer,@@ -41,6 +43,7 @@ _PREFIX = f"bucket/cdc_producer/{_TEAM_ID}/{_SCHEMA_ID}"_NOW = dt.datetime(2026, 8, 14, 12, 0, tzinfo=dt.UTC)# Older than any completed-run start minus the clock-skew margin._OLD_MTIME = _NOW - dt.timedelta(hours=2)+_RECENT = _NOW - dt.timedelta(minutes=1)def _table(ids: list[int], seqs: list[int]) -> pa.Table:@@ -106,6 +109,9 @@ class _FakeS3:missing_prefix: bool = False,mtimes: dict[str, dt.datetime] | None = None,missing_keys: set[str] | None = None,+ etags: dict[str, str] | None = None,+ etags_at_delete: dict[str, str] | None = None,+ conflicting_deletes: set[str] | None = None,) -> None:self.files = dict(files)# Listed but gone by the time the reader opens them, as a concurrent retry leaves things.@@ -114,6 +120,10 @@ class _FakeS3:self.opened: list[str] = []self.missing_prefix = missing_prefixself.mtimes = mtimes or {}+ self.etags = etags or {}+ # What the store holds after the listing, for a file capture rewrote in between.+ self.etags_at_delete = etags_at_delete or {}+ self.conflicting_deletes = conflicting_deletes or set()async def _ls(self, prefix, detail=True, refresh=False):# The manager must always bypass the fsspec dircache — capture writes through a different@@ -121,7 +131,40 @@ class _FakeS3:assert refresh, "buffer listings must pass refresh=True"if self.missing_prefix:raise FileNotFoundError(prefix)- return [{"type": "file", "Key": key, "LastModified": self.mtimes.get(key, _OLD_MTIME)} for key in self.files]+ return [+ {+ "type": "file",+ "Key": key,+ "LastModified": self.mtimes.get(key, _OLD_MTIME),+ "ETag": f'"{self.etags.get(key, "etag-0")}"',+ }+ for key in self.files+ ]++ def _current_etag(self, key):+ return self.etags_at_delete.get(key, self.etags.get(key, "etag-0"))++ def split_path(self, path):+ bucket, _, key = path.partition("/")+ return bucket, key, None++ def invalidate_cache(self, path=None):+ pass++ async def get_s3(self, bucket):+ fake = self++ class _Client:+ async def delete_object(self, Bucket, Key, IfMatch=None):+ full_key = f"{Bucket}/{Key}"+ if full_key in fake.conflicting_deletes:+ raise ClientError({"Error": {"Code": "ConditionalRequestConflict"}}, "DeleteObject")+ if IfMatch is not None and IfMatch != f'"{fake._current_etag(full_key)}"':+ raise ClientError({"Error": {"Code": "PreconditionFailed"}}, "DeleteObject")+ fake.removed.append(full_key)+ fake.files.pop(full_key, None)++ return _Client()async def _rm(self, key):self.removed.append(key)@@ -158,18 +201,18 @@ def _patched(s3: _FakeS3):yield-def _manager(*, deletion_floor: int | None = None, proof_time: dt.datetime | None = None) -> CDCSourceManager:+def _manager(*, deletion_floor: int | None = None, proof: ListingProof | None = None) -> CDCSourceManager:inputs = MagicMock()inputs.team_id = _TEAM_IDinputs.schema_id = _SCHEMA_IDinputs.reset_pipeline = False- return CDCSourceManager(inputs=inputs, logger=AsyncMock(), deletion_floor=deletion_floor, proof_time=proof_time)+ return CDCSourceManager(inputs=inputs, logger=AsyncMock(), deletion_floor=deletion_floor, proof=proof)async def _collect(- s3: _FakeS3, *, deletion_floor: int | None = None, proof_time: dt.datetime | None = None, **kwargs+ s3: _FakeS3, *, deletion_floor: int | None = None, proof: ListingProof | None = None, **kwargs: int) -> list[pa.Table]:- manager = _manager(deletion_floor=deletion_floor, proof_time=proof_time)+ manager = _manager(deletion_floor=deletion_floor, proof=proof)with _patched(s3), patch.object(CDCSourceManager, "stamp_listing", AsyncMock()):return [t async for t in manager.get_items(**kwargs)]@@ -650,7 +693,7 @@ class TestFloorDeletion:async def test_a_file_at_the_floor_goes_once_an_older_completed_listing_covers_it(self):s3 = _FakeS3({_key(11, 20): _parquet_bytes(_table([1], [20]))})- await _collect(s3, deletion_floor=20, proof_time=_NOW)+ await _collect(s3, deletion_floor=20, proof=ListingProof(listed_at=_NOW, tail={}))assert s3.removed == [_key(11, 20)]@@ -661,14 +704,116 @@ class TestFloorDeletion:so without this proof an idle schema re-writes and re-bills its last transaction forever."""s3 = _FakeS3({_key(11, 20): _parquet_bytes(_table([1], [20]))})- await _collect(s3, deletion_floor=20, proof_time=_NOW)+ await _collect(s3, deletion_floor=20, proof=ListingProof(listed_at=_NOW, tail={}))assert s3.removed == [_key(11, 20)]assert s3.opened == []+ @parameterized.expand(+ [+ (+ "listed_with_the_same_etag",+ {build_buffer_file_name(11, 20, 0): "etag-1"},+ _RECENT,+ "etag-1",+ False,+ True,+ ),+ (+ "rewritten_with_an_mtime_that_looks_old",+ {build_buffer_file_name(11, 20, 0): "etag-0"},+ _OLD_MTIME,+ "etag-1",+ False,+ False,+ ),+ ("not_in_the_listing", {}, _RECENT, "etag-1", False, False),+ (+ "rewritten_after_this_runs_listing",+ {build_buffer_file_name(11, 20, 0): "etag-1"},+ _RECENT,+ "etag-2",+ False,+ False,+ ),+ (+ "written_to_during_the_delete",+ {build_buffer_file_name(11, 20, 0): "etag-1"},+ _RECENT,+ "etag-1",+ True,+ False,+ ),+ ]+ )+ async def test_a_file_written_just_before_the_listing_goes_on_the_next_run_only_if_that_listing_read_it(+ self,+ _name: str,+ tail: dict[str, str],+ modified: dt.datetime,+ etag_at_delete: str,+ delete_conflicts: bool,+ deleted: bool,+ ) -> None:+ key = _key(11, 20)+ s3 = _FakeS3(+ {key: _parquet_bytes(_table([1], [20]))},+ mtimes={key: modified},+ etags={key: "etag-1"},+ etags_at_delete={key: etag_at_delete},+ conflicting_deletes={key} if delete_conflicts else None,+ )+ await _collect(s3, deletion_floor=20, proof=ListingProof(listed_at=_NOW, tail=tail))++ assert (s3.removed, s3.opened) == (([key], []) if deleted else ([], [key]))++ async def test_a_listing_records_the_files_at_its_highest_position(self) -> None:+ s3 = _FakeS3(+ {+ _key(1, 10): _parquet_bytes(_table([1], [10])),+ _key(11, 20, 0): _parquet_bytes(_table([2], [20])),+ _key(11, 20, 1): _parquet_bytes(_table([3], [20])),+ },+ etags={_key(11, 20, 0): "etag-a", _key(11, 20, 1): "etag-b"},+ )+ stamp = AsyncMock()+ with _patched(s3), patch.object(CDCSourceManager, "stamp_listing", stamp):+ [t async for t in _manager().get_items()]++ stamp.assert_awaited_once_with(+ ANY,+ {build_buffer_file_name(11, 20, 0): "etag-a", build_buffer_file_name(11, 20, 1): "etag-b"},+ )++ async def test_a_listed_file_that_is_gone_before_the_read_leaves_the_tail(self) -> None:+ s3 = _FakeS3(+ {+ _key(11, 20, 0): _parquet_bytes(_table([2], [20])),+ _key(11, 20, 1): _parquet_bytes(_table([3], [20])),+ },+ etags={_key(11, 20, 0): "etag-a", _key(11, 20, 1): "etag-b"},+ missing_keys={_key(11, 20, 1)},+ )+ stamped: list[dict[str, str]] = []+ stamp = AsyncMock(side_effect=lambda _listed_at, tail: stamped.append(dict(tail)))+ with _patched(s3), patch.object(CDCSourceManager, "stamp_listing", stamp):+ [t async for t in _manager().get_items()]++ first, second = build_buffer_file_name(11, 20, 0), build_buffer_file_name(11, 20, 1)+ assert stamped == [{first: "etag-a", second: "etag-b"}, {first: "etag-a"}]++ async def test_a_tail_too_large_to_store_is_left_out(self) -> None:+ files = {_key(11, 20, index): _parquet_bytes(_table([index], [20])) for index in range(101)}+ s3 = _FakeS3(files, etags={key: f"etag-{key}" for key in files})+ stamp = AsyncMock()+ with _patched(s3), patch.object(CDCSourceManager, "stamp_listing", stamp):+ [t async for t in _manager().get_items()]++ stamp.assert_awaited_once_with(ANY, {})+async def test_nothing_is_deleted_before_every_lane_has_a_position(self):s3 = _FakeS3({_key(1, 10): _parquet_bytes(_table([1], [10]))})- await _collect(s3, deletion_floor=None, proof_time=_NOW)+ await _collect(s3, deletion_floor=None, proof=ListingProof(listed_at=_NOW, tail={}))assert s3.removed == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.pyindex e3d3a9243d78..cdc2e7d1e667 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py@@ -1926,13 +1926,13 @@ class PostgresSource(if job is None:raise ValueError(f"Buffered CDC schema {schema.name} has no job row for run {inputs.job_id}")- proof_time = async_to_sync(completed_listing_proof)(schema)+ proof = async_to_sync(completed_listing_proof)(schema)# The bucket deletes a buffer file once it is older than BUFFER_FILE_RETENTION. A table that has# consumed nothing for longer may have lost changes it never loaded, so reading on would leave it# wrong for good, and only a re-snapshot makes it correct. Capture does the reset once this run# has finished, as it does for any reset a sync could interfere with. A recent proof settles it# without the longer read.- if proof_time is None and async_to_sync(buffer_expired_unread)(schema):+ if proof is None and async_to_sync(buffer_expired_unread)(schema):inputs.logger.warning("cdc_buffer_expired_before_consumption", schema_name=schema.name, last_synced_at=schema.last_synced_at)@@ -1952,7 +1952,7 @@ class PostgresSource(inputs,inputs.logger,deletion_floor=deletion_floor,- proof_time=proof_time,+ proof=proof,)return SourceResponse(name=lanes[0].name,