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.

feat(warehouse-sources): re-snapshot a cdc table after its buffer expires (#106964)

Daniel RCcb45223750b1
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.md
index ba28a5d6dca9..f25f53e560a5 100644
--- a/docs/internal/cdc-buffered-ingress-runbook.md
+++ b/docs/internal/cdc-buffered-ingress-runbook.md
@@ -354,6 +354,17 @@ long since advanced past those changes.
**If files expire before they are consumed, the changes are gone.** There is no partial recovery.
The only fix is a full `reset_pipeline` re-snapshot for that schema.
+A table's own sync does that re-snapshot. When it starts and the table last consumed the buffer
+longer ago than files are kept (`cdc_buffer_expired_before_consumption`), it stands down for the tick
+and hands the reset to capture, which resets the table once the sync has finished and starts the
+snapshot. So a table that resumes after a long stop, such as a billing block lifting, re-snapshots
+instead of loading on past changes it never saw.
+
+Only a run that listed the buffer, or re-seeded the table with a snapshot, counts as having consumed
+it — and only once every table that run writes finished. A `both` run whose history lane never
+completed landed those changes on the consolidated table alone, so it leaves the history table owed
+and does not count.
+
Watch the age of the oldest unconsumed file per schema, not the file count. A schema with few files
that are all thirteen days old is in trouble; one with thousands of fresh files is fine.
diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.py
index b13e40304f5c..dfb557b31458 100644
--- a/products/data_warehouse/backend/facade/api.py
+++ b/products/data_warehouse/backend/facade/api.py
@@ -30,6 +30,7 @@ _LAZY = {
"external_data_workflow_exists": "logic.data_load.service",
"is_any_external_data_schema_paused": "logic.data_load.service",
"is_cdc_enabled_for_team": "logic.data_load.service",
+ "cdc_extraction_schedule_exists": "logic.data_load.service",
"cdc_extraction_schedule_has_running_action": "logic.data_load.service",
"is_cdc_extraction_schedule_paused": "logic.data_load.service",
"is_external_data_schedule_paused": "logic.data_load.service",
diff --git a/products/data_warehouse/backend/logic/data_load/service.py b/products/data_warehouse/backend/logic/data_load/service.py
index 5b2a673adade..555623eab0e3 100644
--- a/products/data_warehouse/backend/logic/data_load/service.py
+++ b/products/data_warehouse/backend/logic/data_load/service.py
@@ -521,11 +521,14 @@ def get_cdc_extraction_schedule(
)
-def sync_cdc_extraction_schedule(source: ExternalDataSource, create: bool = False) -> None:
+def sync_cdc_extraction_schedule(
+ source: ExternalDataSource, create: bool = False, trigger_immediately: bool = True
+) -> None:
"""Create or update the CDC extraction Temporal schedule for a source.
Calculates the interval from the most frequent CDC schema. If no CDC
- schemas are active, deletes the schedule.
+ schemas are active, deletes the schedule. A schedule this creates fires its
+ first run straight away unless `trigger_immediately` is off.
"""
from products.warehouse_sources.backend.facade.models import ExternalDataSchema
from products.warehouse_sources.backend.facade.source_management import source_type_supports_cdc
@@ -585,13 +588,13 @@ def sync_cdc_extraction_schedule(source: ExternalDataSource, create: bool = Fals
)
if create:
- create_schedule(temporal, id=schedule_id, schedule=schedule, trigger_immediately=True)
+ create_schedule(temporal, id=schedule_id, schedule=schedule, trigger_immediately=trigger_immediately)
else:
try:
update_schedule(temporal, id=schedule_id, schedule=schedule)
except temporalio.service.RPCError as e:
if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:
- create_schedule(temporal, id=schedule_id, schedule=schedule, trigger_immediately=True)
+ create_schedule(temporal, id=schedule_id, schedule=schedule, trigger_immediately=trigger_immediately)
else:
raise
@@ -613,6 +616,15 @@ def trigger_cdc_extraction_schedule(source_id: str) -> bool:
return True
+def cdc_extraction_schedule_exists(source_id: str) -> bool:
+ """Whether the source's CDC extraction schedule is there.
+
+ Recreating a missing one is the caller's job, as it is for the trigger: building a schedule
+ reads the source row, and this boundary takes ids.
+ """
+ return external_data_workflow_exists(_get_cdc_extraction_schedule_id(source_id))
+
+
def delete_cdc_extraction_schedule(source_id: str) -> None:
"""Delete the CDC extraction schedule for a source."""
schedule_id = _get_cdc_extraction_schedule_id(source_id)
diff --git a/products/data_warehouse/backend/logic/data_load/test/test_service.py b/products/data_warehouse/backend/logic/data_load/test/test_service.py
index c36b72fcd155..db2d96384668 100644
--- a/products/data_warehouse/backend/logic/data_load/test/test_service.py
+++ b/products/data_warehouse/backend/logic/data_load/test/test_service.py
@@ -31,6 +31,7 @@ from products.data_warehouse.backend.logic.data_load.service import (
a_unpause_external_data_schedule,
bulk_sync_cdc_extraction_schedules,
bulk_update_external_data_job_schedules,
+ cdc_extraction_schedule_exists,
cdc_extraction_schedule_has_running_action,
cdc_min_interval,
get_discover_schemas_schedule,
@@ -604,3 +605,14 @@ def test_triggering_capture_raises_any_other_temporal_error() -> None:
pytest.raises(RPCError),
):
trigger_cdc_extraction_schedule(str(uuid.uuid4()))
+
+
[email protected]("exists", [True, False])
+def test_reporting_whether_a_source_still_has_its_capture_schedule(exists: bool) -> None:
+ # The caller recreates a missing one, so it needs to know without starting a run.
+ source_id = str(uuid.uuid4())
+
+ with patch(f"{SERVICE}.external_data_workflow_exists", return_value=exists) as workflow_exists:
+ assert cdc_extraction_schedule_exists(source_id) is exists
+
+ workflow_exists.assert_called_once_with(_get_cdc_extraction_schedule_id(source_id))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py
index c2d31c52b55d..ab4c3604286c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py
@@ -41,6 +41,7 @@ from __future__ import annotations
import re
import time
+import datetime as dt
from contextlib import suppress
from dataclasses import dataclass
@@ -62,6 +63,8 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
)
BUFFER_ROOT_FOLDER = "cdc_producer"
+# How long the lifecycle rule in the module docstring keeps a buffer file after it is written.
+BUFFER_FILE_RETENTION = dt.timedelta(days=14)
# Per-team gate for the shadow lane — the single on/off control. Fail-closed on
# evaluation errors, so the soak can only ever shrink, never grow, by accident.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/snapshot_lane.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/snapshot_lane.py
index 3532b7e81625..8aed20414461 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/snapshot_lane.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/snapshot_lane.py
@@ -153,18 +153,46 @@ def hand_reset_to_capture_if_sync_running(
hands its resets over before it recreates the slot, and a capture run that fires in between
would otherwise start the snapshot against the dead one.
"""
+ try:
+ if not cancel_sync_that_could_hand_over(schema):
+ return False
+ except Exception:
+ logger.warning("cdc_reset_sync_check_failed", schema_id=str(schema.id), exc_info=True)
+ hand_reset_to_capture(schema, logger, awaiting_slot=awaiting_slot)
+ return True
+
+
+def hand_reset_to_capture(
+ schema: ExternalDataSchema,
+ logger: FilteringBoundLogger,
+ *,
+ start_capture: bool = True,
+ awaiting_slot: bool = False,
+) -> None:
+ """Pause a CDC table's schedule and mark its reset pending, so capture finishes it once no sync can hand over.
+
+ `start_capture` starts a capture run right away. A table's own sync turns it off, because that run
+ would find the sync still finishing and cancel it, and a cancelled sync reports a failure. It then
+ only recreates the capture schedule if it is gone, so capture's next run finishes the reset.
+
+ `awaiting_slot` holds the staged reset back until a capture run has read the slot, as Repair CDC
+ needs while it recreates the slot.
+ """
# Deferred: data_load.service participates in the CDC schedule<->workflow import cycle.
from products.data_warehouse.backend.facade.api import ( # noqa: PLC0415
+ cdc_extraction_schedule_exists,
pause_external_data_schedule,
sync_cdc_extraction_schedule,
trigger_cdc_extraction_schedule,
)
- try:
- if not cancel_sync_that_could_hand_over(schema):
- return False
- except Exception:
- logger.warning("cdc_reset_sync_check_failed", schema_id=str(schema.id), exc_info=True)
+ if not start_capture and not schema.cdc_halted and not cdc_extraction_schedule_exists(str(schema.source_id)):
+ # Capture is the only thing that finishes this reset, and pausing the table's schedule below
+ # is what stops this caller from ever running again. So recreate a missing capture schedule
+ # before that, without its first run, which would cancel the sync that is still finishing.
+ # A failure raises while nothing is paused or staged, and the table's next tick retries.
+ sync_cdc_extraction_schedule(schema.source, create=True, trigger_immediately=False)
+
try:
pause_external_data_schedule(str(schema.id))
except Exception:
@@ -182,7 +210,7 @@ def hand_reset_to_capture_if_sync_running(
# Capture finishes the reset, so start a run now instead of waiting for its schedule: the last
# run may have looked for resets just before this write, and the schedule may be gone. A halted
# source is left alone, because Repair CDC or a resumed capture restarts capture itself.
- if not schema.cdc_halted:
+ if start_capture and not schema.cdc_halted:
try:
if not trigger_cdc_extraction_schedule(str(schema.source_id)):
# The schedule is gone, and creating it fires its first run.
@@ -191,7 +219,6 @@ def hand_reset_to_capture_if_sync_running(
# The capture schedule's next tick still finishes the reset.
logger.warning("cdc_reset_capture_trigger_failed", schema_id=str(schema.id), exc_info=True)
logger.info("cdc_reset_handed_to_capture", schema_id=str(schema.id))
- return True
def stage_handed_over_reset(config: dict[str, Any], *, awaiting_slot: bool = False) -> None:
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.py
index 60b20337aa8d..a07e0259c964 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
@@ -16,6 +16,7 @@ from collections.abc import AsyncGenerator, Callable
from typing import TYPE_CHECKING, Any, Final, Literal
from django.db import transaction
+from django.db.models import Q
from django.utils import timezone
import psycopg
@@ -38,6 +39,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import
companion_resource_name,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import (
+ BUFFER_FILE_RETENTION,
BufferFileSpan,
get_buffer_prefix,
parse_buffer_file_name,
@@ -245,6 +247,52 @@ async def completed_listing_proof(schema: ExternalDataSchema) -> dt.datetime | N
return await database_sync_to_async_pool(db_read_with_retry)(lambda: read_completed_listing_proof(schema))
+def buffer_may_have_expired_unread(schema: ExternalDataSchema, now: dt.datetime) -> bool:
+ """Whether this table may have lost buffered changes it never read.
+
+ The bucket deletes a buffer file BUFFER_FILE_RETENTION after writing it, so what counts is the last
+ run since then that drained the buffer or re-seeded the table with a snapshot. A stand-down, such as
+ the wait for in-flight batches, completes its job without reading the buffer, so neither a completed
+ job nor `last_synced_at`, which every completion moves, proves the table read its changes.
+
+ A run counts only once every table it writes finished, the bar `read_completed_listing_proof` sets:
+ a `both` run whose companion job never completed landed the buffer's changes on one of its two
+ tables, and the other still owes them.
+ """
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+
+ if schema.last_synced_at is None:
+ return False
+ cutoff = now - BUFFER_FILE_RETENTION
+ # Every completion moves it, so nothing has drained since the cutoff either.
+ if schema.last_synced_at < cutoff:
+ return True
+ # Bounded by `created_at` and on the index, as the proof read is. Past the search depth the table
+ # reads as expired: runs that recent with a companion still owing rows are worth re-seeding over.
+ reads = (
+ ExternalDataJob.objects.filter(
+ team_id=schema.team_id,
+ pipeline_id=schema.source_id,
+ schema_id=schema.id,
+ status=ExternalDataJob.Status.COMPLETED,
+ created_at__gte=cutoff,
+ )
+ .filter(
+ Q(schema_snapshot__has_key=BUFFER_LISTED_AT_KEY) | Q(schema_snapshot__sync_type_config__cdc_mode="snapshot")
+ )
+ .order_by("-created_at")
+ .values_list("schema_snapshot", flat=True)[:_PROOF_SEARCH_DEPTH]
+ )
+ return not any(_companions_completed((snapshot or {}).get(COMPANION_JOB_IDS_KEY) or []) for snapshot in reads)
+
+
+async def buffer_expired_unread(schema: ExternalDataSchema) -> bool:
+ """`buffer_may_have_expired_unread`, off the event loop."""
+ return await database_sync_to_async_pool(db_read_with_retry)(
+ lambda: buffer_may_have_expired_unread(schema, timezone.now())
+ )
+
+
def clear_listing(job_id: str, team_id: int) -> None:
"""Drop the listing stamp from a job that a retry is about to hand back without draining.
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.py
index 6d760f0b77b2..dc059f8708ee 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
@@ -1,5 +1,7 @@
+import datetime as dt
+
import pytest
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import ANY, AsyncMock, MagicMock, call, patch
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.temporal.data_imports.cdc.lane_position import LanePosition
@@ -11,6 +13,7 @@ _SCHEMA_MODEL = "products.warehouse_sources.backend.models.external_data_schema.
_JOB_MODEL = "products.warehouse_sources.backend.models.external_data_job.ExternalDataJob"
_MANAGER = "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager"
_COMPANIONS = "products.warehouse_sources.backend.temporal.data_imports.cdc.companion_jobs"
+_SNAPSHOT_LANE = "products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane"
def _schema(ingest_mode: str = "buffered", **overrides) -> MagicMock:
@@ -24,6 +27,7 @@ def _schema(ingest_mode: str = "buffered", **overrides) -> MagicMock:
schema.schema_metadata = {}
schema.resolved_s3_folder_name = None
schema.primary_key_columns = ["id"]
+ schema.last_synced_at = None
schema.source.job_inputs = {"cdc_enabled": True, "cdc_ingest_mode": ingest_mode}
return schema
@@ -45,6 +49,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 _delta_ref() -> MagicMock:
ref = MagicMock()
ref.return_value.get_delta_table = AsyncMock(return_value=MagicMock())
@@ -58,6 +66,9 @@ 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,
+ hand_reset: MagicMock | None = None,
+ expired: AsyncMock | None = None,
):
job = None if job_version is None else MagicMock(pipeline_version=job_version)
with (
@@ -69,7 +80,9 @@ 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=None)),
+ patch(f"{_MANAGER}.completed_listing_proof", AsyncMock(return_value=proof_time)),
+ 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()),
):
objects.select_related.return_value.get.return_value = schema
@@ -158,3 +171,33 @@ class TestBufferedDispatch:
def test_a_reset_on_a_streaming_buffered_schema_is_refused(self):
with pytest.raises(ValueError, match="cdc_mode='snapshot'"):
_dispatch(_schema(), _inputs(reset_pipeline=True))
+
+ @pytest.mark.parametrize(
+ "proof_days_ago, expired, reset",
+ [(None, True, True), (None, False, False), (1, True, False)],
+ )
+ def test_a_table_that_consumed_nothing_for_longer_than_the_buffer_keeps_files_is_reset(
+ self, proof_days_ago: int | None, expired: bool, reset: bool
+ ) -> None:
+ hand_reset = MagicMock()
+ expired_check = AsyncMock(return_value=expired)
+ schema = _schema(cdc_table_mode="both")
+
+ response = _dispatch(
+ schema, _inputs(), proof_time=_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 [])
+ assert (response.lanes is None) is reset
+ assert expired_check.called is (proof_days_ago is None)
+
+ def test_an_expired_buffer_takes_an_earlier_attempts_listing_off_the_job(self) -> None:
+ # The workflow completes the job on the empty response this stand-down hands back, just as
+ # it does for the in-flight one, so a stamp from an earlier attempt must not survive it.
+ clear = MagicMock()
+ schema = _schema(cdc_table_mode="both")
+ inputs = _inputs()
+
+ _dispatch(schema, inputs, clear_listing=clear, hand_reset=MagicMock(), expired=AsyncMock(return_value=True))
+
+ clear.assert_called_once_with(inputs.job_id, inputs.team_id)
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.py
index 05d2a56046b2..3872813d5b68 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
@@ -8,11 +8,13 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.cdc.companion_jobs import (
+ COMPANION_JOB_IDS_KEY,
record_companion_job,
retire_orphaned_companions,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
BUFFER_LISTED_AT_KEY,
+ buffer_may_have_expired_unread,
clear_listing,
read_completed_listing_proof,
)
@@ -101,6 +103,82 @@ class TestCompletedListingProof(BaseTest):
assert self._proof(schema) is None
+class TestBufferExpiredUnread(BaseTest):
+ def _schema(self, *, synced_days_ago: int | None) -> ExternalDataSchema:
+ source = ExternalDataSource.objects.create(
+ team=self.team, source_id="s", connection_id="c", status="Running", source_type="Postgres"
+ )
+ synced = None if synced_days_ago is None else dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=synced_days_ago)
+ return ExternalDataSchema.objects.create(team=self.team, source=source, name="users", last_synced_at=synced)
+
+ def _completed_job(self, schema: ExternalDataSchema, *, days_ago: int, snapshot: dict) -> None:
+ job = ExternalDataJob.objects.create(
+ team=self.team,
+ pipeline=schema.source,
+ schema=schema,
+ status=ExternalDataJob.Status.COMPLETED,
+ rows_synced=0,
+ schema_snapshot=snapshot,
+ )
+ ExternalDataJob.objects.filter(id=job.id).update(
+ created_at=dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=days_ago)
+ )
+
+ @parameterized.expand(
+ [
+ ("never_synced", None, None, False),
+ ("no_completion_since_retention", 15, None, True),
+ ("only_stand_downs_since_retention", 1, (1, {}), True),
+ ("a_run_listed_the_buffer", 1, (10, {BUFFER_LISTED_AT_KEY: "2026-01-01T00:00:00+00:00"}), False),
+ ("a_snapshot_reseeded_the_table", 1, (3, {"sync_type_config": {"cdc_mode": "snapshot"}}), False),
+ (
+ "the_last_listing_is_older_than_retention",
+ 1,
+ (20, {BUFFER_LISTED_AT_KEY: "2026-01-01T00:00:00+00:00"}),
+ True,
+ ),
+ ]
+ )
+ def test_only_a_listing_or_a_snapshot_proves_the_buffer_was_read(
+ self, _name: str, synced_days_ago: int | None, job: tuple[int, dict] | None, expired: bool
+ ) -> None:
+ schema = self._schema(synced_days_ago=synced_days_ago)
+ if job is not None:
+ self._completed_job(schema, days_ago=job[0], snapshot=job[1])
+
+ assert buffer_may_have_expired_unread(schema, dt.datetime.now(tz=dt.UTC)) is expired
+
+ @parameterized.expand([("running", "Running"), ("failed", "Failed")])
+ def test_a_listing_whose_history_lane_did_not_finish_proves_nothing(
+ self, _name: str, companion_status: str
+ ) -> None:
+ # The buffer's changes landed on one of the `both` table's two lanes only, so the other one
+ # still owes them and the files that held them are about to go.
+ schema = self._schema(synced_days_ago=1)
+ companion = ExternalDataJob.objects.create(
+ team=self.team,
+ pipeline=schema.source,
+ schema=schema,
+ status=companion_status,
+ rows_synced=0,
+ billable=False,
+ )
+ self._completed_job(
+ schema,
+ days_ago=1,
+ snapshot={
+ BUFFER_LISTED_AT_KEY: "2026-01-01T00:00:00+00:00",
+ COMPANION_JOB_IDS_KEY: [str(companion.id)],
+ },
+ )
+
+ assert buffer_may_have_expired_unread(schema, dt.datetime.now(tz=dt.UTC)) is True
+
+ ExternalDataJob.objects.filter(id=companion.id).update(status=ExternalDataJob.Status.COMPLETED)
+
+ assert buffer_may_have_expired_unread(schema, dt.datetime.now(tz=dt.UTC)) is False
+
+
class TestRecordCompanionJob(BaseTest):
def test_a_new_attempt_starts_the_list_over(self):
# An earlier attempt's companion was retired or drained by the time this attempt reads;
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_reset_handover.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_reset_handover.py
new file mode 100644
index 000000000000..80f84ecc2b9a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_reset_handover.py
@@ -0,0 +1,71 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import (
+ CDC_RESET_PENDING_KEY,
+ hand_reset_to_capture,
+)
+
+_API = "products.data_warehouse.backend.facade.api"
+_SNAPSHOT_LANE = "products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane"
+
+
+def _schema() -> MagicMock:
+ schema = MagicMock()
+ schema.cdc_halted = False
+ schema.sync_type_config = {}
+ return schema
+
+
+class TestHandingAResetToCapture:
+ def test_a_hand_over_that_starts_no_capture_run_still_makes_sure_capture_is_scheduled(self) -> None:
+ # Capture is the only thing that finishes the reset, and the paused table schedule stops the
+ # sync that handed it over from ever retrying, so a missing schedule is recreated here —
+ # without its first run, which would cancel that sync while it finishes.
+ schema = _schema()
+
+ with (
+ patch(f"{_API}.cdc_extraction_schedule_exists", return_value=False),
+ patch(f"{_API}.sync_cdc_extraction_schedule") as sync_schedule,
+ patch(f"{_API}.pause_external_data_schedule") as pause,
+ patch(f"{_API}.trigger_cdc_extraction_schedule") as trigger,
+ patch(f"{_SNAPSHOT_LANE}.update_sync_type_config_keys", return_value={CDC_RESET_PENDING_KEY: {}}),
+ ):
+ hand_reset_to_capture(schema, MagicMock(), start_capture=False)
+
+ sync_schedule.assert_called_once_with(schema.source, create=True, trigger_immediately=False)
+ pause.assert_called_once()
+ trigger.assert_not_called()
+
+ def test_a_hand_over_leaves_a_capture_schedule_that_is_already_there_alone(self) -> None:
+ schema = _schema()
+
+ with (
+ patch(f"{_API}.cdc_extraction_schedule_exists", return_value=True),
+ patch(f"{_API}.sync_cdc_extraction_schedule") as sync_schedule,
+ patch(f"{_API}.pause_external_data_schedule") as pause,
+ patch(f"{_API}.trigger_cdc_extraction_schedule") as trigger,
+ patch(f"{_SNAPSHOT_LANE}.update_sync_type_config_keys", return_value={CDC_RESET_PENDING_KEY: {}}),
+ ):
+ hand_reset_to_capture(schema, MagicMock(), start_capture=False)
+
+ sync_schedule.assert_not_called()
+ trigger.assert_not_called()
+ pause.assert_called_once()
+
+ def test_a_capture_schedule_that_cannot_be_recreated_leaves_the_table_ticking(self) -> None:
+ # Failing here loses nothing: the table's schedule still runs, and its next tick hands the
+ # reset over again. Pausing it first would leave the reset pending with nothing to finish it.
+ schema = _schema()
+
+ with (
+ patch(f"{_API}.cdc_extraction_schedule_exists", return_value=False),
+ patch(f"{_API}.sync_cdc_extraction_schedule", side_effect=RuntimeError("temporal is down")),
+ patch(f"{_API}.pause_external_data_schedule") as pause,
+ patch(f"{_SNAPSHOT_LANE}.update_sync_type_config_keys") as stage,
+ pytest.raises(RuntimeError),
+ ):
+ hand_reset_to_capture(schema, MagicMock(), start_capture=False)
+
+ pause.assert_not_called()
+ stage.assert_not_called()
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.py
index 0de57a9687a2..8f12a1f754d2 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
@@ -1796,8 +1796,10 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
from products.warehouse_sources.backend.temporal.data_imports.cdc.companion_jobs import (
retire_orphaned_companions,
)
+ from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import hand_reset_to_capture
from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
CDCSourceManager,
+ buffer_expired_unread,
build_output_lanes,
clear_listing,
completed_listing_proof,
@@ -1859,6 +1861,29 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
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)
+ # 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):
+ inputs.logger.warning(
+ "cdc_buffer_expired_before_consumption", schema_name=schema.name, last_synced_at=schema.last_synced_at
+ )
+ # The workflow completes the job on this empty response, so an earlier attempt's stamp
+ # has to come off it first, as it does on the in-flight stand-down above: a Completed
+ # job still carrying one would prove a listing that nothing drained.
+ clear_listing(inputs.job_id, inputs.team_id)
+ hand_reset_to_capture(schema, inputs.logger, start_capture=False)
+ first_lane = served_lanes(schema)[0]
+ return SourceResponse(
+ name=first_lane.resource_name,
+ items=lambda: iter(()),
+ primary_keys=schema.primary_key_columns,
+ cdc_write_mode=first_lane.write_mode,
+ )
+
# Nothing of any earlier run is executing now, so a companion still Running belongs to a
# run that died without its `finally` and nothing else will ever close it.
retired = retire_orphaned_companions(schema)
@@ -1872,7 +1897,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
inputs,
inputs.logger,
deletion_floor=deletion_floor,
- proof_time=async_to_sync(completed_listing_proof)(schema),
+ proof_time=proof_time,
)
return SourceResponse(
name=lanes[0].name,