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): run cdc snapshots through the buffer (#105139)

Daniel RC12b132e7ad0e
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.md
index 1c090a53c906..c9cd5d7358aa 100644
--- a/docs/internal/cdc-buffered-ingress-runbook.md
+++ b/docs/internal/cdc-buffered-ingress-runbook.md
@@ -41,9 +41,24 @@ was: the base class is the single-table path with extract-method seams, and `Lan
`SourceResponse.lanes`. The load queue, the producer and the loader carry nothing about lanes at
all, so a single-table run finalizes exactly as before.
-Schemas still snapshotting stay on legacy extraction until their first sync completes. A source
-with a mix runs hybrid — some schemas buffered, the rest unchanged — and keeps its backpressure
-guard for the legacy ones.
+A table taking its snapshot keeps its changes on legacy deferred runs, as before, unless its snapshot runs in the buffer.
+A snapshot runs in the buffer when capture starts it there, which needs the `dwh-cdc-buffered-snapshot` flag and no deferred runs, or when a streaming table on a buffered source is reset to snapshot with the flag on.
+Either path records `cdc_snapshot_lane: "buffer"` in the schema's `sync_type_config`, and that marker, not the flag, routes the table until the snapshot hands over to streaming.
+So one snapshot never splits between the buffer and deferred runs, even when the flag changes or fails to evaluate.
+Turning the flag off only stops new snapshots from starting in the buffer.
+Turn the flag on only after a deploy has fully rolled, because an older worker ignores the marker.
+
+While the marker holds, the buffer carries an unbroken run of the table's changes, and the hand-over deletes none of them.
+The consumer replays all of them over the snapshot, including changes the snapshot already contains.
+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.
+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.
+A source with a mix runs hybrid, some schemas buffered and the rest unchanged, and keeps its backpressure guard for the legacy ones.
+The rollback command restarts any snapshot the buffer carries as a legacy snapshot, because only the buffer holds those changes and legacy's hand-over would purge them.
**Buffer files are deleted at the start of the next run**, before they are read, so the run that
proves a file consumed is never the run that deletes it. A file goes when it is strictly below the
@@ -231,7 +246,9 @@ The order matters, and the command enforces it:
1. Pause the extraction schedule, so no new capture run starts.
2. Wait for the in-flight extraction run to finish — pausing a schedule does not stop a running
workflow, and a run still executing would keep writing files and advancing the slot behind the
- drain check.
+ drain check. Then restart every snapshot the buffer carries: cancel its running sync, empty its
+ buffer, and reset it to snapshot without the marker. The new snapshot starts after capture
+ stopped, so it covers every change up to there, and legacy capture defers the rest.
3. **Wait for the consumer to drain the buffer.** The buffer's tail holds WAL the slot has already
advanced past — it exists nowhere else, and flipping to legacy before it is applied loses it for
good. The command refuses to proceed (extraction left paused, consumer left running) until every
diff --git a/products/warehouse_sources/backend/ad_hoc_sync.py b/products/warehouse_sources/backend/ad_hoc_sync.py
index d966643590d2..a99cfbf7226f 100644
--- a/products/warehouse_sources/backend/ad_hoc_sync.py
+++ b/products/warehouse_sources/backend/ad_hoc_sync.py
@@ -11,9 +11,11 @@ behavior rather than just their shape.
"""
import time
+from typing import Any
from django.conf import settings
+import structlog
from asgiref.sync import async_to_sync
from temporalio.client import Client
from temporalio.common import WorkflowIDReusePolicy
@@ -22,7 +24,17 @@ from posthog.dataclasses import frozen
from posthog.temporal.utils import ExternalDataWorkflowInputs
from products.data_warehouse.backend.facade.api import pause_external_data_schedule, unpause_external_data_schedule
-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_schema import (
+ CDC_SNAPSHOT_LANE_KEY,
+ ExternalDataSchema,
+ update_sync_type_config_keys,
+)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import (
+ BUFFER_LANE,
+ resnapshot_stays_in_buffer,
+)
+
+logger = structlog.get_logger(__name__)
@frozen
@@ -89,17 +101,18 @@ def trigger_ad_hoc_sync(
except Exception as e:
raise SchedulePauseError(str(e)) from e
- # Single save: the reset, the CDC re-snapshot, and the auto-unpause marker in one round-trip.
+ # Single write: the reset, the CDC re-snapshot, and the auto-unpause marker in one round-trip.
# reset_pipeline goes on sync_type_config rather than the workflow input because the pipeline
# pops it after the first reset; on the input every activity retry would re-read True and wipe
# Delta plus the cursor, restarting from row 0.
- config_before = dict(schema.sync_type_config)
+ config_before = dict(schema.sync_type_config or {})
initial_sync_complete_before = schema.initial_sync_complete
- update_fields: list[str] = []
+ updates: dict[str, Any] = {}
+ removes: list[str] = []
+ extra_model_fields: dict[str, Any] = {}
if reset_pipeline:
- schema.sync_type_config["reset_pipeline"] = True
- update_fields.append("sync_type_config")
+ updates["reset_pipeline"] = True
# A streaming CDC schema no-ops a normal reset — CDCExtractionWorkflow owns it and the
# per-schema run raises CDCHandledExternally. Flip it back to snapshot so this run does a
# full re-snapshot. The job is created non-billable when the caller asks for that, and on
@@ -107,17 +120,27 @@ def trigger_ad_hoc_sync(
# stays billable. The save must precede the workflow start so the source reloads
# cdc_mode="snapshot" instead of racing on stale "streaming".
if schema.is_cdc and schema.cdc_mode == "streaming":
- schema.sync_type_config["cdc_mode"] = "snapshot"
- schema.sync_type_config.pop("cdc_last_log_position", None)
- schema.sync_type_config.pop("cdc_deferred_runs", None)
- schema.initial_sync_complete = False
- update_fields.append("initial_sync_complete")
+ # Decided while the table still streams. Without the marker, the next capture run would
+ # empty the buffer under the new snapshot, deleting changes an in-flight run wrote.
+ if resnapshot_stays_in_buffer(schema, logger):
+ updates[CDC_SNAPSHOT_LANE_KEY] = BUFFER_LANE
+ updates["cdc_mode"] = "snapshot"
+ removes += ["cdc_last_log_position", "cdc_deferred_runs"]
+ extra_model_fields["initial_sync_complete"] = False
if paused_now:
- schema.sync_type_config["admin_unpause_schedule_after_run"] = True
- if "sync_type_config" not in update_fields:
- update_fields.append("sync_type_config")
- if update_fields:
- schema.save(update_fields=update_fields)
+ updates["admin_unpause_schedule_after_run"] = True
+ staged = bool(updates or removes or extra_model_fields)
+ if staged:
+ # Merged under the row lock: capture writes this config concurrently, and saving the copy
+ # loaded above would revert whatever it wrote since.
+ schema.sync_type_config = update_sync_type_config_keys(
+ schema.id,
+ schema.team_id,
+ updates=updates,
+ removes=removes,
+ extra_model_fields=extra_model_fields or None,
+ )
+ schema.initial_sync_complete = extra_model_fields.get("initial_sync_complete", schema.initial_sync_complete)
inputs = ExternalDataWorkflowInputs(
team_id=schema.team_id,
@@ -134,18 +157,24 @@ def trigger_ad_hoc_sync(
# The unpause marker is only read by a workflow that never began, so the schedule would stay
# paused forever. And the staged reset would be consumed by the next *scheduled* run, which
# would wipe the Delta table, or re-snapshot a CDC schema whose log position staging already
- # deleted. Restoring the whole prior config covers the deleted keys, which a key-by-key undo
- # cannot.
+ # deleted. Every staged key goes back to its prior value, the deleted ones included, and
+ # keys other writers set in the meantime survive.
if paused_now:
try:
unpause_external_data_schedule(str(schema.id))
except Exception:
pass
- if update_fields:
- schema.sync_type_config = config_before
- schema.initial_sync_complete = initial_sync_complete_before
+ if staged:
+ staged_keys = [*updates, *removes]
try:
- schema.save(update_fields=["sync_type_config", "initial_sync_complete"])
+ schema.sync_type_config = update_sync_type_config_keys(
+ schema.id,
+ schema.team_id,
+ updates={key: config_before[key] for key in staged_keys if key in config_before},
+ removes=[key for key in staged_keys if key not in config_before],
+ extra_model_fields={"initial_sync_complete": initial_sync_complete_before},
+ )
+ schema.initial_sync_complete = initial_sync_complete_before
except Exception:
pass
raise WorkflowStartError(str(e)) from e
diff --git a/products/warehouse_sources/backend/facade/models.py b/products/warehouse_sources/backend/facade/models.py
index c71d86dba565..4f30a05fe3bb 100644
--- a/products/warehouse_sources/backend/facade/models.py
+++ b/products/warehouse_sources/backend/facade/models.py
@@ -30,6 +30,7 @@ from products.warehouse_sources.backend.models.external_data_job import (
latest_completed_job_prefetch,
)
from products.warehouse_sources.backend.models.external_data_schema import (
+ CDC_SNAPSHOT_LANE_KEY,
ExternalDataSchema,
auto_enable_new_schemas,
get_all_schemas_for_source_id,
@@ -126,6 +127,7 @@ __all__ = [
"update_should_sync",
"mark_schema_running_unless_halted",
"update_sync_type_config_keys",
+ "CDC_SNAPSHOT_LANE_KEY",
"validate_source_prefix",
"validate_warehouse_table_url_pattern",
]
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.py
index e51a61e9a1e3..fc4495c6e93f 100644
--- a/products/warehouse_sources/backend/facade/source_management.py
+++ b/products/warehouse_sources/backend/facade/source_management.py
@@ -25,6 +25,8 @@ _LAZY = {
"SELF_MANAGED_LAG_REASON": "cdc.broken",
"purge_buffer_prefix": "cdc.buffer",
"CDC_SEQ_COLUMN": "cdc.batcher",
+ "BUFFER_LANE": "cdc.snapshot_lane",
+ "resnapshot_stays_in_buffer": "cdc.snapshot_lane",
"ClickHouseConnectionError": "sources.clickhouse.clickhouse",
"ClickHouseSource": "sources.clickhouse.source",
"AnySource": "sources.common.base",
diff --git a/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.py b/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.py
index 12b67adf8009..85507f3e7e54 100644
--- a/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.py
+++ b/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.py
@@ -20,6 +20,7 @@ from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import (
+ CDC_SNAPSHOT_LANE_KEY,
ExternalDataSchema,
update_sync_type_config_keys,
)
@@ -31,6 +32,10 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import
purge_buffer_prefix,
)
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 (
+ cancel_running_sync,
+ snapshot_in_buffer,
+)
from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
BUFFERED_BEFORE_KEY,
serves_buffered_lane,
@@ -118,6 +123,9 @@ class Command(BaseCommand):
# schemas that consume the buffer (scheduled_sync_consumes_buffer), so the flip does
# not depend on the team's general rollout flag.
self._require_no_reserved_columns(eligible)
+ if rollback:
+ for schema in self._snapshots_in_buffer(source):
+ self.stdout.write(f" {schema.name}: snapshot running in the buffer, will restart on legacy")
if dry_run:
self.stdout.write(self.style.WARNING("Dry run — no changes made."))
return
@@ -127,6 +135,36 @@ class Command(BaseCommand):
else:
self._flip_to_buffered(source, eligible, cdc_schemas, options["drain_timeout"])
+ def _snapshots_in_buffer(self, source: ExternalDataSource) -> list[ExternalDataSchema]:
+ return sorted(
+ (
+ s
+ for s in ExternalDataSchema.objects.filter(source_id=source.id, deleted=False)
+ if s.is_cdc and snapshot_in_buffer(s)
+ ),
+ key=lambda s: s.name,
+ )
+
+ def _demote_snapshots_in_buffer(self, source: ExternalDataSource) -> None:
+ """Restart every snapshot the buffer carries as a legacy snapshot.
+
+ Only the buffer holds such a table's changes since its snapshot began, and legacy's hand-over
+ purges the whole buffer. Capture is idle here, so a snapshot that starts after this point reads
+ every change up to where capture stopped, and legacy capture defers the rest. The running
+ snapshot is cancelled first, so it cannot hand over without those changes.
+ """
+ for schema in self._snapshots_in_buffer(source):
+ cancel_running_sync(schema)
+ purge_buffer_prefix(schema.team_id, str(schema.id), logger, strict=True)
+ update_sync_type_config_keys(
+ schema.id,
+ schema.team_id,
+ updates={"cdc_mode": "snapshot", "reset_pipeline": True},
+ removes=[CDC_SNAPSHOT_LANE_KEY, "cdc_last_log_position"],
+ extra_model_fields={"initial_sync_complete": False},
+ )
+ self.stdout.write(f" {schema.name}: snapshot restarted on legacy")
+
def _require_no_reserved_columns(self, eligible: list[ExternalDataSchema]) -> None:
"""Refuse to flip a schema whose source table has a column named `_ph_cdc_seq`.
@@ -302,6 +340,12 @@ class Command(BaseCommand):
pause_cdc_extraction_schedule(source_id)
self.stdout.write("2/6 waiting for the in-flight extraction run to finish")
self._wait_for_extraction_idle(source_id, drain_timeout)
+ # Only once capture is idle, so no run can start another snapshot in the buffer afterwards.
+ try:
+ self._demote_snapshots_in_buffer(source)
+ except BaseException:
+ unpause_cdc_extraction_schedule(source_id)
+ raise
# The buffer's tail holds WAL the slot has already advanced past — it exists nowhere else.
# The consumer must apply it BEFORE legacy delivery resumes, or it is lost for good. Capture
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 2f3d48ea9123..cc205702fcfd 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -213,6 +213,11 @@ class ExternalDataSchemaQuerySet(models.QuerySet["ExternalDataSchema"]):
return updated
+# In `sync_type_config`: set while the S3 change buffer carries this table's snapshot. Cleared by the
+# snapshot to streaming flip. See cdc/snapshot_lane.py.
+CDC_SNAPSHOT_LANE_KEY = "cdc_snapshot_lane"
+
+
class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel, DeletedMetaFields):
# Kept on the model so the nested names and the `choices=` below stay unchanged.
Status = ExternalDataSchemaStatus
@@ -716,23 +721,30 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
partition_mode: Optional[PartitionMode],
partition_format: Optional[PartitionFormat],
) -> None:
- self.sync_type_config["partitioning_enabled"] = True
- self.sync_type_config["partition_count"] = partition_count
- self.sync_type_config["partition_size"] = partition_size
- self.sync_type_config["partitioning_keys"] = partitioning_keys
- self.sync_type_config["partition_mode"] = partition_mode
- self.sync_type_config["partition_format"] = partition_format
- # Consume any operator-pinned overrides: they've now been baked into the effective
- # settings above, so drop them. This makes the pin one-shot — a later reset falls
- # back to auto-detection instead of re-applying a stale pin (re-pin via the admin
- # repartition action if needed).
- self.sync_type_config.pop("partition_count_override", None)
- self.sync_type_config.pop("partition_size_override", None)
- self.sync_type_config.pop("partition_mode_override", None)
- self.sync_type_config.pop("partitioning_keys_override", None)
- # Pipeline-internal bookkeeping, not a user edit — skip_activity_log avoids the extra
- # `_get_before_update` SELECT (see save()).
- self.save(skip_activity_log=True)
+ # Merged under the row lock rather than saved from this copy, which the loader holds for the
+ # whole run while CDC capture writes the same JSON (the snapshot marker among it).
+ self.sync_type_config = update_sync_type_config_keys(
+ self.id,
+ self.team_id,
+ updates={
+ "partitioning_enabled": True,
+ "partition_count": partition_count,
+ "partition_size": partition_size,
+ "partitioning_keys": partitioning_keys,
+ "partition_mode": partition_mode,
+ "partition_format": partition_format,
+ },
+ # Consume any operator-pinned overrides: they've now been baked into the effective
+ # settings above, so drop them. This makes the pin one-shot — a later reset falls
+ # back to auto-detection instead of re-applying a stale pin (re-pin via the admin
+ # repartition action if needed).
+ removes=[
+ "partition_count_override",
+ "partition_size_override",
+ "partition_mode_override",
+ "partitioning_keys_override",
+ ],
+ )
# --- In-place repartition controller state ------------------------------------------------
# These keys drive the automated, no-source-pull repartition that bounds per-partition memory
@@ -1041,24 +1053,26 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
return str(value)
def update_sync_type_config_for_reset_pipeline(self, *, clear_initial_sync_complete: bool = True) -> None:
- self.sync_type_config.pop("reset_pipeline", None)
- # Any reset resolves a pending safe-widening marker; the re-created table adopts the new
- # type. column_type_widened_last_reset_at is deliberately kept so the auto-resync cooldown
- # survives the reset it timestamps.
- self.sync_type_config.pop("column_type_widened", None)
- self.sync_type_config.pop("incremental_field_last_value", None)
- self.sync_type_config.pop("incremental_field_earliest_value", None)
- self.sync_type_config.pop("incremental_staged", None)
- self.sync_type_config.pop("incremental_staged_pending", None)
- self.sync_type_config.pop("partitioning_enabled", None)
- self.sync_type_config.pop("partition_size", None)
- self.sync_type_config.pop("partition_count", None)
- self.sync_type_config.pop("partitioning_keys", None)
- self.sync_type_config.pop("partition_mode", None)
- self.sync_type_config.pop("backfilled_partition_format", None)
- self.sync_type_config.pop("xmin_last_value", None)
- self.sync_type_config.pop("xmin_ceiling", None)
- self.sync_type_config.pop("xmin_num_wraparound", None)
+ removes = [
+ "reset_pipeline",
+ # Any reset resolves a pending safe-widening marker; the re-created table adopts the new
+ # type. column_type_widened_last_reset_at is deliberately kept so the auto-resync cooldown
+ # survives the reset it timestamps.
+ "column_type_widened",
+ "incremental_field_last_value",
+ "incremental_field_earliest_value",
+ "incremental_staged",
+ "incremental_staged_pending",
+ "partitioning_enabled",
+ "partition_size",
+ "partition_count",
+ "partitioning_keys",
+ "partition_mode",
+ "backfilled_partition_format",
+ "xmin_last_value",
+ "xmin_ceiling",
+ "xmin_num_wraparound",
+ ]
# We don't reset partition_format
# We don't reset chunk_size_override
# We intentionally don't reset partition_count_override / partition_size_override /
@@ -1071,11 +1085,16 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
# it false between runs whenever a sync wrote zero rows (no Delta table means post-load
# never re-set it). Explicit resets (reset_pipeline, corruption rebuild, sync-method
# change, delete_table) keep clearing so CDC's False->True streaming flip still fires.
+ extra_model_fields = {"initial_sync_complete": False} if clear_initial_sync_complete else None
+
+ # Merged under the row lock rather than saved from this copy: the sync loaded it when it
+ # started, and CDC capture writes the same JSON meanwhile (the snapshot marker among it).
+ self.sync_type_config = update_sync_type_config_keys(
+ self.id, self.team_id, removes=removes, extra_model_fields=extra_model_fields
+ )
if clear_initial_sync_complete:
self.initial_sync_complete = False
- self.save(skip_activity_log=True)
-
def update_incremental_field_value(
self, last_value: Any, save: bool = True, type: Literal["last"] | Literal["earliest"] = "last"
) -> None:
@@ -1624,6 +1643,8 @@ def mark_initial_sync_complete(schema_id: str | uuid.UUID, team_id: int) -> None
if schema.is_cdc and schema.cdc_mode == "snapshot":
config = schema.sync_type_config or {}
config["cdc_mode"] = "streaming"
+ # In the same lock as the flip, so a hand-over retried after a failed flip still finds it.
+ config.pop(CDC_SNAPSHOT_LANE_KEY, None)
schema.sync_type_config = config
update_fields.append("sync_type_config")
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
index 0d343da0e8ba..93c8ddaf5646 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -43,6 +43,7 @@ from products.data_warehouse.backend.facade.api import (
update_external_job_status,
)
from products.warehouse_sources.backend.facade.models import (
+ CDC_SNAPSHOT_LANE_KEY,
ExternalDataJob,
ExternalDataSchema,
ExternalDataSchemaDestination,
@@ -55,6 +56,7 @@ from products.warehouse_sources.backend.facade.models import (
)
from products.warehouse_sources.backend.facade.pipelines import finish_row_tracking
from products.warehouse_sources.backend.facade.source_management import (
+ BUFFER_LANE,
CDC_SEQ_COLUMN,
AnySource,
RowFilterValidationError,
@@ -63,6 +65,7 @@ from products.warehouse_sources.backend.facade.source_management import (
filter_dwh_columns_by_enabled_columns as _filter_dwh_columns_by_enabled_columns,
get_cdc_adapter,
purge_buffer_prefix,
+ resnapshot_stays_in_buffer,
source_type_supports_cdc,
validate_and_coerce_row_filters,
)
@@ -175,11 +178,12 @@ def _reset_cdc_for_full_resnapshot(instance: ExternalDataSchema) -> None:
# Merge under a row lock so the reset can't clobber a concurrent CDC extract activity's
# sync_type_config writes (and the status/initial_sync_complete save below skips the JSON
# column, leaving no second window for the merged config to be overwritten).
+ updates: dict[str, Any] = {"reset_pipeline": True, "cdc_mode": "snapshot"}
+ removes = ["cdc_last_log_position", "cdc_deferred_runs"]
+ if resnapshot_stays_in_buffer(instance, logger):
+ updates[CDC_SNAPSHOT_LANE_KEY] = BUFFER_LANE
instance.sync_type_config = update_sync_type_config_keys(
- instance.id,
- instance.team_id,
- updates={"reset_pipeline": True, "cdc_mode": "snapshot"},
- removes=["cdc_last_log_position", "cdc_deferred_runs"],
+ instance.id, instance.team_id, updates=updates, removes=removes
)
instance.initial_sync_complete = False
instance.save(update_fields=["initial_sync_complete", "updated_at"])
@@ -1506,6 +1510,9 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
# Add table to capture set when enabling CDC or toggling sync on
if newly_set_to_cdc or (should_sync is True and not instance.should_sync):
adapter.add_table(source, db_schema, source_table_name)
+ # Capture skipped the table while it was out of the set, so its buffer has a gap. Without
+ # the marker, capture empties the buffer before the new snapshot instead of replaying it.
+ instance.sync_type_config.pop(CDC_SNAPSHOT_LANE_KEY, None)
# Always force a full re-snapshot on re-enable: while removed from the
# publication the replication slot kept advancing, so any changes made
@@ -1525,6 +1532,7 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
# Remove table from capture set when toggling sync off
elif should_sync is False and instance.should_sync:
adapter.remove_table(source, db_schema, source_table_name)
+ instance.sync_type_config.pop(CDC_SNAPSHOT_LANE_KEY, None)
class ExternalDataSchemaListSerializer(serializers.ModelSerializer):
@@ -1877,6 +1885,10 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# Reset CDC state so the next run does a full re-snapshot
updates["cdc_mode"] = "snapshot"
removes = ["cdc_last_log_position", "cdc_deferred_runs"]
+ # Without the marker, the next capture run would empty the buffer, deleting changes a
+ # capture run already in progress wrote after the snapshot started reading.
+ if resnapshot_stays_in_buffer(instance, logger):
+ updates[CDC_SNAPSHOT_LANE_KEY] = BUFFER_LANE
# Merge under a row lock so this reset can't clobber a concurrent CDC extract activity's
# sync_type_config writes. Persist BEFORE triggering the workflow so the Postgres source
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 050f9a20722b..bc948e1e7ace 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -35,6 +35,7 @@ from posthog.utils import get_machine_id
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import (
+ CDC_SNAPSHOT_LANE_KEY,
ExternalDataSchema,
complete_schema_run,
mark_schema_running_unless_halted,
@@ -76,10 +77,20 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import
classify_cdc_error,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import has_engine_seq
-from products.warehouse_sources.backend.temporal.data_imports.cdc.naming import cdc_qualified_table_name
+from products.warehouse_sources.backend.temporal.data_imports.cdc.naming import (
+ CDC_EXTRACTION_WORKFLOW_ID_PREFIX,
+ cdc_qualified_table_name,
+)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import (
+ BUFFER_LANE,
+ cancel_running_sync,
+ is_buffered_snapshot_enabled,
+ snapshot_in_buffer,
+)
from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
+ captures_to_buffer,
consolidated_resource_name,
- serves_buffered_lane,
+ snapshot_can_start_in_buffer,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import SyncTypeLiteral
@@ -121,9 +132,6 @@ CDC_MAX_EXTRACTION_ATTEMPTS = 3
# identical one says nothing new while burying the runs that do.
CDC_FAILURE_VISIBILITY_COOLDOWN = dt.timedelta(hours=1)
-# Every extraction run carries the schedule's workflow id, which is built from this prefix (see
-# _get_cdc_extraction_schedule_id). Scopes the cooldown lookup to change-capture runs.
-CDC_EXTRACTION_WORKFLOW_ID_PREFIX = "cdc-extraction-"
# Shown as latest_error on prior-run jobs reconciled by _reconcile_orphaned_prior_jobs.
CDC_ORPHANED_JOB_MESSAGE = (
@@ -263,6 +271,9 @@ class CDCExtractActivity:
# Table names whose changes this run delivers by buffer alone — no transforms, no
# sourcebatch dispatch. Resolved once in _setup.
self._buffered_table_names: set[str] = set()
+ self._source_buffered = False
+ self._buffered_snapshot_flag: bool | None = None
+ self._truncated_tables: list[str] = []
# ------------------------------------------------------------------
# Logger helpers
@@ -966,11 +977,12 @@ class CDCExtractActivity:
# events travel one lane. Deferred batches carry no position column, so nothing orders
# them against buffered writes — mixing lanes lets an older deferred row land after a
# newer buffered one. The consumer holds off too (has_batches_in_flight).
- self._buffered_table_names = {
- s.name
- for s in self.cdc_schemas
- if serves_buffered_lane(s) and not s.sync_type_config.get("cdc_deferred_runs")
- }
+ self._source_buffered = True
+ for schema in self.cdc_schemas:
+ if schema.sync_type_config.get("cdc_deferred_runs"):
+ continue
+ if captures_to_buffer(schema) or self._start_snapshot_in_buffer(schema):
+ self._buffered_table_names.add(schema.name)
if self._buffered_table_names:
self.log.info(
"cdc_buffered_ingress_active",
@@ -986,6 +998,35 @@ class CDCExtractActivity:
self.log.info("cdc_extract_retry_attempt", attempt=attempt)
return True
+ def _buffered_snapshot_enabled(self) -> bool:
+ if self._buffered_snapshot_flag is None:
+ self._buffered_snapshot_flag = is_buffered_snapshot_enabled(self.inputs.team_id, self.log)
+ return self._buffered_snapshot_flag
+
+ def _start_snapshot_in_buffer(self, schema: ExternalDataSchema) -> bool:
+ """Route a snapshotting table the buffer does not carry yet to the buffer, if the flag allows.
+
+ Only a table with no deferred runs gets here, so none of its changes since the snapshot began
+ went to the legacy lane. Its buffer is emptied first: files left from before a gap in capture,
+ such as a re-enable, must not be replayed over the snapshot.
+ """
+ if not (snapshot_can_start_in_buffer(schema) and self._buffered_snapshot_enabled()):
+ return False
+ purge_buffer_prefix(schema.team_id, str(schema.id), self._schema_log(schema), strict=True)
+
+ def _mark_if_still_snapshotting(config: dict[str, typing.Any]) -> None:
+ # Read under the row lock. A hand-over that flipped the table to streaming after this run
+ # loaded it has already cleared the marker, and a new one would outlive the snapshot. The
+ # table's changes still belong in the buffer, which its streaming consumer now reads.
+ if config.get("cdc_mode") == "snapshot":
+ config[CDC_SNAPSHOT_LANE_KEY] = BUFFER_LANE
+
+ self._update_schema_sync_type_config(schema, mutate=_mark_if_still_snapshotting)
+ self._schema_log(schema).info(
+ "cdc_snapshot_started_in_buffer", schema_id=str(schema.id), marked=snapshot_in_buffer(schema)
+ )
+ return True
+
def _delete_own_schedule(self) -> None:
try:
from products.data_warehouse.backend.facade.api import delete_cdc_extraction_schedule
@@ -1330,6 +1371,7 @@ class CDCExtractActivity:
self.last_complete_txn_end_lsn is not None
and self.last_complete_txn_end_lsn != self.last_confirmed_lsn
):
+ self._handle_truncates()
self._confirm_position(self.last_complete_txn_end_lsn)
self.last_confirmed_lsn = self.last_complete_txn_end_lsn
self.log.info(
@@ -1387,6 +1429,7 @@ class CDCExtractActivity:
commit_lsn = self.reader.last_commit_end_lsn
if commit_lsn is not None and commit_lsn != self.last_confirmed_lsn:
+ self._handle_truncates()
self._confirm_position(commit_lsn)
self.last_confirmed_lsn = commit_lsn
self.last_end_lsn = commit_lsn
@@ -1420,11 +1463,13 @@ class CDCExtractActivity:
def _handle_truncates(self) -> list[str]:
"""Process any truncated tables observed during decoding.
- Returns the list of truncated table names so the no-changes path can
- decide whether to advance the slot.
+ 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.
"""
truncated_tables = list(self.reader.truncated_tables)
self.reader.clear_truncated_tables()
+ self._truncated_tables.extend(truncated_tables)
# The decoder names a table `schema.table`, while a schema created with a source schema set is
# stored bare, so the lookup goes through the same map as the change events.
stored_names = self._build_event_name_map()
@@ -1437,25 +1482,47 @@ class CDCExtractActivity:
)
self._reset_schema_to_snapshot(trunc_schema)
self._unpause_schema_schedule(trunc_schema)
- return truncated_tables
+ 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)
+ # 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:
+ self.batcher.discard(schema.name)
+ # Purged before the marker is set, because the hand-over keeps every file of a marked schema.
+ # On a buffered source a stale file can outlive the run and be replayed, so a failed purge
+ # fails the run while the slot still holds the TRUNCATE, and the next run repeats the reset.
+ purge_buffer_prefix(schema.team_id, str(schema.id), self._schema_log(schema), strict=self._source_buffered)
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}
+ # 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 (
+ snapshot_in_buffer(schema) or self._buffered_snapshot_enabled()
+ ):
+ updates[CDC_SNAPSHOT_LANE_KEY] = BUFFER_LANE
+ else:
+ removes.append(CDC_SNAPSHOT_LANE_KEY)
+ # The unmarked hand-over purges the buffer, so the rest of this run's changes go to
+ # deferred runs, as the next run's will.
+ self._buffered_table_names.discard(schema.name)
# reset_pipeline forces the batch import to wipe the table first (handle_reset_or_full_refresh),
# preventing pre-truncate rows from surviving a TRUNCATE or lost-slot re-snapshot.
self._update_schema_sync_type_config(
schema,
- updates={"cdc_mode": "snapshot", "reset_pipeline": True},
+ updates=updates,
removes=removes,
extra_model_fields={"initial_sync_complete": False},
)
- # The reset invalidates every buffered change file: the table is wiped and
- # re-seeded through the snapshot lane the buffer never sees, and the filename
- # contract has no way to express that discontinuity. Best-effort purge.
- purge_buffer_prefix(schema.team_id, str(schema.id), self._schema_log(schema))
if clear_deferred_runs:
self._emit_deferred_runs_depth()
@@ -1578,15 +1645,18 @@ class CDCExtractActivity:
tracker.job.save(update_fields=["rows_synced", "status", "finished_at", "updated_at"])
def _advance_slot_after_run(self) -> None:
- """Advance the slot to the last LSN if the final flush moved past the last incremental advance.
+ """Advance the slot past everything this run read, once the final flush has landed.
- Intermediate micro-batches already advanced the slot incrementally inside the
- read loop, so this only fires if the final flush contained new events beyond
- the last incremental advance.
+ A read always stops at a transaction boundary, and by now every event up to the decoder's
+ last commit is flushed. Confirming that commit rather than the last event also moves past
+ trailing transactions with no row events. A TRUNCATE on its own is one: this run already
+ handled it, and reading it again would reset the table a second time.
"""
- if self.last_end_lsn is not None and self.last_end_lsn != self.last_confirmed_lsn:
- self._confirm_position(self.last_end_lsn)
- self.log.info("slot_advanced", position=self.last_end_lsn)
+ target = self.reader.last_commit_end_lsn or self.last_end_lsn
+ if target is not None and target != self.last_confirmed_lsn:
+ self._confirm_position(target)
+ self.last_end_lsn = target
+ self.log.info("slot_advanced", position=target)
def _update_log_positions(self) -> None:
"""Update per-schema cdc_last_log_position (skip schemas reset to snapshot mode)."""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py
index 568b9e13e9a9..337bb3bcfcfb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py
@@ -90,6 +90,7 @@ class ChangeEventBatcher:
position_to_seq: Callable[[str], int] | None = None,
) -> None:
self._events: defaultdict[str, list[ChangeEvent]] = defaultdict(list)
+ self._table_bytes: defaultdict[str, int] = defaultdict(int)
self._estimated_bytes: int = 0
self._max_events = max_events
self._max_bytes = max_bytes
@@ -98,8 +99,10 @@ class ChangeEventBatcher:
self._position_to_seq = position_to_seq
def add(self, event: ChangeEvent) -> None:
+ size = self._estimate_event_bytes(event)
self._events[event.table_name].append(event)
- self._estimated_bytes += self._estimate_event_bytes(event)
+ self._table_bytes[event.table_name] += size
+ self._estimated_bytes += size
@property
def should_flush(self) -> bool:
@@ -119,9 +122,15 @@ class ChangeEventBatcher:
result[table_name] = _events_to_table(events, position_to_seq=self._position_to_seq)
self._events.clear()
+ self._table_bytes.clear()
self._estimated_bytes = 0
return result
+ def discard(self, table_name: str) -> None:
+ """Drop a table's pending events so no later flush writes them."""
+ self._events.pop(table_name, None)
+ self._estimated_bytes -= self._table_bytes.pop(table_name, 0)
+
@property
def event_count(self) -> int:
return sum(len(events) for events in self._events.values())
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 630ddd87839d..c2d31c52b55d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py
@@ -49,13 +49,13 @@ from django.conf import settings
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq
-import posthoganalytics
from structlog.types import FilteringBoundLogger
from posthog.dataclasses import frozen
from products.data_warehouse.backend.facade.api import get_s3_client
from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN
+from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import team_flag_enabled
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common import (
ensure_bucket,
strip_s3_protocol,
@@ -84,30 +84,7 @@ def is_shadow_write_enabled(team_id: int, logger: FilteringBoundLogger) -> bool:
Never raises: a flag-service failure leaves the lane off, which costs a gap in
validation data — the legacy path is unaffected either way.
"""
- from posthog.models.team import Team
-
- try:
- team = Team.objects.get(pk=team_id)
- return bool(
- posthoganalytics.feature_enabled(
- SHADOW_WRITE_FLAG,
- str(team.uuid),
- groups={"organization": str(team.organization_id), "project": str(team.id)},
- # team_id drives the release conditions (the warehouse convention for
- # per-team rollouts); the group context is passed for consistency with
- # the other warehouse flags and for org-wide kill switches.
- person_properties={"team_id": str(team.id)},
- group_properties={
- "organization": {"id": str(team.organization_id)},
- "project": {"id": str(team.id)},
- },
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
- )
- except Exception:
- logger.warning("cdc_shadow_flag_check_failed", team_id=team_id, exc_info=True)
- return False
+ return team_flag_enabled(SHADOW_WRITE_FLAG, team_id, logger)
def get_buffer_prefix(team_id: int, schema_id: str) -> str:
@@ -331,11 +308,11 @@ class CDCBufferWriter:
def purge_buffer_prefix(team_id: int, schema_id: str, logger: FilteringBoundLogger, *, strict: bool = False) -> None:
"""Remove a schema's entire buffer prefix.
- Called on schema reset (TRUNCATE / lost-slot re-snapshot) and again right before the
- snapshot→streaming flip: the table is wiped and re-seeded through the snapshot lane the
- buffer never sees, so every existing buffer file predates a discontinuity no consumer
- could order across. Best-effort by default; `strict` propagates failures (except a
- missing prefix) for callers where a survived stale file would corrupt the table.
+ Called when a table is emptied for a new snapshot (TRUNCATE, lost slot, repair), and at the
+ snapshot→streaming flip when the snapshot's changes went to legacy deferred runs: there every
+ buffer file predates a gap no consumer could order across. Best-effort by default; `strict`
+ propagates failures (except a missing prefix) for callers where a survived stale file would
+ corrupt the table.
"""
prefix = strip_s3_protocol(get_buffer_prefix(team_id, schema_id))
try:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/naming.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/naming.py
index 96a296c12c73..832ac4f0cc2a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/naming.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/naming.py
@@ -5,6 +5,10 @@ from __future__ import annotations
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+# Every extraction run carries the schedule's workflow id, which is built from this prefix (see
+# _get_cdc_extraction_schedule_id). A table's scheduled sync uses the schema id instead.
+CDC_EXTRACTION_WORKFLOW_ID_PREFIX = "cdc-extraction-"
+
def cdc_qualified_table_name(schema: ExternalDataSchema, default_schema: str | None) -> str:
"""Resolve a CDC schema row to its source-qualified `schema.table` name.
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
new file mode 100644
index 000000000000..789365668a76
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/snapshot_lane.py
@@ -0,0 +1,118 @@
+"""Which lane carries a CDC table's changes while it takes a snapshot on a buffered source.
+
+The buffer can carry them only when it holds every change since the table's buffer was last
+emptied. Replaying an unbroken run of changes over the snapshot, in order, converges on the
+source's state even when some of them predate the snapshot, so the hand-over deletes nothing. A
+gap breaks that: an older change replayed without the ones after it leaves a stale row.
+
+A marker on the schema records that the buffer carries the current snapshot. Routing and the
+hand-over read the marker, never the flag, so one snapshot never splits between the buffer and
+legacy deferred runs when the flag flips or its evaluation fails. Kept free of the pipeline
+imports, so the schema API can call it.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import posthoganalytics
+from structlog.types import FilteringBoundLogger
+from temporalio.service import RPCError, RPCStatusCode
+
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import CDC_SNAPSHOT_LANE_KEY
+from products.warehouse_sources.backend.temporal.data_imports.cdc.naming import CDC_EXTRACTION_WORKFLOW_ID_PREFIX
+from products.warehouse_sources.backend.temporal.data_imports.cdc.types import parse_ingest_mode
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+# Gates starting a snapshot in the buffer. Turned on once no worker runs the previous release: an
+# older worker ignores the marker, so it would defer that table's changes or purge its buffer.
+BUFFERED_SNAPSHOT_FLAG = "dwh-cdc-buffered-snapshot"
+BUFFER_LANE = "buffer"
+
+
+def team_flag_enabled(flag: str, team_id: int, logger: FilteringBoundLogger) -> bool:
+ """Evaluate a per-team warehouse flag. Never raises: a flag-service failure reads as off."""
+ from posthog.models.team import Team
+
+ try:
+ team = Team.objects.get(pk=team_id)
+ return bool(
+ posthoganalytics.feature_enabled(
+ flag,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ # team_id drives the release conditions (the warehouse convention for
+ # per-team rollouts); the group context is passed for consistency with
+ # the other warehouse flags and for org-wide kill switches.
+ person_properties={"team_id": str(team.id)},
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ "project": {"id": str(team.id)},
+ },
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ logger.warning("cdc_flag_check_failed", flag=flag, team_id=team_id, exc_info=True)
+ return False
+
+
+def is_buffered_snapshot_enabled(team_id: int, logger: FilteringBoundLogger) -> bool:
+ return team_flag_enabled(BUFFERED_SNAPSHOT_FLAG, team_id, logger)
+
+
+def snapshot_in_buffer(schema: ExternalDataSchema) -> bool:
+ """Whether the buffer carries this schema's current snapshot."""
+ return (schema.sync_type_config or {}).get(CDC_SNAPSHOT_LANE_KEY) == BUFFER_LANE
+
+
+def resnapshot_stays_in_buffer(schema: ExternalDataSchema, logger: FilteringBoundLogger) -> bool:
+ """Whether a reset of this schema to snapshot keeps its changes in the buffer.
+
+ True for a table whose changes already go to the buffer: a streaming table on a buffered source
+ with no deferred runs left, or one already snapshotting there. Its buffer holds an unbroken run
+ of changes up to the reset, and a capture run in progress keeps adding to it. Any other table is
+ decided by capture, which first empties the buffer, because files from before a gap in capture
+ must not be replayed.
+ """
+ if snapshot_in_buffer(schema):
+ return True
+ return (
+ parse_ingest_mode(schema.source.job_inputs) == "buffered"
+ and schema.cdc_mode == "streaming"
+ and schema.initial_sync_complete
+ and not (schema.sync_type_config or {}).get("cdc_deferred_runs")
+ and is_buffered_snapshot_enabled(schema.team_id, logger)
+ )
+
+
+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.
+ """
+ # 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
+
+ job = (
+ ExternalDataJob.objects.filter(
+ team_id=schema.team_id, schema_id=schema.id, status=ExternalDataJob.Status.RUNNING
+ )
+ .exclude(workflow_id__isnull=True)
+ .exclude(workflow_id__startswith=CDC_EXTRACTION_WORKFLOW_ID_PREFIX)
+ .order_by("-created_at")
+ .first()
+ )
+ if job is None or not job.workflow_id:
+ return None
+ try:
+ cancel_external_data_workflow(job.workflow_id)
+ except RPCError as e:
+ if e.status != RPCStatusCode.NOT_FOUND:
+ raise
+ 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 da2691193eb2..39c0edabe5cb 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
@@ -41,6 +41,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import
BufferFileSpan,
get_buffer_prefix,
parse_buffer_file_name,
+ purge_buffer_prefix,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.companion_jobs import COMPANION_JOB_IDS_KEY
from products.warehouse_sources.backend.temporal.data_imports.cdc.lane_position import (
@@ -54,6 +55,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolutio
drop_superseded_rows,
has_engine_seq,
)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import snapshot_in_buffer
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import parse_ingest_mode
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
normalize_column_name,
@@ -125,6 +127,42 @@ def serves_buffered_lane(schema: ExternalDataSchema) -> bool:
)
+def captures_to_buffer(schema: ExternalDataSchema) -> bool:
+ """Schema-side condition for capture to write this schema's changes into the buffer.
+
+ Wider than `serves_buffered_lane`: a table whose snapshot the buffer carries is captured too,
+ and the consumer reads those changes once the snapshot completes.
+ """
+ return bool(
+ schema.is_cdc
+ and schema.cdc_table_mode in _LANE_WRITE_MODES
+ and (serves_buffered_lane(schema) or snapshot_in_buffer(schema))
+ )
+
+
+def snapshot_can_start_in_buffer(schema: ExternalDataSchema) -> bool:
+ """Schema-side condition for routing a snapshotting table the buffer does not carry yet to it."""
+ return bool(
+ schema.is_cdc
+ and schema.cdc_mode == "snapshot"
+ and schema.cdc_table_mode in _LANE_WRITE_MODES
+ and not snapshot_in_buffer(schema)
+ )
+
+
+def purge_buffer_before_handover(schema: ExternalDataSchema, logger: FilteringBoundLogger) -> None:
+ """Before a snapshot hands over to streaming, drop the buffer files it must not replay.
+
+ When the buffer carried the snapshot, it holds an unbroken run of changes, and replaying all of
+ them over the snapshot converges, so nothing goes. Otherwise the snapshot's changes went to
+ legacy deferred runs, and every file predates a gap: an old file replayed after them would bring
+ back rows. Strict, because a surviving stale file corrupts the table.
+ """
+ if snapshot_in_buffer(schema):
+ return
+ purge_buffer_prefix(schema.team_id, str(schema.id), logger, strict=True)
+
+
def consumes_buffer(schema: ExternalDataSchema, *, ingest_mode: str) -> bool:
"""Whether this schema's changes are delivered through the buffer."""
return ingest_mode == "buffered" and serves_buffered_lane(schema)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py
index c8e2d2f2255b..3db4312f420d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py
@@ -49,6 +49,17 @@ def _make_event(
class TestChangeEventBatcher:
+ def test_discarding_a_table_releases_its_share_of_the_flush_budget(self):
+ batcher = ChangeEventBatcher(max_bytes=1)
+ batcher.add(_make_event(table="users"))
+ batcher.add(_make_event(table="orders"))
+
+ batcher.discard("users")
+ batcher.discard("orders")
+
+ assert batcher.event_count == 0
+ assert batcher.should_flush is False
+
def test_empty_flush(self):
batcher = ChangeEventBatcher()
result = batcher.flush()
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.py
index 82338642f3c8..09d12de615bc 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
@@ -76,7 +76,7 @@ class TestIsShadowWriteEnabled:
with (
patch.dict("sys.modules", {"posthog.models.team": MagicMock(Team=team_manager)}),
patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.buffer.posthoganalytics.feature_enabled",
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane.posthoganalytics.feature_enabled",
flag_fn,
),
):
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 74361b1ae70c..2e36d96e4d77 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
@@ -11,11 +11,12 @@ from django.db.utils import InterfaceError, OperationalError
import pyarrow as pa
import psycopg.errors
from parameterized import parameterized
+from temporalio.service import RPCError, RPCStatusCode
from posthog.temporal.common.errors import NonReportableError
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_schema import CDC_SNAPSHOT_LANE_KEY, ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.cdc.activities import (
CDC_BACKPRESSURE_STUCK_AGE,
@@ -31,6 +32,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.types import ChangeEvent
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
BatchQueue,
@@ -165,6 +167,10 @@ def _fake_mark_schema_running_unless_halted(schema):
def _stub_sync_type_config_merge():
"""Route every activity sync_type_config write onto the in-memory mock schema (no DB)."""
with (
+ patch(
+ "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.mark_schema_running_unless_halted",
side_effect=_fake_mark_schema_running_unless_halted,
@@ -212,7 +218,7 @@ def _setup_mocks(
MockSourceModel.objects.get.return_value = source
mock_get_schemas.return_value = schemas
- mock_reader = MagicMock()
+ mock_reader = MagicMock(last_commit_end_lsn=None)
mock_reader.read_changes.return_value = iter(events)
mock_reader.truncated_tables = []
# Below CDC_MAX_CHANGES_PER_READ so the bounded read loop treats this as a single drained pass.
@@ -1032,7 +1038,7 @@ class TestCDCExtractActivity:
schema = _make_schema("users", cdc_mode="streaming", source=source)
mock_get_schemas.return_value = [schema]
- mock_reader = MagicMock()
+ mock_reader = MagicMock(last_commit_end_lsn=None)
mock_reader.read_changes.return_value = iter([])
mock_reader.truncated_tables = []
mock_reader.last_rows_consumed = 0
@@ -1176,7 +1182,7 @@ class TestCDCExtractActivity:
schema = _make_schema("users", cdc_mode="streaming", source=source)
mock_get_schemas.return_value = [schema]
- mock_reader = MagicMock()
+ mock_reader = MagicMock(last_commit_end_lsn=None)
mock_reader.read_changes.side_effect = RuntimeError("connection lost")
mock_reader.truncated_tables = []
mock_adapter = MagicMock()
@@ -1436,7 +1442,7 @@ class TestCDCExtractActivity:
schema = _make_schema("users", cdc_mode="streaming", source=source)
mock_get_schemas.return_value = [schema]
- mock_reader = MagicMock()
+ mock_reader = MagicMock(last_commit_end_lsn=None)
mock_reader.read_changes.return_value = iter([]) # no DML events
mock_reader.truncated_tables = ["users"]
mock_reader.last_rows_consumed = 0
@@ -2195,7 +2201,7 @@ class TestErrorClassification:
schema = _make_schema("users", cdc_mode="streaming", source=source)
mock_get_schemas.return_value = [schema]
- mock_reader = MagicMock()
+ mock_reader = MagicMock(last_commit_end_lsn=None)
mock_reader.read_changes.side_effect = psycopg.errors.InvalidPassword(
'password authentication failed for user "test"'
)
@@ -2282,7 +2288,7 @@ class TestErrorClassification:
schema = _make_schema("users", cdc_mode="streaming", source=source)
mock_get_schemas.return_value = [schema]
- mock_reader = MagicMock()
+ mock_reader = MagicMock(last_commit_end_lsn=None)
mock_reader.read_changes.side_effect = exc_cls(exc_message)
mock_reader.truncated_tables = []
mock_adapter = MagicMock()
@@ -2349,7 +2355,7 @@ class TestErrorClassification:
schema = _make_schema("users", cdc_mode="streaming", source=source)
mock_get_schemas.return_value = [schema]
- mock_reader = MagicMock()
+ mock_reader = MagicMock(last_commit_end_lsn=None)
mock_adapter = MagicMock()
mock_adapter.create_reader.return_value = mock_reader
mock_adapter.is_slot_invalidation_error.return_value = False
@@ -2402,7 +2408,7 @@ class TestErrorClassification:
schema = _make_schema("users", cdc_mode="streaming", source=source)
mock_get_schemas.return_value = [schema]
- mock_reader = MagicMock()
+ mock_reader = MagicMock(last_commit_end_lsn=None)
mock_reader.read_changes.side_effect = psycopg.errors.InvalidPassword(
'password authentication failed for user "test"'
)
@@ -2450,7 +2456,7 @@ class TestErrorClassification:
schema = _make_schema("users", cdc_mode="streaming", source=source)
mock_get_schemas.return_value = [schema]
- mock_reader = MagicMock()
+ mock_reader = MagicMock(last_commit_end_lsn=None)
mock_reader.read_changes.side_effect = psycopg.OperationalError(
'connection to server at "db" failed: Connection refused'
)
@@ -2504,7 +2510,7 @@ class TestErrorClassification:
mock_get_schemas.return_value = [schema]
# A non-psycopg error the adapter can't classify falls back to retryable UNKNOWN.
- mock_reader = MagicMock()
+ mock_reader = MagicMock(last_commit_end_lsn=None)
mock_reader.read_changes.side_effect = RuntimeError("arrow merge blew up")
mock_reader.truncated_tables = []
mock_adapter = MagicMock()
@@ -2565,7 +2571,7 @@ class TestErrorClassification:
schema = _make_schema("users", cdc_mode="streaming", source=source)
mock_get_schemas.return_value = [schema]
- mock_reader = MagicMock()
+ mock_reader = MagicMock(last_commit_end_lsn=None)
mock_reader.read_changes.side_effect = psycopg.errors.SyntaxError("invalid syntax")
mock_reader.truncated_tables = []
mock_adapter = MagicMock()
@@ -2608,7 +2614,7 @@ class TestSlotInvalidationRecovery:
'can no longer get changes from replication slot "posthog_slot"\n'
"DETAIL: This slot has been invalidated because it exceeded the maximum reserved size."
)
- mock_reader = MagicMock()
+ mock_reader = MagicMock(last_commit_end_lsn=None)
mock_reader.read_changes.side_effect = invalidation_error
mock_reader.truncated_tables = []
@@ -2899,7 +2905,7 @@ class TestFailureVisibilityJobs:
MockSourceModel.objects.get.return_value = source
mock_get_schemas.return_value = schemas
- mock_reader = MagicMock()
+ mock_reader = MagicMock(last_commit_end_lsn=None)
mock_reader.read_changes.side_effect = error
mock_reader.truncated_tables = []
mock_adapter = MagicMock()
@@ -3678,8 +3684,22 @@ class TestBufferedIngressCapture:
# keep today's transforms and sourcebatch dispatch, and a buffer failure must fail the run —
# the slot is about to advance past those changes.
- def _run(self, MockBufferWriter, events, schemas, source, capture: dict | None = None):
+ def _run(
+ self,
+ MockBufferWriter,
+ events,
+ schemas,
+ source,
+ capture: dict | None = None,
+ truncated=(),
+ snapshot_flag=True,
+ commit_end_lsn=None,
+ ):
with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.is_buffered_snapshot_enabled",
+ return_value=snapshot_flag,
+ ),
patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections"),
patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob") as MockJob,
patch(
@@ -3719,6 +3739,8 @@ class TestBufferedIngressCapture:
events,
)
mock_get_adapter.return_value.parse_cdc_config.return_value.ingest_mode = "buffered"
+ mock_reader.truncated_tables = list(truncated)
+ mock_reader.last_commit_end_lsn = commit_end_lsn
if capture is not None:
capture["reader_ref"] = mock_reader
capture["complete_schema_run"] = mock_complete
@@ -3746,19 +3768,155 @@ class TestBufferedIngressCapture:
# The point of the whole design: durable buffer releases the customer's WAL immediately.
mock_reader.confirm_position.assert_called_once_with("0/200")
+ @parameterized.expand(
+ [
+ ("flag_on_starts_it_in_the_buffer", True, {}, True),
+ ("flag_off_keeps_it_on_deferred_runs", False, {}, False),
+ (
+ "a_snapshot_already_in_the_buffer_stays_there_when_the_flag_is_off",
+ False,
+ {CDC_SNAPSHOT_LANE_KEY: "buffer"},
+ True,
+ ),
+ ]
+ )
+ @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_an_ineligible_schema_on_a_flipped_source_keeps_the_legacy_path(self, MockBufferWriter):
+ def test_a_snapshotting_tables_changes_follow_its_snapshot_lane(
+ self, _name, snapshot_flag, config, buffered, MockBufferWriter, mock_purge
+ ):
source = _make_source()
- # No table yet, so the buffer has nothing to merge its changes into.
- seeding = _make_schema("events", cdc_mode="streaming", source=source)
+ seeding = _make_schema("events", cdc_mode="snapshot", source=source)
seeding.initial_sync_complete = False
+ seeding.sync_type_config.update(config)
events = [_make_event(op="I", position="0/100", table="events", columns={"id": 1})]
- _reader, mock_s3, mock_producer = self._run(MockBufferWriter, events, [seeding], source)
+ _reader, mock_s3, _producer = self._run(
+ MockBufferWriter, events, [seeding], source, snapshot_flag=snapshot_flag
+ )
+ assert MockBufferWriter.return_value.write_batch.called is buffered
+ assert mock_s3.write_batch.called is not buffered
+ assert (seeding.sync_type_config.get(CDC_SNAPSHOT_LANE_KEY) == "buffer") is buffered
+ # Only a snapshot starting in the buffer empties it: files from before a gap must not replay.
+ assert [c.kwargs["strict"] for c in mock_purge.call_args_list] == ([True] if buffered and not config else [])
+
+ def test_a_truncate_is_handled_before_the_slot_advances_past_it(self):
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ act = _make_extract_activity(source)
+ act.cdc_schemas = [schema]
+ act.schema_by_name = {"users": schema}
+ act._buffered_table_names = {"users"}
+ act.batcher = MagicMock(event_count=0)
+ act.reader = MagicMock(truncated_tables=["users"], last_commit_end_lsn="0/300")
+ order = MagicMock()
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix",
+ side_effect=lambda *_a, **_k: order.purge(),
+ ),
+ patch.object(act, "_confirm_position", side_effect=lambda *_a: order.confirm()),
+ patch.object(act, "_unpause_schema_schedule"),
+ ):
+ act._drain_and_advance_page()
+
+ assert [call[0] for call in order.mock_calls] == ["purge", "confirm"]
+
+ @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_truncate_drops_the_tables_pending_changes_and_purges_strictly(self, MockBufferWriter, mock_purge):
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ events = [_make_event(op="I", position="0/100", columns={"id": 1})]
+
+ # The TRUNCATE commits after the last row event, in a transaction of its own.
+ reader, _s3, _producer = self._run(
+ MockBufferWriter, events, [schema], source, truncated=["users"], commit_end_lsn="0/300"
+ )
+
+ # Confirming only the last event's position would read the TRUNCATE again and reset the table
+ # a second time, dropping changes a snapshot started in between never saw.
+ assert reader.confirm_position.call_args_list[-1].args == ("0/300",)
MockBufferWriter.return_value.write_batch.assert_not_called()
- mock_s3.write_batch.assert_called_once()
- mock_producer.send_batch_notification.assert_called_once()
+ assert mock_purge.call_args.kwargs["strict"] is True
+ assert schema.sync_type_config["cdc_mode"] == "snapshot"
+ assert schema.sync_type_config[CDC_SNAPSHOT_LANE_KEY] == "buffer"
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix",
+ side_effect=Exception("s3 down"),
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
+ def test_a_failed_purge_after_a_truncate_leaves_the_table_unmarked(self, MockBufferWriter, _mock_purge):
+ # The hand-over keeps every file of a marked schema, so a marker left by a failed purge would
+ # replay the pre-TRUNCATE files over the re-snapshot.
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ events = [_make_event(op="I", position="0/100", columns={"id": 1})]
+ captured: dict = {}
+
+ with pytest.raises(Exception, match="s3 down"):
+ self._run(MockBufferWriter, events, [schema], source, capture=captured, truncated=["users"])
+
+ captured["reader_ref"].confirm_position.assert_not_called()
+ assert schema.sync_type_config["cdc_mode"] == "streaming"
+ assert CDC_SNAPSHOT_LANE_KEY not in schema.sync_type_config
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")
+ def test_a_snapshot_that_hands_over_first_is_left_unmarked(self, mock_purge):
+ # The hand-over clears the marker when it flips the table. A marker set after the flip would
+ # outlive the snapshot, and the rollback command would refuse the source for good.
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="snapshot", source=source)
+ act = _make_extract_activity(source)
+ mock_purge.side_effect = lambda *_a, **_k: schema.sync_type_config.update(cdc_mode="streaming")
+
+ with patch.object(act, "_buffered_snapshot_enabled", return_value=True):
+ assert act._start_snapshot_in_buffer(schema) is True
+
+ assert CDC_SNAPSHOT_LANE_KEY not in schema.sync_type_config
+
+ @parameterized.expand(
+ [
+ ("cancelled", None),
+ ("already_finished", RPCError("workflow not found", RPCStatusCode.NOT_FOUND, b"")),
+ ("temporal_unavailable", RPCError("unavailable", RPCStatusCode.UNAVAILABLE, b"")),
+ ]
+ )
+ @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):
+ # 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)
+ 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(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.cancel_running_sync",
+ cancel_running_sync,
+ ),
+ patch(
+ "products.data_warehouse.backend.facade.api.cancel_external_data_workflow",
+ side_effect=cancel_error,
+ ) as cancel,
+ ):
+ if fails:
+ with pytest.raises(RPCError):
+ act._reset_schema_to_snapshot(schema)
+ else:
+ act._reset_schema_to_snapshot(schema)
+
+ 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)
@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):
@@ -3838,15 +3996,9 @@ class TestBufferedIngressCapture:
# tick would erase a failing consumer run within a minute and hide a buffer backlog.
source = _make_source()
buffered = _make_schema("users", cdc_mode="streaming", source=source)
- legacy = _make_schema("events", cdc_mode="streaming", source=source)
- legacy.initial_sync_complete = False
- events = [
- _make_event(op="I", position="0/100", columns={"id": 1}),
- _make_event(op="I", position="0/100", table="events", columns={"id": 1}),
- ]
+ events = [_make_event(op="I", position="0/100", columns={"id": 1})]
captured: dict = {}
- self._run(MockBufferWriter, events, [buffered, legacy], source, capture=captured)
+ self._run(MockBufferWriter, events, [buffered], source, capture=captured)
- repainted = [call.args[0].name for call in captured["complete_schema_run"].call_args_list]
- assert repainted == ["events"]
+ captured["complete_schema_run"].assert_not_called()
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.py
index 39749af5eb57..bad46d08f5f9 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
@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import build_buffer_file_name
from products.warehouse_sources.backend.temporal.data_imports.cdc.lane_position import LanePosition
+from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import resnapshot_stays_in_buffer
from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
COMPANION_WRITE_MODE,
CONSOLIDATED_WRITE_MODE,
@@ -26,6 +27,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager
CDCSourceManager,
ReplayFilter,
build_output_lanes,
+ captures_to_buffer,
consumes_buffer,
has_batches_in_flight,
scheduled_sync_consumes_buffer,
@@ -289,6 +291,50 @@ class TestServedLanes:
assert [lane.resource_name for lane in served_lanes(schema)] == ["users", "public.users_cdc"]
+class TestSnapshotCapture:
+ @parameterized.expand(
+ [
+ ("streaming", {}, True),
+ (
+ "snapshotting_in_the_buffer",
+ {"cdc_mode": "snapshot", "sync_type_config": {"cdc_snapshot_lane": "buffer"}},
+ True,
+ ),
+ ("snapshotting_on_deferred_runs", {"cdc_mode": "snapshot", "initial_sync_complete": False}, False),
+ ("not_cdc", {"is_cdc": False}, False),
+ ("unrecognized_table_mode", {"cdc_table_mode": "something_new"}, False),
+ ]
+ )
+ def test_capture_follows_the_snapshot_lane(self, _name, overrides, captured):
+ assert captures_to_buffer(_schema(**overrides)) is captured
+
+ @parameterized.expand(
+ [
+ ("streaming_on_a_buffered_source", {}, True, True),
+ ("flag_off", {}, False, False),
+ ("legacy_source", {"job_inputs": {}}, True, False),
+ ("deferred_runs_pending", {"sync_type_config": {"cdc_deferred_runs": [{"run": 1}]}}, True, False),
+ ("snapshotting_outside_the_buffer", {"cdc_mode": "snapshot", "initial_sync_complete": False}, True, False),
+ (
+ "already_in_the_buffer",
+ {"cdc_mode": "snapshot", "sync_type_config": {"cdc_snapshot_lane": "buffer"}},
+ False,
+ True,
+ ),
+ ]
+ )
+ def test_a_resnapshot_stays_in_the_buffer_only_when_the_buffer_holds_every_change(
+ self, _name, overrides, flag, stays
+ ):
+ schema = _schema(**{"job_inputs": {"cdc_ingest_mode": "buffered"}, **overrides})
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane.is_buffered_snapshot_enabled",
+ return_value=flag,
+ ):
+ assert resnapshot_stays_in_buffer(schema, MagicMock()) is stays
+
+
class TestBufferedGating:
@parameterized.expand(
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
index 4b9b8152788f..072a49327f49 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
@@ -148,20 +148,24 @@ async def update_last_synced_at(job_id: str, schema_id: str, team_id: int) -> No
def _purge_stale_buffer_then_mark_initial_sync_complete(
schema_id: str, team_id: int, logger: FilteringBoundLogger
) -> None:
- # cdc.buffer pulls in pipeline_v3, whose package __init__ imports common.load, which imports
- # this module back — a true cycle only a deferred import breaks.
- from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import purge_buffer_prefix # noqa: PLC0415
-
- schema = ExternalDataSchema.objects.exclude(deleted=True).get(id=schema_id, team_id=team_id)
- # About to flip a CDC schema snapshot→streaming: anything in the prefix predates the snapshot
- # that just landed — a leftover from before a TRUNCATE, a re-enable, or this run's own capture
- # tail — and merging it after the flip would resurrect rows the snapshot wiped. The ingress lane
- # cannot write here until the flip commits; the shadow lane writes on its flag alone, so a
- # concurrent capture tick is the one remaining writer, and the consumer's position guard covers
- # what it leaves. Strict because a survived stale file corrupts the table.
- if schema.is_cdc and not schema.initial_sync_complete and schema.cdc_mode == "snapshot":
- purge_buffer_prefix(team_id, str(schema_id), logger, strict=True)
- mark_initial_sync_complete(schema_id=schema_id, team_id=team_id)
+ # cdc.source_manager pulls in pipeline_v3, whose package __init__ imports common.load, which
+ # imports this module back — a true cycle only a deferred import breaks.
+ from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import ( # noqa: PLC0415
+ purge_buffer_before_handover,
+ )
+
+ # The row lock is held from the marker read through the flip. Capture sets the marker under the
+ # same lock before it writes the table's first file, so it cannot mark the table and write
+ # between the read and a purge that would delete what it wrote.
+ with transaction.atomic():
+ schema = ExternalDataSchema.objects.select_for_update().exclude(deleted=True).get(id=schema_id, team_id=team_id)
+ # About to flip a CDC schema snapshot→streaming, after which the consumer merges the buffer, so
+ # what it must not replay goes first. A table the buffer does not carry gets no ingress writes
+ # until the flip commits; the shadow lane writes on its flag alone, so a concurrent capture tick
+ # is the one remaining writer, and the consumer's position guard covers what it leaves.
+ if schema.is_cdc and not schema.initial_sync_complete and schema.cdc_mode == "snapshot":
+ purge_buffer_before_handover(schema, logger)
+ mark_initial_sync_complete(schema_id=schema_id, team_id=team_id)
async def set_initial_sync_complete(schema_id: str, team_id: int, logger: FilteringBoundLogger) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py
index f612dba2f9bb..ded0e6e20de9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py
@@ -1,10 +1,10 @@
import uuid
import pytest
-from posthog.test.base import BaseTest
+from posthog.test.base import BaseTest, NonAtomicBaseTest
from unittest.mock import MagicMock, patch
-from django.db import OperationalError, transaction
+from django.db import OperationalError, connections, transaction
from asgiref.sync import async_to_sync
from clickhouse_driver.errors import ServerException
@@ -531,13 +531,16 @@ class TestSetInitialSyncComplete(BaseTest):
wiped), and NEVER purged when the schema is already streaming (those files are live,
unconsumed changes)."""
- def _schema(self, *, sync_type: str, config: dict, initial_sync_complete: bool) -> ExternalDataSchema:
+ def _schema(
+ self, *, sync_type: str, config: dict, initial_sync_complete: bool, job_inputs: dict | None = None
+ ) -> ExternalDataSchema:
source = ExternalDataSource.objects.create(
team_id=self.team.pk,
source_id=str(uuid.uuid4()),
connection_id=str(uuid.uuid4()),
status="Completed",
source_type="Postgres",
+ job_inputs=job_inputs or {},
)
return ExternalDataSchema.objects.create(
team_id=self.team.pk,
@@ -581,7 +584,7 @@ class TestSetInitialSyncComplete(BaseTest):
calls.append(schema_id)
with patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.buffer.purge_buffer_prefix",
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.purge_buffer_prefix",
side_effect=_record_purge,
):
_purge_stale_buffer_then_mark_initial_sync_complete(str(schema.id), self.team.pk, MagicMock())
@@ -590,3 +593,77 @@ class TestSetInitialSyncComplete(BaseTest):
assert schema.initial_sync_complete is True
assert (calls == [str(schema.id)]) is expects_purge
assert schema.sync_type_config.get("cdc_mode") == expected_cdc_mode
+
+ def test_a_snapshot_the_buffer_carried_keeps_its_files_and_the_flip_clears_the_marker(self) -> None:
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (
+ _purge_stale_buffer_then_mark_initial_sync_complete,
+ )
+
+ schema = self._schema(
+ sync_type="cdc",
+ config={"cdc_mode": "snapshot", "cdc_snapshot_lane": "buffer"},
+ initial_sync_complete=False,
+ job_inputs={"cdc_ingest_mode": "buffered"},
+ )
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.purge_buffer_prefix"
+ ) as purge:
+ _purge_stale_buffer_then_mark_initial_sync_complete(str(schema.id), self.team.pk, MagicMock())
+
+ purge.assert_not_called()
+ schema.refresh_from_db()
+ assert schema.initial_sync_complete is True
+ assert schema.sync_type_config.get("cdc_mode") == "streaming"
+ assert "cdc_snapshot_lane" not in schema.sync_type_config
+
+
+class TestSnapshotHandoverHoldsTheRowLock(NonAtomicBaseTest):
+ def test_capture_cannot_mark_the_table_while_the_hand_over_purges(self) -> None:
+ # Capture marks the table under this row lock before it writes. Were the lock released
+ # between the hand-over's marker read and its purge, capture could mark the table and write a
+ # file that the purge then deletes.
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (
+ _purge_stale_buffer_then_mark_initial_sync_complete,
+ )
+
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type="Postgres",
+ job_inputs={"cdc_ingest_mode": "buffered"},
+ )
+ schema = ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source=source,
+ name="public.users",
+ sync_type="cdc",
+ sync_type_config={"cdc_mode": "snapshot"},
+ initial_sync_complete=False,
+ )
+ row_free_during_purge: list[bool] = []
+
+ def _lock_from_another_connection(*_args, **_kwargs) -> None:
+ other = connections.create_connection("default")
+ try:
+ with other.cursor() as cursor:
+ cursor.execute(
+ "SELECT 1 FROM posthog_externaldataschema WHERE id = %s FOR UPDATE NOWAIT", [str(schema.id)]
+ )
+ row_free_during_purge.append(cursor.fetchone() is not None)
+ except OperationalError:
+ row_free_during_purge.append(False)
+ finally:
+ other.close()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.purge_buffer_prefix",
+ side_effect=_lock_from_another_connection,
+ ):
+ _purge_stale_buffer_then_mark_initial_sync_complete(str(schema.id), self.team.pk, MagicMock())
+
+ assert row_free_during_purge == [False]
+ schema.refresh_from_db()
+ assert schema.sync_type_config["cdc_mode"] == "streaming"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py
index c39b8ceb758e..8e779bbb7119 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py
@@ -203,6 +203,10 @@ class PgOutputDecoder:
self._tx_event_count = 0
self._tx_timestamp: datetime | None = None
self._truncated_tables: list[str] = []
+ # Truncates of the open transaction. They become visible only once its changes are consumed,
+ # so a caller that handles truncates mid-transaction never purges ahead of the changes before
+ # them.
+ self._tx_truncated_tables: list[str] = []
self._last_commit_end_lsn: str | None = None
def decode_message(self, data: bytes, lsn: str) -> Iterable[ChangeEvent]:
@@ -238,7 +242,7 @@ class PgOutputDecoder:
@property
def truncated_tables(self) -> list[str]:
- """Tables that received a Truncate message. Caller should trigger re-snapshot."""
+ """Tables truncated by a transaction whose changes the caller has consumed. Caller should re-snapshot them."""
return list(self._truncated_tables)
def clear_truncated_tables(self) -> None:
@@ -276,16 +280,26 @@ class PgOutputDecoder:
self._last_commit_end_lsn = end_lsn
self._check_decode_time()
spill, tail, types = self._tx_spill, self._tx_buffer, self._tx_spill_types
+ truncated = self._tx_truncated_tables
self._tx_spill = None
self._reset_transaction()
self._tx_timestamp = None
+ events: Iterable[ChangeEvent]
if spill is None:
- return [dataclass_replace(e, position_serialized=end_lsn) for e in tail]
- # A caller that abandoned the previous replay would otherwise keep its budget share.
- if self._replay_spill is not None:
- self._replay_spill.close()
- self._replay_spill = spill
- return _replay_spilled_transaction(spill, types, tail, end_lsn)
+ events = [dataclass_replace(e, position_serialized=end_lsn) for e in tail]
+ else:
+ # A caller that abandoned the previous replay would otherwise keep its budget share.
+ if self._replay_spill is not None:
+ self._replay_spill.close()
+ self._replay_spill = spill
+ events = _replay_spilled_transaction(spill, types, tail, end_lsn)
+ if not truncated:
+ return events
+ return self._publish_truncates_after(events, truncated)
+
+ def _publish_truncates_after(self, events: Iterable[ChangeEvent], truncated: list[str]) -> Iterator[ChangeEvent]:
+ yield from events
+ self._truncated_tables.extend(truncated)
def _check_decode_time(self) -> None:
if time.monotonic() - self._tx_started_at > MAX_TX_DECODE_SECONDS:
@@ -306,6 +320,7 @@ class PgOutputDecoder:
self._tx_spill_types = []
self._tx_buffer = []
self._tx_event_count = 0
+ self._tx_truncated_tables = []
def _handle_relation(self, payload: bytes) -> None:
"""R message: relation_id(4) + namespace(str) + name(str) + replica_identity(1) + n_cols(2) + columns"""
@@ -472,7 +487,7 @@ class PgOutputDecoder:
relation.schema_name,
relation.table_name,
)
- self._truncated_tables.append(relation.qualified_name)
+ self._tx_truncated_tables.append(relation.qualified_name)
# --- Helpers ---
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py
index 971a42e05e3c..193dd81602e1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py
@@ -411,7 +411,7 @@ class TestPgOutputDecoder:
decoder.decode_message(rel1, "0/50")
decoder.decode_message(_make_begin(), "0/100")
- decoder.decode_message(_make_insert(1, [("t", "1"), ("t", "Alice")]), "0/110")
+ decoder.decode_message(_make_insert(1, [("t", "1"), ("t", "Alice"), None]), "0/110")
events1 = list(decoder.decode_message(_make_commit(), "0/200"))
assert events1[0].columns == {"id": 1, "name": "Alice"}
@@ -431,13 +431,20 @@ class TestPgOutputDecoder:
assert events2[0].columns == {"id": 2, "name": "Bob", "email": "[email protected]"}
- def test_truncate_marks_table(self):
- decoder = self._setup_decoder_with_relation(relation_id=1, table="users")
-
- truncate = _make_truncate([1])
- decoder.decode_message(truncate, "0/100")
-
- assert decoder.truncated_tables == ["public.users"]
+ @parameterized.expand([("in_memory", 100), ("spilled", 1)])
+ def test_a_truncate_shows_only_once_its_transactions_changes_are_consumed(self, _name, chunk):
+ with patch(f"{_DECODER_MODULE}.TX_SPILL_CHUNK_EVENTS", chunk):
+ decoder = self._setup_decoder_with_relation(relation_id=1, table="users")
+ decoder.decode_message(_make_begin(), "0/100")
+ decoder.decode_message(_make_insert(1, [("t", "1"), ("t", "Alice"), None]), "0/110")
+ decoder.decode_message(_make_insert(1, [("t", "2"), ("t", "Bob"), None]), "0/120")
+ decoder.decode_message(_make_truncate([1]), "0/130")
+ events = iter(decoder.decode_message(_make_commit(), "0/200"))
+
+ next(events)
+ assert decoder.truncated_tables == []
+ assert len(list(events)) == 1
+ assert decoder.truncated_tables == ["public.users"]
decoder.clear_truncated_tables()
assert decoder.truncated_tables == []
@@ -505,7 +512,7 @@ class TestPgOutputDecoder:
decoder = self._setup_decoder_with_relation(columns=[("id", _OID_INT4, -1), ("name", _OID_TEXT, -1)])
decoder.decode_message(_make_begin(), "0/100")
- decoder.decode_message(_make_insert(1, [("t", "1"), ("t", "Alice")]), "0/110")
+ decoder.decode_message(_make_insert(1, [("t", "1"), ("t", "Alice"), None]), "0/110")
decoder.decode_message(_make_update(1, [("t", "1"), ("t", "Alice Updated")]), "0/120")
decoder.decode_message(_make_delete(1, [("t", "2"), None]), "0/130")
events = list(decoder.decode_message(_make_commit(), "0/200"))
diff --git a/products/warehouse_sources/backend/tests/api/test_cdc_table_mode_patch.py b/products/warehouse_sources/backend/tests/api/test_cdc_table_mode_patch.py
index 82c77556bade..2e071ad7dbfd 100644
--- a/products/warehouse_sources/backend/tests/api/test_cdc_table_mode_patch.py
+++ b/products/warehouse_sources/backend/tests/api/test_cdc_table_mode_patch.py
@@ -24,6 +24,7 @@ from products.warehouse_sources.backend.facade.types import ExternalDataSourceTy
pytestmark = [pytest.mark.django_db]
+_VIEW = "products.warehouse_sources.backend.presentation.views.external_data_schema"
_PATCH_TARGETS = {
"is_cdc_enabled_for_team": "products.warehouse_sources.backend.presentation.views.external_data_schema.is_cdc_enabled_for_team",
# Single private method backing both add_table/remove_table on the adapter — patching it
@@ -49,6 +50,9 @@ _PATCH_TARGETS = {
"is_any_external_data_schema_paused": (
"products.warehouse_sources.backend.presentation.views.external_data_schema.is_any_external_data_schema_paused"
),
+ "is_buffered_snapshot_enabled": (
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane.is_buffered_snapshot_enabled"
+ ),
}
@@ -79,17 +83,21 @@ def _make_cdc_source_and_schema(
cdc_last_log_position: str | None = "0/12345",
cdc_deferred_runs: list[dict] | None = None,
initial_sync_complete: bool = True,
+ ingest_mode: str | None = None,
) -> tuple[ExternalDataSource, ExternalDataSchema]:
+ job_inputs = {
+ "schema": "public",
+ "cdc_enabled": True,
+ "cdc_management_mode": "posthog",
+ "cdc_slot_name": "test_slot",
+ "cdc_publication_name": "test_pub",
+ }
+ if ingest_mode is not None:
+ job_inputs["cdc_ingest_mode"] = ingest_mode
source = ExternalDataSource.objects.create(
team=team,
source_type=ExternalDataSourceType.POSTGRES,
- job_inputs={
- "schema": "public",
- "cdc_enabled": True,
- "cdc_management_mode": "posthog",
- "cdc_slot_name": "test_slot",
- "cdc_publication_name": "test_pub",
- },
+ job_inputs=job_inputs,
)
sync_type_config: dict = {
"cdc_mode": "streaming",
@@ -114,19 +122,25 @@ def _make_cdc_source_and_schema(
@pytest.mark.parametrize(
- ("old_mode", "new_mode"),
+ ("old_mode", "new_mode", "ingest_mode"),
[
- ("consolidated", "cdc_only"),
- ("consolidated", "both"),
- ("cdc_only", "consolidated"),
- ("cdc_only", "both"),
+ ("consolidated", "cdc_only", None),
+ ("consolidated", "both", None),
+ ("cdc_only", "consolidated", None),
+ ("cdc_only", "both", None),
+ ("consolidated", "both", "buffered"),
],
)
-def test_patch_cdc_table_mode_adding_target_triggers_resnapshot(team, user, client: HttpClient, old_mode, new_mode):
+def test_patch_cdc_table_mode_adding_target_triggers_resnapshot(
+ team, user, client: HttpClient, old_mode, new_mode, ingest_mode
+):
source, schema = _make_cdc_source_and_schema(
team,
cdc_table_mode=old_mode,
- cdc_deferred_runs=[{"job_id": "stale", "run_uuid": "stale", "batch_results": []}],
+ # Pending deferred runs keep a buffered source's table on the legacy lane, so only the legacy
+ # cases carry them.
+ cdc_deferred_runs=None if ingest_mode else [{"job_id": "stale", "run_uuid": "stale", "batch_results": []}],
+ ingest_mode=ingest_mode,
)
running_job = ExternalDataJob.objects.create(
team=team,
@@ -145,6 +159,7 @@ def test_patch_cdc_table_mode_adding_target_triggers_resnapshot(team, user, clie
mock.patch(_PATCH_TARGETS["sync_cdc_extraction_schedule"]),
mock.patch(_PATCH_TARGETS["cancel_external_data_workflow"]) as mock_cancel,
mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]) as mock_trigger,
+ mock.patch(_PATCH_TARGETS["is_buffered_snapshot_enabled"], return_value=True),
):
response = client.patch(
f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",
@@ -156,6 +171,8 @@ def test_patch_cdc_table_mode_adding_target_triggers_resnapshot(team, user, clie
schema.refresh_from_db()
assert schema.cdc_table_mode == new_mode
+ # A buffered source's changes keep going to the buffer, which the new snapshot then replays.
+ assert (schema.sync_type_config.get("cdc_snapshot_lane") == "buffer") is (ingest_mode == "buffered")
assert schema.sync_type_config.get("cdc_mode") == "snapshot"
assert schema.sync_type_config.get("cdc_last_log_position") is None
assert schema.sync_type_config.get("cdc_deferred_runs") is None
@@ -165,6 +182,56 @@ def test_patch_cdc_table_mode_adding_target_triggers_resnapshot(team, user, clie
mock_trigger.assert_called_once()
[email protected](("should_sync_before", "should_sync_after"), [(True, False), (False, True)])
+def test_toggling_sync_drops_the_snapshot_marker(team, user, client: HttpClient, should_sync_before, should_sync_after):
+ # Capture skips a table while its sync is off, so its buffer has a gap. A marker left behind would
+ # have the hand-over replay files from before the gap and bring deleted rows back.
+ _, schema = _make_cdc_source_and_schema(team, cdc_table_mode="consolidated", ingest_mode="buffered")
+ ExternalDataSchema.objects.filter(id=schema.id).update(
+ should_sync=should_sync_before,
+ initial_sync_complete=False,
+ sync_type_config={**schema.sync_type_config, "cdc_mode": "snapshot", "cdc_snapshot_lane": "buffer"},
+ )
+ client.force_login(user)
+ with (
+ mock.patch(_PATCH_TARGETS["is_cdc_enabled_for_team"], return_value=True),
+ mock.patch(_PATCH_TARGETS["alter_cdc_publication"]),
+ mock.patch(_PATCH_TARGETS["external_data_workflow_exists"], return_value=True),
+ mock.patch(_PATCH_TARGETS["sync_external_data_job_workflow"]),
+ mock.patch(_PATCH_TARGETS["sync_cdc_extraction_schedule"]),
+ mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]),
+ mock.patch(f"{_VIEW}.pause_external_data_schedule"),
+ mock.patch(f"{_VIEW}.unpause_external_data_schedule"),
+ ):
+ response = client.patch(
+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",
+ data={"should_sync": should_sync_after},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200, response.content
+ schema.refresh_from_db()
+ assert "cdc_snapshot_lane" not in schema.sync_type_config
+
+
[email protected]("ingest_mode", [None, "buffered"])
+def test_resync_of_a_streaming_table_keeps_its_buffer_on_a_buffered_source(team, user, client: HttpClient, ingest_mode):
+ _, schema = _make_cdc_source_and_schema(team, cdc_table_mode="consolidated", ingest_mode=ingest_mode)
+ client.force_login(user)
+ with (
+ mock.patch(_PATCH_TARGETS["is_any_external_data_schema_paused"], return_value=False),
+ mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]),
+ mock.patch(_PATCH_TARGETS["is_buffered_snapshot_enabled"], return_value=True),
+ ):
+ response = client.post(f"/api/environments/{team.pk}/external_data_schemas/{schema.id}/resync")
+
+ assert response.status_code == 200, response.content
+ schema.refresh_from_db()
+ assert schema.sync_type_config.get("cdc_mode") == "snapshot"
+ # Unmarked, the next capture run empties the buffer and can delete changes the snapshot never saw.
+ assert (schema.sync_type_config.get("cdc_snapshot_lane") == "buffer") is (ingest_mode == "buffered")
+
+
@pytest.mark.parametrize(
("old_mode", "new_mode"),
[
diff --git a/products/warehouse_sources/backend/tests/management/test_migrate_cdc_source_to_buffered.py b/products/warehouse_sources/backend/tests/management/test_migrate_cdc_source_to_buffered.py
index 7f6ee61f08e4..7b8c703887c0 100644
--- a/products/warehouse_sources/backend/tests/management/test_migrate_cdc_source_to_buffered.py
+++ b/products/warehouse_sources/backend/tests/management/test_migrate_cdc_source_to_buffered.py
@@ -233,6 +233,46 @@ class TestMigrateCDCSourceToBuffered(BaseTest):
mocks["pause_schema"].assert_not_called()
mocks["unpause_schema"].assert_not_called()
+ @parameterized.expand(
+ [
+ ("marked_before_the_rollback", False, True),
+ ("marked_by_the_run_it_waited_out", True, True),
+ ("sync_turned_off", False, False),
+ ]
+ )
+ def test_rollback_restarts_a_snapshot_the_buffer_carries_on_legacy(
+ self, _name, started_during_the_wait, should_sync
+ ):
+ # Only the buffer holds that table's changes since its snapshot began, and legacy's hand-over
+ # would purge them. Refusing instead would block the emergency switch for as long as the
+ # snapshot cannot finish.
+ source = self._source(ingest_mode="buffered")
+ self._schema(source, "users")
+ snapshotting = self._schema(source, "orders", cdc_mode="snapshot", initial_sync_complete=False)
+ ExternalDataSchema.objects.filter(id=snapshotting.id).update(should_sync=should_sync)
+
+ def start_snapshot_in_buffer(*_args):
+ update_sync_type_config_keys(snapshotting.id, self.team.pk, updates={"cdc_snapshot_lane": "buffer"})
+
+ if not started_during_the_wait:
+ start_snapshot_in_buffer()
+ with (
+ _mocked_side_effects() as mocks,
+ patch(f"{_CMD}.Command._wait_for_extraction_idle", side_effect=start_snapshot_in_buffer),
+ patch(f"{_CMD}.cancel_running_sync") as cancel,
+ ):
+ self._run(source, rollback=True, drain_timeout=0)
+
+ source.refresh_from_db()
+ assert source.job_inputs["cdc_ingest_mode"] == "legacy"
+ snapshotting.refresh_from_db()
+ assert "cdc_snapshot_lane" not in snapshotting.sync_type_config
+ assert snapshotting.sync_type_config["reset_pipeline"] is True
+ assert cancel.call_args.args[0].id == snapshotting.id
+ assert [(c.args[1], c.kwargs.get("strict")) for c in mocks["purge"].call_args_list] == [
+ (str(snapshotting.id), True)
+ ]
+
def test_rollback_ignores_prefixes_the_buffered_lane_never_served(self):
# A legacy schema's prefix holds shadow copies no consumer ever reads, so scanning it would
# wedge every rollback of a hybrid source with capture left paused.
diff --git a/products/warehouse_sources/backend/tests/test_ad_hoc_sync.py b/products/warehouse_sources/backend/tests/test_ad_hoc_sync.py
index 41f731be3cf7..f176fb0049f7 100644
--- a/products/warehouse_sources/backend/tests/test_ad_hoc_sync.py
+++ b/products/warehouse_sources/backend/tests/test_ad_hoc_sync.py
@@ -5,7 +5,10 @@ from posthog.api.test.test_organization import create_organization
from posthog.api.test.test_team import create_team
from products.warehouse_sources.backend.ad_hoc_sync import WorkflowStartError, trigger_ad_hoc_sync
-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_schema import (
+ ExternalDataSchema,
+ update_sync_type_config_keys,
+)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
pytestmark = [pytest.mark.django_db]
@@ -81,3 +84,31 @@ def test_failed_start_restores_staged_reset_state(schema):
assert schema.sync_type_config["cdc_mode"] == "streaming"
assert schema.sync_type_config["cdc_last_log_position"] == "0/ABC"
assert schema.initial_sync_complete is True
+
+
[email protected]("ingest_mode", [None, "buffered"])
+def test_a_reset_of_a_streaming_cdc_table_keeps_its_buffer_and_concurrent_keys(schema, ingest_mode):
+ schema.source.job_inputs = {"cdc_ingest_mode": ingest_mode} if ingest_mode else {}
+ schema.source.save()
+ schema.sync_type = ExternalDataSchema.SyncType.CDC
+ schema.sync_type_config = {"cdc_mode": "streaming", "cdc_table_mode": "consolidated"}
+ schema.initial_sync_complete = True
+ schema.save()
+ # Capture writes the row after this copy was loaded; the reset must not revert it.
+ update_sync_type_config_keys(schema.id, schema.team_id, updates={"cdc_last_run_at": "2026-09-24T00:00:00+00:00"})
+
+ with (
+ patch(f"{MODULE}.is_schedule_paused", return_value=True),
+ patch(f"{MODULE}.start_external_data_workflow"),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane.is_buffered_snapshot_enabled",
+ return_value=True,
+ ),
+ ):
+ trigger_ad_hoc_sync(MagicMock(), schema, billable=False, reset_pipeline=True, workflow_id_prefix="test")
+
+ schema.refresh_from_db()
+ assert schema.sync_type_config["cdc_mode"] == "snapshot"
+ # Unmarked, the next capture run empties the buffer and can delete changes the snapshot never saw.
+ assert (schema.sync_type_config.get("cdc_snapshot_lane") == "buffer") is (ingest_mode == "buffered")
+ assert schema.sync_type_config["cdc_last_run_at"] == "2026-09-24T00:00:00+00:00"
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index d8717a1fcf75..50b183bf35ed 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -355,6 +355,26 @@ class TestPartitionMeasurementPreservesConcurrentKeys(BaseTest):
assert schema.sync_type_config["max_partition_bytes"] == 4096
assert schema.sync_type_config["incremental_field"] == "updated_at"
+ @parameterized.expand(
+ [
+ ("reset", lambda schema: schema.update_sync_type_config_for_reset_pipeline()),
+ ("partitioning", lambda schema: schema.set_partitioning_enabled(["id"], 10, None, "md5", None)),
+ ]
+ )
+ def test_a_snapshot_marker_set_after_this_instance_loaded_survives(self, _name, write) -> None:
+ # A sync holds its copy for the whole run while capture marks the table's snapshot. Losing the
+ # marker makes the next capture run empty the buffer under the snapshot.
+ schema = ExternalDataSchema.objects.create(
+ team_id=self.team.pk, source=self.source, name="orders", sync_type_config={"cdc_mode": "snapshot"}
+ )
+ stale = ExternalDataSchema.objects.get(id=schema.id)
+
+ update_sync_type_config_keys(schema.id, self.team.pk, updates={"cdc_snapshot_lane": "buffer"})
+ write(stale)
+
+ schema.refresh_from_db()
+ assert schema.sync_type_config["cdc_snapshot_lane"] == "buffer"
+
class TestExternalDataSchemaOOMEvent(BaseTest):
def _source(self, team_id: int | None = None) -> ExternalDataSource:
@@ -981,13 +1001,38 @@ def test_update_xmin_state_writes_all_keys() -> None:
assert (schema.xmin_last_value, schema.xmin_ceiling, schema.xmin_num_wraparound) == (100, 4294967396, 1)
+@contextmanager
+def _merge_in_memory(schema: ExternalDataSchema) -> Iterator[None]:
+ def apply(
+ schema_id: Any,
+ team_id: Any,
+ *,
+ updates: dict[str, Any] | None = None,
+ removes: Any = None,
+ extra_model_fields: dict[str, Any] | None = None,
+ **_: Any,
+ ) -> dict[str, Any]:
+ schema.sync_type_config.update(updates or {})
+ for key in removes or []:
+ schema.sync_type_config.pop(key, None)
+ for field, value in (extra_model_fields or {}).items():
+ setattr(schema, field, value)
+ return schema.sync_type_config
+
+ with patch(
+ "products.warehouse_sources.backend.models.external_data_schema.update_sync_type_config_keys",
+ side_effect=apply,
+ ):
+ yield
+
+
def test_reset_pipeline_clears_xmin_state() -> None:
schema = ExternalDataSchema(
sync_type=ExternalDataSchema.SyncType.XMIN,
sync_type_config={"xmin_last_value": 100, "xmin_ceiling": 4294967396, "xmin_num_wraparound": 1},
initial_sync_complete=True,
)
- with patch.object(schema, "save"):
+ with _merge_in_memory(schema):
schema.update_sync_type_config_for_reset_pipeline()
assert "xmin_last_value" not in schema.sync_type_config
assert "xmin_ceiling" not in schema.sync_type_config
@@ -1008,7 +1053,7 @@ def test_reset_pipeline_preserves_partition_overrides_but_clears_auto_detected()
"partition_mode": "md5",
}
)
- with patch.object(schema, "save"):
+ with _merge_in_memory(schema):
schema.update_sync_type_config_for_reset_pipeline()
assert "partition_count" not in schema.sync_type_config
assert "partitioning_enabled" not in schema.sync_type_config
@@ -1020,7 +1065,7 @@ def test_set_partitioning_enabled_consumes_partition_overrides() -> None:
# Once the override is baked into the effective settings, it's a one-shot pin: drop it so
# a later reset re-detects instead of re-applying a stale value.
schema = ExternalDataSchema(sync_type_config={"partition_count_override": 10, "partition_size_override": 5})
- with patch.object(schema, "save"):
+ with _merge_in_memory(schema):
schema.set_partitioning_enabled(
partitioning_keys=["id"],
partition_count=10,
@@ -1048,7 +1093,7 @@ def test_reset_pipeline_preserves_partition_mode_override() -> None:
"partitioning_enabled": True,
}
)
- with patch.object(schema, "save"):
+ with _merge_in_memory(schema):
schema.update_sync_type_config_for_reset_pipeline()
assert "partition_mode" not in schema.sync_type_config
assert "partitioning_keys" not in schema.sync_type_config
@@ -1062,7 +1107,7 @@ def test_set_partitioning_enabled_consumes_partition_mode_override() -> None:
schema = ExternalDataSchema(
sync_type_config={"partition_mode_override": "datetime", "partitioning_keys_override": ["action_date"]}
)
- with patch.object(schema, "save"):
+ with _merge_in_memory(schema):
schema.set_partitioning_enabled(
partitioning_keys=["action_date"],
partition_count=None,
@@ -1382,7 +1427,7 @@ class TestStagedIncrementalCursor:
incremental_staged={"run_uuid": "run-1", "last_value": 42},
incremental_staged_pending=[{"run_uuid": "run-0", "last_value": 1}],
)
- with patch.object(schema, "save"):
+ with _merge_in_memory(schema):
schema.update_sync_type_config_for_reset_pipeline()
assert "incremental_staged" not in schema.sync_type_config
assert "incremental_staged_pending" not in schema.sync_type_config