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(warehouse-sources): wait for a table's sync to stop before a cdc reset (#106270)

Daniel RC27a8e5ba3b3d
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.md
index c9cd5d7358aa..66421c973d4a 100644
--- a/docs/internal/cdc-buffered-ingress-runbook.md
+++ b/docs/internal/cdc-buffered-ingress-runbook.md
@@ -53,7 +53,13 @@ The consumer replays all of them over the snapshot, including changes the snapsh
Replaying an unbroken run in order converges on the source's state, because the merge is an upsert by primary key.
A gap would break that, so capture empties the table's buffer when it starts a snapshot there, which drops files left from before a re-enable.
A TRUNCATE resets the table, empties its buffer, and drops that run's pending changes for it.
-The reset also cancels the table's running sync, so a snapshot that began before a repeated reset cannot hand over without the changes the reset drops.
+The reset also pauses the table's schedule and cancels its running sync, so a snapshot that began before a repeated reset cannot hand over without the changes the reset drops.
+A cancel only asks the workflow to stop, and the loader still applies batches the sync queued, so while either is in progress the reset waits (`cdc_reset_waits_for_running_sync`).
+The table then carries `cdc_reset_pending`, capture leaves it out, and each later run tries the reset again before it reads the WAL.
+The new snapshot reads the table after the reset, so nothing skipped is lost.
+The key stays until the schedule is unpaused, so a failed unpause is retried too.
+A reset from slot-invalidation recovery marks the key `awaiting_slot` until the replacement slot exists, so no later run can unpause the table before capture has a point to resume from, and the table stays out of capture until then.
+Recovery clears the flag once the slot is back, and so does any read that succeeds, so a failure right after the recreation cannot leave the table waiting for good.
Turning a table's sync off, or adding it back to capture, drops its marker, because capture skipped the table in between and its buffer has a gap.
Capture handles a TRUNCATE only after every change of its transaction has been read, so no pre-TRUNCATE change can land in the buffer after the purge.
Without the marker, the hand-over purges the whole buffer, as legacy always did.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
index bc948e1e7ace..83f30d50a0a4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -90,6 +90,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane
from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
captures_to_buffer,
consolidated_resource_name,
+ has_queued_batches,
snapshot_can_start_in_buffer,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent
@@ -116,6 +117,10 @@ SLOT_INVALIDATION_RECOVERY_MESSAGE = (
"once the re-sync completes."
)
+# Marks a table whose reset waits for its running sync to stop. The slot moves past the TRUNCATE
+# meanwhile, so this key is what makes a later capture run finish the reset.
+CDC_RESET_PENDING_KEY = "cdc_reset_pending"
+
# The sweeper's auto-drop must fire below the engine's own retention cap, otherwise the
# engine invalidates the slot first and we lose the chance to act cleanly.
RETENTION_CAP_SAFETY_FACTOR = 0.8
@@ -274,6 +279,9 @@ class CDCExtractActivity:
self._source_buffered = False
self._buffered_snapshot_flag: bool | None = None
self._truncated_tables: list[str] = []
+ # Tables whose reset waits for a sync that can still hand over. The reset re-snapshots them, so
+ # this run drops their changes.
+ self._tables_awaiting_reset: set[str] = set()
# ------------------------------------------------------------------
# Logger helpers
@@ -729,7 +737,7 @@ class CDCExtractActivity:
for table_name, raw_table in tables.items():
schema = self.schema_by_name.get(table_name)
- if schema is None:
+ if schema is None or table_name in self._tables_awaiting_reset:
continue
self._safe_heartbeat()
@@ -884,6 +892,7 @@ class CDCExtractActivity:
try:
self._require_configured_slot()
+ self._finish_pending_resets()
self.reader.connect()
# Taken before the peek, so anything committed after it stays above this position and
# is decoded by a later run.
@@ -891,6 +900,10 @@ class CDCExtractActivity:
self._load_pk_columns()
self._read_wal_loop()
+ # A read that got this far proves the slot is back, so a reset held for it can finish on
+ # the next run even if recovery never runs again.
+ for schema in self.cdc_schemas:
+ self._release_reset_awaiting_slot(schema)
self.log.info("wal_changes_read", event_count=self.event_count, tables=list(self.all_table_names))
@@ -1464,8 +1477,9 @@ class CDCExtractActivity:
"""Process any truncated tables observed during decoding.
Runs before every slot advance, so a failed reset or purge fails the run while the slot still
- holds the TRUNCATE and the retry repeats it. Returns every table truncated this run, so the
- no-changes path can decide whether to advance the slot.
+ holds the TRUNCATE and the retry repeats it. A reset that must wait for a sync to stop is
+ recorded on the table instead, so the slot can move on. Returns every table truncated this
+ run, so the no-changes path can decide whether to advance the slot.
"""
truncated_tables = list(self.reader.truncated_tables)
self.reader.clear_truncated_tables()
@@ -1480,18 +1494,58 @@ class CDCExtractActivity:
self._schema_log(trunc_schema).warning(
"truncate_detected", table=table_name, schema_id=str(trunc_schema.id)
)
- self._reset_schema_to_snapshot(trunc_schema)
- self._unpause_schema_schedule(trunc_schema)
+ if self._reset_schema_to_snapshot(trunc_schema):
+ self._unpause_schema_schedule(trunc_schema)
return list(self._truncated_tables)
- def _reset_schema_to_snapshot(self, schema: ExternalDataSchema, *, clear_deferred_runs: bool = False) -> None:
- """Put a schema back into snapshot mode so its own schedule re-syncs it from scratch."""
- # A snapshot already running may have read the table before changes this reset drops, as
- # when a retry reads a TRUNCATE again. It must not reach its hand-over. A failed cancel fails
- # the run while the slot still holds the TRUNCATE, so the retry repeats the reset.
- cancelled = cancel_running_sync(schema)
- if cancelled:
- self._schema_log(schema).info("cdc_reset_cancelled_running_sync", workflow_id=cancelled)
+ def _finish_pending_resets(self) -> None:
+ """Retry the resets earlier runs left pending, before this run reads the WAL.
+
+ Repeating a reset that already happened is safe: its schedule stayed paused, so no new sync
+ has started since. A reset still waiting on a slot is held back, so no snapshot starts before
+ capture has a point to resume from, and its table stays out of capture meanwhile.
+ """
+ for schema in self.cdc_schemas:
+ pending = self._pending_reset(schema)
+ if pending is None:
+ continue
+ if pending.get("awaiting_slot"):
+ self._tables_awaiting_reset.add(schema.name)
+ continue
+ if self._reset_schema_to_snapshot(schema):
+ self._unpause_schema_schedule(schema)
+
+ def _pending_reset(self, schema: ExternalDataSchema) -> dict[str, typing.Any] | None:
+ pending = (schema.sync_type_config or {}).get(CDC_RESET_PENDING_KEY)
+ if not pending:
+ return None
+ return pending if isinstance(pending, dict) else {}
+
+ def _reset_schema_to_snapshot(
+ self, schema: ExternalDataSchema, *, clear_deferred_runs: bool = False, awaiting_slot: bool = False
+ ) -> bool:
+ """Put a schema back into snapshot mode so its own schedule re-syncs it from scratch.
+
+ Returns False when a sync of the table could still hand over, which leaves the reset pending.
+ """
+ # A sync that hands over after the reset flips the table to streaming with reset_pipeline still
+ # set, so its next run wipes the table. A cancel only asks the workflow to stop, and the loader
+ # still applies its queued batches, so the reset waits until neither can happen. A failed pause
+ # or cancel fails the run while the slot still holds the TRUNCATE.
+ pending = self._pending_reset(schema)
+ if pending is not None and pending.get("clear_deferred_runs"):
+ clear_deferred_runs = True
+ self._pause_schema_schedule(schema)
+ stopping = cancel_running_sync(schema)
+ # The queue alone, because deferred runs flush only after a hand-over, which the pause prevents.
+ if stopping is not None or has_queued_batches(schema):
+ self._defer_reset(
+ schema,
+ clear_deferred_runs=clear_deferred_runs,
+ awaiting_slot=awaiting_slot,
+ stopping_workflow_id=stopping,
+ )
+ return False
# The re-seeding snapshot starts after this run, so it covers every change this run read.
# Pending changes go too, because a change from before a TRUNCATE would bring back rows.
if self.batcher is not None:
@@ -1503,7 +1557,12 @@ class CDCExtractActivity:
removes = ["cdc_last_log_position"]
if clear_deferred_runs:
removes.append("cdc_deferred_runs")
- updates: dict[str, typing.Any] = {"cdc_mode": "snapshot", "reset_pipeline": True}
+ # Pending until the schedule is unpaused, so a failed unpause repeats on the next run.
+ updates: dict[str, typing.Any] = {
+ "cdc_mode": "snapshot",
+ "reset_pipeline": True,
+ CDC_RESET_PENDING_KEY: {"clear_deferred_runs": clear_deferred_runs, "awaiting_slot": awaiting_slot},
+ }
# Later runs write the table's changes to the emptied buffer as an unbroken run, so the next
# snapshot stays in the buffer with them.
if schema.name in self._buffered_table_names and (
@@ -1523,10 +1582,52 @@ class CDCExtractActivity:
removes=removes,
extra_model_fields={"initial_sync_complete": False},
)
+ self._tables_awaiting_reset.discard(schema.name)
if clear_deferred_runs:
self._emit_deferred_runs_depth()
+ return True
+
+ def _defer_reset(
+ self,
+ schema: ExternalDataSchema,
+ *,
+ clear_deferred_runs: bool,
+ awaiting_slot: bool,
+ stopping_workflow_id: str | None,
+ ) -> None:
+ """Leave the table out of capture until a later run can reset it."""
+ if self.batcher is not None:
+ self.batcher.discard(schema.name)
+ self._tables_awaiting_reset.add(schema.name)
+ self._update_schema_sync_type_config(
+ schema,
+ updates={
+ CDC_RESET_PENDING_KEY: {"clear_deferred_runs": clear_deferred_runs, "awaiting_slot": awaiting_slot}
+ },
+ )
+ self._schema_log(schema).info("cdc_reset_waits_for_running_sync", stopping_workflow_id=stopping_workflow_id)
+
+ def _release_reset_awaiting_slot(self, schema: ExternalDataSchema) -> None:
+ """Let a later run finish a reset held back for the slot, now that a slot is there to read.
+
+ Called both by recovery and by a successful read, so a failure between the recreation and
+ this write cannot strand the reset: recovery only runs while the slot is still broken.
+ """
+ pending = self._pending_reset(schema)
+ if pending is None or not pending.get("awaiting_slot"):
+ return
+ self._update_schema_sync_type_config(
+ schema, updates={CDC_RESET_PENDING_KEY: {**pending, "awaiting_slot": False}}
+ )
+
+ def _pause_schema_schedule(self, schema: ExternalDataSchema) -> None:
+ # Deferred: data_load.service participates in the CDC schedule<->workflow import cycle.
+ from products.data_warehouse.backend.facade.api import pause_external_data_schedule # noqa: PLC0415
+
+ pause_external_data_schedule(str(schema.id))
def _unpause_schema_schedule(self, schema: ExternalDataSchema) -> None:
+ """Let a reset table's schedule start its snapshot. A failure leaves the reset pending for the next run."""
schema_log = self._schema_log(schema)
try:
from products.data_warehouse.backend.facade.api import unpause_external_data_schedule
@@ -1535,6 +1636,8 @@ class CDCExtractActivity:
schema_log.info("unpaused_schema_schedule_for_resnapshot", schema_id=str(schema.id))
except Exception:
schema_log.warning("failed_to_unpause_schema_schedule", schema_id=str(schema.id), exc_info=True)
+ return
+ self._update_schema_sync_type_config(schema, removes=[CDC_RESET_PENDING_KEY])
def _pause_cdc_extraction_schedule(self) -> None:
"""Pause the source's CDC extraction schedule after a non-retryable failure (best-effort)."""
@@ -1709,9 +1812,14 @@ class CDCExtractActivity:
# fails below, the next run hits the invalidation again and recovery reruns
# idempotently — no schema keeps streaming across the gap unnoticed. Deferred
# runs are dropped: they reference WAL from the dead slot, the re-snapshot
- # supersedes them, and flushing them later would merge stale rows over fresh ones.
+ # supersedes them, and flushing them later would merge stale rows over fresh ones. A schema
+ # whose sync is still stopping keeps its reset pending, and a later run finishes it. Every
+ # reset here waits on the slot, so a recreation that fails below cannot leave a later run
+ # free to start a snapshot before capture has a point to resume from.
+ reset_schemas = []
for schema in self.cdc_schemas:
- self._reset_schema_to_snapshot(schema, clear_deferred_runs=True)
+ if self._reset_schema_to_snapshot(schema, clear_deferred_runs=True, awaiting_slot=True):
+ reset_schemas.append(schema)
schema.status = ExternalDataSchema.Status.FAILED
schema.latest_error = SLOT_INVALIDATION_RECOVERY_MESSAGE
schema.save(update_fields=["status", "latest_error", "updated_at"])
@@ -1725,8 +1833,11 @@ class CDCExtractActivity:
self.source.save(update_fields=["job_inputs", "updated_at"])
# Unpause only after the new slot exists, so no snapshot can run before change
- # capture has a consistent point to resume from.
+ # capture has a consistent point to resume from. Same for the resets still pending: the
+ # slot is back, so a later run may finish them.
for schema in self.cdc_schemas:
+ self._release_reset_awaiting_slot(schema)
+ for schema in reset_schemas:
self._unpause_schema_schedule(schema)
self.log.info("cdc_slot_recovery_complete", schemas_reset=len(self.cdc_schemas))
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 789365668a76..8f89ffb8801c 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
@@ -93,8 +93,9 @@ def resnapshot_stays_in_buffer(schema: ExternalDataSchema, logger: FilteringBoun
def cancel_running_sync(schema: ExternalDataSchema) -> str | None:
"""Cancel the table's running scheduled sync, so a snapshot begun before a reset cannot hand over.
- Returns the workflow id it cancelled. A workflow that already finished counts as cancelled. Any
- other failure raises, so the caller stops before it changes the table.
+ Returns the id of the workflow it asked to stop. That workflow can still be finishing, and the
+ loader can still apply batches it queued. Returns None when no sync runs, or its workflow already
+ closed. Any other failure raises, so the caller stops before it changes the table.
"""
# Deferred: data_load.service participates in the CDC schedule<->workflow import cycle.
from products.data_warehouse.backend.facade.api import cancel_external_data_workflow # noqa: PLC0415
@@ -115,4 +116,5 @@ def cancel_running_sync(schema: ExternalDataSchema) -> str | None:
except RPCError as e:
if e.status != RPCStatusCode.NOT_FOUND:
raise
+ return None
return job.workflow_id
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 39c0edabe5cb..60b20337aa8d 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
@@ -402,7 +402,11 @@ def has_batches_in_flight(schema: ExternalDataSchema) -> bool:
"""
if schema.sync_type_config.get("cdc_deferred_runs"):
return True
+ return has_queued_batches(schema)
+
+def has_queued_batches(schema: ExternalDataSchema) -> bool:
+ """Whether any batch of this schema is still waiting or loading in the queue."""
conn = psycopg.Connection.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True)
try:
age = BatchQueue.get_oldest_non_terminal_batch_age_seconds(
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.py
index 2e36d96e4d77..5f95f498afd1 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
@@ -33,6 +33,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.activities imp
from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN, CDC_SEQ_PROVENANCE
from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCErrorCategory, cdc_error_info
from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import cancel_running_sync
+from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import has_queued_batches
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
BatchQueue,
@@ -171,6 +172,11 @@ def _stub_sync_type_config_merge():
"products.warehouse_sources.backend.temporal.data_imports.cdc.activities.cancel_running_sync",
return_value=None,
),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.has_queued_batches",
+ return_value=False,
+ ),
+ patch("products.data_warehouse.backend.facade.api.pause_external_data_schedule"),
patch(
"products.warehouse_sources.backend.temporal.data_imports.cdc.activities.mark_schema_running_unless_halted",
side_effect=_fake_mark_schema_running_unless_halted,
@@ -2733,6 +2739,49 @@ class TestSlotInvalidationRecovery:
assert "cannot recreate slot" not in schema.latest_error
mock_reader.close.assert_called_once()
+ @parameterized.expand([("recreation_failed", True), ("recreation_succeeded", False)])
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
+ @patch.object(CDCExtractActivity, "_get_cdc_schemas")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
+ def test_a_reset_waits_for_the_new_slot_before_a_later_run_can_finish_it(
+ self,
+ _name,
+ awaits_slot,
+ mock_close_conns,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ mock_activity,
+ ):
+ # A reset left pending by recovery must stay paused while the slot is missing: its snapshot
+ # would start with no consistent point for capture to resume from.
+ source, schema, mock_reader, mock_adapter = self._setup(
+ mock_get_schemas, mock_get_adapter, MockSourceModel, mock_activity
+ )
+ if awaits_slot:
+ mock_adapter.recreate_slot.side_effect = RuntimeError("cannot recreate slot")
+ else:
+ mock_adapter.recreate_slot.return_value = {"cdc_consistent_point": "0/AA"}
+
+ inputs = CDCExtractInput(team_id=1, source_id=source.id)
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.cancel_running_sync",
+ return_value="users-snapshot",
+ ),
+ patch("products.data_warehouse.backend.facade.api.unpause_external_data_schedule") as unpause,
+ ):
+ if awaits_slot:
+ with pytest.raises(RuntimeError, match="cannot recreate slot"):
+ cdc_extract_activity(inputs)
+ else:
+ cdc_extract_activity(inputs)
+
+ unpause.assert_not_called()
+ assert schema.sync_type_config["cdc_reset_pending"]["awaiting_slot"] is awaits_slot
+
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -3880,22 +3929,44 @@ class TestBufferedIngressCapture:
@parameterized.expand(
[
- ("cancelled", None),
- ("already_finished", RPCError("workflow not found", RPCStatusCode.NOT_FOUND, b"")),
- ("temporal_unavailable", RPCError("unavailable", RPCStatusCode.UNAVAILABLE, b"")),
+ ("sync_still_stopping", None, None, {}, "waits"),
+ (
+ "sync_closed_with_batches_still_loading",
+ RPCError("workflow not found", RPCStatusCode.NOT_FOUND, b""),
+ 30.0,
+ {},
+ "waits",
+ ),
+ (
+ "sync_closed_and_nothing_queued",
+ RPCError("workflow not found", RPCStatusCode.NOT_FOUND, b""),
+ None,
+ {},
+ "resets",
+ ),
+ (
+ "deferred_runs_left_and_nothing_queued",
+ RPCError("workflow not found", RPCStatusCode.NOT_FOUND, b""),
+ None,
+ {"cdc_deferred_runs": [{"run_uuid": "r1"}]},
+ "resets",
+ ),
+ ("temporal_unavailable", RPCError("unavailable", RPCStatusCode.UNAVAILABLE, b""), None, {}, "raises"),
]
)
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane.ExternalDataJob")
- def test_a_reset_stops_the_tables_running_sync_first(self, _name, cancel_error, MockJob, mock_purge):
+ def test_a_reset_stops_the_tables_running_sync_first(
+ self, _name, cancel_error, oldest_queued_batch_age, config, outcome, MockJob, mock_purge
+ ):
# A snapshot that started before a repeated reset missed the changes the reset drops, so it
# must not reach its hand-over.
source = _make_source()
schema = _make_schema("users", cdc_mode="snapshot", source=source)
+ schema.sync_type_config.update(config)
act = _make_extract_activity(source)
running = MockJob.objects.filter.return_value.exclude.return_value.exclude.return_value
running.order_by.return_value.first.return_value = MagicMock(workflow_id="users-snapshot")
- fails = cancel_error is not None and cancel_error.status != RPCStatusCode.NOT_FOUND
with (
patch(
@@ -3906,17 +3977,87 @@ class TestBufferedIngressCapture:
"products.data_warehouse.backend.facade.api.cancel_external_data_workflow",
side_effect=cancel_error,
) as cancel,
+ patch("products.data_warehouse.backend.facade.api.pause_external_data_schedule") as pause,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.has_queued_batches",
+ has_queued_batches,
+ ),
+ patch("products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.psycopg"),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.BatchQueue.get_oldest_non_terminal_batch_age_seconds",
+ return_value=oldest_queued_batch_age,
+ ),
):
- if fails:
+ if outcome == "raises":
with pytest.raises(RPCError):
act._reset_schema_to_snapshot(schema)
else:
act._reset_schema_to_snapshot(schema)
+ assert mock_purge.called is (outcome == "resets")
+ assert schema.sync_type_config.get("reset_pipeline") is (True if outcome == "resets" else None)
+ assert ("cdc_reset_pending" in schema.sync_type_config) is (outcome != "raises")
+ assert (schema.name in act._tables_awaiting_reset) is (outcome == "waits")
+ pause.assert_called_once_with(str(schema.id))
cancel.assert_called_once_with("users-snapshot")
- # A cancel that did not go through fails the run before the reset, so the retry repeats both.
- assert mock_purge.called is not fails
- assert schema.sync_type_config.get("reset_pipeline") is (None if fails else True)
+
+ @parameterized.expand(
+ [
+ ("sync_still_stopping", "users-snapshot", True),
+ ("sync_stopped", None, False),
+ ]
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
+ def test_a_pending_reset_finishes_before_the_read_once_the_sync_stopped(
+ self, _name, stopping_workflow_id, waits, MockBufferWriter, mock_purge
+ ):
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ schema.sync_type_config["cdc_reset_pending"] = {"clear_deferred_runs": False}
+ events = [_make_event(op="I", position="0/100", columns={"id": 1})]
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.cancel_running_sync",
+ return_value=stopping_workflow_id,
+ ),
+ patch("products.data_warehouse.backend.facade.api.unpause_external_data_schedule") as unpause,
+ ):
+ reader, _s3, _producer = self._run(MockBufferWriter, events, [schema], source)
+
+ assert mock_purge.called is not waits
+ assert unpause.called is not waits
+ assert schema.sync_type_config.get("reset_pipeline") is (None if waits else True)
+ assert ("cdc_reset_pending" in schema.sync_type_config) is waits
+ assert MockBufferWriter.return_value.write_batch.called is not waits
+ reader.confirm_position.assert_called_once_with("0/100")
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
+ def test_a_reset_waiting_on_a_slot_holds_the_table_out_until_the_slot_reads(self, MockBufferWriter, mock_purge):
+ # Recovery leaves this marker when it could not recreate the slot. Finishing the reset here
+ # would unpause the schedule, and the snapshot would start with no slot to resume from. A
+ # read that succeeds proves the slot is back, so the next run finishes the reset — recovery
+ # is not the only way out, or a failure right after the recreation would strand the table.
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ schema.sync_type_config["cdc_reset_pending"] = {"clear_deferred_runs": True, "awaiting_slot": True}
+ events = [_make_event(op="I", position="0/100", columns={"id": 1})]
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.cancel_running_sync"
+ ) as cancel,
+ patch("products.data_warehouse.backend.facade.api.unpause_external_data_schedule") as unpause,
+ ):
+ self._run(MockBufferWriter, events, [schema], source)
+
+ cancel.assert_not_called()
+ unpause.assert_not_called()
+ assert mock_purge.called is False
+ assert MockBufferWriter.return_value.write_batch.called is False
+ assert schema.sync_type_config["cdc_reset_pending"] == {"clear_deferred_runs": True, "awaiting_slot": False}
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
def test_a_buffer_write_failure_fails_the_run_and_leaves_the_slot(self, MockBufferWriter):