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): consume the CDC change buffer on the scheduled sync (#83333)

Daniel RC8b4215a51ed2
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.md
new file mode 100644
index 000000000000..8d5350837df8
--- /dev/null
+++ b/docs/internal/cdc-buffered-ingress-runbook.md
@@ -0,0 +1,169 @@
+# CDC buffered ingress — flip runbook
+
+How to move a Postgres CDC source from legacy extraction onto the S3 change buffer, and how to move
+it back.
+
+## What changes
+
+Capture stops transforming and dispatching change events. It decodes WAL, writes Parquet to
+`s3://{DATAWAREHOUSE_BUCKET}/cdc_producer/{team_id}/{schema_id}/`, and advances the replication slot
+as soon as those files are durable. The normal per-schema scheduled sync then consumes them like any
+other source.
+
+The point is that a stalled load can no longer hold the customer's WAL. It spends our S3 retention
+instead.
+
+**Only consolidated schemas move.** `cdc_only` and `both` schemas produce two tables per run, which
+one pipeline run cannot express, so they stay on legacy extraction. A source with a mix runs
+hybrid — some schemas buffered, the rest unchanged — and keeps its backpressure guard for the
+legacy ones.
+
+Nothing is re-snapshotted. The slot, the Delta tables, and `initial_sync_complete` are all
+preserved, so there is no WAL gap and no re-sync.
+
+## Before flipping
+
+0. The team runs the v3 pipeline for this source type. **The command refuses to flip a v2 team.**
+ Position resolution lives only in the v3 loader; on v2 nothing records a load position, so every
+ scheduled sync re-merges the entire buffer and no file is ever deleted — per-run row counts grow
+ with the buffer on every tick.
+1. `dwh-cdc-write-resolution` is on for the team. **The command refuses to flip without it.**
+ Without the flag the loader records no load position, so no consumed file is ever proven safe to
+ delete; the buffer then fills until the S3 TTL expires it, with the slot long advanced past those
+ changes. That is unrecoverable loss, not a stall. Rollback does not require the flag.
+ **The flag must also stay on after the flip** — turning it off later freezes the load position,
+ and the symptom is a frozen `cdc_load_position` with buffer files aging toward the TTL.
+2. No source table has a column named `_ph_cdc_seq`. **The command refuses to flip if one does** —
+ the name is reserved for change ordering, and capture hard-errors on the collision rather than
+ writing files whose ordering and retry cleanup derive from customer data. A schema that already
+ consumed the buffer carries the column for our own reasons, and its recorded load position tells
+ the check apart from a real collision, so a re-flip after a rollback is not blocked by it.
+3. Every CDC schema on the source is at `sync_frequency_interval = 5min`. The command warns
+ when an eligible schema is off cadence — consumption paces to the schema's own schedule.
+4. Buffer validation is clean over a busy window:
+
+ ```bash
+ python manage.py validate_cdc_buffer --source-id <uuid> --since-hours 40
+ ```
+
+5. Check what will move:
+
+ ```bash
+ python manage.py migrate_cdc_source_to_buffered --source-id <uuid> --dry-run
+ ```
+
+ Anything reported under "staying on legacy" keeps today's behavior.
+
+## Flip
+
+```bash
+python manage.py migrate_cdc_source_to_buffered --source-id <uuid>
+```
+
+The command pauses the extraction schedule, waits for the in-flight extraction run to finish, waits
+for in-flight `sourcebatch` batches to reach a terminal state, purges pre-flip buffer files **and
+aborts if any file survives the purge**, sets `job_inputs.cdc_ingest_mode = "buffered"`, then
+unpauses the extraction schedule and each eligible schema's own schedule.
+
+If a batch is still working after the drain timeout the command aborts with the source **left
+paused**. That is deliberate — flipping on top of a stuck load lets that batch land against a table
+the buffered lane has already started writing. Investigate the stuck load, then re-run.
+
+Pre-flip buffer files are purged because the legacy lane already delivered those rows, and the load
+position has no watermark for them yet.
+
+The wait for the extraction run matters because pausing a Temporal schedule does not stop a workflow
+already running. With the shadow lane on — the normal state before a flip, since validation needs
+it — that run keeps writing buffer files, and one landing after the purge would be merged by the
+consumer even though the legacy lane already delivered those rows.
+
+The consumer also no-ops while any legacy delivery for the schema is in flight (deferred runs or
+unfinished `sourcebatch` batches), so a legacy batch that lands late still lands before the first
+buffered merge. The same gate holds the consumer off during a post-flip re-snapshot until the
+deferred backlog lands.
+
+### Verify
+
+- Capture writes files under the schema's prefix and advances the slot (`cdc_last_log_position`
+ moves).
+- The next scheduled sync merges and advances `sync_type_config["cdc_load_position"]`.
+- Consumed files disappear on the run **after** the one that read them — deletion follows the
+ committed position, not the read.
+- Row counts track the pre-flip day.
+- `warehouse_load_cdc_delete_enrichment_violations_total` stays at zero.
+- The schema's status in the Syncs UI now comes from the scheduled sync alone — capture heartbeats
+ but never repaints a buffered schema COMPLETED, so a failing consumer run stays visible.
+
+## Rollback
+
+```bash
+python manage.py migrate_cdc_source_to_buffered --source-id <uuid> --rollback
+```
+
+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.
+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
+ remaining file sits strictly below the schema's load position. A file ending exactly at the
+ position does not count: one transaction shares a commit position across its events, so that file
+ can still be the unread tail of a transaction split across files. The consumer settles it by
+ deleting the file once a completed run proves it read it, which takes a tick or two.
+4. Pause the per-schema schedules and wait for running sync jobs, so no in-flight merge of old
+ buffered rows can land after legacy delivery resumes and overwrite newer rows.
+5. Set the mode to `legacy` and unpause the extraction schedule.
+
+The buffer-drain check covers every schema the buffered lane serves, including ones disabled after
+the flip — a disabled schema's unconsumed files still block, and draining them means re-enabling the
+schema so its sync can catch up first. It skips the schemas that stayed on legacy: with the shadow
+lane on, their prefixes hold validation copies no consumer reads, so scanning them would block the
+rollback forever with capture paused.
+
+Fully-applied buffer files are **not** purged: the position guard makes a replay a no-op, and the
+14-day S3 TTL clears them. Rows already merged stay merged — the same rows the legacy lane would
+have written.
+
+## Buffer expiry — no partial recovery
+
+Buffer files expire after 14 days (`expire-cdc-producer-buffer`). If a schema stops consuming —
+paused, erroring, or wedged — its oldest unconsumed file ages toward that limit while the slot has
+long since advanced past those changes.
+
+**If files expire before they are consumed, the changes are gone.** There is no partial recovery.
+The only fix is a full `reset_pipeline` re-snapshot for that schema.
+
+Watch the age of the oldest unconsumed file per schema, not the file count. A schema with few files
+that are all thirteen days old is in trouble; one with thousands of fresh files is fine.
+
+## Known gap: zombie-attempt file collision
+
+A Temporal activity attempt declared dead by heartbeat timeout can still be running and writing.
+Buffer files are not idempotent overwrites — micro-batch boundaries shift between attempts — so a
+zombie can overwrite a live attempt's file covering the same position range with fewer rows. Those
+rows then exist nowhere, and the slot has advanced past them.
+
+This is an accepted risk, not a fixed one. It needs a retry **and** a transaction spanning a flush
+boundary **and** the boundary to shift between attempts.
+
+There is no detector. `validate_cdc_buffer`'s continuity check compares adjacent filename ranges,
+and in this failure the ranges stay contiguous — rows go missing inside a range.
+
+Track `cdc_extract_retried_attempts_total` as the exposure proxy. A quiet counter bounds the risk;
+a retry-heavy period is the signal to revisit. Candidate fixes are costed in the plan doc
+(attempt-scoped prefix; polling `activity.is_cancelled()` at flush boundaries).
+
+## Billing
+
+Consume runs are ordinary jobs: `billable=True`, `rows_synced` = consumed rows. A consolidated
+source bills the same change events once per run, so the flip is billing-neutral by construction.
+One bounded exception: the trailing file of a burst is re-read for a tick or two until a completed
+run proves it consumed and it is deleted — rows at the recorded position re-apply as no-op upserts
+in that window, never perpetually.
+
+Note for later: `both`-mode schemas create two `ExternalDataJob` rows per run, each carrying
+`rows_synced`, so those customers are double-billed today. Buffered ingress halves it. That lands
+with the companion lane, not this flip.
diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.py
index 2097144f004d..8f287bac98b8 100644
--- a/products/data_warehouse/backend/facade/api.py
+++ b/products/data_warehouse/backend/facade/api.py
@@ -38,6 +38,7 @@ _LAZY = {
"external_data_workflow_exists": "logic.data_load.service",
"is_any_external_data_schema_paused": "logic.data_load.service",
"is_cdc_enabled_for_team": "logic.data_load.service",
+ "cdc_extraction_schedule_has_running_action": "logic.data_load.service",
"is_cdc_extraction_schedule_paused": "logic.data_load.service",
"is_custom_source_ai_builder_enabled_for_team": "logic.data_load.service",
"pause_cdc_extraction_schedule": "logic.data_load.service",
diff --git a/products/data_warehouse/backend/logic/data_load/service.py b/products/data_warehouse/backend/logic/data_load/service.py
index 9c0a4293cf53..a50a8a55b5b5 100644
--- a/products/data_warehouse/backend/logic/data_load/service.py
+++ b/products/data_warehouse/backend/logic/data_load/service.py
@@ -624,6 +624,25 @@ async def is_cdc_extraction_schedule_paused(source_id: str) -> bool:
return desc.schedule.state.paused
+@async_to_sync
+async def cdc_extraction_schedule_has_running_action(source_id: str) -> bool:
+ """Whether an extraction run started by the source's schedule is still executing.
+
+ Pausing a schedule stops future firings but not a workflow already running — anything that
+ must not race an in-flight extraction (the buffered-ingress rollback) has to wait on this
+ after pausing. A missing schedule has nothing running.
+ """
+ schedule_id = _get_cdc_extraction_schedule_id(source_id)
+ temporal = await async_connect()
+ try:
+ desc = await describe_schedule(temporal, schedule_id=schedule_id)
+ except temporalio.service.RPCError as e:
+ if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:
+ return False
+ raise
+ return bool(desc.info.running_actions)
+
+
@async_to_sync
async def bulk_sync_cdc_extraction_schedules(
source_intervals: list[tuple[ExternalDataSource, timedelta]],
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
new file mode 100644
index 000000000000..64ec8d991404
--- /dev/null
+++ b/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.py
@@ -0,0 +1,438 @@
+"""Flip one CDC source between legacy extraction and buffered ingress.
+
+In place: the slot, the tables, and `initial_sync_complete` are all preserved, so there is no
+re-snapshot and no WAL gap. Only consolidated schemas move — see `cdc/source_manager.py`.
+"""
+
+from __future__ import annotations
+
+import time
+import datetime as dt
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError
+
+import psycopg
+import structlog
+
+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 ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN
+from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import (
+ get_buffer_prefix,
+ parse_buffer_file_name,
+ purge_buffer_prefix,
+)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import (
+ WRITE_RESOLUTION_FLAG,
+ is_cdc_write_resolution_enabled,
+ read_load_position,
+)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
+ consolidated_resource_name,
+ serves_buffered_lane,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
+ BatchQueue,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common import strip_s3_protocol
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (
+ is_pipeline_v3_enabled,
+)
+
+logger = structlog.get_logger(__name__)
+
+# How long to wait for in-flight work to reach a terminal state before giving up. Past this the
+# operator should investigate rather than flip on top of a stuck run.
+DRAIN_TIMEOUT_SECONDS = 15 * 60
+DRAIN_POLL_SECONDS = 10
+
+EXPECTED_SYNC_INTERVAL = dt.timedelta(minutes=5)
+
+
+class Command(BaseCommand):
+ help = "Move a CDC source onto buffered ingress (or back). Consolidated schemas only."
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--source-id", required=True, help="ExternalDataSource UUID")
+ parser.add_argument("--rollback", action="store_true", help="Return the source to legacy extraction")
+ parser.add_argument("--dry-run", action="store_true", help="Report what would change and exit")
+ parser.add_argument(
+ "--drain-timeout",
+ type=int,
+ default=DRAIN_TIMEOUT_SECONDS,
+ help=f"Seconds to wait for in-flight work to drain (default {DRAIN_TIMEOUT_SECONDS})",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ source_id = options["source_id"]
+ rollback = options["rollback"]
+ dry_run = options["dry_run"]
+ target_mode = "legacy" if rollback else "buffered"
+
+ try:
+ source = ExternalDataSource.objects.get(id=source_id)
+ except ExternalDataSource.DoesNotExist:
+ raise CommandError(f"No source {source_id}")
+
+ schemas = list(ExternalDataSchema.objects.filter(source_id=source.id, deleted=False))
+ cdc_schemas = [s for s in schemas if s.is_cdc]
+ if not cdc_schemas:
+ raise CommandError(f"Source {source_id} has no CDC schemas")
+
+ # Mirror capture's _get_cdc_schemas: a user-disabled schema must not be flipped — the last
+ # step would unpause its schedule, reversing the disable.
+ eligible = [s for s in cdc_schemas if s.should_sync and serves_buffered_lane(s)]
+ ineligible = [s for s in cdc_schemas if s not in eligible]
+ current_mode = (source.job_inputs or {}).get("cdc_ingest_mode", "legacy")
+
+ self._report(source, current_mode, target_mode, eligible, ineligible)
+
+ if not eligible and not rollback:
+ raise CommandError(
+ "No schema on this source serves the buffered lane — nothing to flip. "
+ "Buffered ingress covers consolidated streaming schemas whose initial sync is done."
+ )
+ if current_mode == target_mode:
+ self.stdout.write(self.style.WARNING(f"Already {target_mode}; nothing to do."))
+ return
+ if not rollback:
+ self._require_pipeline_v3(source)
+ self._require_write_resolution(source, eligible)
+ self._require_no_reserved_columns(eligible)
+ if dry_run:
+ self.stdout.write(self.style.WARNING("Dry run — no changes made."))
+ return
+
+ if rollback:
+ self._roll_back(source, eligible, cdc_schemas, options["drain_timeout"])
+ else:
+ self._flip_to_buffered(source, eligible, options["drain_timeout"])
+
+ def _require_pipeline_v3(self, source: ExternalDataSource) -> None:
+ """Refuse to flip a team that still runs the v2 pipeline.
+
+ Position resolution lives only in the v3 loader; on v2 nothing records a load position, so
+ every scheduled sync re-merges the entire buffer and no file is ever deleted — a snowballing
+ re-merge on every tick, observed live before this guard existed.
+ """
+ if is_pipeline_v3_enabled(source.team_id, source.source_type):
+ return
+ raise CommandError(
+ f"Team {source.team_id} runs the v2 pipeline for {source.source_type}. Buffered ingress "
+ "requires v3: v2 has no position resolution, so the buffer re-merges in full on every "
+ "sync and consumed files are never deleted."
+ )
+
+ def _require_write_resolution(self, source: ExternalDataSource, eligible: list[ExternalDataSchema]) -> None:
+ """Refuse to flip a team whose write resolution is off.
+
+ Without the flag the loader never records a load position, so the consumer never has grounds
+ to delete a consumed file. Files then accumulate until the 14-day TTL expires them — and the
+ slot advanced long ago, so that expiry is unrecoverable data loss rather than a stall.
+ """
+ if is_cdc_write_resolution_enabled(source.team_id, str(eligible[0].id), f"preflight-{source.id}"):
+ return
+ raise CommandError(
+ f"{WRITE_RESOLUTION_FLAG} is off for team {source.team_id}. Buffered ingress needs it: "
+ "without it no load position is recorded, consumed files are never deleted, and they "
+ "expire at the S3 TTL with the slot already advanced past them."
+ )
+
+ 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`.
+
+ The collision stops the batcher stamping the engine position, and capture hard-errors on it
+ (CDCReservedColumnError) — catching it here keeps the source out of a flip-then-break loop.
+
+ The buffered lane writes its own `_ph_cdc_seq` into the warehouse table, so the column alone
+ proves nothing once a schema has consumed the buffer. A recorded load position is proof the
+ column is ours: capture would have hard-errored on a real collision before any file existed.
+ """
+ conflicted = [
+ s.name
+ for s in eligible
+ if s.table is not None
+ and CDC_SEQ_COLUMN in (s.table.columns or {})
+ and read_load_position(s.sync_type_config, consolidated_resource_name(s)) is None
+ ]
+ if conflicted:
+ raise CommandError(
+ f"Schemas with a source column named {CDC_SEQ_COLUMN}: {', '.join(sorted(conflicted))}. "
+ "That name is reserved for change ordering — rename the column or keep the source on legacy."
+ )
+
+ def _report(
+ self,
+ source: ExternalDataSource,
+ current_mode: str,
+ target_mode: str,
+ eligible: list[ExternalDataSchema],
+ ineligible: list[ExternalDataSchema],
+ ) -> None:
+ self.stdout.write(f"Source {source.id} (team {source.team_id}): {current_mode} → {target_mode}")
+ self.stdout.write(f" buffered lane ({len(eligible)}): {', '.join(s.name for s in eligible) or '—'}")
+ off_cadence = [s.name for s in eligible if s.sync_frequency_interval != EXPECTED_SYNC_INTERVAL]
+ if off_cadence:
+ self.stdout.write(
+ self.style.WARNING(
+ f" ⚠ not at the 5min platform cadence: {', '.join(sorted(off_cadence))} — "
+ "consumption paces to the schema's schedule; set them to 5min first"
+ )
+ )
+ if ineligible:
+ detail = ", ".join(
+ f"{s.name} [{'disabled' if not s.should_sync else s.cdc_table_mode}]" for s in ineligible
+ )
+ self.stdout.write(self.style.WARNING(f" staying on legacy ({len(ineligible)}): {detail}"))
+ self.stdout.write(
+ self.style.WARNING(
+ " → hybrid source: capture keeps its transforms and the backpressure guard for those schemas"
+ )
+ )
+
+ def _flip_to_buffered(
+ self, source: ExternalDataSource, eligible: list[ExternalDataSchema], drain_timeout: int
+ ) -> None:
+ from products.data_warehouse.backend.facade.api import (
+ pause_cdc_extraction_schedule,
+ unpause_cdc_extraction_schedule,
+ )
+
+ source_id = str(source.id)
+
+ self.stdout.write("1/6 pausing extraction schedule")
+ pause_cdc_extraction_schedule(source_id)
+
+ # Pausing the schedule stops future firings, not a workflow already running. A legacy run
+ # with the shadow lane on keeps writing buffer files, and one landing after the purge would
+ # be merged by the consumer even though the legacy lane already delivered those rows.
+ self.stdout.write("2/6 waiting for the in-flight extraction run to finish")
+ self._wait_for_extraction_idle(source_id, drain_timeout)
+
+ self.stdout.write("3/6 draining sourcebatch")
+ self._wait_for_sourcebatch_drain(source.team_id, [str(s.id) for s in eligible], drain_timeout)
+
+ # Pre-flip files were already delivered by the legacy lane, and replaying them would
+ # re-apply rows against a position the guard has no watermark for yet.
+ self.stdout.write("4/6 purging pre-flip buffer files")
+ for schema in eligible:
+ purge_buffer_prefix(source.team_id, str(schema.id), logger)
+ self._verify_prefixes_empty(source.team_id, eligible)
+
+ self.stdout.write("5/6 setting cdc_ingest_mode=buffered")
+ source.job_inputs = {**(source.job_inputs or {}), "cdc_ingest_mode": "buffered"}
+ source.save(update_fields=["job_inputs"])
+
+ self.stdout.write("6/6 unpausing schedules")
+ unpause_cdc_extraction_schedule(source_id)
+ self._set_schema_schedules(eligible, paused=False)
+
+ self.stdout.write(self.style.SUCCESS(f"Source {source_id} is now buffered."))
+ self.stdout.write(
+ "Verify: capture writes buffer files and advances the slot; the next sync merges and "
+ 'advances sync_type_config["cdc_load_position"]; consumed files disappear on the run after.'
+ )
+
+ def _roll_back(
+ self,
+ source: ExternalDataSource,
+ eligible: list[ExternalDataSchema],
+ cdc_schemas: list[ExternalDataSchema],
+ drain_timeout: int,
+ ) -> None:
+ from products.data_warehouse.backend.facade.api import (
+ pause_cdc_extraction_schedule,
+ unpause_cdc_extraction_schedule,
+ )
+
+ source_id = str(source.id)
+
+ # Pausing the schedule stops future firings, not a workflow already running — which can
+ # keep writing buffer files and advancing the slot. The drain check below is meaningless
+ # until capture is actually idle.
+ self.stdout.write("1/6 pausing extraction schedule")
+ 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)
+
+ # 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
+ # is idle so the buffer is static; the still-running scheduled sync drains it. Scanned over
+ # every schema the buffered lane serves, which includes ones disabled after the flip — but
+ # not the legacy ones, whose prefixes hold shadow copies no consumer will ever read.
+ self.stdout.write("3/6 waiting for the consumer to drain the buffer")
+ self._wait_for_buffer_drain(source.team_id, [s for s in cdc_schemas if serves_buffered_lane(s)], drain_timeout)
+
+ # Consumer next: a sync merging old buffered rows AFTER legacy capture resumed would
+ # overwrite newer legacy writes — legacy writes carry no position, so the guard can't
+ # protect them. Strict: a schedule that failed to pause could start such a sync.
+ self.stdout.write("4/6 pausing per-schema schedules")
+ self._pause_schema_schedules_strict(eligible)
+ self._wait_for_running_sync_jobs(source.team_id, [str(s.id) for s in eligible], drain_timeout)
+
+ self.stdout.write("5/6 setting cdc_ingest_mode=legacy")
+ source.job_inputs = {**(source.job_inputs or {}), "cdc_ingest_mode": "legacy"}
+ source.save(update_fields=["job_inputs"])
+
+ # Leftover fully-applied files stay: the position guard no-ops a replay, the S3 TTL clears them.
+ self.stdout.write("6/6 unpausing extraction schedule")
+ unpause_cdc_extraction_schedule(source_id)
+
+ self.stdout.write(self.style.SUCCESS(f"Source {source_id} is now legacy."))
+
+ def _wait_for_extraction_idle(self, source_id: str, timeout: int) -> None:
+ from products.data_warehouse.backend.facade.api import cdc_extraction_schedule_has_running_action
+
+ deadline = time.monotonic() + timeout
+ while cdc_extraction_schedule_has_running_action(source_id):
+ if time.monotonic() >= deadline:
+ raise CommandError(
+ f"An extraction run is still executing after {timeout}s. The schedule is left "
+ "paused and the mode unchanged — wait for it to finish, then re-run."
+ )
+ self.stdout.write(" waiting, extraction run still executing")
+ time.sleep(DRAIN_POLL_SECONDS)
+
+ def _wait_for_buffer_drain(self, team_id: int, schemas: list[ExternalDataSchema], timeout: int) -> None:
+ """Block until every remaining buffer file sits strictly below the schema's load position.
+
+ A file AT the position is not proof of consumption: one Postgres transaction shares a commit
+ position across every event, so a transaction split across files leaves an unread tail whose
+ `end_seq` already equals the floor, and `drop_superseded_rows` keeps rows at the watermark
+ precisely so that tail can still land. The consumer settles it by deleting the file once a
+ completed run proves it read it, so waiting for the deletion is the same proof the consumer
+ uses — a couple of ticks on an idle schema.
+ """
+ from products.data_warehouse.backend.facade.api import get_s3_client
+
+ s3 = get_s3_client()
+ deadline = time.monotonic() + timeout
+ while True:
+ behind: list[str] = []
+ for schema in schemas:
+ schema.refresh_from_db(fields=["sync_type_config"])
+ floor = read_load_position(schema.sync_type_config, consolidated_resource_name(schema)) or 0
+ prefix = strip_s3_protocol(get_buffer_prefix(team_id, str(schema.id)))
+ try:
+ keys = s3.ls(prefix, detail=False, refresh=True)
+ except FileNotFoundError:
+ continue
+ for key in keys:
+ parsed = parse_buffer_file_name(key.rsplit("/", 1)[-1])
+ if parsed is not None and parsed.end_seq >= floor:
+ behind.append(schema.name)
+ break
+ if not behind:
+ return
+ if time.monotonic() >= deadline:
+ raise CommandError(
+ f"Buffered changes not yet proven applied for: {', '.join(sorted(behind))} after "
+ f"{timeout}s. Rolling back now could lose them — the slot already advanced past that "
+ "WAL, and the consumer deletes each file only once it proves it read it. Extraction "
+ "is left paused; let the scheduled syncs catch up, then re-run."
+ )
+ self.stdout.write(f" waiting, buffer not drained for: {', '.join(sorted(behind))}")
+ time.sleep(DRAIN_POLL_SECONDS)
+
+ def _pause_schema_schedules_strict(self, schemas: list[ExternalDataSchema]) -> None:
+ from products.data_warehouse.backend.facade.api import pause_external_data_schedule
+
+ for schema in schemas:
+ try:
+ pause_external_data_schedule(str(schema.id))
+ except Exception as exc:
+ raise CommandError(
+ f"Could not pause the schedule for {schema.name}; a sync starting mid-rollback "
+ f"could overwrite newer legacy rows. Mode unchanged — fix and re-run. ({exc})"
+ )
+
+ def _verify_prefixes_empty(self, team_id: int, eligible: list[ExternalDataSchema]) -> None:
+ """Abort if any buffer file survived the purge.
+
+ The purge itself is best-effort, but a leftover file here means the first buffered sync
+ replays rows the legacy lane already delivered, against a lane with no watermark yet —
+ silently. The source is still paused and the mode unset, so aborting is clean.
+ """
+ from products.data_warehouse.backend.facade.api import get_s3_client
+
+ s3 = get_s3_client()
+ leftovers: list[str] = []
+ for schema in eligible:
+ prefix = strip_s3_protocol(get_buffer_prefix(team_id, str(schema.id)))
+ try:
+ keys = s3.ls(prefix, detail=False, refresh=True)
+ except FileNotFoundError:
+ continue
+ leftovers.extend(k for k in keys if parse_buffer_file_name(k.rsplit("/", 1)[-1]) is not None)
+ if leftovers:
+ raise CommandError(
+ f"{len(leftovers)} buffer file(s) survived the purge (first: {leftovers[0]}). "
+ "The source is left paused and the mode unchanged — clear the prefix and re-run."
+ )
+
+ def _wait_for_sourcebatch_drain(self, team_id: int, schema_ids: list[str], timeout: int) -> None:
+ """Block until no sourcebatch batch for these schemas is still working.
+
+ Flipping while a batch is mid-flight would leave it to land after the source stopped
+ producing them, against a table the buffered lane has started writing.
+ """
+ if not schema_ids:
+ return
+
+ deadline = time.monotonic() + timeout
+ conn = psycopg.Connection.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True)
+ try:
+ while True:
+ age = BatchQueue.get_oldest_non_terminal_batch_age_seconds(conn, team_id=team_id, schema_ids=schema_ids)
+ if age is None:
+ return
+ if time.monotonic() >= deadline:
+ raise CommandError(
+ f"sourcebatch still has a batch {age:.0f}s old after {timeout}s. "
+ "The source is left paused — investigate the stuck load before flipping."
+ )
+ self.stdout.write(f" waiting, oldest batch {age:.0f}s old")
+ time.sleep(DRAIN_POLL_SECONDS)
+ finally:
+ conn.close()
+
+ def _wait_for_running_sync_jobs(self, team_id: int, schema_ids: list[str], timeout: int) -> None:
+ if not schema_ids:
+ return
+
+ deadline = time.monotonic() + timeout
+ while True:
+ running = ExternalDataJob.objects.filter(
+ team_id=team_id, schema_id__in=schema_ids, status=ExternalDataJob.Status.RUNNING
+ ).count()
+ if running == 0:
+ return
+ if time.monotonic() >= deadline:
+ raise CommandError(
+ f"{running} sync job(s) still running after {timeout}s. Schedules are left "
+ "paused and the mode unchanged — wait for them to finish, then re-run."
+ )
+ self.stdout.write(f" waiting, {running} sync job(s) running")
+ time.sleep(DRAIN_POLL_SECONDS)
+
+ def _set_schema_schedules(self, schemas: list[ExternalDataSchema], *, paused: bool) -> None:
+ from products.data_warehouse.backend.facade.api import (
+ pause_external_data_schedule,
+ unpause_external_data_schedule,
+ )
+
+ for schema in schemas:
+ try:
+ if paused:
+ pause_external_data_schedule(str(schema.id))
+ else:
+ unpause_external_data_schedule(str(schema.id))
+ except Exception:
+ # The mode is already persisted, so a failed schedule call is recoverable by hand;
+ # aborting here would leave the source half-flipped instead.
+ self.stdout.write(self.style.WARNING(f" could not set schedule for {schema.name} — do it manually"))
+ logger.warning("cdc_flip_schedule_failed", schema_id=str(schema.id), exc_info=True)
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 37b0199abe6e..e85993256700 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -57,6 +57,7 @@ from products.warehouse_sources.backend.facade.source_management import (
WebhookSource,
filter_dwh_columns_by_enabled_columns as _filter_dwh_columns_by_enabled_columns,
get_cdc_adapter,
+ purge_buffer_prefix,
source_type_supports_cdc,
validate_and_coerce_row_filters,
)
@@ -1501,6 +1502,23 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
instance.table.soft_delete()
instance.soft_delete()
+ # CDC teardown, both best-effort: leaving the table in the publication makes the
+ # customer's WAL carry its changes forever, and the buffer files are raw change data
+ # nothing will consume — otherwise they sit until the 14-day lifecycle expiry.
+ if instance.sync_type == ExternalDataSchema.SyncType.CDC:
+ try:
+ source = instance.source
+ adapter = get_cdc_adapter(source)
+ _, db_schema, source_table_name = get_postgres_source_location(
+ schema_name=instance.name,
+ schema_metadata=instance.schema_metadata,
+ default_schema=(source.job_inputs or {}).get("schema"),
+ )
+ adapter.remove_table(source, db_schema, source_table_name)
+ except Exception:
+ logger.exception("Failed to remove deleted CDC schema from publication", schema_id=str(instance.id))
+ purge_buffer_prefix(self.team_id, str(instance.id), logger)
+
return Response(status=status.HTTP_204_NO_CONTENT)
@extend_schema(parameters=[LogEntryRequestSerializer])
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.py
index 877a142a0fa7..77589caa3b47 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py
@@ -483,6 +483,9 @@ _CDC_EXPOSED_JOB_INPUT_KEYS = {
"cdc_lag_warning_threshold_mb",
"cdc_lag_critical_threshold_mb",
"cdc_consistent_point",
+ # Set by migrate_cdc_source_to_buffered, never by the API. Losing it on an unrelated PATCH
+ # would resume legacy delivery from an advanced slot and strand the unread buffer.
+ "cdc_ingest_mode",
}
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 eba44f8aa497..1e9677d2b3d9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -64,14 +64,18 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import
MAX_FRIENDLY_MESSAGE_LENGTH,
CDCErrorCategory,
CDCErrorInfo,
+ CDCReservedColumnError,
CDCSchemaMergeError,
CDCSlotNotConfiguredError,
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.source_manager import (
+ consolidated_resource_name,
+ serves_buffered_lane,
+)
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import resolve_table_and_folder_names
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import SyncTypeLiteral
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
BatchQueue,
@@ -234,17 +238,21 @@ class CDCExtractActivity:
self.all_table_names: set[str] = set()
# Wall-clock start, set in run(); drives cdc_extraction_duration_seconds.
self._run_started_at: float | None = None
- # Shadow buffered-ingress state (dwh-cdc-buffer-shadow flag). Writer is lazy so
- # runs with shadow off never touch S3 setup; the per-schema file index keeps
- # same-position-range batches (a split transaction) from overwriting each other.
- self._shadow_buffer_writer: CDCBufferWriter | None = None
- self._shadow_file_index: dict[str, int] = {}
- self._shadow_cleaned_schemas: set[str] = set()
+ # Buffer state, shared by the shadow lane and buffered ingress. Writer is lazy so runs that
+ # buffer nothing never touch S3 setup; the per-schema file index keeps same-position-range
+ # batches (a split transaction) from overwriting each other.
+ self._buffer_writer: CDCBufferWriter | None = None
+ self._buffer_file_index: dict[str, int] = {}
+ self._buffer_cleaned_schemas: set[str] = set()
+ # Shadow-only: the lane is validation, so it disables itself rather than failing a run.
self._shadow_write_failures: int = 0
self._shadow_disabled_for_run: bool = False
# Resolved once in _setup (the dwh-cdc-buffer-shadow flag) so neither the
# flush path nor the batcher re-evaluates a flag per micro-batch.
self._shadow_enabled: bool = False
+ # 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()
# ------------------------------------------------------------------
# Logger helpers
@@ -587,15 +595,6 @@ class CDCExtractActivity:
# ------------------------------------------------------------------
# Storage naming
# ------------------------------------------------------------------
- def _consolidated_resource_name(self, schema: ExternalDataSchema) -> str:
- """Storage name for the consolidated table — must match the snapshot pipeline's.
-
- The CDC stream must target the same folder, otherwise streamed changes
- land in a parallel Delta table no query reads. `name` and folder diverge
- for rows renamed bare→qualified (`name="public.users"`, folder `users`).
- """
- return resolve_table_and_folder_names(schema.name, schema.resolved_s3_folder_name).folder_name
-
def _partition_kwargs(self, schema: ExternalDataSchema) -> dict[str, typing.Any]:
"""Replay snapshot partitioning so CDC rows match the target Delta.
@@ -619,56 +618,68 @@ class CDCExtractActivity:
# micro-batch, stalling the WAL drain loop. The next run retries fresh.
_SHADOW_MAX_CONSECUTIVE_FAILURES = 3
- def _maybe_shadow_write_buffer(self, schema: ExternalDataSchema, table_name: str, table: pa.Table) -> None:
- """Shadow-write one micro-batch to the S3 change buffer (dwh-cdc-buffer-shadow flag).
-
- Validation-only while the legacy path stays authoritative: failures are
- swallowed (metric + log) so shadow can never fail an extraction, and the
- slot-advance rules are untouched — gaps in the buffer are expected and
- surfaced by the validate_cdc_buffer command, not guarded against here.
+ def _write_buffer_file(self, schema: ExternalDataSchema, table_name: str, table: pa.Table, *, lane: str) -> None:
+ """Write one micro-batch to the S3 change buffer. Raises on failure — the caller owns the
+ policy, which differs by lane: shadow swallows, buffered ingress must not.
"""
- if not self._shadow_enabled or self._shadow_disabled_for_run:
- return
- if table.num_rows == 0 or not has_engine_seq(table):
- return
-
- file_index = self._shadow_file_index.get(table_name, 0)
+ file_index = self._buffer_file_index.get(table_name, 0)
try:
- if self._shadow_buffer_writer is None:
- self._shadow_buffer_writer = CDCBufferWriter(self.log)
+ if self._buffer_writer is None:
+ self._buffer_writer = CDCBufferWriter(self.log)
schema_id = str(schema.id)
- if schema_id not in self._shadow_cleaned_schemas:
+ if schema_id not in self._buffer_cleaned_schemas:
# First write this run: remove files a superseded attempt left at or
# past where this run restarted (batch boundaries are not stable
# across attempts — see buffer.py). The batch's min seq IS the
# restart floor for this schema.
restart_seq = pc.min(table.column(CDC_SEQ_COLUMN)).as_py()
- self._shadow_buffer_writer.cleanup_superseded_files(
+ self._buffer_writer.cleanup_superseded_files(
team_id=schema.team_id, schema_id=schema_id, restart_seq=restart_seq
)
- self._shadow_cleaned_schemas.add(schema_id)
+ self._buffer_cleaned_schemas.add(schema_id)
- result = self._shadow_buffer_writer.write_batch(
+ result = self._buffer_writer.write_batch(
team_id=schema.team_id,
schema_id=schema_id,
table=table,
file_index=file_index,
)
- self._shadow_write_failures = 0
- metrics.get_shadow_buffer_files_written_metric(self.inputs.team_id, str(self.inputs.source_id)).add(1)
- metrics.get_shadow_buffer_write_duration_metric(self.inputs.team_id, str(self.inputs.source_id)).record(
+ metrics.get_buffer_files_written_metric(self.inputs.team_id, str(self.inputs.source_id), lane).add(1)
+ metrics.get_buffer_write_duration_metric(self.inputs.team_id, str(self.inputs.source_id), lane).record(
result.write_duration_seconds
)
self._schema_log(schema).debug(
- "cdc_shadow_buffer_written",
+ "cdc_buffer_written",
table=table_name,
s3_path=result.s3_path,
rows=result.row_count,
start_seq=result.start_seq,
end_seq=result.end_seq,
)
+ finally:
+ # Advance even on failure so ordinals stay aligned with batch position:
+ # a lost chunk becomes an honest index gap instead of a later chunk
+ # silently claiming its slot.
+ self._buffer_file_index[table_name] = file_index + 1
+
+ def _maybe_shadow_write_buffer(self, schema: ExternalDataSchema, table_name: str, table: pa.Table) -> None:
+ """Shadow-write one micro-batch to the S3 change buffer (dwh-cdc-buffer-shadow flag).
+
+ Validation-only while the legacy path stays authoritative: failures are
+ swallowed (metric + log) so shadow can never fail an extraction, and the
+ slot-advance rules are untouched — gaps in the buffer are expected and
+ surfaced by the validate_cdc_buffer command, not guarded against here.
+ """
+ if not self._shadow_enabled or self._shadow_disabled_for_run:
+ return
+ if table.num_rows == 0 or not has_engine_seq(table):
+ return
+
+ try:
+ self._write_buffer_file(schema, table_name, table, lane="shadow")
+ self._shadow_write_failures = 0
except Exception:
self._shadow_write_failures += 1
metrics.get_shadow_buffer_write_errors_metric(self.inputs.team_id, str(self.inputs.source_id)).add(1)
@@ -676,11 +687,6 @@ class CDCExtractActivity:
if self._shadow_write_failures >= self._SHADOW_MAX_CONSECUTIVE_FAILURES:
self._shadow_disabled_for_run = True
self.log.warning("cdc_shadow_buffer_disabled_for_run", consecutive_failures=self._shadow_write_failures)
- finally:
- # Advance even on failure so ordinals stay aligned with batch position:
- # a lost chunk becomes an honest index gap instead of a later chunk
- # silently claiming its slot.
- self._shadow_file_index[table_name] = file_index + 1
# ------------------------------------------------------------------
# Per-flush processing
@@ -718,6 +724,19 @@ class CDCExtractActivity:
enriched_table = enrich_toast_omitted_rows(raw_table, key_columns)
enriched_table = enrich_delete_rows(enriched_table, key_columns)
+ if table_name in self._buffered_table_names:
+ # The buffer IS the delivery for this schema — the scheduled sync consumes it.
+ # A swallowed failure here would lose changes the slot is about to advance past,
+ # so this write must fail the run.
+ if enriched_table.num_rows:
+ # A source column named _ph_cdc_seq means the batcher could not append the
+ # engine position; writing anyway would name, order, and clean up files by
+ # customer data — cleanup can then delete unconsumed files (see errors.py).
+ if not has_engine_seq(enriched_table):
+ raise CDCReservedColumnError(f"Table {table_name} has a source column named {CDC_SEQ_COLUMN}")
+ self._write_buffer_file(schema, table_name, enriched_table, lane="ingress")
+ continue
+
# Buffer the raw (pre-dedup/SCD2) stream, then strip the seq column so the legacy write
# path stays byte-identical. Only ours — a source column of the same name stays.
self._maybe_shadow_write_buffer(schema, table_name, enriched_table)
@@ -728,7 +747,7 @@ class CDCExtractActivity:
# CDC-only and stays self-consistent with its `name`-keyed snapshot seed.
batch_writes: list[tuple[pa.Table, str, str]] = []
if cdc_table_mode == "consolidated":
- consolidated_name = self._consolidated_resource_name(schema)
+ consolidated_name = consolidated_resource_name(schema)
batch_writes.append(
(deduplicate_table(enriched_table, key_columns), consolidated_name, "incremental_merge")
)
@@ -741,7 +760,7 @@ class CDCExtractActivity:
)
)
elif cdc_table_mode == "both":
- consolidated_name = self._consolidated_resource_name(schema)
+ consolidated_name = consolidated_resource_name(schema)
batch_writes.append(
(deduplicate_table(enriched_table, key_columns), consolidated_name, "incremental_merge")
)
@@ -912,6 +931,30 @@ class CDCExtractActivity:
self.adapter = get_cdc_adapter(self.source)
self.reader = self.adapter.create_reader(self.source)
self._shadow_enabled = is_shadow_write_enabled(self.inputs.team_id, self.log)
+
+ if self.adapter.parse_cdc_config(self.source).ingest_mode == "buffered":
+ # A schema with deferred runs pending stays legacy this tick, so the flush and any new
+ # 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_pending_legacy_backlog).
+ 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")
+ }
+ if self._buffered_table_names:
+ self.log.info(
+ "cdc_buffered_ingress_active",
+ buffered=sorted(self._buffered_table_names),
+ legacy=sorted(s.name for s in self.cdc_schemas if s.name not in self._buffered_table_names),
+ )
+
+ # Guarded like the metric meter: CDC activity bodies are also exercised by direct
+ # instantiation outside an activity context, where activity.info() raises.
+ attempt = activity.info().attempt if activity.in_activity() else 1
+ if attempt > 1:
+ metrics.get_extract_retry_metric(self.inputs.team_id, str(self.inputs.source_id)).add(1)
+ self.log.info("cdc_extract_retry_attempt", attempt=attempt)
return True
def _delete_own_schedule(self) -> None:
@@ -943,7 +986,14 @@ class CDCExtractActivity:
which triggers the existing full re-sync recovery. Fail-open on probe errors — the
producer writes to the same DB, so a run that can't be probed can't enqueue either.
"""
- schema_ids = [str(s.id) for s in self.cdc_schemas]
+ # Buffered schemas enqueue nothing and their loads can't reorder — the scheduled sync runs
+ # one job per schema at a time and the position guard backstops it. The guard only remains
+ # while some schema still dispatches through sourcebatch.
+ legacy_schemas = [s for s in self.cdc_schemas if s.name not in self._buffered_table_names]
+ if not legacy_schemas:
+ return False
+
+ schema_ids = [str(s.id) for s in legacy_schemas]
try:
conn = psycopg.Connection.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True)
except Exception:
@@ -1194,11 +1244,12 @@ class CDCExtractActivity:
assert self._run_started_at is not None
assert self.adapter is not None
event_name_to_schema_name = self._build_event_name_map()
- # Converter only when shadow is on: with the flag off, the legacy lane
- # must not gain the seq column's per-event cost or its parse/overflow
- # crash surface.
+ # Converter only when a lane consumes positions: an all-legacy run must not gain the seq
+ # column's per-event cost or its parse/overflow crash surface.
self.batcher = ChangeEventBatcher(
- position_to_seq=self.adapter.position_to_seq if self._shadow_enabled else None
+ position_to_seq=self.adapter.position_to_seq
+ if (self._shadow_enabled or self._buffered_table_names)
+ else None
)
on_row = self._make_read_heartbeat()
@@ -1790,6 +1841,11 @@ class CDCExtractActivity:
try:
# The heartbeat records liveness (this run happened), independent of health.
self._record_run_heartbeat(schema, now)
+ # A buffered schema's status belongs to the scheduled sync that consumes its files.
+ # Repainting COMPLETED here would erase a failing consumer run within one capture tick,
+ # hiding a buffer backlog until its files hit the S3 TTL — which is unrecoverable.
+ if schema.name in self._buffered_table_names:
+ return False
if not complete_schema_run(schema, last_synced_at=now):
self._schema_log(schema).info("cdc_success_repaint_skipped_broken")
return False
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 fa1d97ea086a..63fd88a745eb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py
@@ -22,14 +22,17 @@ positions with differently-shaped files. Writers therefore call
past the position the retry re-reads from is superseded and removed. A schema
reset (TRUNCATE / lost slot) invalidates the whole prefix — `purge_buffer_prefix`.
-Enablement is the `dwh-cdc-buffer-shadow` feature flag alone (per team, so a soak
-covers a couple of projects rather than every CDC source on the worker). Evaluated
-once per extraction run, never per flush, and fail-closed: a flag-service outage
-leaves the lane off, so there is no path to accidental enablement.
-
-Retention: no TTL exists yet; resets and CDC-disable purge, ordinary settled files
-do not expire. An S3 lifecycle rule on `cdc_producer/` is tracked for the fleet-wide
-soak — until it exists, keep the flag on a handful of projects.
+Two lanes write here. Shadow (the `dwh-cdc-buffer-shadow` feature flag, per team,
+evaluated once per extraction run and fail-closed) writes a validation copy while
+legacy delivery stays authoritative. Buffered ingress (`cdc_ingest_mode="buffered"`
+in the source's `job_inputs`) writes the same files as the ONLY delivery — the
+scheduled sync consumes them, and a write failure fails the run rather than being
+swallowed, because the slot is about to advance past those changes.
+
+Retention: an S3 lifecycle rule on `cdc_producer/` (`expire-cdc-producer-buffer`)
+expires files after 14 days. Resets and CDC-disable purge sooner. For a buffered
+schema, expiry of unconsumed files is unrecoverable — the slot advanced long ago —
+so consumer lag is watched against file age, not file count.
"""
from __future__ import annotations
@@ -252,15 +255,23 @@ class CDCBufferWriter:
return removed
-def purge_buffer_prefix(team_id: int, schema_id: str, logger: FilteringBoundLogger) -> None:
- """Best-effort removal of a schema's entire buffer prefix.
+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): the legacy 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.
+ 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.
"""
prefix = strip_s3_protocol(get_buffer_prefix(team_id, schema_id))
- with suppress(Exception):
+ try:
s3 = get_s3_client()
s3.rm(prefix, recursive=True)
logger.info("cdc_buffer_prefix_purged", schema_id=schema_id)
+ except FileNotFoundError:
+ pass
+ except Exception:
+ if strict:
+ raise
+ logger.warning("cdc_buffer_prefix_purge_failed", schema_id=schema_id, exc_info=True)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py
index 9680cce2a6f1..a48b7404048c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py
@@ -35,6 +35,7 @@ class CDCErrorCategory(enum.StrEnum):
WAL_DECODE_ERROR = "wal_decode_error"
TRANSACTION_TOO_LARGE = "transaction_too_large"
SCHEMA_MERGE_INCOMPATIBLE = "schema_merge_incompatible"
+ RESERVED_COLUMN_CONFLICT = "reserved_column_conflict"
UNKNOWN = "unknown"
@@ -65,6 +66,18 @@ class CDCSlotNotConfiguredError(Exception):
"""
+class CDCReservedColumnError(Exception):
+ """A source table carries a column whose name PostHog reserves for change ordering.
+
+ Non-retryable: the collision is a property of the customer's table, so replaying re-fails.
+ Raised only on the buffered-ingress path — buffer files derive their name, ordering, and
+ retry cleanup from the engine position column, and a same-named source column means the
+ batcher could not append it. Writing anyway would order and clean up by customer data,
+ which can silently delete unconsumed buffer files. The legacy path is unaffected: it
+ passes the customer's column through untouched.
+ """
+
+
class CDCSchemaMergeError(Exception):
"""A column's values can't be reconciled into one Parquet type across micro-batches.
@@ -142,6 +155,12 @@ _CATEGORY_DEFAULTS: dict[CDCErrorCategory, tuple[str, bool]] = {
"re-enable change data capture to re-sync from a fresh snapshot.",
False,
),
+ CDCErrorCategory.RESERVED_COLUMN_CONFLICT: (
+ "A source table has a column named _ph_cdc_seq, which PostHog reserves for ordering change "
+ "data. Rename that column on the source table, or contact support to keep this table on the "
+ "previous sync mode.",
+ False,
+ ),
CDCErrorCategory.UNKNOWN: (
"Change data capture hit an unexpected error. PostHog will retry automatically — if it "
"persists, check the source's sync logs or contact support.",
@@ -180,6 +199,8 @@ def classify_cdc_error(exc: BaseException, adapter: CDCSourceAdapter | None) ->
return cdc_error_info(CDCErrorCategory.TRANSACTION_TOO_LARGE)
if isinstance(err, CDCSchemaMergeError):
return cdc_error_info(CDCErrorCategory.SCHEMA_MERGE_INCOMPATIBLE)
+ if isinstance(err, CDCReservedColumnError):
+ return cdc_error_info(CDCErrorCategory.RESERVED_COLUMN_CONFLICT)
if adapter is not None:
info = adapter.classify_error(err)
if info is not None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.py
index 55d3837dc23f..3c40bd3a36ce 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.py
@@ -43,9 +43,24 @@ def get_micro_batches_flushed_metric(team_id: int, source_id: str) -> MetricCoun
)
-def get_shadow_buffer_files_written_metric(team_id: int, source_id: str) -> MetricCounter:
+def get_buffer_files_written_metric(team_id: int, source_id: str, lane: str) -> MetricCounter:
+ """`lane` is "shadow" (validation copy) or "ingress" (authoritative delivery)."""
+ return (
+ _source_meter(team_id, source_id)
+ .with_additional_attributes({"lane": lane})
+ .create_counter("cdc_buffer_files_written_total", "Total buffer files written, by lane")
+ )
+
+
+def get_extract_retry_metric(team_id: int, source_id: str) -> MetricCounter:
+ """Extraction runs that are not the first attempt.
+
+ Exposure proxy for the zombie-attempt collision: a superseded attempt that is still alive can
+ overwrite a live attempt's buffer file over the same position range with fewer rows, and that
+ loss has no detector of its own. It takes a retry to reach, so a quiet counter bounds the risk.
+ """
return _source_meter(team_id, source_id).create_counter(
- "cdc_shadow_buffer_files_written_total", "Total buffer files written in shadow mode"
+ "cdc_extract_retried_attempts_total", "Extraction runs starting at attempt > 1"
)
@@ -55,9 +70,11 @@ def get_shadow_buffer_write_errors_metric(team_id: int, source_id: str) -> Metri
)
-def get_shadow_buffer_write_duration_metric(team_id: int, source_id: str) -> MetricHistogramFloat:
- return _source_meter(team_id, source_id).create_histogram_float(
- "cdc_shadow_buffer_write_duration_seconds", "Duration of shadow buffer S3 writes", "s"
+def get_buffer_write_duration_metric(team_id: int, source_id: str, lane: str) -> MetricHistogramFloat:
+ return (
+ _source_meter(team_id, source_id)
+ .with_additional_attributes({"lane": lane})
+ .create_histogram_float("cdc_buffer_write_duration_seconds", "Duration of buffer S3 writes, by lane", "s")
)
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
new file mode 100644
index 000000000000..7f1d26540ed6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/source_manager.py
@@ -0,0 +1,300 @@
+"""Consume the S3 change buffer on the normal scheduled sync.
+
+The egress half of buffered CDC: capture writes position-named Parquet files (see `buffer.py`) and
+this reads them back as an ordinary source, so change events reach the loader through the same path
+every other source uses.
+
+Files are deleted once the persisted load position proves their rows are committed, never on yield —
+the v3 batcher buffers across generator yields, so a yielded table can still be in memory when the
+generator resumes.
+"""
+
+from __future__ import annotations
+
+import uuid
+import datetime as dt
+from collections.abc import AsyncGenerator
+from typing import TYPE_CHECKING
+
+import psycopg
+import pyarrow as pa
+import pyarrow.parquet as pq
+from structlog.types import FilteringBoundLogger
+
+from posthog.dataclasses import frozen
+from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
+from posthog.sync import database_sync_to_async_pool
+
+from products.data_warehouse.backend.facade.api import aget_s3_client
+from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import (
+ BufferFileSpan,
+ get_buffer_prefix,
+ parse_buffer_file_name,
+)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import read_load_position
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import resolve_table_and_folder_names
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
+ BatchQueue,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.batching import (
+ DEFAULT_BATCH_BYTE_LIMIT,
+ DEFAULT_BATCH_ROW_LIMIT,
+ TableBatcher,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.db import db_read_with_retry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+# The only lane this manager serves. `cdc_only` and `both` need a second output per run, which one
+# pipeline run cannot express — those schemas stay on the legacy extraction path.
+CONSOLIDATED_TABLE_MODE = "consolidated"
+
+# The loader's write mode for this lane, and the flag that tells the pipeline a run carries change
+# events rather than rows read from a table.
+CONSOLIDATED_WRITE_MODE = "incremental_merge"
+
+
+# Slack when comparing an S3 mtime against a listing timestamp from our clock, so skew between the
+# two can never make a file look older than a listing that in fact never saw it.
+_CONSUMED_MTIME_MARGIN = dt.timedelta(minutes=5)
+
+# The last buffer listing, `{"listed_at": iso, "job_id": str}` — a sibling of `cdc_load_position`.
+# It matures into a deletion proof only if that job COMPLETES (see _completed_listing_time).
+BUFFER_LISTING_CONFIG_KEY = "cdc_buffer_listing"
+
+
+def serves_buffered_lane(schema: ExternalDataSchema) -> bool:
+ """Schema-side conditions for buffered ingress; the source's `ingest_mode` is the other half.
+
+ Fails closed on every axis: a lane this manager cannot write, or a schema with no table yet,
+ stays on the legacy extraction path.
+ """
+ return bool(
+ schema.is_cdc
+ and schema.cdc_mode == "streaming"
+ and schema.cdc_table_mode == CONSOLIDATED_TABLE_MODE
+ and schema.initial_sync_complete
+ )
+
+
+def is_buffered_consolidated(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)
+
+
+def has_pending_legacy_backlog(schema: ExternalDataSchema) -> bool:
+ """Whether legacy-lane deliveries for this schema are still in flight.
+
+ Deferred runs and sourcebatch batches carry no position column, so nothing orders them against
+ buffered writes — a consumer merge racing them lets an older legacy row land after a newer
+ buffered one. The consumer no-ops until both are drained; buffer files just wait.
+ """
+ if schema.sync_type_config.get("cdc_deferred_runs"):
+ return True
+
+ conn = psycopg.Connection.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True)
+ try:
+ age = BatchQueue.get_oldest_non_terminal_batch_age_seconds(
+ conn, team_id=schema.team_id, schema_ids=[str(schema.id)]
+ )
+ finally:
+ conn.close()
+ return age is not None
+
+
+def consolidated_resource_name(schema: ExternalDataSchema) -> str:
+ """Storage name for the consolidated table — must match the snapshot pipeline's.
+
+ `name` and folder diverge for rows renamed bare→qualified (`name="public.users"`, folder
+ `users`), and targeting the wrong one lands changes in a parallel Delta table no query reads.
+ """
+ return resolve_table_and_folder_names(schema.name, schema.resolved_s3_folder_name).folder_name
+
+
+@frozen
+class _BufferFile:
+ span: BufferFileSpan
+ key: str
+ modified: dt.datetime | None
+
+
+class CDCSourceManager:
+ """Reads one schema's buffered change events in position order."""
+
+ def __init__(self, inputs: SourceInputs, logger: FilteringBoundLogger) -> None:
+ self._inputs = inputs
+ self._logger = logger
+
+ async def _read_consume_state(self, resource_name: str) -> tuple[int | None, dict | None]:
+ """The lane's committed floor and the last listing stamp, read once per run.
+
+ The floor decides which files are still needed, not correctness — `drop_superseded_rows` is
+ that, and it re-reads the config per batch on the load side. Reading a stale value here
+ costs one redundant file read whose rows the guard then drops.
+ """
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+ sync_type_config = await database_sync_to_async_pool(db_read_with_retry)(
+ lambda: ExternalDataSchema.objects.values_list("sync_type_config", flat=True).get(
+ id=self._inputs.schema_id, team_id=self._inputs.team_id
+ )
+ )
+ listing = (sync_type_config or {}).get(BUFFER_LISTING_CONFIG_KEY)
+ return read_load_position(sync_type_config, resource_name), listing if isinstance(listing, dict) else None
+
+ async def _stamp_listing(self, listed_at: dt.datetime) -> None:
+ """Record that this run listed the buffer, before any file is read.
+
+ The stamp becomes a deletion proof only once this run's job COMPLETES — see
+ `_completed_listing_time`. Crashing after the stamp leaves the job un-completed, so a
+ partial run can never prove anything.
+ """
+ from products.warehouse_sources.backend.models.external_data_schema import update_sync_type_config_keys
+
+ stamp = {"listed_at": listed_at.isoformat(), "job_id": str(self._inputs.job_id)}
+
+ def _merge(config: dict) -> None:
+ config[BUFFER_LISTING_CONFIG_KEY] = stamp
+
+ await database_sync_to_async_pool(db_read_with_retry)(
+ lambda: update_sync_type_config_keys(self._inputs.schema_id, self._inputs.team_id, mutate=_merge)
+ )
+
+ async def _completed_listing_time(self, listing: dict | None) -> dt.datetime | None:
+ """When the buffer was last listed by a run that went on to COMPLETE, or None.
+
+ Only a completed run proves consumption: completion means the generator drained every
+ listed file and every staged batch committed. A job-status check on the stamped job is what
+ keeps a no-op run (the legacy-backlog gate returns an empty response without listing) or a
+ crashed run from ever serving as proof.
+ """
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+
+ if not listing:
+ return None
+ try:
+ listed_at = dt.datetime.fromisoformat(listing["listed_at"])
+ job_id = uuid.UUID(str(listing["job_id"]))
+ except (KeyError, TypeError, ValueError):
+ return None
+ if listed_at.tzinfo is None:
+ return None
+
+ completed = await database_sync_to_async_pool(db_read_with_retry)(
+ lambda: ExternalDataJob.objects.filter(
+ id=job_id, team_id=self._inputs.team_id, status=ExternalDataJob.Status.COMPLETED
+ ).exists()
+ )
+ return listed_at if completed else None
+
+ async def _list_buffer_files(self) -> list[_BufferFile]:
+ """Buffer files under this schema's prefix, in position order.
+
+ Sorted by the filename's `(start, end, index)` and never by S3 mtime: the position range is
+ the ordering token, and mtime would interleave a retry's files with the attempt it replaced.
+ Names that don't match the contract are ignored rather than guessed at.
+ """
+ prefix = get_buffer_prefix(self._inputs.team_id, str(self._inputs.schema_id))
+
+ async with aget_s3_client() as s3:
+ try:
+ # refresh: capture writes through a different process, so this client's dircache is
+ # never invalidated by them — a cached listing could miss files indefinitely.
+ ls_res = await s3._ls(prefix, detail=True, refresh=True)
+ except FileNotFoundError:
+ await self._logger.adebug("cdc_buffer_prefix_not_found", prefix=prefix)
+ return []
+
+ ls_values = ls_res.values() if isinstance(ls_res, dict) else ls_res
+
+ files: list[_BufferFile] = []
+ for entry in ls_values:
+ if entry["type"] == "directory":
+ continue
+ key = entry["Key"]
+ parsed = parse_buffer_file_name(key.rsplit("/", 1)[-1])
+ if parsed is None:
+ continue
+ modified = entry.get("LastModified")
+ files.append(
+ _BufferFile(span=parsed, key=key, modified=modified if isinstance(modified, dt.datetime) else None)
+ )
+
+ files.sort(key=lambda f: (f.span.start_seq, f.span.end_seq, f.span.file_index))
+ await self._logger.adebug("cdc_buffer_files_listed", prefix=prefix, file_count=len(files))
+ return files
+
+ def _is_consumed(
+ self,
+ end_seq: int,
+ modified: dt.datetime | None,
+ floor: int | None,
+ proof_time: dt.datetime | None,
+ ) -> bool:
+ """Whether a file's rows are all proven committed, so the file can be deleted.
+
+ Strictly below the floor is position-proof: the load-side guard would drop every row anyway.
+ AT the floor, position alone cannot tell a consumed file from the unread tail of a
+ transaction split across files (all its rows share one commit position) — but a file that
+ already existed at `proof_time` (a completed run's listing) was listed, drained, and
+ committed by that run. The margin absorbs clock skew between S3 and our DB; an idle schema's
+ trailing file clears it within a couple of ticks instead of being re-merged and re-billed
+ forever.
+ """
+ if floor is None or end_seq > floor:
+ return False
+ if end_seq < floor:
+ return True
+ if modified is None or modified.tzinfo is None or proof_time is None:
+ return False
+ return modified < proof_time - _CONSUMED_MTIME_MARGIN
+
+ async def get_items(
+ self,
+ resource_name: str,
+ batch_row_limit: int = DEFAULT_BATCH_ROW_LIMIT,
+ batch_byte_limit: int = DEFAULT_BATCH_BYTE_LIMIT,
+ ) -> AsyncGenerator[pa.Table]:
+ listed_at = dt.datetime.now(tz=dt.UTC)
+ files = await self._list_buffer_files()
+ floor, prior_listing = await self._read_consume_state(resource_name)
+ # Proof comes from the PRIOR stamp, resolved before this run overwrites it.
+ proof_time = await self._completed_listing_time(prior_listing) if floor is not None else None
+ await self._stamp_listing(listed_at)
+
+ batch: TableBatcher[str] = TableBatcher(row_limit=batch_row_limit, byte_limit=batch_byte_limit)
+
+ async with aget_s3_client() as s3:
+ for file in files:
+ key = file.key
+ # The only place a buffer file is deleted — see _is_consumed for the proof.
+ if self._is_consumed(file.span.end_seq, file.modified, floor, proof_time):
+ await s3._rm(key)
+ continue
+
+ try:
+ async with await s3.open_async(key, "rb") as f:
+ data = await f.read()
+ table = pq.read_table(pa.BufferReader(data))
+ except FileNotFoundError:
+ # A concurrent run, or a retry of this activity, can have deleted the file
+ # between the listing and this open — the listing is a snapshot, not a lease.
+ await self._logger.adebug("cdc_buffer_file_already_consumed", key=key)
+ continue
+
+ if table.num_rows == 0:
+ continue
+
+ if batch.add(table):
+ yield self._finalize_batch(batch.tables)
+ batch.reset()
+
+ if batch:
+ yield self._finalize_batch(batch.tables)
+
+ def _finalize_batch(self, tables: list[pa.Table]) -> pa.Table:
+ # `permissive` because a column added to the source table mid-stream makes later files
+ # wider; the loader's schema evolution handles the union.
+ return pa.concat_tables(tables, promote_options="permissive")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py
new file mode 100644
index 000000000000..dbc41b149c17
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py
@@ -0,0 +1,80 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import CDCHandledExternally
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSource
+
+_SCHEMA_MODEL = "products.warehouse_sources.backend.models.external_data_schema.ExternalDataSchema"
+_MANAGER = "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager"
+
+
+def _schema(ingest_mode: str = "buffered", **overrides) -> MagicMock:
+ schema = MagicMock()
+ schema.name = "users"
+ schema.is_cdc = overrides.get("is_cdc", True)
+ schema.cdc_mode = overrides.get("cdc_mode", "streaming")
+ schema.cdc_table_mode = overrides.get("cdc_table_mode", "consolidated")
+ schema.initial_sync_complete = overrides.get("initial_sync_complete", True)
+ schema.sync_type_config = {}
+ schema.schema_metadata = {}
+ schema.resolved_s3_folder_name = None
+ schema.primary_key_columns = ["id"]
+ schema.source.job_inputs = {"cdc_enabled": True, "cdc_ingest_mode": ingest_mode}
+ return schema
+
+
+def _inputs(reset_pipeline: bool = False) -> SourceInputs:
+ return SourceInputs(
+ schema_name="users",
+ schema_id="3f7c1f4e-0000-0000-0000-000000000001",
+ source_id="3f7c1f4e-0000-0000-0000-000000000002",
+ team_id=7,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job-1",
+ logger=MagicMock(),
+ reset_pipeline=reset_pipeline,
+ )
+
+
+def _dispatch(schema: MagicMock, inputs: SourceInputs, backlog: bool = False):
+ with (
+ patch(f"{_SCHEMA_MODEL}.objects") as objects,
+ patch(f"{_MANAGER}.has_pending_legacy_backlog", return_value=backlog),
+ patch.object(PostgresSource, "make_ssh_tunnel_func", return_value=MagicMock()),
+ ):
+ objects.select_related.return_value.get.return_value = schema
+ return PostgresSource().source_for_pipeline(MagicMock(), inputs)
+
+
+class TestBufferedDispatch:
+ def test_a_flipped_schema_is_consumed_here_instead_of_by_the_extraction_workflow(self):
+ response = _dispatch(_schema(), _inputs())
+
+ assert response.name == "users"
+ assert response.cdc_write_mode == "incremental_merge"
+
+ @pytest.mark.parametrize(
+ "overrides,ingest_mode",
+ [
+ ({}, "legacy"),
+ ({"cdc_table_mode": "cdc_only"}, "buffered"),
+ ({"initial_sync_complete": False}, "buffered"),
+ ],
+ )
+ def test_a_schema_the_buffer_does_not_serve_stays_with_the_extraction_workflow(self, overrides, ingest_mode):
+ with pytest.raises(CDCHandledExternally):
+ _dispatch(_schema(ingest_mode, **overrides), _inputs())
+
+ def test_a_pending_legacy_backlog_yields_an_empty_run_rather_than_pausing_the_schedule(self):
+ response = _dispatch(_schema(), _inputs(), backlog=True)
+
+ assert list(response.items()) == []
+
+ def test_a_reset_on_a_streaming_buffered_schema_is_refused(self):
+ with pytest.raises(ValueError, match="cdc_mode='snapshot'"):
+ _dispatch(_schema(), _inputs(reset_pipeline=True))
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 6ec5e38b4223..2f87f3c0d2ae 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
@@ -988,6 +988,7 @@ class TestCDCExtractActivity:
):
source = _make_source()
MockSourceModel.objects.get.return_value = source
+ mock_activity.info.return_value = MagicMock(workflow_id="wf-1", workflow_run_id="run-1", attempt=1)
schema = _make_schema("users", cdc_mode="streaming", source=source)
mock_get_schemas.return_value = [schema]
@@ -3568,3 +3569,137 @@ class TestFailureVisibilityCooldown:
rows_this_run = ExternalDataJob.objects.filter(schema=schema, workflow_run_id="run-2").count()
assert rows_this_run == (1 if expect_new_row else 0)
+
+
+class TestBufferedIngressCapture:
+ # Capture for a flipped source: eligible schemas are delivered by buffer alone, ineligible ones
+ # 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):
+ with (
+ 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(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource"
+ ) as MockSourceModel,
+ patch.object(CDCExtractActivity, "_get_cdc_schemas") as mock_get_schemas,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter"
+ ) as mock_get_adapter,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter"
+ ) as MockS3Writer,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer"
+ ) as MockProducer,
+ patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity") as mock_activity,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.is_shadow_write_enabled",
+ return_value=False,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.complete_schema_run"
+ ) as mock_complete,
+ ):
+ MockBufferWriter.return_value.write_batch.return_value.write_duration_seconds = 0.01
+ mock_reader, mock_s3, mock_producer, _mock_job = _setup_mocks(
+ mock_activity,
+ MockProducer,
+ MockS3Writer,
+ mock_get_adapter,
+ mock_get_schemas,
+ MockSourceModel,
+ MockJob,
+ MagicMock(),
+ source,
+ schemas,
+ events,
+ )
+ mock_get_adapter.return_value.parse_cdc_config.return_value.ingest_mode = "buffered"
+ if capture is not None:
+ capture["reader_ref"] = mock_reader
+ capture["complete_schema_run"] = mock_complete
+ cdc_extract_activity(CDCExtractInput(team_id=1, source_id=source.id))
+ return mock_reader, mock_s3, mock_producer
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
+ def test_a_buffered_schema_is_delivered_by_buffer_alone(self, MockBufferWriter):
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ events = [
+ _make_event(op="I", position="0/100", columns={"id": 1, "name": "Alice"}),
+ _make_event(op="U", position="0/200", columns={"id": 1, "name": "Bob"}),
+ ]
+
+ mock_reader, mock_s3, mock_producer = self._run(MockBufferWriter, events, [schema], source)
+
+ buffered = MockBufferWriter.return_value.write_batch.call_args.kwargs["table"]
+ assert buffered.column(CDC_SEQ_COLUMN).to_pylist() == [0x100, 0x200]
+ # Raw stream, seq intact — the loader dedupes and resolves positions.
+ assert buffered.num_rows == 2
+ # No legacy delivery: no S3 batch, no sourcebatch row, so no ExternalDataJob to bill.
+ mock_s3.write_batch.assert_not_called()
+ mock_producer.send_batch_notification.assert_not_called()
+ # The point of the whole design: durable buffer releases the customer's WAL immediately.
+ mock_reader.confirm_position.assert_called_once_with("0/200")
+
+ @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):
+ source = _make_source()
+ companion = _make_schema("events", cdc_mode="streaming", cdc_table_mode="cdc_only", source=source)
+ events = [_make_event(op="I", position="0/100", table="events", columns={"id": 1})]
+
+ _reader, mock_s3, mock_producer = self._run(MockBufferWriter, events, [companion], source)
+
+ MockBufferWriter.return_value.write_batch.assert_not_called()
+ mock_s3.write_batch.assert_called_once()
+ mock_producer.send_batch_notification.assert_called_once()
+
+ @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):
+ # The opposite of the shadow lane's policy: swallowing here would advance the slot past
+ # changes that reached nothing, losing them for good.
+ MockBufferWriter.return_value.write_batch.side_effect = Exception("s3 down")
+ 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"):
+ captured["reader"] = self._run(MockBufferWriter, events, [schema], source, capture=captured)
+
+ captured["reader_ref"].confirm_position.assert_not_called()
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
+ def test_a_source_column_named_like_seq_fails_the_buffered_run(self, MockBufferWriter):
+ # The batcher skips its append on the collision, so the file's name, ordering, and retry
+ # cleanup would all derive from customer data — cleanup can then delete unconsumed files.
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ events = [_make_event(op="I", position="0/100", columns={"id": 1, CDC_SEQ_COLUMN: 42})]
+ captured: dict = {}
+
+ with pytest.raises(Exception, match="_ph_cdc_seq"):
+ self._run(MockBufferWriter, events, [schema], source, capture=captured)
+
+ MockBufferWriter.return_value.write_batch.assert_not_called()
+ captured["reader_ref"].confirm_position.assert_not_called()
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
+ def test_capture_does_not_repaint_a_buffered_schema_healthy(self, MockBufferWriter):
+ # The scheduled sync owns a buffered schema's status; capture repainting COMPLETED every
+ # 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", cdc_table_mode="cdc_only", source=source)
+ events = [
+ _make_event(op="I", position="0/100", columns={"id": 1}),
+ _make_event(op="I", position="0/100", table="events", columns={"id": 1}),
+ ]
+ captured: dict = {}
+
+ self._run(MockBufferWriter, events, [buffered, legacy], source, capture=captured)
+
+ repainted = [call.args[0].name for call in captured["complete_schema_run"].call_args_list]
+ assert repainted == ["events"]
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
new file mode 100644
index 000000000000..308091e1acc4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py
@@ -0,0 +1,358 @@
+import datetime as dt
+import contextlib
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pyarrow as pa
+import pyarrow.parquet as pq
+from parameterized import parameterized
+
+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.buffer import build_buffer_file_name
+from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
+ CDCSourceManager,
+ has_pending_legacy_backlog,
+ is_buffered_consolidated,
+ serves_buffered_lane,
+)
+
+_TEAM_ID = 7
+_SCHEMA_ID = "3f7c1f4e-0000-0000-0000-000000000001"
+_PREFIX = f"bucket/cdc_producer/{_TEAM_ID}/{_SCHEMA_ID}"
+
+_NOW = dt.datetime(2026, 8, 14, 12, 0, tzinfo=dt.UTC)
+# Older than any completed-run start minus the clock-skew margin.
+_OLD_MTIME = _NOW - dt.timedelta(hours=2)
+
+
+def _table(ids: list[int], seqs: list[int]) -> pa.Table:
+ return pa.table({"id": pa.array(ids, pa.int64())}).append_column(
+ pa.field(CDC_SEQ_COLUMN, pa.int64(), metadata=CDC_SEQ_PROVENANCE), pa.array(seqs, pa.int64())
+ )
+
+
+def _parquet_bytes(table: pa.Table) -> bytes:
+ buf = pa.BufferOutputStream()
+ pq.write_table(table, buf)
+ return buf.getvalue().to_pybytes()
+
+
+def _key(start: int, end: int, index: int = 0) -> str:
+ return f"{_PREFIX}/{build_buffer_file_name(start, end, index)}"
+
+
+class _FakeS3:
+ """Minimal stand-in for the async fsspec client the manager uses."""
+
+ def __init__(
+ self,
+ files: dict[str, bytes],
+ missing_prefix: bool = False,
+ mtimes: dict[str, dt.datetime] | None = None,
+ ) -> None:
+ self.files = dict(files)
+ self.removed: list[str] = []
+ self.opened: list[str] = []
+ self.missing_prefix = missing_prefix
+ self.mtimes = mtimes or {}
+
+ async def _ls(self, prefix, detail=True, refresh=False):
+ # The manager must always bypass the fsspec dircache — capture writes through a different
+ # process, so a cached listing could miss its files indefinitely.
+ assert refresh, "buffer listings must pass refresh=True"
+ if self.missing_prefix:
+ raise FileNotFoundError(prefix)
+ return [{"type": "file", "Key": key, "LastModified": self.mtimes.get(key, _OLD_MTIME)} for key in self.files]
+
+ async def _rm(self, key):
+ self.removed.append(key)
+ self.files.pop(key, None)
+
+ async def open_async(self, key, mode):
+ self.opened.append(key)
+ if key not in self.files:
+ raise FileNotFoundError(key)
+ data = self.files[key]
+
+ @contextlib.asynccontextmanager
+ async def _reader():
+ handle = AsyncMock()
+ handle.read = AsyncMock(return_value=data)
+ yield handle
+
+ return _reader()
+
+
+def _patched(s3: _FakeS3, load_position: int | None, proof_time: dt.datetime | None):
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.aget_s3_client"
+ ) as mock_client,
+ patch.object(CDCSourceManager, "_read_consume_state", AsyncMock(return_value=(load_position, None))),
+ patch.object(CDCSourceManager, "_completed_listing_time", AsyncMock(return_value=proof_time)),
+ patch.object(CDCSourceManager, "_stamp_listing", AsyncMock()) as mock_stamp,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.get_buffer_prefix",
+ return_value=f"s3://{_PREFIX}",
+ ),
+ ):
+ mock_client.return_value.__aenter__ = AsyncMock(return_value=s3)
+ mock_client.return_value.__aexit__ = AsyncMock(return_value=False)
+ yield mock_stamp
+
+
+def _manager() -> CDCSourceManager:
+ inputs = MagicMock()
+ inputs.team_id = _TEAM_ID
+ inputs.schema_id = _SCHEMA_ID
+ inputs.reset_pipeline = False
+ return CDCSourceManager(inputs=inputs, logger=AsyncMock())
+
+
+async def _collect(
+ s3: _FakeS3,
+ load_position: int | None = None,
+ proof_time: dt.datetime | None = None,
+ **kwargs,
+) -> list[pa.Table]:
+ with _patched(s3, load_position, proof_time):
+ return [t async for t in _manager().get_items("users", **kwargs)]
+
+
+def _schema(**overrides) -> MagicMock:
+ schema = MagicMock()
+ schema.is_cdc = overrides.get("is_cdc", True)
+ schema.cdc_mode = overrides.get("cdc_mode", "streaming")
+ schema.cdc_table_mode = overrides.get("cdc_table_mode", "consolidated")
+ schema.initial_sync_complete = overrides.get("initial_sync_complete", True)
+ schema.sync_type_config = overrides.get("sync_type_config", {})
+ return schema
+
+
+class TestCDCSourceManager:
+ async def test_files_are_read_in_position_order_not_listing_order(self):
+ # S3 returns keys in arbitrary order; only the filename's position range may order them.
+ s3 = _FakeS3(
+ {
+ _key(300, 399): _parquet_bytes(_table([3], [300])),
+ _key(100, 199): _parquet_bytes(_table([1], [100])),
+ _key(200, 299): _parquet_bytes(_table([2], [200])),
+ }
+ )
+
+ tables = await _collect(s3)
+
+ assert len(tables) == 1
+ assert tables[0].column(CDC_SEQ_COLUMN).to_pylist() == [100, 200, 300]
+
+ async def test_files_sharing_a_position_range_order_by_file_index(self):
+ # One transaction's events share a commit position, so the index is the only tiebreak.
+ s3 = _FakeS3(
+ {
+ _key(100, 100, 2): _parquet_bytes(_table([3], [100])),
+ _key(100, 100, 0): _parquet_bytes(_table([1], [100])),
+ _key(100, 100, 1): _parquet_bytes(_table([2], [100])),
+ }
+ )
+
+ tables = await _collect(s3)
+
+ assert tables[0].column("id").to_pylist() == [1, 2, 3]
+
+ async def test_files_strictly_below_the_position_are_deleted_and_never_read(self):
+ s3 = _FakeS3(
+ {
+ _key(100, 199): _parquet_bytes(_table([1], [100])),
+ _key(200, 299): _parquet_bytes(_table([2], [200])),
+ }
+ )
+
+ tables = await _collect(s3, load_position=250)
+
+ assert s3.removed == [_key(100, 199)]
+ assert s3.opened == [_key(200, 299)]
+ assert tables[0].column("id").to_pylist() == [2]
+
+ async def test_a_trailing_file_is_deleted_once_a_completed_listing_predates_it(self):
+ # Position alone cannot prove the file at the floor consumed, so an idle schema would
+ # otherwise re-merge and re-bill its trailing file on every sync forever.
+ s3 = _FakeS3({_key(100, 200): _parquet_bytes(_table([1], [200]))})
+
+ tables = await _collect(s3, load_position=200, proof_time=_OLD_MTIME + dt.timedelta(hours=1))
+
+ assert s3.removed == [_key(100, 200)]
+ assert tables == []
+
+ @parameterized.expand(
+ [
+ # A file written after the proving run's listing was never in it — it can hold the
+ # unread tail of a transaction split across files (all rows share one position).
+ ("written_after_the_proving_listing", _NOW, _NOW - dt.timedelta(minutes=30)),
+ # Within the clock-skew margin of the listing, existence in it is unproven.
+ ("within_the_skew_margin", _NOW - dt.timedelta(minutes=32), _NOW - dt.timedelta(minutes=30)),
+ ("no_completed_listing_yet", _OLD_MTIME, None),
+ ]
+ )
+ async def test_a_file_at_the_position_is_kept_when_consumption_is_unproven(self, _name, mtime, proof_time):
+ key = _key(100, 200)
+ s3 = _FakeS3({key: _parquet_bytes(_table([1], [200]))}, mtimes={key: mtime})
+
+ tables = await _collect(s3, load_position=200, proof_time=proof_time)
+
+ assert s3.removed == []
+ assert len(tables) == 1
+
+ async def test_no_files_are_deleted_before_anything_is_committed(self):
+ s3 = _FakeS3({_key(100, 199): _parquet_bytes(_table([1], [100]))})
+
+ await _collect(s3, load_position=None, proof_time=_NOW)
+
+ assert s3.removed == []
+
+ async def test_files_are_not_deleted_on_yield(self):
+ # The v3 batcher buffers across yields, so a yielded table can still be in memory. Only a
+ # committed position may delete a file.
+ s3 = _FakeS3(
+ {
+ _key(100, 199): _parquet_bytes(_table(list(range(6000)), [100] * 6000)),
+ _key(200, 299): _parquet_bytes(_table([1], [200])),
+ }
+ )
+
+ tables = await _collect(s3)
+
+ assert len(tables) == 2
+ assert s3.removed == []
+
+ async def test_names_that_do_not_match_the_contract_are_ignored(self):
+ s3 = _FakeS3(
+ {
+ f"{_PREFIX}/_delta_log": b"",
+ f"{_PREFIX}/whatever.parquet": b"",
+ _key(100, 199): _parquet_bytes(_table([1], [100])),
+ }
+ )
+
+ tables = await _collect(s3)
+
+ assert s3.opened == [_key(100, 199)]
+ assert len(tables) == 1
+
+ async def test_a_file_consumed_between_listing_and_read_is_skipped(self):
+ s3 = _FakeS3({_key(100, 199): _parquet_bytes(_table([1], [100]))})
+ s3.files.pop(_key(100, 199)) # a concurrent run deleted it after our listing
+
+ tables = await _collect(s3)
+
+ assert tables == []
+
+ async def test_a_missing_prefix_yields_nothing(self):
+ # Before capture's first write the prefix does not exist; that is a no-op, not a failure.
+ assert await _collect(_FakeS3({}, missing_prefix=True)) == []
+
+ async def test_batches_are_cut_at_the_row_limit(self):
+ s3 = _FakeS3(
+ {
+ _key(i * 100, i * 100 + 99): _parquet_bytes(_table(list(range(400)), [i * 100] * 400))
+ for i in range(1, 4)
+ }
+ )
+
+ tables = await _collect(s3, batch_row_limit=500)
+
+ # 400 → under the limit, 800 → cut, then the trailing 400 flushes at the end.
+ assert [t.num_rows for t in tables] == [800, 400]
+
+
+class TestBufferedGating:
+ @parameterized.expand(
+ [
+ ("not_cdc", {"is_cdc": False}),
+ ("still_snapshotting", {"cdc_mode": "snapshot"}),
+ ("companion_lane", {"cdc_table_mode": "cdc_only"}),
+ ("both_lanes", {"cdc_table_mode": "both"}),
+ ("no_table_yet", {"initial_sync_complete": False}),
+ ]
+ )
+ def test_ineligible_schemas_stay_on_the_legacy_path(self, _name, overrides):
+ assert serves_buffered_lane(_schema(**overrides)) is False
+
+ def test_a_consolidated_streaming_schema_serves_the_buffered_lane(self):
+ assert serves_buffered_lane(_schema()) is True
+
+ @parameterized.expand([("legacy",), ("",), ("nonsense",)])
+ def test_a_source_that_was_not_flipped_stays_on_the_legacy_path(self, ingest_mode):
+ assert is_buffered_consolidated(_schema(), ingest_mode=ingest_mode) is False
+
+ def test_a_flipped_consolidated_schema_consumes_the_buffer(self):
+ assert is_buffered_consolidated(_schema(), ingest_mode="buffered") is True
+
+
+class TestPendingLegacyBacklog:
+ # Legacy deliveries carry no position column, so a consumer merge racing them can be overwritten
+ # by an older row. These prove both backlog forms hold the consumer off.
+
+ def test_deferred_runs_are_a_backlog_without_touching_the_queue(self):
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.psycopg"
+ ) as mock_psycopg:
+ assert has_pending_legacy_backlog(_schema(sync_type_config={"cdc_deferred_runs": [{"x": 1}]})) is True
+ mock_psycopg.Connection.connect.assert_not_called()
+
+ @parameterized.expand([("batches_pending", 12.5, True), ("queue_drained", None, False)])
+ def test_sourcebatch_state_decides_when_no_deferred_runs(self, _name, age, expected):
+ schema = _schema()
+ schema.team_id = _TEAM_ID
+ schema.id = _SCHEMA_ID
+ with (
+ patch("products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.psycopg"),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.BatchQueue.get_oldest_non_terminal_batch_age_seconds",
+ return_value=age,
+ ),
+ ):
+ assert has_pending_legacy_backlog(schema) is expected
+
+
+class TestListingProof:
+ # The deletion proof must come only from a run that listed the buffer AND completed. A gated
+ # no-op run (which never lists) or a crashed run (whose job never completes) must prove nothing.
+
+ async def test_every_consuming_run_stamps_its_listing(self):
+ s3 = _FakeS3({_key(100, 199): _parquet_bytes(_table([1], [100]))})
+
+ with _patched(s3, None, None) as mock_stamp:
+ [t async for t in _manager().get_items("users")]
+
+ mock_stamp.assert_awaited_once()
+
+ @parameterized.expand([("job_completed", True, True), ("job_not_completed", False, False)])
+ async def test_a_stamp_proves_only_once_its_job_completes(self, _name, completed, expect_proof):
+ listing = {"listed_at": _NOW.isoformat(), "job_id": "018f0000-0000-0000-0000-000000000001"}
+ exists_qs = MagicMock()
+ exists_qs.exists.return_value = completed
+
+ with patch(
+ "products.warehouse_sources.backend.models.external_data_job.ExternalDataJob.objects.filter",
+ return_value=exists_qs,
+ ):
+ proof = await _manager()._completed_listing_time(listing)
+
+ assert (proof == _NOW) is expect_proof
+ assert (proof is None) is (not expect_proof)
+
+ @parameterized.expand(
+ [
+ ("no_stamp", None),
+ ("malformed_date", {"listed_at": "not-a-date", "job_id": "018f0000-0000-0000-0000-000000000001"}),
+ ("naive_timestamp", {"listed_at": "2026-08-14T12:00:00", "job_id": "018f0000-0000-0000-0000-000000000001"}),
+ ("malformed_job_id", {"listed_at": "2026-08-14T12:00:00+00:00", "job_id": "not-a-uuid"}),
+ ("missing_job", {"listed_at": "2026-08-14T12:00:00+00:00"}),
+ ]
+ )
+ async def test_unusable_stamps_prove_nothing(self, _name, listing):
+ assert await _manager()._completed_listing_time(listing) is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py
index e502d8af76fd..fef7da2febfe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py
@@ -9,6 +9,10 @@ import pyarrow as pa
ManagementMode = Literal["posthog", "self_managed"]
+# How a source's change events reach the loader. `legacy`: capture transforms and dispatches them
+# itself. `buffered`: capture only writes the S3 buffer, and the normal scheduled sync consumes it.
+IngestMode = Literal["legacy", "buffered"]
+
@dataclass(frozen=True)
class CDCConfig:
@@ -26,6 +30,7 @@ class CDCConfig:
lag_warning_threshold_mb: int
lag_critical_threshold_mb: int
auto_drop_slot: bool
+ ingest_mode: IngestMode
class CDCPosition(Protocol):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
index 0f482128a701..73bed95a728c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
@@ -330,7 +330,11 @@ async def persist_primary_keys(
inside the row lock so a concurrent API edit isn't clobbered. Best-effort: a failure here
must not fail an otherwise successful sync.
"""
- if not is_incremental or schema.primary_key_columns:
+ # A CDC schema snapshots as full_refresh but streams incrementally, so its key has to be
+ # persisted during that first non-incremental run or the streaming phase has none.
+ if schema.primary_key_columns:
+ return
+ if not is_incremental and not schema.is_cdc:
return
primary_keys = resource.primary_keys
if not primary_keys:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
index 0f87c2d143c5..99bb579d0eba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
@@ -369,7 +369,7 @@ async def _finalize_sync_bookkeeping(
if not schema.initial_sync_complete:
await logger.adebug("Setting initial_sync_complete on schema")
- await set_initial_sync_complete(schema_id=schema.id, team_id=job.team_id)
+ await set_initial_sync_complete(schema_id=schema.id, team_id=job.team_id, logger=logger)
if resource is not None:
await finalize_desc_sort_incremental_value(resource, schema, last_incremental_field_value, logger)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
index f35297b49b8b..15f614284320 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
@@ -71,19 +71,24 @@ class TestResolvePrimaryKeys:
class TestPersistPrimaryKeys:
@parameterized.expand(
[
- # name, is_incremental, persisted_pk, resource_pks, db_config_before, expected_written (None = no write attempted)
+ # name, is_incremental, is_cdc, persisted_pk, resource_pks, db_config_before, expected_written (None = no write attempted)
# Full-refresh schemas don't merge on a PK — never touch sync_type_config.
- ("skips_when_not_incremental", False, None, ["id"], {}, None),
+ ("skips_when_not_incremental", False, False, None, ["id"], {}, None),
+ # A CDC schema snapshots as full_refresh but streams incrementally, so its key must be
+ # persisted during that first run — otherwise the streaming phase has no merge key and
+ # trips the keyless-table guardrail.
+ ("backfills_for_cdc_snapshot", False, True, None, ["id"], {}, {"primary_key_columns": ["id"]}),
# A stored PK is already the source of truth — nothing to backfill.
- ("skips_when_already_persisted", True, ["existing"], ["id"], {}, None),
+ ("skips_when_already_persisted", True, False, ["existing"], ["id"], {}, None),
# No resolvable PK -> leave it empty so the keyless-table guardrail still fires.
- ("skips_when_no_resolved_pk", True, None, None, {}, None),
+ ("skips_when_no_resolved_pk", True, False, None, None, {}, None),
# The fix: an incremental schema with no stored PK backfills the resolved one.
- ("backfills_when_incremental_and_empty", True, None, ["id"], {}, {"primary_key_columns": ["id"]}),
+ ("backfills_when_incremental_and_empty", True, False, None, ["id"], {}, {"primary_key_columns": ["id"]}),
# A concurrent API edit that landed a PK first must not be clobbered inside the lock.
(
"does_not_clobber_concurrent_write",
True,
+ False,
None,
["id"],
{"primary_key_columns": ["already"]},
@@ -96,12 +101,13 @@ class TestPersistPrimaryKeys:
self,
_name: str,
is_incremental: bool,
+ is_cdc: bool,
persisted: list[str] | None,
resource_pks: list[str] | None,
db_config_before: dict,
expected_written: dict | None,
):
- schema = MagicMock(id="s1", team_id=1, primary_key_columns=persisted)
+ schema = MagicMock(id="s1", team_id=1, primary_key_columns=persisted, is_cdc=is_cdc)
resource = MagicMock(primary_keys=resource_pks)
captured: dict = {}
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 77c0a71d127e..6f7331dd2db1 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
@@ -130,8 +130,29 @@ async def update_last_synced_at(job_id: str, schema_id: str, team_id: int) -> No
await _update()
-async def set_initial_sync_complete(schema_id: str, team_id: int) -> None:
- await database_sync_to_async_pool(mark_initial_sync_complete)(schema_id=schema_id, team_id=team_id)
+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)
+
+
+async def set_initial_sync_complete(schema_id: str, team_id: int, logger: FilteringBoundLogger) -> None:
+ await database_sync_to_async_pool(_purge_stale_buffer_then_mark_initial_sync_complete)(
+ schema_id=schema_id, team_id=team_id, logger=logger
+ )
def _refresh_cumulative_row_count(table: DataWarehouseTable, logger: FilteringBoundLogger, context: str) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index 42a8a03e0dd0..7a345054177d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -138,7 +138,13 @@ class PipelineV3(Generic[ResumableData]):
self._table = models.table
# xmin reads deltas and upserts on the primary key, so it writes incrementally too — never
# as a full_refresh overwrite, which would wipe earlier data on the second (delta-only) sync.
- self._is_incremental = models.schema.is_incremental or models.schema.is_webhook or models.schema.is_xmin
+ # Same for a change stream, which only ever carries the rows that changed.
+ self._is_incremental = (
+ models.schema.is_incremental
+ or models.schema.is_webhook
+ or models.schema.is_xmin
+ or source_response.cdc_write_mode is not None
+ )
self._delta_table_ref = DeltaTableRef(self._resource_name, self._job, self._logger)
@@ -151,7 +157,9 @@ class PipelineV3(Generic[ResumableData]):
self._attempt = attempt
sync_type: SyncTypeLiteral = "full_refresh"
- if self._schema.is_incremental or self._schema.is_webhook or self._schema.is_xmin:
+ if source_response.cdc_write_mode is not None:
+ sync_type = "cdc"
+ elif self._schema.is_incremental or self._schema.is_webhook or self._schema.is_xmin:
sync_type = "incremental"
elif self._schema.is_append:
sync_type = "append"
@@ -198,6 +206,7 @@ class PipelineV3(Generic[ResumableData]):
run_uuid=self._s3_batch_writer.get_run_uuid(),
logger=self._logger,
primary_keys=self._resource.primary_keys,
+ cdc_write_mode=self._resource.cdc_write_mode,
is_resume=is_resume,
partition_count=partition_count,
partition_size=partition_size,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
index b05380eb46ce..41a1a7b3b3bc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
@@ -96,6 +96,7 @@ class TestAttemptScopedRunUuid:
partition_keys=None,
partition_format=None,
partition_mode=None,
+ cdc_write_mode=None,
)
with (
@@ -189,3 +190,122 @@ class TestExtractionFailureDoesNotCleanupS3:
await pipeline.run()
s3_writer.cleanup.assert_not_called()
+
+
+# Both properties below are silent when wrong: a `full_refresh` overwrites the customer's table
+# with one micro-batch of changes, and a missing `cdc_write_mode` turns off enrichment and position
+# resolution while every other test still passes.
+class TestCDCSourceWiring:
+ def _build(self, cdc_write_mode: str | None) -> tuple[PipelineV3, MagicMock]:
+ mock_job = MagicMock(team_id=1, workflow_run_id="wfrun-abc", billable=False, id="job-1")
+ mock_schema = MagicMock(
+ id="schema-1",
+ source_id="source-1",
+ is_incremental=False,
+ is_webhook=False,
+ is_xmin=False,
+ is_append=False,
+ table=None,
+ primary_key_columns=["id"],
+ partition_count=None,
+ partition_size=None,
+ partitioning_keys=None,
+ partition_format=None,
+ partition_mode=None,
+ partition_count_override=None,
+ partition_size_override=None,
+ partitioning_keys_override=None,
+ partition_mode_override=None,
+ )
+ mock_resource = MagicMock(
+ name="users",
+ primary_keys=["id"],
+ partition_count=None,
+ partition_size=None,
+ partition_keys=None,
+ partition_format=None,
+ partition_mode=None,
+ cdc_write_mode=cdc_write_mode,
+ )
+
+ base = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline"
+ with (
+ patch(f"{base}.current_activity_attempt", return_value=1),
+ patch(f"{base}.current_workflow_id", return_value="wf-1"),
+ patch(f"{base}.current_workflow_run_id", return_value="wfrun-abc"),
+ patch(f"{base}.S3BatchWriter"),
+ patch(f"{base}.PostgresProducer") as mock_producer_cls,
+ patch(f"{base}.DeltaTableRef"),
+ ):
+ pipeline: PipelineV3 = PipelineV3(
+ source_response=mock_resource,
+ logger=_make_logger(),
+ job_id="job-1",
+ reset_pipeline=False,
+ shutdown_monitor=MagicMock(),
+ resumable_source_manager=None,
+ models=ImportJobModels(
+ job=mock_job, schema=mock_schema, source=MagicMock(source_type="Postgres"), table=None
+ ),
+ )
+ return pipeline, mock_producer_cls
+
+ def test_a_cdc_run_writes_incrementally_and_carries_its_write_mode(self) -> None:
+ pipeline, mock_producer_cls = self._build("incremental_merge")
+
+ assert pipeline._is_incremental is True
+ assert mock_producer_cls.call_args.kwargs["sync_type"] == "cdc"
+ assert mock_producer_cls.call_args.kwargs["cdc_write_mode"] == "incremental_merge"
+
+ def test_a_non_cdc_run_is_unaffected(self) -> None:
+ pipeline, mock_producer_cls = self._build(None)
+
+ assert pipeline._is_incremental is False
+ assert mock_producer_cls.call_args.kwargs["sync_type"] == "full_refresh"
+ assert mock_producer_cls.call_args.kwargs["cdc_write_mode"] is None
+
+
+class TestCDCSeqProvenanceSurvivesStaging:
+ def test_the_stamp_survives_every_extract_side_hop(self) -> None:
+ # The loader gates all position resolution on the provenance stamp. If any hop between the
+ # buffer read and the loader's parquet read strips field metadata, resolution silently turns
+ # itself off: the floor never advances, files re-merge every run, and every other test still
+ # passes. Chain mirrors PipelineV3.run: normalize → evolve against a Delta-derived schema
+ # (which carries no arrow metadata) → batcher concat → staged-parquet round trip.
+ import io
+
+ import pyarrow as pa
+ import deltalake
+ import pyarrow.parquet as pq
+
+ 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.load_resolution import has_engine_seq
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
+ evolve_pyarrow_schema,
+ normalize_table_column_names,
+ )
+
+ table = pa.table({"id": pa.array([1, 2], pa.int64())}).append_column(
+ pa.field(CDC_SEQ_COLUMN, pa.int64(), metadata=CDC_SEQ_PROVENANCE), pa.array([10, 20], pa.int64())
+ )
+ # The target as Delta reports it: same columns plus one this batch lacks, and no arrow
+ # field metadata (Delta stores none), which is what could strip the stamp on evolve.
+ target_fields: list[pa.Field] = [
+ pa.field("id", pa.int64()),
+ pa.field(CDC_SEQ_COLUMN, pa.int64()),
+ pa.field("extra", pa.string()),
+ ]
+ delta_schema = deltalake.Schema.from_arrow(pa.schema(target_fields))
+
+ staged = pa.concat_tables(
+ [evolve_pyarrow_schema(normalize_table_column_names(table), delta_schema)] * 2,
+ promote_options="permissive",
+ )
+ buf = io.BytesIO()
+ pq.write_table(staged, buf)
+ buf.seek(0)
+
+ assert has_engine_seq(pq.read_table(buf))
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 451dd65228c4..429224a3b41d 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
@@ -385,3 +385,70 @@ class TestUpdateLastSyncedAt:
schema.save.assert_called_once_with(skip_activity_log=True)
close.assert_called_once()
sleep.assert_called_once_with(2)
+
+
+class TestSetInitialSyncComplete(BaseTest):
+ """The purge-then-flip contract: a CDC snapshot schema's buffer prefix is purged before the
+ streaming flip (stale pre-snapshot files merged after the flip resurrect rows the snapshot
+ 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:
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type="Postgres",
+ )
+ return ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source=source,
+ name="public.users",
+ sync_type=sync_type,
+ sync_type_config=config,
+ initial_sync_complete=initial_sync_complete,
+ )
+
+ @parameterized.expand(
+ [
+ # The flip: stale buffer must be gone before streaming resumes.
+ ("cdc_snapshot_first_completion", "cdc", {"cdc_mode": "snapshot"}, False, True, "streaming"),
+ # Already streaming (idempotent completion call): purging would delete live files.
+ ("cdc_already_streaming", "cdc", {"cdc_mode": "streaming"}, True, False, "streaming"),
+ # Non-CDC schemas have no buffer; purge must not run.
+ ("non_cdc", "full_refresh", {}, False, False, None),
+ ]
+ )
+ def test_purges_buffer_only_on_snapshot_to_streaming_flip(
+ self,
+ _name: str,
+ sync_type: str,
+ config: dict,
+ initial_flag: bool,
+ expects_purge: bool,
+ expected_cdc_mode: str | None,
+ ) -> 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=sync_type, config=config, initial_sync_complete=initial_flag)
+ calls: list[str] = []
+
+ def _record_purge(team_id: int, schema_id: str, logger, *, strict: bool = False) -> None:
+ assert strict, "flip purge must be strict — a swallowed failure re-ships the phantom-row bug"
+ fresh = ExternalDataSchema.objects.get(id=schema_id)
+ assert not fresh.initial_sync_complete, "purge must run BEFORE the flip commits"
+ calls.append(schema_id)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.buffer.purge_buffer_prefix",
+ side_effect=_record_purge,
+ ):
+ _purge_stale_buffer_then_mark_initial_sync_complete(str(schema.id), self.team.pk, MagicMock())
+
+ schema.refresh_from_db()
+ 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
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/batching.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/batching.py
new file mode 100644
index 000000000000..256ac1cc7cea
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/batching.py
@@ -0,0 +1,47 @@
+"""Batch accumulation shared by the S3-backed source managers."""
+
+from __future__ import annotations
+
+from typing import Generic, TypeVar
+
+import pyarrow as pa
+
+DEFAULT_BATCH_ROW_LIMIT = 5000
+DEFAULT_BATCH_BYTE_LIMIT = 200 * 1024 * 1024
+
+T = TypeVar("T")
+
+
+class TableBatcher(Generic[T]):
+ """Accumulate tables until a row or byte limit, carrying each table's source item alongside.
+
+ Accumulation only: when a file may be deleted differs per manager — the change buffer deletes on
+ proof of consumption, the webhook producer deletes once its batch is yielded — and that contract
+ stays with the caller.
+ """
+
+ def __init__(self, *, row_limit: int = DEFAULT_BATCH_ROW_LIMIT, byte_limit: int = DEFAULT_BATCH_BYTE_LIMIT) -> None:
+ self._row_limit = row_limit
+ self._byte_limit = byte_limit
+ self.tables: list[pa.Table] = []
+ self.items: list[T] = []
+ self._rows = 0
+ self._bytes = 0
+
+ def add(self, table: pa.Table, item: T | None = None) -> bool:
+ """Take one table, reporting whether the batch has reached a limit and should be yielded."""
+ self.tables.append(table)
+ if item is not None:
+ self.items.append(item)
+ self._rows += table.num_rows
+ self._bytes += table.nbytes
+ return self._rows >= self._row_limit or self._bytes >= self._byte_limit
+
+ def reset(self) -> None:
+ self.tables = []
+ self.items = []
+ self._rows = 0
+ self._bytes = 0
+
+ def __bool__(self) -> bool:
+ return bool(self.tables)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/db.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/db.py
new file mode 100644
index 000000000000..162998a82002
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/db.py
@@ -0,0 +1,36 @@
+from __future__ import annotations
+
+import time
+from collections.abc import Callable
+from typing import TypeVar
+
+from django.db import OperationalError, close_old_connections
+
+T = TypeVar("T")
+
+_MAX_DB_READ_ATTEMPTS = 4
+
+
+def db_read_with_retry(fn: Callable[[], T]) -> T:
+ """Run an idempotent main-DB read, retrying a transient connection failure with backoff.
+
+ Temporal activities run in a long-lived worker that never goes through Django's request
+ cycle, so a pooled Postgres connection can be closed server-side while it sits idle, or the
+ connection pooler can reject the query with a wait timeout when the pool is saturated. Both
+ surface as a transient ``OperationalError`` and both clear once a healthy connection is used.
+ ``close_old_connections()`` evicts connections already known to be stale (and, after a failed
+ query marks one unusable, drops it), so each attempt runs on a fresh connection; the short
+ backoff also gives a saturated pool time to drain rather than retrying straight back into the
+ same wait timeout. Must run inside the ``database_sync_to_async_pool`` thread so the eviction
+ targets the same connection the query uses. ``DoesNotExist`` and other errors propagate.
+ """
+ attempt = 0
+ while True:
+ close_old_connections()
+ try:
+ return fn()
+ except OperationalError:
+ attempt += 1
+ if attempt >= _MAX_DB_READ_ATTEMPTS:
+ raise
+ time.sleep(min(2 * attempt, 30))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_webhook_s3.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_webhook_s3.py
index 028015a2ed02..785a86621b92 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_webhook_s3.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_webhook_s3.py
@@ -19,15 +19,13 @@ import pyarrow.parquet as pq
from aiobotocore.config import AioConfig
from parameterized import parameterized
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import (
- WebhookSourceManager,
- _db_read_with_retry,
-)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.db import db_read_with_retry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
_CLOSE_CONNECTIONS_PATH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3.close_old_connections"
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.db.close_old_connections"
)
-_SLEEP_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3.time.sleep"
+_SLEEP_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.db.time.sleep"
def _table_to_parquet_bytes(table: pa.Table) -> bytes:
@@ -445,7 +443,7 @@ class TestDbReadWithRetry:
)
with patch(_CLOSE_CONNECTIONS_PATH) as close, patch(_SLEEP_PATH) as sleep:
- result = _db_read_with_retry(fn)
+ result = db_read_with_retry(fn)
assert result is sentinel
assert fn.call_count == 3
@@ -459,7 +457,7 @@ class TestDbReadWithRetry:
with patch(_CLOSE_CONNECTIONS_PATH), patch(_SLEEP_PATH):
with pytest.raises(OperationalError):
- _db_read_with_retry(fn)
+ db_read_with_retry(fn)
assert fn.call_count == 4
@@ -468,7 +466,7 @@ class TestDbReadWithRetry:
with patch(_CLOSE_CONNECTIONS_PATH), patch(_SLEEP_PATH) as sleep:
with pytest.raises(ValueError):
- _db_read_with_retry(fn)
+ db_read_with_retry(fn)
assert fn.call_count == 1
sleep.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py
index b3a1c47d481d..1d1a3f56304f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py
@@ -43,7 +43,7 @@ class _Dataclass(Protocol):
ResumableData = TypeVar("ResumableData", bound=_Dataclass)
[email protected](frozen=False) # callers mutate `primary_keys` after construction
class SourceResponse:
name: str
items: Callable[[], Iterable[Any] | AsyncIterable[Any]]
@@ -66,6 +66,10 @@ class SourceResponse:
"""Webhook-fed resource whose poll path does no backfill: after a wipe the poll cannot
rebuild the table, so a requested pipeline reset preserves the Delta table and resumes
webhook ingestion instead."""
+ cdc_write_mode: Optional[str] = None
+ """Set by a source serving change events, naming the lane the loader writes
+ (`incremental_merge`). Drives the loader's CDC enrichment and position resolution, and marks the
+ run incremental — a change stream must never write as a full_refresh overwrite."""
chunk_size: Optional[int] = None
"""Override the batcher's rows-per-chunk (defaults to DEFAULT_CHUNK_SIZE)."""
chunk_size_bytes: Optional[int] = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py
index 44f1a653895b..42fab212dabe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py
@@ -1,11 +1,9 @@
from __future__ import annotations
-import time
from collections.abc import AsyncGenerator, Callable
-from typing import Optional, TypeVar
+from typing import Optional
from django.conf import settings
-from django.db import OperationalError, close_old_connections
import orjson
import pyarrow as pa
@@ -17,37 +15,14 @@ from posthog.sync import database_sync_to_async_pool
from products.data_warehouse.backend.facade.api import aget_s3_client
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.batching import (
+ DEFAULT_BATCH_BYTE_LIMIT,
+ DEFAULT_BATCH_ROW_LIMIT,
+ TableBatcher,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.db import db_read_with_retry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
-T = TypeVar("T")
-
-_MAX_DB_READ_ATTEMPTS = 4
-
-
-def _db_read_with_retry(fn: Callable[[], T]) -> T:
- """Run an idempotent main-DB read, retrying a transient connection failure with backoff.
-
- Temporal activities run in a long-lived worker that never goes through Django's request
- cycle, so a pooled Postgres connection can be closed server-side while it sits idle, or the
- connection pooler can reject the query with a wait timeout when the pool is saturated. Both
- surface as a transient ``OperationalError`` and both clear once a healthy connection is used.
- ``close_old_connections()`` evicts connections already known to be stale (and, after a failed
- query marks one unusable, drops it), so each attempt runs on a fresh connection; the short
- backoff also gives a saturated pool time to drain rather than retrying straight back into the
- same wait timeout. Must run inside the ``database_sync_to_async_pool`` thread so the eviction
- targets the same connection the query uses. ``DoesNotExist`` and other errors propagate.
- """
- attempt = 0
- while True:
- close_old_connections()
- try:
- return fn()
- except OperationalError:
- attempt += 1
- if attempt >= _MAX_DB_READ_ATTEMPTS:
- raise
- time.sleep(min(2 * attempt, 30))
-
class WebhookSourceManager:
_inputs: SourceInputs
@@ -67,7 +42,7 @@ class WebhookSourceManager:
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
- schema = await database_sync_to_async_pool(_db_read_with_retry)(
+ schema = await database_sync_to_async_pool(db_read_with_retry)(
lambda: ExternalDataSchema.objects.get(id=self._inputs.schema_id, team_id=self._inputs.team_id)
)
@@ -86,7 +61,7 @@ class WebhookSourceManager:
)
return False
- has_webhook_function = await database_sync_to_async_pool(_db_read_with_retry)(
+ has_webhook_function = await database_sync_to_async_pool(db_read_with_retry)(
lambda: HogFunction.objects.filter(
inputs__source_id__value=self._inputs.source_id,
team_id=self._inputs.team_id,
@@ -101,7 +76,7 @@ class WebhookSourceManager:
async def schema_is_webhook(self) -> bool:
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
- schema = await database_sync_to_async_pool(_db_read_with_retry)(
+ schema = await database_sync_to_async_pool(db_read_with_retry)(
lambda: ExternalDataSchema.objects.get(id=self._inputs.schema_id, team_id=self._inputs.team_id)
)
return bool(schema.is_webhook)
@@ -130,8 +105,8 @@ class WebhookSourceManager:
async def get_items(
self,
table_transformer: Optional[Callable[[pa.Table], pa.Table]] = None,
- batch_row_limit: int = 5000,
- batch_byte_limit: int = 200 * 1024 * 1024,
+ batch_row_limit: int = DEFAULT_BATCH_ROW_LIMIT,
+ batch_byte_limit: int = DEFAULT_BATCH_BYTE_LIMIT,
) -> AsyncGenerator[pa.Table]:
files = await self._list_webhook_parquet_files()
@@ -153,10 +128,7 @@ class WebhookSourceManager:
merged = table_from_py_list(rows)
return table_transformer(merged) if table_transformer else merged
- batch_tables: list[pa.Table] = []
- batch_paths: list[str] = []
- batch_rows = 0
- batch_bytes = 0
+ batch: TableBatcher[str] = TableBatcher(row_limit=batch_row_limit, byte_limit=batch_byte_limit)
async with aget_s3_client() as s3:
for file in files:
@@ -182,42 +154,34 @@ class WebhookSourceManager:
table = self._transform_webhook_table(table)
- batch_tables.append(table)
- batch_paths.append(path)
- batch_rows += table.num_rows
- batch_bytes += table.nbytes
-
- if batch_rows >= batch_row_limit or batch_bytes >= batch_byte_limit:
- merged = finalize_batch(batch_tables)
+ if batch.add(table, path):
+ merged = finalize_batch(batch.tables)
await self._logger.adebug(
"webhook_batch_yield",
- file_count=len(batch_paths),
+ file_count=len(batch.items),
row_count=merged.num_rows,
byte_count=merged.nbytes,
)
yield merged
- for p in batch_paths:
+ for p in batch.items:
await s3._rm(p)
- batch_tables = []
- batch_paths = []
- batch_rows = 0
- batch_bytes = 0
+ batch.reset()
# Yield any remaining rows
- if batch_tables:
- merged = finalize_batch(batch_tables)
+ if batch:
+ merged = finalize_batch(batch.tables)
await self._logger.adebug(
"webhook_batch_yield",
- file_count=len(batch_paths),
+ file_count=len(batch.items),
row_count=merged.num_rows,
byte_count=merged.nbytes,
)
yield merged
- for p in batch_paths:
+ for p in batch.items:
await s3._rm(p)
async def _validate_webhook_table(self, table: pa.Table) -> pa.Table:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py
index 63c1f687e33e..2dbd513dcc7b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py
@@ -13,7 +13,7 @@ from typing import TYPE_CHECKING
from posthog.utils import str_to_bool
-from products.warehouse_sources.backend.temporal.data_imports.cdc.types import CDCConfig, ManagementMode
+from products.warehouse_sources.backend.temporal.data_imports.cdc.types import CDCConfig, IngestMode, ManagementMode
if TYPE_CHECKING:
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -38,6 +38,9 @@ class PostgresCDCConfig(CDCConfig):
management_mode: ManagementMode = (
"self_managed" if ji.get("cdc_management_mode") == "self_managed" else "posthog"
)
+ # Anything unrecognized reads as legacy: an unknown value must not route a source onto a
+ # path it was never flipped to.
+ ingest_mode: IngestMode = "buffered" if ji.get("cdc_ingest_mode") == "buffered" else "legacy"
return cls(
enabled=str_to_bool(ji.get("cdc_enabled", False)),
slot_name=ji.get("cdc_slot_name") or "",
@@ -47,6 +50,7 @@ class PostgresCDCConfig(CDCConfig):
lag_critical_threshold_mb=int(ji.get("cdc_lag_critical_threshold_mb", DEFAULT_LAG_CRITICAL_THRESHOLD_MB)),
auto_drop_slot=str_to_bool(ji.get("cdc_auto_drop_slot", True)),
consistent_point=ji.get("cdc_consistent_point"),
+ ingest_mode=ingest_mode,
)
@classmethod
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
index 4d9045f33347..be65c9ac1b00 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
@@ -7,6 +7,7 @@ from psycopg.errors import SqlclientUnableToEstablishSqlconnection
from sshtunnel import BaseSSHTunnelForwarderError
if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from posthog.schema import (
@@ -1309,6 +1310,59 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
finally:
conn.close()
+ def _buffered_cdc_source(self, schema: "ExternalDataSchema", inputs: SourceInputs) -> SourceResponse | None:
+ """A `SourceResponse` reading this schema's S3 change buffer, or None if it isn't flipped.
+
+ Returning None keeps the caller on the legacy `CDCHandledExternally` path, so a source that
+ was never flipped — or a lane the buffer doesn't serve — behaves exactly as before.
+ """
+ from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
+ CONSOLIDATED_WRITE_MODE,
+ CDCSourceManager,
+ consolidated_resource_name,
+ has_pending_legacy_backlog,
+ is_buffered_consolidated,
+ )
+ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.config import (
+ PostgresCDCConfig,
+ )
+
+ ingest_mode = PostgresCDCConfig.from_source(schema.source).ingest_mode
+ if not is_buffered_consolidated(schema, ingest_mode=ingest_mode):
+ return None
+
+ # A CDC reset must travel through snapshot mode (which purges the buffer and re-seeds the
+ # table); every reset writer does that. Standing down here instead would route into
+ # CDCHandledExternally, whose handler pauses this schedule — and nothing on a buffered
+ # source ever unpauses it, so the buffer would age to the S3 TTL unconsumed.
+ if inputs.reset_pipeline:
+ raise ValueError(
+ f"reset_pipeline is set on buffered CDC schema {schema.name} while cdc_mode is still "
+ "'streaming'. Reset it to snapshot (cdc_mode='snapshot') so the re-snapshot path runs."
+ )
+
+ resource_name = consolidated_resource_name(schema)
+
+ if has_pending_legacy_backlog(schema):
+ # Legacy deliveries carry no position column, so merging buffered rows before they land
+ # lets an older row overwrite a newer one. No-op this run — an empty response keeps the
+ # schedule alive, unlike CDCHandledExternally, which would pause it for good.
+ inputs.logger.info("cdc_buffered_waiting_for_legacy_backlog", schema_name=schema.name)
+ return SourceResponse(
+ name=resource_name,
+ items=lambda: iter(()),
+ primary_keys=schema.primary_key_columns,
+ cdc_write_mode=CONSOLIDATED_WRITE_MODE,
+ )
+
+ manager = CDCSourceManager(inputs, inputs.logger)
+ return SourceResponse(
+ name=resource_name,
+ items=lambda: manager.get_items(resource_name),
+ primary_keys=schema.primary_key_columns,
+ cdc_write_mode=CONSOLIDATED_WRITE_MODE,
+ )
+
def source_for_pipeline(self, config: PostgresSourceConfig, inputs: SourceInputs) -> SourceResponse:
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import (
@@ -1341,8 +1395,12 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
source_schema = source_schema or inferred_schema
source_table_name = source_table_name or inferred_table
- # CDC streaming schemas are handled by CDCExtractionWorkflow, not here
+ # A buffered source's changes are consumed here like any other source; every other CDC
+ # streaming schema is still dispatched by CDCExtractionWorkflow.
if schema.is_cdc and schema.cdc_mode == "streaming":
+ buffered_response = self._buffered_cdc_source(schema, inputs)
+ if buffered_response is not None:
+ return buffered_response
raise CDCHandledExternally(
f"Schema {schema.name} is in CDC streaming mode — handled by CDCExtractionWorkflow"
)
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index d8ff2a90adca..5aa745d29075 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -939,6 +939,7 @@ class TestExternalDataSource(APIBaseTest):
"cdc_lag_warning_threshold_mb": 512,
"cdc_lag_critical_threshold_mb": 1024,
"cdc_consistent_point": "0/AA",
+ "cdc_ingest_mode": "buffered",
},
)
@@ -959,6 +960,7 @@ class TestExternalDataSource(APIBaseTest):
"cdc_lag_warning_threshold_mb": 1,
"cdc_lag_critical_threshold_mb": 2,
"cdc_consistent_point": "0/BAD",
+ "cdc_ingest_mode": "legacy",
}
},
format="json",
@@ -975,6 +977,7 @@ class TestExternalDataSource(APIBaseTest):
assert str(source.job_inputs["cdc_lag_warning_threshold_mb"]) == "512"
assert str(source.job_inputs["cdc_lag_critical_threshold_mb"]) == "1024"
assert source.job_inputs["cdc_consistent_point"] == "0/AA"
+ assert source.job_inputs["cdc_ingest_mode"] == "buffered"
@patch(
"products.warehouse_sources.backend.presentation.views.external_data_schema.external_data_workflow_exists",
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
new file mode 100644
index 000000000000..303bee7489a8
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/management/test_migrate_cdc_source_to_buffered.py
@@ -0,0 +1,388 @@
+import io
+from contextlib import contextmanager
+
+import pytest
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
+from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN
+from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import build_buffer_file_name
+from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import consolidated_resource_name
+
+_CMD = "products.warehouse_sources.backend.management.commands.migrate_cdc_source_to_buffered"
+
+
+@contextmanager
+def _mocked_side_effects(
+ oldest_batch_age: float | None = None,
+ write_resolution: bool = True,
+ pipeline_v3: bool = True,
+ buffer_keys: list[str] | None = None,
+ buffer_keys_by_schema: dict[str, list[str]] | None = None,
+ extraction_running: bool = False,
+):
+ """Stub every outside effect: Temporal schedules, the sourcebatch probe, the flag, and S3.
+
+ `buffer_keys` is what any prefix listing returns; None means the prefix does not exist, which is
+ both a clean purge and a drained buffer. `buffer_keys_by_schema` answers per schema id instead,
+ for the prefixes that hold different files.
+ """
+ s3 = MagicMock()
+ if buffer_keys_by_schema is not None:
+
+ def _ls(prefix, **kwargs):
+ for schema_id, keys in buffer_keys_by_schema.items():
+ if schema_id in prefix:
+ return keys
+ raise FileNotFoundError(prefix)
+
+ s3.ls.side_effect = _ls
+ elif buffer_keys is None:
+ s3.ls.side_effect = FileNotFoundError()
+ else:
+ s3.ls.return_value = buffer_keys
+ with (
+ patch(f"{_CMD}.psycopg.Connection.connect") as mock_connect,
+ patch(f"{_CMD}.BatchQueue.get_oldest_non_terminal_batch_age_seconds", return_value=oldest_batch_age),
+ patch(f"{_CMD}.is_cdc_write_resolution_enabled", return_value=write_resolution),
+ patch(f"{_CMD}.is_pipeline_v3_enabled", return_value=pipeline_v3),
+ patch(f"{_CMD}.purge_buffer_prefix") as mock_purge,
+ patch("products.data_warehouse.backend.facade.api.get_s3_client", return_value=s3),
+ patch(
+ "products.data_warehouse.backend.facade.api.cdc_extraction_schedule_has_running_action",
+ return_value=extraction_running,
+ ),
+ patch("products.data_warehouse.backend.facade.api.pause_cdc_extraction_schedule") as mock_pause,
+ patch("products.data_warehouse.backend.facade.api.unpause_cdc_extraction_schedule") as mock_unpause,
+ patch("products.data_warehouse.backend.facade.api.pause_external_data_schedule") as mock_pause_schema,
+ patch("products.data_warehouse.backend.facade.api.unpause_external_data_schedule") as mock_unpause_schema,
+ ):
+ mock_connect.return_value = MagicMock()
+ yield {
+ "purge": mock_purge,
+ "pause": mock_pause,
+ "unpause": mock_unpause,
+ "pause_schema": mock_pause_schema,
+ "unpause_schema": mock_unpause_schema,
+ "s3": s3,
+ }
+
+
+class TestMigrateCDCSourceToBuffered(BaseTest):
+ def _source(self, ingest_mode: str | None = None) -> ExternalDataSource:
+ job_inputs: dict = {"cdc_enabled": True}
+ if ingest_mode:
+ job_inputs["cdc_ingest_mode"] = ingest_mode
+ return ExternalDataSource.objects.create(team=self.team, source_type="Postgres", job_inputs=job_inputs)
+
+ def _schema(self, source: ExternalDataSource, name: str, table_mode: str = "consolidated", **overrides):
+ return ExternalDataSchema.objects.create(
+ team=self.team,
+ source=source,
+ name=name,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ sync_type_config={
+ "cdc_mode": overrides.get("cdc_mode", "streaming"),
+ "cdc_table_mode": table_mode,
+ },
+ initial_sync_complete=overrides.get("initial_sync_complete", True),
+ table=overrides.get("table"),
+ )
+
+ def _run(self, source, **kwargs) -> str:
+ out = io.StringIO()
+ call_command("migrate_cdc_source_to_buffered", source_id=str(source.id), stdout=out, **kwargs)
+ return out.getvalue()
+
+ def test_flipping_sets_buffered_and_purges_pre_flip_files(self):
+ source = self._source()
+ schema = self._schema(source, "users")
+
+ with _mocked_side_effects() as mocks:
+ self._run(source)
+
+ source.refresh_from_db()
+ assert source.job_inputs["cdc_ingest_mode"] == "buffered"
+ # Pre-flip files were already delivered by the legacy lane; replaying them would re-apply
+ # rows against a position the guard has no watermark for yet.
+ assert mocks["purge"].call_args.args[:2] == (self.team.pk, str(schema.id))
+ mocks["pause"].assert_called_once()
+ mocks["unpause"].assert_called_once()
+ mocks["unpause_schema"].assert_called_once_with(str(schema.id))
+
+ def test_flip_aborts_when_a_buffer_file_survives_the_purge(self):
+ # The purge itself is best-effort; a surviving file would replay legacy-delivered rows
+ # against a lane with no watermark, silently. Abort with the mode unchanged.
+ source = self._source()
+ self._schema(source, "users")
+ leftover = f"bucket/cdc_producer/x/{build_buffer_file_name(1, 2, 0)}"
+
+ with _mocked_side_effects(buffer_keys=[leftover]) as mocks:
+ with pytest.raises(CommandError, match="survived the purge"):
+ self._run(source)
+
+ source.refresh_from_db()
+ assert "cdc_ingest_mode" not in source.job_inputs
+ mocks["unpause"].assert_not_called()
+
+ def test_rollback_drains_the_buffer_then_pauses_the_consumer_before_the_mode_flips(self):
+ source = self._source(ingest_mode="buffered")
+ schema = self._schema(source, "users")
+
+ with _mocked_side_effects() as mocks:
+ self._run(source, rollback=True)
+
+ source.refresh_from_db()
+ assert source.job_inputs["cdc_ingest_mode"] == "legacy"
+ # Fully-applied leftovers stay: the position guard no-ops a replay, the TTL clears them.
+ mocks["purge"].assert_not_called()
+ mocks["pause_schema"].assert_called_once_with(str(schema.id))
+
+ def test_rollback_refuses_while_the_buffer_holds_unapplied_changes(self):
+ # The buffer tail is WAL the slot already advanced past — flipping to legacy before the
+ # consumer applies it loses that WAL for good.
+ source = self._source(ingest_mode="buffered")
+ self._schema(source, "users")
+ unapplied = f"bucket/cdc_producer/x/{build_buffer_file_name(100, 200, 0)}"
+
+ with _mocked_side_effects(buffer_keys=[unapplied]) as mocks:
+ with pytest.raises(CommandError, match="lose them"):
+ self._run(source, rollback=True, drain_timeout=0)
+
+ source.refresh_from_db()
+ assert source.job_inputs["cdc_ingest_mode"] == "buffered"
+ # Consumer schedules must still be live so they can catch up for the re-run.
+ mocks["pause_schema"].assert_not_called()
+
+ def _record_load_position(self, schema: ExternalDataSchema, position: int) -> None:
+ schema.sync_type_config = {
+ **schema.sync_type_config,
+ "cdc_load_position": {consolidated_resource_name(schema): position},
+ }
+ schema.save(update_fields=["sync_type_config"])
+
+ 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.
+ source = self._source(ingest_mode="buffered")
+ self._schema(source, "users")
+ companion = self._schema(source, "events", table_mode="cdc_only")
+ shadow = f"bucket/cdc_producer/x/{build_buffer_file_name(100, 200, 0)}"
+
+ with _mocked_side_effects(buffer_keys_by_schema={str(companion.id): [shadow]}):
+ self._run(source, rollback=True, drain_timeout=0)
+
+ source.refresh_from_db()
+ assert source.job_inputs["cdc_ingest_mode"] == "legacy"
+
+ @parameterized.expand([("at_the_position", 200, True), ("below_the_position", 199, False)])
+ def test_rollback_waits_for_the_consumer_to_delete_the_file_at_the_position(
+ self, _name, end_seq: int, blocks: bool
+ ):
+ # One transaction shares a commit position across its events, so a file ending AT the
+ # position can still be an unread tail. Only the consumer's deletion proves it landed.
+ source = self._source(ingest_mode="buffered")
+ schema = self._schema(source, "users")
+ self._record_load_position(schema, 200)
+ remaining = f"bucket/cdc_producer/x/{build_buffer_file_name(100, end_seq, 0)}"
+
+ with _mocked_side_effects(buffer_keys=[remaining]):
+ if blocks:
+ with pytest.raises(CommandError, match="not yet proven applied"):
+ self._run(source, rollback=True, drain_timeout=0)
+ else:
+ self._run(source, rollback=True, drain_timeout=0)
+
+ source.refresh_from_db()
+ assert source.job_inputs["cdc_ingest_mode"] == ("buffered" if blocks else "legacy")
+
+ def test_a_reflip_is_allowed_once_the_reserved_column_is_ours(self):
+ # The buffered lane writes `_ph_cdc_seq` into the warehouse table, so after a rollback the
+ # column is there for our own reasons — a recorded position proves capture never collided.
+ source = self._source()
+ table = DataWarehouseTable.objects.create(
+ team_id=self.team.pk,
+ name="users",
+ format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,
+ url_pattern="https://bucket/users/*",
+ external_data_source=source,
+ columns={"id": {"hogql": "IntegerDatabaseField"}, CDC_SEQ_COLUMN: {"hogql": "IntegerDatabaseField"}},
+ )
+ schema = self._schema(source, "users", table=table)
+ self._record_load_position(schema, 42)
+
+ with _mocked_side_effects():
+ self._run(source)
+
+ source.refresh_from_db()
+ assert source.job_inputs["cdc_ingest_mode"] == "buffered"
+
+ def test_a_hybrid_source_flips_only_its_consolidated_schemas(self):
+ source = self._source()
+ consolidated = self._schema(source, "users")
+ companion = self._schema(source, "events", table_mode="cdc_only")
+
+ with _mocked_side_effects() as mocks:
+ output = self._run(source)
+
+ assert "staying on legacy" in output
+ assert "events [cdc_only]" in output
+ purged = [call.args[1] for call in mocks["purge"].call_args_list]
+ assert purged == [str(consolidated.id)]
+ mocks["unpause_schema"].assert_called_once_with(str(consolidated.id))
+ assert str(companion.id) not in str(mocks["unpause_schema"].call_args_list)
+
+ def test_a_source_with_no_eligible_schema_is_refused(self):
+ source = self._source()
+ self._schema(source, "events", table_mode="both")
+
+ with _mocked_side_effects():
+ with pytest.raises(CommandError, match="No schema on this source serves the buffered lane"):
+ self._run(source)
+
+ source.refresh_from_db()
+ assert "cdc_ingest_mode" not in source.job_inputs
+
+ def test_a_still_snapshotting_schema_is_not_eligible(self):
+ source = self._source()
+ self._schema(source, "users", cdc_mode="snapshot")
+
+ with _mocked_side_effects():
+ with pytest.raises(CommandError, match="No schema on this source serves the buffered lane"):
+ self._run(source)
+
+ def test_dry_run_changes_nothing_and_reports_the_cadence(self):
+ source = self._source()
+ self._schema(source, "users")
+
+ with _mocked_side_effects() as mocks:
+ output = self._run(source, dry_run=True)
+
+ source.refresh_from_db()
+ assert "cdc_ingest_mode" not in source.job_inputs
+ assert "Dry run" in output
+ # Default schema interval is not the 5min platform cadence — the report must say so.
+ assert "not at the 5min platform cadence" in output
+ mocks["pause"].assert_not_called()
+ mocks["purge"].assert_not_called()
+
+ def test_a_reserved_seq_column_on_the_source_table_refuses_the_flip(self):
+ # The batcher cannot stamp the engine position over a same-named source column, and capture
+ # hard-errors on it — refusing here keeps the source out of a flip-then-break loop.
+ source = self._source()
+ table = DataWarehouseTable.objects.create(
+ team_id=self.team.pk,
+ name="users",
+ format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,
+ url_pattern="https://bucket/users/*",
+ external_data_source=source,
+ columns={"id": {"hogql": "IntegerDatabaseField"}, CDC_SEQ_COLUMN: {"hogql": "IntegerDatabaseField"}},
+ )
+ self._schema(source, "users", table=table)
+
+ with _mocked_side_effects():
+ with pytest.raises(CommandError, match="reserved for change ordering"):
+ self._run(source)
+
+ source.refresh_from_db()
+ assert "cdc_ingest_mode" not in source.job_inputs
+
+ def test_flipping_without_write_resolution_is_refused(self):
+ # No load position means no file is ever proven consumed, so the buffer fills until the S3
+ # TTL expires it — with the slot long advanced, that is unrecoverable loss, not a stall.
+ source = self._source()
+ self._schema(source, "users")
+
+ with _mocked_side_effects(write_resolution=False) as mocks:
+ with pytest.raises(CommandError, match="dwh-cdc-write-resolution is off"):
+ self._run(source)
+
+ source.refresh_from_db()
+ assert "cdc_ingest_mode" not in source.job_inputs
+ mocks["pause"].assert_not_called()
+
+ def test_flipping_a_v2_pipeline_team_is_refused(self):
+ # v2 has no position resolution: nothing records a load position, so the consumer re-merges
+ # the whole buffer on every sync and never deletes a file.
+ source = self._source()
+ self._schema(source, "users")
+
+ with _mocked_side_effects(pipeline_v3=False) as mocks:
+ with pytest.raises(CommandError, match="requires v3"):
+ self._run(source)
+
+ source.refresh_from_db()
+ assert "cdc_ingest_mode" not in source.job_inputs
+ mocks["pause"].assert_not_called()
+
+ def test_rollback_does_not_need_write_resolution(self):
+ source = self._source(ingest_mode="buffered")
+ self._schema(source, "users")
+
+ with _mocked_side_effects(write_resolution=False):
+ self._run(source, rollback=True)
+
+ source.refresh_from_db()
+ assert source.job_inputs["cdc_ingest_mode"] == "legacy"
+
+ def test_a_stuck_sourcebatch_aborts_the_flip_with_the_source_paused(self):
+ source = self._source()
+ self._schema(source, "users")
+
+ with _mocked_side_effects(oldest_batch_age=9999.0) as mocks:
+ with pytest.raises(CommandError, match="still has a batch"):
+ self._run(source, drain_timeout=0)
+
+ source.refresh_from_db()
+ # Flipping on top of a stuck load would let that batch land against a table the buffered
+ # lane has already started writing.
+ assert "cdc_ingest_mode" not in source.job_inputs
+ mocks["pause"].assert_called_once()
+ mocks["unpause"].assert_not_called()
+
+ def test_the_flip_waits_out_an_in_flight_extraction_run(self):
+ # A legacy run with the shadow lane on keeps writing buffer files after the schedule pauses;
+ # one landing after the purge would be merged on top of rows legacy already delivered.
+ source = self._source()
+ self._schema(source, "users")
+
+ with _mocked_side_effects(extraction_running=True) as mocks:
+ with pytest.raises(CommandError, match="still executing"):
+ self._run(source, drain_timeout=0)
+
+ source.refresh_from_db()
+ assert "cdc_ingest_mode" not in source.job_inputs
+ mocks["purge"].assert_not_called()
+ mocks["unpause"].assert_not_called()
+
+ def test_rollback_waits_out_an_in_flight_extraction_run(self):
+ # Pausing the schedule does not stop a running workflow — one still executing would keep
+ # writing buffer files and advancing the slot behind the drain check.
+ source = self._source(ingest_mode="buffered")
+ self._schema(source, "users")
+
+ with _mocked_side_effects(extraction_running=True):
+ with pytest.raises(CommandError, match="still executing"):
+ self._run(source, rollback=True, drain_timeout=0)
+
+ source.refresh_from_db()
+ assert source.job_inputs["cdc_ingest_mode"] == "buffered"
+
+ def test_a_user_disabled_schema_is_not_flipped(self):
+ # Step 5 unpauses eligible schedules; flipping a disabled schema would reverse the disable.
+ source = self._source()
+ disabled = self._schema(source, "users")
+ disabled.should_sync = False
+ disabled.save(update_fields=["should_sync"])
+
+ with _mocked_side_effects():
+ with pytest.raises(CommandError, match="No schema on this source serves the buffered lane"):
+ self._run(source)