:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): shadow-write CDC changes to an S3 buffer (Phase A of buffered ingress) (#74877)
Daniel RCfa0497fc1458
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.pyindex 31bff95a1dd1..b9438c9872cc 100644--- a/products/warehouse_sources/backend/facade/source_management.py+++ b/products/warehouse_sources/backend/facade/source_management.py@@ -22,6 +22,7 @@ _LAZY = {"CDCRepairError": "cdc.repair","CDCRepairInProgress": "cdc.repair","repair_cdc_source": "cdc.repair",+ "purge_buffer_prefix": "cdc.buffer","ClickHouseSource": "sources.clickhouse.source","AnySource": "sources.common.base","ExternalWebhookInfo": "sources.common.base",diff --git a/products/warehouse_sources/backend/management/commands/validate_cdc_buffer.py b/products/warehouse_sources/backend/management/commands/validate_cdc_buffer.pynew file mode 100644index 000000000000..41ad19520798--- /dev/null+++ b/products/warehouse_sources/backend/management/commands/validate_cdc_buffer.py@@ -0,0 +1,214 @@+"""Validate CDC shadow-buffer files against the legacy sourcebatch lane.++Read-only exit gate for the buffered-ingress flip: while the dwh-cdc-buffer-shadow+flag is on, the legacy path stays authoritative and this command reconciles what the+shadow wrote against what legacy dispatched over the same time window.++Checks per CDC schema:+- filename contract: every buffer file parses, start <= end, and ranges are+ non-overlapping in filename-sort order (a shared boundary is legal — a split+ transaction's batches share its commit position).+- row reconciliation: the `{name}_cdc` (scd2_append) lane keeps one row per+ change event, so its sourcebatch row sum must equal the buffer's row sum+ exactly. The consolidated lane dedupes per PK, so it only bounds the buffer+ from below (buffer >= consolidated).++Windows are aligned by timestamp (buffer LastModified vs sourcebatch created_at),+so edge-of-window skew of one micro-batch is possible — treat single-batch-sized+deltas near the window edge as noise and re-run with a wider --since-hours.++Known windows where sums legitimately diverge:+- Around the snapshot→streaming flip: shadow writes buffer files during the+ snapshot phase, but their legacy dispatches are deferred and inserted with+ created_at = flip time. Validate with a window that starts after the schema+ began streaming (or spans the entire snapshot phase).+- After a mid-run activity retry: the legacy lane re-inserts the replayed prefix+ of an in-flight transaction (accepted duplicate scd2 rows) while the buffer's+ same-named files overwrite. Multiple run_uuids in the window therefore+ downgrade the scd2 exact-match to a warning.+"""++from datetime import UTC, datetime, timedelta+from typing import Any++from django.core.management.base import BaseCommand, CommandError, CommandParser++import psycopg+import pyarrow.parquet as pq++from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL++from products.data_warehouse.backend.facade.api import get_s3_client+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_COMPANION_SUFFIX+from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import (+ get_buffer_prefix,+ parse_buffer_file_name,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (+ BATCH_TABLE,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common import strip_s3_protocol+++class Command(BaseCommand):+ help = "Validate CDC shadow-buffer files against legacy sourcebatch dispatches (read-only)"++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--source-id", required=True, help="ExternalDataSource id to validate")+ parser.add_argument("--since-hours", type=int, default=24, help="Comparison window (default 24)")++ def handle(self, *args: Any, **options: Any) -> None:+ source = ExternalDataSource.objects.get(id=options["source_id"])+ cutoff = datetime.now(UTC) - timedelta(hours=options["since_hours"])++ schemas = list(+ ExternalDataSchema.objects.filter(source=source, sync_type=ExternalDataSchema.SyncType.CDC, deleted=False)+ )+ if not schemas:+ raise CommandError(f"Source {source.id} has no CDC schemas")++ legacy_rows, run_counts = self._fetch_legacy_row_sums(source, cutoff)+ s3 = get_s3_client()+ violations: list[str] = []++ for schema in schemas:+ buffer_rows, file_count, schema_violations = self._scan_buffer(s3, schema, cutoff)+ violations.extend(schema_violations)++ scd2_rows = legacy_rows.get((str(schema.id), "scd2"))+ consolidated_rows = legacy_rows.get((str(schema.id), "consolidated"))++ self.stdout.write(+ f"{schema.name} (mode={schema.cdc_table_mode}, cdc_mode={schema.cdc_mode}): "+ f"buffer={buffer_rows} rows in {file_count} files, "+ f"legacy scd2={scd2_rows}, legacy consolidated={consolidated_rows}"+ )++ # Snapshot-phase schemas defer legacy dispatch (cdc_deferred_runs), so+ # row reconciliation only means something once the schema streams.+ if schema.cdc_mode != "streaming":+ continue++ # A streaming flush dispatches legacy immediately, so buffered rows with+ # no legacy dispatches at all means the legacy lane is stalled — absence+ # must fail, not silently skip the comparison.+ required_lanes = {"consolidated": ["consolidated"], "cdc_only": ["scd2"], "both": ["scd2", "consolidated"]}+ if buffer_rows > 0:+ for lane in required_lanes.get(schema.cdc_table_mode, []):+ if legacy_rows.get((str(schema.id), lane)) is None:+ violations.append(+ f"{schema.name}: buffer has {buffer_rows} rows but no legacy {lane} dispatches "+ "in the window — legacy lane stalled or producer failing"+ )++ if scd2_rows is not None and scd2_rows != buffer_rows:+ # Legacy re-inserts replayed rows on activity retry while buffer+ # files overwrite — with multiple runs in the window the exact+ # match is expected to skew, so it warns instead of failing.+ if run_counts.get(str(schema.id), 0) > 1:+ self.stdout.write(+ self.style.WARNING(+ f"WARNING: {schema.name}: scd2 rows ({scd2_rows}) != buffer rows ({buffer_rows}) "+ "with multiple runs in the window — likely retry-replay skew, verify manually"+ )+ )+ else:+ violations.append(+ f"{schema.name}: scd2 lane rows ({scd2_rows}) != buffer rows ({buffer_rows}) — "+ "exact match expected"+ )+ if consolidated_rows is not None and buffer_rows < consolidated_rows:+ violations.append(+ f"{schema.name}: buffer rows ({buffer_rows}) < consolidated rows ({consolidated_rows}) — "+ "shadow is missing data (dedupe can only shrink, never grow, the legacy count)"+ )++ if violations:+ for violation in violations:+ self.stdout.write(self.style.ERROR(f"VIOLATION: {violation}"))+ raise CommandError(f"{len(violations)} violation(s) found")++ self.stdout.write(self.style.SUCCESS("Buffer validation passed"))++ def _scan_buffer(self, s3: Any, schema: ExternalDataSchema, cutoff: datetime) -> tuple[int, int, list[str]]:+ """Return (row_sum, file_count, violations) for one schema's buffer prefix."""+ prefix = strip_s3_protocol(get_buffer_prefix(schema.team_id, str(schema.id)))+ try:+ ls_result = s3.ls(prefix, detail=True)+ except FileNotFoundError:+ return 0, 0, []+ # Some fsspec ls implementations return a dict keyed by path.+ entries = ls_result.values() if isinstance(ls_result, dict) else ls_result++ violations: list[str] = []+ named: list[tuple[str, tuple[int, int, int]]] = []+ for entry in entries:+ if entry.get("type") == "directory":+ continue+ key = entry["Key"]+ file_name = key.rsplit("/", 1)[-1]+ parsed = parse_buffer_file_name(file_name)+ if parsed is None:+ violations.append(f"{schema.name}: foreign file in buffer prefix: {file_name}")+ continue+ modified = entry.get("LastModified")+ if modified is not None and modified < cutoff:+ continue+ named.append((key, parsed))++ # Filename sort must equal WAL order: ranges strictly ordered, overlap+ # only as a shared boundary (split transaction).+ named.sort(key=lambda item: item[0].rsplit("/", 1)[-1])+ row_sum = 0+ prev_end: int | None = None+ for key, (start_seq, end_seq, _file_index) in named:+ if start_seq > end_seq:+ violations.append(f"{schema.name}: inverted range in {key}")+ if prev_end is not None and start_seq < prev_end:+ violations.append(f"{schema.name}: overlapping range in {key} (starts before previous end {prev_end})")+ prev_end = end_seq++ # A failed shadow write can leave a truncated object; report it as a+ # violation instead of crashing the whole validation run.+ try:+ with s3.open(key, "rb") as f:+ row_sum += pq.ParquetFile(f).metadata.num_rows+ except Exception as e:+ violations.append(f"{schema.name}: unreadable buffer file {key} ({type(e).__name__})")++ return row_sum, len(named), violations++ def _fetch_legacy_row_sums(+ self, source: ExternalDataSource, cutoff: datetime+ ) -> tuple[dict[tuple[str, str], int], dict[str, int]]:+ """Sum sourcebatch row_count per (schema_id, lane) since cutoff, plus the+ distinct run count per schema (for retry-replay downgrades).++ Only `sync_type = 'cdc'` dispatches count: snapshots and resyncs flow into+ the same table as full_refresh/incremental and would otherwise inflate the+ consolidated lane into a guaranteed false violation. Lane is derived from+ resource_name via the shared companion suffix.+ """+ companion_pattern = "%" + CDC_COMPANION_SUFFIX.replace("_", r"\_")+ with psycopg.connect(WAREHOUSE_SOURCES_DATABASE_URL) as conn:+ rows = conn.execute(+ f"""+ SELECT schema_id,+ CASE WHEN resource_name LIKE %(companion_pattern)s THEN 'scd2' ELSE 'consolidated' END AS lane,+ COALESCE(SUM(row_count), 0),+ COUNT(DISTINCT run_uuid)+ FROM {BATCH_TABLE}+ WHERE source_id = %(source_id)s AND created_at >= %(cutoff)s AND sync_type = 'cdc'+ GROUP BY schema_id, lane+ """,+ {"source_id": str(source.id), "cutoff": cutoff, "companion_pattern": companion_pattern},+ ).fetchall()++ sums: dict[tuple[str, str], int] = {}+ run_counts: dict[str, int] = {}+ for schema_id, lane, total, runs in rows:+ sums[(str(schema_id), lane)] = int(total)+ run_counts[str(schema_id)] = max(run_counts.get(str(schema_id), 0), int(runs))+ return sums, run_countsdiff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.pyindex 9871899d73ea..0eba098a33ad 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py@@ -146,6 +146,7 @@ from products.warehouse_sources.backend.facade.source_management import (filter_integration_accounts,get_cdc_adapter,get_primary_key_columns,+ purge_buffer_prefix,repair_cdc_source,source_requires_ssl,source_type_supports_cdc,@@ -3969,18 +3970,20 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiif not cdc_config.enabled:return Response(status=status.HTTP_200_OK, data={"success": True, "already_disabled": True})- # Cancel running jobs for this source's CDC schemas — one holding the slot fails- # pg_drop_replication_slot. Scope to CDC schemas so we don't cancel unrelated- # incremental/full-refresh syncs on the same source. Read before the sync_type reset- # below, while these schemas are still marked CDC.- cdc_schema_ids = list(+ # Read the CDC schemas before the sync_type reset below, while they're still+ # marked CDC. Scoped so we don't touch unrelated incremental/full-refresh syncs.+ cdc_schemas = list(ExternalDataSchema.objects.filter(source=instance,sync_type=ExternalDataSchema.SyncType.CDC,).exclude(deleted=True)- .values_list("id", flat=True)+ .select_related("table"))+ # Disabling cancels jobs, drops the slot, purges buffered change data, and resets+ # every CDC schema — editor on the source isn't enough when a table is locked below it.+ self._assert_can_write_schemas(cdc_schemas)+ cdc_schema_ids = [schema.id for schema in cdc_schemas]running_jobs = ExternalDataJob.objects.filter(pipeline_id=instance.pk,team_id=instance.team_id,@@ -4008,6 +4011,11 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixilogger.exception("Failed engine-side CDC cleanup during disable_cdc", exc_info=e)capture_exception(e, {"source_id": str(instance.id)})+ # Drop each schema's S3 change buffer: the shadow lane's files are raw customer+ # change data with no consumer once CDC is off, and nothing else expires them.+ for schema_id in cdc_schema_ids:+ purge_buffer_prefix(instance.team_id, str(schema_id), logger)+with transaction.atomic():# Clear any broken marker (recovery contract): leaving a stale cdc_broken in# sync_type_config would make CDC look broken the moment it's re-enabled.diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.pyindex ea4c03126d50..380da9b8dc26 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py@@ -23,6 +23,7 @@ from django.db import InterfaceError, OperationalError, close_old_connectionsimport psycopgimport pyarrow as paimport structlog+import pyarrow.compute as pcimport posthoganalyticsfrom temporalio import activity@@ -45,6 +46,8 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.adapters imporget_cdc_adapter,)from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (+ CDC_COMPANION_SUFFIX,+ CDC_SEQ_COLUMN,ChangeEventBatcher,build_scd2_table,deduplicate_table,@@ -52,6 +55,11 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher importenrich_toast_omitted_rows,)from products.warehouse_sources.backend.temporal.data_imports.cdc.broken import mark_cdc_broken+from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import (+ CDCBufferWriter,+ is_shadow_write_enabled,+ purge_buffer_prefix,+)from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import (MAX_FRIENDLY_MESSAGE_LENGTH,CDCErrorCategory,@@ -225,6 +233,17 @@ 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()+ 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# ------------------------------------------------------------------# Logger helpers@@ -591,6 +610,80 @@ class CDCExtractActivity:"partition_format": schema.partition_format,}+ # ------------------------------------------------------------------+ # Shadow buffered ingress+ # ------------------------------------------------------------------+ # Consecutive shadow-write failures before the lane disables for the rest of+ # the run: a persistent S3 failure otherwise pays full retry latency on every+ # 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.+ """+ if not self._shadow_enabled or self._shadow_disabled_for_run:+ return+ # The engine seq column is always LAST when the batcher appended it; a+ # same-named source column (collision → append skipped) is never last.+ # Checking by name would let the user's column masquerade as positions.+ if table.num_rows == 0 or table.schema.field(table.num_columns - 1).name != CDC_SEQ_COLUMN:+ return++ file_index = self._shadow_file_index.get(table_name, 0)+ try:+ if self._shadow_buffer_writer is None:+ self._shadow_buffer_writer = CDCBufferWriter(self.log)++ schema_id = str(schema.id)+ if schema_id not in self._shadow_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(table.num_columns - 1)).as_py()+ self._shadow_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)++ result = self._shadow_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(+ result.write_duration_seconds+ )+ self._schema_log(schema).debug(+ "cdc_shadow_buffer_written",+ table=table_name,+ s3_path=result.s3_path,+ rows=result.row_count,+ start_seq=result.start_seq,+ end_seq=result.end_seq,+ )+ 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)+ self._schema_log(schema).warning("cdc_shadow_buffer_write_failed", table=table_name, exc_info=True)+ 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# ------------------------------------------------------------------@@ -627,6 +720,16 @@ class CDCExtractActivity:enriched_table = enrich_toast_omitted_rows(raw_table, key_columns)enriched_table = enrich_delete_rows(enriched_table, key_columns)+ # Shadow buffered ingress: persist the raw (pre-dedup/SCD2) stream, then+ # strip the seq column so the legacy write path stays byte-identical.+ # Strip by LAST field only — the batcher appends its seq column last and+ # skips the append on collision, so a source column that happens to be+ # named _ph_cdc_seq is never ours and must pass through untouched.+ self._maybe_shadow_write_buffer(schema, table_name, enriched_table)+ last_field_idx = enriched_table.num_columns - 1+ if enriched_table.schema.field(last_field_idx).name == CDC_SEQ_COLUMN:+ enriched_table = enriched_table.remove_column(last_field_idx)+# Consolidated shares the snapshot's canonical folder; the `_cdc` companion is# CDC-only and stays self-consistent with its `name`-keyed snapshot seed.batch_writes: list[tuple[pa.Table, str, str]] = []@@ -637,7 +740,11 @@ class CDCExtractActivity:)elif cdc_table_mode == "cdc_only":batch_writes.append(- (build_scd2_table(enriched_table, key_columns), f"{schema.name}_cdc", "scd2_append")+ (+ build_scd2_table(enriched_table, key_columns),+ f"{schema.name}{CDC_COMPANION_SUFFIX}",+ "scd2_append",+ ))elif cdc_table_mode == "both":consolidated_name = self._consolidated_resource_name(schema)@@ -645,7 +752,11 @@ class CDCExtractActivity:(deduplicate_table(enriched_table, key_columns), consolidated_name, "incremental_merge"))batch_writes.append(- (build_scd2_table(enriched_table, key_columns), f"{schema.name}_cdc", "scd2_append")+ (+ build_scd2_table(enriched_table, key_columns),+ f"{schema.name}{CDC_COMPANION_SUFFIX}",+ "scd2_append",+ ))for write_table, write_resource_name, cdc_write_mode in batch_writes:@@ -806,6 +917,7 @@ class CDCExtractActivity:self.schema_by_name = {s.name: s for s in self.cdc_schemas}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)return Truedef _delete_own_schedule(self) -> None:@@ -1055,8 +1167,14 @@ class CDCExtractActivity:events on the next run."""assert self._run_started_at is not None+ assert self.adapter is not Noneevent_name_to_schema_name = self._build_event_name_map()- self.batcher = ChangeEventBatcher()+ # 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.+ self.batcher = ChangeEventBatcher(+ position_to_seq=self.adapter.position_to_seq if self._shadow_enabled else None+ )on_row = self._make_read_heartbeat()limit = CDC_MAX_CHANGES_PER_READ@@ -1218,6 +1336,10 @@ class CDCExtractActivity:removes=removes,extra_model_fields={"initial_sync_complete": False},)+ # The reset invalidates every buffered change file: the table is wiped and+ # re-seeded through the snapshot lane the buffer never sees, and the filename+ # contract has no way to express that discontinuity. Best-effort purge.+ purge_buffer_prefix(schema.team_id, str(schema.id), self._schema_log(schema))if clear_deferred_runs:self._emit_deferred_runs_depth()@@ -1726,6 +1848,14 @@ def cleanup_orphan_slots_activity() -> None:source_log.exception("failed_to_cleanup_deleted_source_slot")metrics.get_sweeper_source_errors_metric().add(1)sources_errored += 1++ # Shadow-buffer prefixes: destroy() defers all external reaping to this+ # sweep, so without this the raw change files outlive the source until+ # a lifecycle rule exists. Idempotent — a purged prefix is a no-op.+ for schema_id in ExternalDataSchema.objects.filter(+ source=source, sync_type=ExternalDataSchema.SyncType.CDC+ ).values_list("id", flat=True):+ purge_buffer_prefix(source.team_id, str(schema_id), source_log)continue# 2. Active sources — check WAL lagdiff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.pyindex 2744e8bf4774..2dcd41b6908a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py@@ -40,6 +40,12 @@ class CDCSourceAdapter(Protocol[CDCConfigT_co]):def create_reader(self, source: ExternalDataSource) -> CDCStreamReader: ...+ def position_to_seq(self, position_serialized: str) -> int:+ """Convert an event's serialized position to the engine-neutral monotonic+ integer used for `_ph_cdc_seq` and buffer-file position ranges (PG: the+ LSN's 64-bit value). Must be strictly order-preserving within one source."""+ ...+@contextmanagerdef management_connection(self, source: ExternalDataSource, connect_timeout: int = 15) -> Iterator[Any]: ...diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.pyindex 0b00d3b1b9f3..bebd10a29392 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py@@ -1,6 +1,7 @@from __future__ import annotationsfrom collections import defaultdict+from collections.abc import Callableimport pyarrow as pa@@ -11,6 +12,16 @@ CDC_OP_COLUMN = "_ph_cdc_op"CDC_TIMESTAMP_COLUMN = "_ph_cdc_timestamp"DELETED_COLUMN = "_ph_deleted"DELETED_AT_COLUMN = "_ph_deleted_at"+# Engine-neutral monotonic position per row (Postgres: the commit LSN as an+# integer), converted from ChangeEvent.position_serialized by the engine+# adapter. int64 rather than uint64 because Delta has no unsigned types and+# real positions never approach 2^63. Names the buffer files' position range+# and (in Phase B) drives the merge's monotonicity guard.+CDC_SEQ_COLUMN = "_ph_cdc_seq"++# Suffix of the SCD2 companion table's resource name ({schema.name}_cdc). Shared+# so lane classification (validate_cdc_buffer) can never drift from the writers.+CDC_COMPANION_SUFFIX = "_cdc"# Per-row list of source columns the change stream omitted because they are# unchanged from the previous row version (Postgres: unchanged TOAST values).# Consumed by enrich_toast_omitted_rows; the load processor drops it before@@ -27,6 +38,7 @@ _CDC_METADATA_COLUMNS: frozenset[str] = frozenset({CDC_OP_COLUMN,CDC_TIMESTAMP_COLUMN,+ CDC_SEQ_COLUMN,DELETED_COLUMN,DELETED_AT_COLUMN,TOAST_OMITTED_COLUMN,@@ -59,11 +71,15 @@ class ChangeEventBatcher:self,max_events: int = CDC_FLUSH_MAX_EVENTS,max_bytes: int = CDC_FLUSH_MAX_BYTES,+ position_to_seq: Callable[[str], int] | None = None,) -> None:self._events: defaultdict[str, list[ChangeEvent]] = defaultdict(list)self._estimated_bytes: int = 0self._max_events = max_eventsself._max_bytes = max_bytes+ # Engine adapter's position_serialized → int converter. When set, flushed+ # tables carry CDC_SEQ_COLUMN; when None the column is absent entirely.+ self._position_to_seq = position_to_seqdef add(self, event: ChangeEvent) -> None:self._events[event.table_name].append(event)@@ -84,7 +100,7 @@ class ChangeEventBatcher:for table_name, events in self._events.items():if not events:continue- result[table_name] = _events_to_table(events)+ result[table_name] = _events_to_table(events, position_to_seq=self._position_to_seq)self._events.clear()self._estimated_bytes = 0@@ -445,7 +461,7 @@ def build_scd2_table(pa_table: pa.Table, pk_columns: list[str]) -> pa.Table:)-def _events_to_table(events: list[ChangeEvent]) -> pa.Table:+def _events_to_table(events: list[ChangeEvent], position_to_seq: Callable[[str], int] | None = None) -> pa.Table:"""Convert a list of ChangeEvents (same table) to a PyArrow table with CDC metadata."""# Collect all column names across all events (order-preserving). Omitted# (unchanged-TOAST) columns are included so the batch table always carries a@@ -525,5 +541,14 @@ def _events_to_table(events: list[ChangeEvent]) -> pa.Table:arrays.append(pa.array(omitted_lists, type=pa.list_(pa.string())))fields.append(pa.field(TOAST_OMITTED_COLUMN, pa.list_(pa.string())))+ # Skip on collision: a source column literally named _ph_cdc_seq must pass+ # through to the legacy lane untouched. The batch then carries no engine seq+ # and the shadow writer skips it. Appended LAST by construction — the caller+ # relies on that to strip our column without touching a same-named user one.+ if position_to_seq is not None and CDC_SEQ_COLUMN not in column_names:+ seq_values = [position_to_seq(event.position_serialized) for event in events]+ arrays.append(pa.array(seq_values, type=pa.int64()))+ fields.append(pa.field(CDC_SEQ_COLUMN, pa.int64()))+schema = pa.schema(fields)return pa.table(arrays, schema=schema)diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.pynew file mode 100644index 000000000000..d575f98caed8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py@@ -0,0 +1,254 @@+"""S3 change buffer for CDC — the ingress side of buffered CDC.++Capture demuxes decoded change events per schema and writes each micro-batch as+one Parquet file under a stable per-schema prefix:++ s3://{DATAWAREHOUSE_BUCKET}/cdc_producer/{team_id}/{schema_id}/{start_seq}-{end_seq}-{file_index}.parquet++The filename carries the batch's position range (`_ph_cdc_seq` min/max) zero-padded+to fixed width so lexicographic order equals numeric order — consumers sort by+filename, never by S3 mtime, and never parse Parquet to establish order.++`file_index` disambiguates batches that share a position range: a micro-flush can+split one transaction (all of whose events share a commit position) across+consecutive batches. Within a capture run the index is strictly increasing per+schema, so (start, end, index) sorts in WAL order.++Replay semantics: micro-batch boundaries are NOT deterministic across activity+attempts (the flush budget spans tables, the slot micro-advances mid-run, and a+soft deadline cuts runs on wall clock), so a retried attempt may cover the same+positions with differently-shaped files. Writers therefore call+`cleanup_superseded_files` before their first write per schema: anything at or+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.+"""++from __future__ import annotations++import re+import time+from contextlib import suppress+from dataclasses import dataclass++from django.conf import settings++import pyarrow as pa+import pyarrow.compute as pc+import pyarrow.parquet as pq+import posthoganalytics+from structlog.types import FilteringBoundLogger++from products.data_warehouse.backend.facade.api import get_s3_client+from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common import (+ ensure_bucket,+ strip_s3_protocol,+)++BUFFER_ROOT_FOLDER = "cdc_producer"++# Per-team gate for the shadow lane — the single on/off control. Fail-closed on+# evaluation errors, so the soak can only ever shrink, never grow, by accident.+SHADOW_WRITE_FLAG = "dwh-cdc-buffer-shadow"++_SEQ_WIDTH = 20 # zero-pad width covering the full u64 range+_INDEX_WIDTH = 6++# ASCII digits only: int() also accepts "+", "_", whitespace, and Unicode digits,+# any of which would break "lexicographic order equals numeric order".+_FILE_NAME_RE = re.compile(rf"([0-9]{{{_SEQ_WIDTH}}})-([0-9]{{{_SEQ_WIDTH}}})-([0-9]{{{_INDEX_WIDTH}}})\.parquet")+++def is_shadow_write_enabled(team_id: int, logger: FilteringBoundLogger) -> bool:+ """Whether the shadow lane may write for this team, evaluated once per run.++ Never raises: a flag-service failure leaves the lane off, which costs a gap in+ validation data — the legacy path is unaffected either way.+ """+ from posthog.models.team import Team++ try:+ team = Team.objects.get(pk=team_id)+ return bool(+ posthoganalytics.feature_enabled(+ SHADOW_WRITE_FLAG,+ str(team.uuid),+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ # team_id drives the release conditions (the warehouse convention for+ # per-team rollouts); the group context is passed for consistency with+ # the other warehouse flags and for org-wide kill switches.+ person_properties={"team_id": str(team.id)},+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {"id": str(team.id)},+ },+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception:+ logger.warning("cdc_shadow_flag_check_failed", team_id=team_id, exc_info=True)+ return False+++def get_buffer_prefix(team_id: int, schema_id: str) -> str:+ return f"s3://{settings.DATAWAREHOUSE_BUCKET}/{BUFFER_ROOT_FOLDER}/{team_id}/{schema_id}"+++def build_buffer_file_name(start_seq: int, end_seq: int, file_index: int) -> str:+ if not (0 <= start_seq <= end_seq < 10**_SEQ_WIDTH):+ raise ValueError(f"Invalid buffer position range: {start_seq}-{end_seq}")+ if not (0 <= file_index < 10**_INDEX_WIDTH):+ raise ValueError(f"Buffer file index out of range: {file_index}")+ return f"{start_seq:0{_SEQ_WIDTH}d}-{end_seq:0{_SEQ_WIDTH}d}-{file_index:0{_INDEX_WIDTH}d}.parquet"+++def parse_buffer_file_name(file_name: str) -> tuple[int, int, int] | None:+ """Parse `{start}-{end}-{index}.parquet` → (start_seq, end_seq, file_index).++ Returns None for names that don't match the contract (foreign files are+ ignored, never treated as buffer data).+ """+ match = _FILE_NAME_RE.fullmatch(file_name)+ if match is None:+ return None+ return int(match.group(1)), int(match.group(2)), int(match.group(3))+++@dataclass(frozen=True, slots=True)+class BufferFileWriteResult:+ s3_path: str+ row_count: int+ start_seq: int+ end_seq: int+ file_index: int+ write_duration_seconds: float+++class CDCBufferWriter:+ """Writes per-schema change batches to the S3 buffer.++ The table must carry `_ph_cdc_seq` (engine-neutral monotonic position per row);+ the file's position range is derived from it.+ """++ def __init__(self, logger: FilteringBoundLogger) -> None:+ self._logger = logger+ self._s3 = get_s3_client()+ ensure_bucket()++ def write_batch(+ self,+ *,+ team_id: int,+ schema_id: str,+ table: pa.Table,+ file_index: int,+ ) -> BufferFileWriteResult:+ if CDC_SEQ_COLUMN not in table.column_names:+ raise ValueError(f"Buffer batches must carry {CDC_SEQ_COLUMN}")+ if table.num_rows == 0:+ raise ValueError("Refusing to write an empty buffer file")+ seq_column = table.column(CDC_SEQ_COLUMN)+ # Any null (not just all-null) is rejected: pc.min_max skips nulls, so a+ # partially-null column would silently narrow the filename's range.+ if seq_column.null_count != 0:+ raise ValueError(f"{CDC_SEQ_COLUMN} must be non-null in buffer batches")++ min_max = pc.min_max(seq_column)+ start_seq = min_max["min"].as_py()+ end_seq = min_max["max"].as_py()++ file_name = build_buffer_file_name(start_seq, end_seq, file_index)+ s3_path = f"{get_buffer_prefix(team_id, schema_id)}/{file_name}"+ key = strip_s3_protocol(s3_path)++ write_start = time.perf_counter()+ try:+ with self._s3.open(key, "wb") as f:+ pq.write_table(table, f, compression="zstd")+ except Exception:+ # fsspec's close() flushes buffered bytes even after a mid-write+ # failure, so a truncated object can land under a contract-valid+ # name. Best-effort removal keeps the failure a gap, not corruption.+ with suppress(Exception):+ self._s3.rm(key)+ raise+ write_duration = time.perf_counter() - write_start++ self._logger.debug(+ "cdc_buffer_file_written",+ s3_path=s3_path,+ row_count=table.num_rows,+ start_seq=start_seq,+ end_seq=end_seq,+ file_index=file_index,+ )++ return BufferFileWriteResult(+ s3_path=s3_path,+ row_count=table.num_rows,+ start_seq=start_seq,+ end_seq=end_seq,+ file_index=file_index,+ write_duration_seconds=write_duration,+ )++ def cleanup_superseded_files(self, *, team_id: int, schema_id: str, restart_seq: int) -> int:+ """Remove files a retried attempt is about to regenerate.++ Called before the first write per schema in a run: every file whose+ start_seq >= the position this run reads from (`restart_seq`) belongs to+ a superseded attempt whose batch boundaries may differ. Files strictly+ below restart_seq are settled — their WAL was released and will never be+ re-produced. Returns the number of files removed.+ """+ prefix = strip_s3_protocol(get_buffer_prefix(team_id, schema_id))+ try:+ # refresh: the fsspec instance cache can serve a stale listing in a+ # long-lived worker; a missed entry here silently skips a supersede-delete.+ keys = self._s3.ls(prefix, detail=False, refresh=True)+ except FileNotFoundError:+ return 0++ removed = 0+ for key in keys:+ parsed = parse_buffer_file_name(key.rsplit("/", 1)[-1])+ if parsed is None:+ continue+ start_seq, _end_seq, _file_index = parsed+ if start_seq >= restart_seq:+ with suppress(Exception):+ self._s3.rm(key)+ removed += 1+ if removed:+ self._logger.info(+ "cdc_buffer_superseded_files_removed",+ schema_id=schema_id,+ restart_seq=restart_seq,+ removed=removed,+ )+ 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.++ 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.+ """+ prefix = strip_s3_protocol(get_buffer_prefix(team_id, schema_id))+ with suppress(Exception):+ s3 = get_s3_client()+ s3.rm(prefix, recursive=True)+ logger.info("cdc_buffer_prefix_purged", schema_id=schema_id)diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.pyindex e66bac021b73..55d3837dc23f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.py@@ -43,6 +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:+ return _source_meter(team_id, source_id).create_counter(+ "cdc_shadow_buffer_files_written_total", "Total buffer files written in shadow mode"+ )+++def get_shadow_buffer_write_errors_metric(team_id: int, source_id: str) -> MetricCounter:+ return _source_meter(team_id, source_id).create_counter(+ "cdc_shadow_buffer_write_errors_total", "Total swallowed shadow buffer write failures"+ )+++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_extraction_duration_metric(team_id: int, source_id: str, status: str) -> MetricHistogramFloat:return (_meter()diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.pyindex 12622d61f1f8..8cb7a51ba58b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py@@ -8,6 +8,7 @@ from parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (CDC_OP_COLUMN,+ CDC_SEQ_COLUMN,CDC_TIMESTAMP_COLUMN,DELETED_AT_COLUMN,DELETED_COLUMN,@@ -646,3 +647,61 @@ class TestEnrichToastOmittedRows:assert result.column("big")[0].as_py() is Noneassert result.column(TOAST_OMITTED_COLUMN)[0].as_py() == ["big"]+++def _pg_position_to_seq(position: str) -> int:+ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.position import PgLSN++ return PgLSN.deserialize(position).value+++class TestSeqColumn:+ def test_seq_column_emitted_with_converter(self):+ batcher = ChangeEventBatcher(position_to_seq=_pg_position_to_seq)+ batcher.add(_make_event(op="I", position="0/100"))+ batcher.add(_make_event(op="U", position="0/200"))+ table = batcher.flush()["users"]++ assert table.schema.field(CDC_SEQ_COLUMN).type == pa.int64()+ assert table.column(CDC_SEQ_COLUMN).to_pylist() == [0x100, 0x200]++ def test_seq_column_absent_without_converter(self):+ batcher = ChangeEventBatcher()+ batcher.add(_make_event(op="I", position="0/100"))+ table = batcher.flush()["users"]++ assert CDC_SEQ_COLUMN not in table.column_names++ def test_source_column_named_like_seq_wins_and_append_is_skipped(self):+ # A user column literally named _ph_cdc_seq must pass through with its own+ # values; the engine seq append is skipped rather than shadowing it.+ batcher = ChangeEventBatcher(position_to_seq=_pg_position_to_seq)+ batcher.add(_make_event(op="I", position="0/100", columns={"id": 1, CDC_SEQ_COLUMN: 42}))+ table = batcher.flush()["users"]++ assert table.column_names.count(CDC_SEQ_COLUMN) == 1+ assert table.column(CDC_SEQ_COLUMN).to_pylist() == [42]+ # Not last: the caller's strip-by-last-field rule must not remove it.+ assert table.schema.field(table.num_columns - 1).name != CDC_SEQ_COLUMN++ def test_seq_survives_enrichment_untouched(self):+ # Seq is CDC metadata: DELETE/TOAST enrichment must never fill or copy it.+ batcher = ChangeEventBatcher(position_to_seq=_pg_position_to_seq)+ batcher.add(+ _make_event(+ op="U",+ position="0/100",+ columns={"id": 1, "name": "Alice"},+ omitted_columns=frozenset({"big"}),+ )+ )+ batcher.add(_make_event(op="D", position="0/200", columns={"id": 1}))+ table = batcher.flush()["users"]++ enriched = enrich_toast_omitted_rows(table, ["id"])+ enriched = enrich_delete_rows(enriched, ["id"])++ assert enriched.column(CDC_SEQ_COLUMN).to_pylist() == [0x100, 0x200]+ # The DELETE row copied `name` from the preceding update, proving+ # enrichment ran while seq stayed per-event.+ assert enriched.column("name")[1].as_py() == "Alice"diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.pynew file mode 100644index 000000000000..d402e658c646--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.py@@ -0,0 +1,228 @@+import io+import random+from contextlib import contextmanager++import pytest+from unittest.mock import MagicMock, patch++import pyarrow as pa+import pyarrow.parquet as pq++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 (+ CDCBufferWriter,+ build_buffer_file_name,+ get_buffer_prefix,+ parse_buffer_file_name,+)+++class TestBufferFileName:+ def test_roundtrip(self):+ name = build_buffer_file_name(256, 512, 3)+ assert parse_buffer_file_name(name) == (256, 512, 3)++ def test_rejects_foreign_names(self):+ assert parse_buffer_file_name("part-0000.parquet") is None+ assert parse_buffer_file_name("schema.json") is None+ assert parse_buffer_file_name("256-512-3.parquet") is None # unpadded+ assert parse_buffer_file_name(build_buffer_file_name(1, 2, 3).removesuffix(".parquet")) is None++ def test_rejects_non_canonical_numeric_spellings(self):+ # int() accepts these; the contract must not — they break lexicographic order.+ base = build_buffer_file_name(100, 200, 0)+ assert parse_buffer_file_name(base.replace("-", "-+", 1)) is None+ assert parse_buffer_file_name("0000000000000001_000-" + base.split("-", 1)[1]) is None+ assert parse_buffer_file_name(" " + base[1:]) is None+ assert parse_buffer_file_name(base.replace("0", "0", 1)) is None # fullwidth digit++ def test_build_rejects_out_of_contract_values(self):+ with pytest.raises(ValueError, match="range"):+ build_buffer_file_name(300, 200, 0) # inverted+ with pytest.raises(ValueError, match="range"):+ build_buffer_file_name(-1, 200, 0)+ with pytest.raises(ValueError, match="index"):+ build_buffer_file_name(1, 2, 10**6) # would emit 7 digits and break sort+ with pytest.raises(ValueError, match="index"):+ build_buffer_file_name(1, 2, -1)++ def test_lexicographic_sort_equals_numeric_sort(self):+ # The consumer's only ordering primitive is a filename sort — padding must+ # make that equal to numeric (start, end, index) order across magnitudes.+ ranges = [(1, 9, 0), (10, 15, 0), (15, 15, 1), (15, 15, 2), (16, 2**63 - 1, 0), (2**40, 2**41, 5)]+ names = [build_buffer_file_name(*r) for r in ranges]+ shuffled = names[:]+ random.Random(42).shuffle(shuffled)+ assert sorted(shuffled) == [build_buffer_file_name(*r) for r in sorted(ranges)]+++class TestIsShadowWriteEnabled:+ """The per-team flag is the single gate, and it fails closed."""++ def _call(self, *, flag, team_lookup_ok: bool = True) -> bool:+ from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import is_shadow_write_enabled++ team = MagicMock(uuid="team-uuid", id=2, organization_id="org-uuid")+ team_manager = MagicMock()+ team_manager.objects.get.return_value = team+ if not team_lookup_ok:+ team_manager.objects.get.side_effect = Exception("db down")++ flag_fn = MagicMock(side_effect=flag) if callable(flag) else MagicMock(return_value=flag)+ with (+ patch.dict("sys.modules", {"posthog.models.team": MagicMock(Team=team_manager)}),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.cdc.buffer.posthoganalytics.feature_enabled",+ flag_fn,+ ),+ ):+ result = is_shadow_write_enabled(2, MagicMock())+ self._last_flag_call = flag_fn+ return result++ def test_follows_the_flag(self):+ assert self._call(flag=True) is True+ assert self._call(flag=False) is False++ def test_passes_team_scoped_targeting_context(self):+ # team_id drives the release conditions (warehouse per-team rollout convention),+ # so a soak covers single teams rather than whole orgs.+ self._call(flag=True)+ kwargs = self._last_flag_call.call_args.kwargs+ assert kwargs["person_properties"]["team_id"] == "2"+ assert kwargs["groups"]["project"] == "2"++ def test_flag_service_failure_disables_rather_than_raises(self):+ def boom(*_a, **_k):+ raise RuntimeError("flag service down")++ assert self._call(flag=boom) is False++ def test_team_lookup_failure_disables_rather_than_raises(self):+ assert self._call(flag=True, team_lookup_ok=False) is False+++class TestCDCBufferWriter:+ def _writer_with_captured_files(self) -> tuple[CDCBufferWriter, dict[str, io.BytesIO]]:+ files: dict[str, io.BytesIO] = {}++ @contextmanager+ def fake_open(path, mode):+ buf = io.BytesIO()+ files[path] = buf+ yield buf++ mock_s3 = MagicMock()+ mock_s3.open = fake_open+ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.cdc.buffer.get_s3_client",+ return_value=mock_s3,+ ),+ patch("products.warehouse_sources.backend.temporal.data_imports.cdc.buffer.ensure_bucket"),+ ):+ writer = CDCBufferWriter(MagicMock())+ return writer, files++ def _table(self, seqs: list[int]) -> pa.Table:+ return pa.table(+ {+ "id": pa.array(range(len(seqs)), type=pa.int64()),+ CDC_SEQ_COLUMN: pa.array(seqs, type=pa.int64()),+ }+ )++ def test_writes_window_file_with_range_from_seq_column(self):+ writer, files = self._writer_with_captured_files()+ result = writer.write_batch(team_id=1, schema_id="abc", table=self._table([512, 256, 300]), file_index=2)++ assert result.start_seq == 256+ assert result.end_seq == 512+ assert result.row_count == 3+ assert result.s3_path == f"{get_buffer_prefix(1, 'abc')}/{build_buffer_file_name(256, 512, 2)}"++ assert len(files) == 1+ written = pq.read_table(io.BytesIO(next(iter(files.values())).getvalue()))+ assert written.column(CDC_SEQ_COLUMN).to_pylist() == [512, 256, 300]++ def test_rejects_empty_table(self):+ writer, _files = self._writer_with_captured_files()+ with pytest.raises(ValueError, match="empty"):+ writer.write_batch(team_id=1, schema_id="abc", table=self._table([]), file_index=0)++ def test_rejects_table_without_seq_column(self):+ writer, _files = self._writer_with_captured_files()+ table = pa.table({"id": pa.array([1], type=pa.int64())})+ with pytest.raises(ValueError, match=CDC_SEQ_COLUMN):+ writer.write_batch(team_id=1, schema_id="abc", table=table, file_index=0)++ def test_rejects_any_null_seq(self):+ # pc.min_max skips nulls, so a partially-null column would silently+ # narrow the filename's range — reject nulls outright.+ writer, files = self._writer_with_captured_files()+ for seqs in ([None], [256, None, 512]):+ table = pa.table(+ {+ "id": pa.array(range(len(seqs)), type=pa.int64()),+ CDC_SEQ_COLUMN: pa.array(seqs, type=pa.int64()),+ }+ )+ with pytest.raises(ValueError, match="non-null"):+ writer.write_batch(team_id=1, schema_id="abc", table=table, file_index=0)+ assert not files++ def test_failed_write_removes_the_partial_object(self):+ # fsspec close() flushes buffered bytes even after a failure, so the key+ # must be removed or a truncated file lands under a contract-valid name.+ files: dict[str, io.BytesIO] = {}++ @contextmanager+ def fake_open(path, mode):+ buf = io.BytesIO()+ files[path] = buf+ yield buf++ mock_s3 = MagicMock()+ mock_s3.open = fake_open+ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.cdc.buffer.get_s3_client",+ return_value=mock_s3,+ ),+ patch("products.warehouse_sources.backend.temporal.data_imports.cdc.buffer.ensure_bucket"),+ ):+ writer = CDCBufferWriter(MagicMock())+ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.cdc.buffer.pq.write_table",+ side_effect=OSError("mid-write failure"),+ ),+ pytest.raises(OSError),+ ):+ writer.write_batch(team_id=1, schema_id="abc", table=self._table([256]), file_index=0)+ mock_s3.rm.assert_called_once_with(next(iter(files)))++ def test_cleanup_superseded_files_removes_at_or_past_restart(self):+ writer, _files = self._writer_with_captured_files()+ prefix = "data-warehouse/cdc_producer/1/abc"+ keys = [+ f"{prefix}/{build_buffer_file_name(100, 200, 0)}", # settled, below restart+ f"{prefix}/{build_buffer_file_name(300, 400, 1)}", # superseded+ f"{prefix}/{build_buffer_file_name(300, 300, 2)}", # superseded, shared boundary+ f"{prefix}/schema.json", # foreign — never touched+ ]+ writer._s3.ls = MagicMock(return_value=keys)+ writer._s3.rm = MagicMock()++ removed = writer.cleanup_superseded_files(team_id=1, schema_id="abc", restart_seq=300)++ # A cached listing that misses a fresh file silently skips its supersede-delete.+ assert writer._s3.ls.call_args.kwargs["refresh"] is True+ assert removed == 2+ removed_keys = [c.args[0] for c in writer._s3.rm.call_args_list]+ assert removed_keys == keys[1:3]++ def test_cleanup_handles_missing_prefix(self):+ writer, _files = self._writer_with_captured_files()+ writer._s3.ls = MagicMock(side_effect=FileNotFoundError)+ assert writer.cleanup_superseded_files(team_id=1, schema_id="abc", restart_seq=1) == 0diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.pyindex 86d18c3b605e..267102962669 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py@@ -130,6 +130,23 @@ def test_deleted_self_managed_drops_schedule_but_not_slot(team):adapter.drop_resources.assert_not_called()+def test_deleted_source_purges_shadow_buffer_prefixes(team):+ # destroy() defers all external reaping to the sweep, so the sweep must purge the+ # deleted source's buffer prefixes — including soft-deleted CDC schema rows.+ source = _create_source(team, deleted=True, job_inputs=_cdc_job_inputs())+ schema = _create_cdc_schema(team, source)+ schema.deleted = True+ schema.save()++ adapter = _mock_adapter()+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix"+ ) as mock_purge:+ _run(adapter)++ assert [call.args[1] for call in mock_purge.call_args_list] == [str(schema.id)]++def test_critical_lag_posthog_auto_drop_marks_broken_and_pauses(team):source = _create_source(team, job_inputs=_cdc_job_inputs(auto_drop_slot=True))schema = _create_cdc_schema(team, source)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.pyindex f1c69e6cf1d2..01e714a9a968 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@@ -28,12 +28,14 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.activities impcdc_extract_activity,cleanup_orphan_slots_activity,)+from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMNfrom products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCErrorCategory, cdc_error_infofrom products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEventfrom 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.postgres.cdc.adapter import PostgresCDCAdapter+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.position import PgLSNfrom products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException@@ -205,6 +207,9 @@ def _setup_mocks(mock_adapter.create_reader.return_value = mock_readermock_adapter.is_slot_invalidation_error.return_value = Falsemock_adapter.classify_error.return_value = None # default: unrecognized -> unknown/retryable+ # Real converter, not a MagicMock return: the batcher feeds its output into a+ # typed pa.array, which would reject a MagicMock in every streaming test.+ mock_adapter.position_to_seq.side_effect = lambda position: PgLSN.deserialize(position).valuemock_get_adapter.return_value = mock_adaptermock_s3 = MagicMock()@@ -333,6 +338,16 @@ class TestGetCDCAdapter:assert isinstance(reader, PgCDCStreamReader)assert reader._params.require_ssl is False+ def test_position_to_seq_matches_lsn_value_and_preserves_order(self):+ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter import (+ PostgresCDCAdapter,+ )++ adapter = PostgresCDCAdapter()+ assert adapter.position_to_seq("0/100") == 0x100+ assert adapter.position_to_seq("0/200") > adapter.position_to_seq("0/100")+ assert adapter.position_to_seq("1/0") > adapter.position_to_seq("0/FFFFFFFF")+def _make_extract_activity(source, log=None) -> CDCExtractActivity:"""Build a CDCExtractActivity with source and log pre-injected for unit tests."""@@ -553,6 +568,168 @@ class TestBuildEventNameMap:assert activity_obj._build_event_name_map().get(wal_event_name) == expected_canonical+class TestShadowBufferWrite:+ """Shadow buffered-ingress writes around _process_flush.++ Enablement is the per-team dwh-cdc-buffer-shadow flag, resolved once in _setup;+ these drive it end-to-end through the real gate (`is_shadow_write_enabled`).+ """++ def _run(self, MockBufferWriter, events, shadow_on: bool):+ 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=shadow_on,+ ),+ ):+ MockBufferWriter.return_value.write_batch.return_value.write_duration_seconds = 0.01+ source = _make_source()+ schema = _make_schema("users", cdc_mode="streaming", source=source)+ mock_reader, mock_s3, mock_producer, _mock_job = _setup_mocks(+ mock_activity,+ MockProducer,+ MockS3Writer,+ mock_get_adapter,+ mock_get_schemas,+ MockSourceModel,+ MockJob,+ MagicMock(),+ source,+ [schema],+ events,+ )+ cdc_extract_activity(CDCExtractInput(team_id=1, source_id=source.id))+ return schema, mock_reader, mock_s3, mock_producer++ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")+ def test_shadow_off_by_default_writes_nothing(self, MockBufferWriter):+ events = [_make_event(op="I", position="0/100")]+ _schema, _reader, mock_s3, _producer = self._run(MockBufferWriter, events, shadow_on=False)++ MockBufferWriter.assert_not_called()+ # Legacy lane stays byte-identical: no seq column reaches the S3 writer.+ legacy_table = mock_s3.write_batch.call_args[0][0]+ assert CDC_SEQ_COLUMN not in legacy_table.column_names++ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")+ def test_shadow_on_writes_raw_stream_with_seq(self, MockBufferWriter):+ 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"}),+ ]+ schema, _reader, mock_s3, mock_producer = self._run(MockBufferWriter, events, shadow_on=True)++ buffer_call = MockBufferWriter.return_value.write_batch.call_args+ assert buffer_call.kwargs["team_id"] == 1+ assert buffer_call.kwargs["schema_id"] == str(schema.id)+ assert buffer_call.kwargs["file_index"] == 0+ shadow_table = buffer_call.kwargs["table"]+ assert shadow_table.column(CDC_SEQ_COLUMN).to_pylist() == [0x100, 0x200]+ # Raw stream: one row per change event, before dedup collapses the PK.+ assert shadow_table.num_rows == 2++ legacy_table = mock_s3.write_batch.call_args[0][0]+ assert CDC_SEQ_COLUMN not in legacy_table.column_names+ mock_producer.send_batch_notification.assert_called_once()++ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")+ def test_shadow_failure_never_fails_extraction(self, MockBufferWriter):+ MockBufferWriter.return_value.write_batch.side_effect = Exception("s3 down")+ events = [_make_event(op="I", position="0/100")]+ _schema, mock_reader, mock_s3, mock_producer = self._run(MockBufferWriter, events, shadow_on=True)++ # Legacy lane completed despite the shadow failure — including slot advance.+ mock_s3.write_batch.assert_called_once()+ mock_producer.send_batch_notification.assert_called_once()+ mock_reader.confirm_position.assert_called_once_with("0/100")++ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")+ def test_source_column_named_like_seq_passes_through_legacy_untouched(self, MockBufferWriter):+ # Collision: batcher skips the engine seq append, the strip must not touch+ # the user's column, and the shadow lane must not treat it as positions.+ events = [_make_event(op="I", position="0/100", columns={"id": 1, CDC_SEQ_COLUMN: 42})]+ _schema, _reader, mock_s3, _producer = self._run(MockBufferWriter, events, shadow_on=True)++ MockBufferWriter.return_value.write_batch.assert_not_called()+ legacy_table = mock_s3.write_batch.call_args[0][0]+ assert legacy_table.column(CDC_SEQ_COLUMN).to_pylist() == [42]++ def _hook_activity(self):+ source = _make_source()+ act = _make_extract_activity(source)+ schema = _make_schema("users", cdc_mode="streaming", source=source)+ table = pa.table({"id": pa.array([1], type=pa.int64()), CDC_SEQ_COLUMN: pa.array([256], type=pa.int64())})+ return act, schema, table++ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")+ def test_shadow_file_index_increments_per_table_including_failures(self, MockBufferWriter):+ act, schema, table = self._hook_activity()+ MockBufferWriter.return_value.write_batch.side_effect = [+ MagicMock(write_duration_seconds=0.01),+ Exception("s3 down"),+ MagicMock(write_duration_seconds=0.01),+ ]+ act._shadow_enabled = True+ with nullcontext():+ act._maybe_shadow_write_buffer(schema, "users", table)+ act._maybe_shadow_write_buffer(schema, "users", table)+ act._maybe_shadow_write_buffer(schema, "users", table)+ act._maybe_shadow_write_buffer(schema, "other", table)++ calls = MockBufferWriter.return_value.write_batch.call_args_list+ # Failure still advances the ordinal: a lost chunk is an index gap, not a+ # later chunk silently claiming its slot.+ assert [c.kwargs["file_index"] for c in calls] == [0, 1, 2, 0]++ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")+ def test_shadow_disables_for_run_after_consecutive_failures(self, MockBufferWriter):+ act, schema, table = self._hook_activity()+ MockBufferWriter.return_value.write_batch.side_effect = Exception("s3 down")+ act._shadow_enabled = True+ with nullcontext():+ for _ in range(5):+ act._maybe_shadow_write_buffer(schema, "users", table)++ # Breaker trips at 3 consecutive failures; later flushes skip entirely.+ assert MockBufferWriter.return_value.write_batch.call_count == 3+ assert act._shadow_disabled_for_run is True++ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")+ def test_first_write_per_schema_cleans_superseded_files(self, MockBufferWriter):+ act, schema, table = self._hook_activity()+ MockBufferWriter.return_value.write_batch.return_value.write_duration_seconds = 0.01+ act._shadow_enabled = True+ with nullcontext():+ act._maybe_shadow_write_buffer(schema, "users", table)+ act._maybe_shadow_write_buffer(schema, "users", table)++ cleanup = MockBufferWriter.return_value.cleanup_superseded_files+ cleanup.assert_called_once_with(team_id=schema.team_id, schema_id=str(schema.id), restart_seq=256)++ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")+ def test_reset_to_snapshot_purges_buffer_prefix(self, mock_purge):+ act, schema, _table = self._hook_activity()+ act._reset_schema_to_snapshot(schema)+ mock_purge.assert_called_once()+ assert mock_purge.call_args.args[1] == str(schema.id)++class TestCDCExtractActivity:"""Integration tests for cdc_extract_activity with mocked external deps."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.pyindex 28a9af2754f3..f02e1020e913 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py@@ -81,6 +81,11 @@ class PostgresCDCAdapter:def parse_cdc_config(self, source: ExternalDataSource) -> PostgresCDCConfig:return PostgresCDCConfig.from_source(source)+ def position_to_seq(self, position_serialized: str) -> int:+ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.position import PgLSN++ return PgLSN.deserialize(position_serialized).value+def create_reader(self, source: ExternalDataSource) -> CDCStreamReader:from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.stream_reader import (PgCDCConnectionParams,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.pyindex 53fe871d1f50..f91cd24655c6 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@@ -20,7 +20,7 @@ import requestsfrom google.auth.exceptions import RefreshErrorfrom parameterized import parameterizedfrom rest_framework import status-from rest_framework.exceptions import ValidationError+from rest_framework.exceptions import PermissionDenied, ValidationErrorfrom sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.schema import (@@ -56,6 +56,7 @@ from products.warehouse_sources.backend.facade.models import (from products.warehouse_sources.backend.facade.types import IncrementalFieldTypefrom products.warehouse_sources.backend.presentation.views.external_data_schema import ExternalDataSchemaSerializerfrom products.warehouse_sources.backend.presentation.views.external_data_source import (+ ExternalDataSourceViewSet,get_direct_connection_metadata,get_nonsensitive_and_sensitive_field_names,get_oauth_integration_kinds,@@ -10439,6 +10440,65 @@ class TestDisableCDC(APIBaseTest):assert non_cdc_schema.sync_type == ExternalDataSchema.SyncType.INCREMENTALassert non_cdc_schema.should_sync is True+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.purge_buffer_prefix")+ def test_disable_cdc_requires_editor_on_every_table(self, mock_purge) -> None:+ # A table can be locked below source-level editor; the per-table gate must run+ # before any destructive step (job cancel, slot drop, buffer purge, schema reset).+ source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)+ cdc_schema = ExternalDataSchema.objects.create(+ name="cdc_table",+ team_id=self.team.pk,+ source_id=source.pk,+ sync_type=ExternalDataSchema.SyncType.CDC,+ should_sync=True,+ )++ with patch.object(+ ExternalDataSourceViewSet,+ "_assert_can_write_schemas",+ side_effect=PermissionDenied("You do not have editor access to every table in this source."),+ ):+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/disable_cdc/",+ )++ assert response.status_code == 403+ mock_purge.assert_not_called()+ cdc_schema.refresh_from_db()+ assert cdc_schema.sync_type == ExternalDataSchema.SyncType.CDC # nothing was reset++ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.purge_buffer_prefix")+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.cleanup_resources",+ return_value=None,+ )+ def test_disable_cdc_purges_shadow_buffer_prefixes(self, _cleanup, mock_purge) -> None:+ # The shadow lane's buffer files are raw customer change data with no consumer+ # once CDC is off, and nothing else expires them.+ source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)+ cdc_schema = ExternalDataSchema.objects.create(+ name="cdc_table",+ team_id=self.team.pk,+ source_id=source.pk,+ sync_type=ExternalDataSchema.SyncType.CDC,+ should_sync=True,+ )+ ExternalDataSchema.objects.create(+ name="incremental_table",+ team_id=self.team.pk,+ source_id=source.pk,+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ should_sync=True,+ )++ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/disable_cdc/",+ )+ assert response.status_code == 200, response.content++ purged = {call.args[1] for call in mock_purge.call_args_list}+ assert purged == {str(cdc_schema.id)} # CDC schemas only+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.cleanup_resources",return_value=None,diff --git a/products/warehouse_sources/backend/tests/management/test_validate_cdc_buffer.py b/products/warehouse_sources/backend/tests/management/test_validate_cdc_buffer.pynew file mode 100644index 000000000000..d8527d8ac764--- /dev/null+++ b/products/warehouse_sources/backend/tests/management/test_validate_cdc_buffer.py@@ -0,0 +1,275 @@+import io+import uuid+import asyncio+from contextlib import contextmanager+from datetime import UTC, datetime, timedelta++import pytest+from unittest.mock import MagicMock, patch++from django.core.management import call_command+from django.core.management.base import CommandError++import psycopg+import pyarrow as pa+import pyarrow.parquet as pq++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++_CMD = "products.warehouse_sources.backend.management.commands.validate_cdc_buffer"+++def _parquet_bytes(rows: int) -> bytes:+ buf = io.BytesIO()+ table = pa.table(+ {"id": pa.array(range(rows), type=pa.int64()), CDC_SEQ_COLUMN: pa.array(range(rows), type=pa.int64())}+ )+ pq.write_table(table, buf)+ return buf.getvalue()+++def _fake_s3(files: dict[str, bytes | tuple[bytes, datetime | None]]) -> MagicMock:+ """files: key (no protocol) -> parquet bytes, or (bytes, LastModified)."""++ def _content(value) -> bytes:+ return value[0] if isinstance(value, tuple) else value++ def _modified(value) -> datetime | None:+ return value[1] if isinstance(value, tuple) else None++ s3 = MagicMock()++ def ls(prefix, detail=True):+ matching = [key for key in files if key.startswith(prefix)]+ if not matching:+ raise FileNotFoundError(prefix)+ return [{"Key": key, "type": "file", "LastModified": _modified(files[key])} for key in matching]++ @contextmanager+ def open_(key, mode):+ yield io.BytesIO(_content(files[key]))++ s3.ls = ls+ s3.open = open_+ return s3+++def _schema_mock(mode: str = "consolidated", cdc_mode: str = "streaming"):+ schema = MagicMock()+ schema.id = uuid.uuid4()+ schema.team_id = 1+ schema.name = "users"+ schema.cdc_table_mode = mode+ schema.cdc_mode = cdc_mode+ return schema+++class TestValidateCDCBuffer:+ def _run(self, schema, files, legacy: dict[tuple[str, str], int], runs: dict[str, int] | None = None):+ source = MagicMock()+ source.id = uuid.uuid4()++ with (+ patch(f"{_CMD}.ExternalDataSource") as MockSource,+ patch(f"{_CMD}.ExternalDataSchema") as MockSchema,+ patch(f"{_CMD}.get_s3_client", return_value=_fake_s3(files)),+ patch.object(+ __import__(_CMD, fromlist=["Command"]).Command,+ "_fetch_legacy_row_sums",+ return_value=(legacy, runs or {}),+ ),+ ):+ MockSource.objects.get.return_value = source+ MockSchema.objects.filter.return_value = [schema]+ MockSchema.SyncType.CDC = "cdc"+ call_command("validate_cdc_buffer", "--source-id", str(source.id))++ def _key(self, schema, name: str) -> str:+ from django.conf import settings++ return f"{settings.DATAWAREHOUSE_BUCKET}/cdc_producer/{schema.team_id}/{schema.id}/{name}"++ def test_passes_on_consistent_buffer(self):+ schema = _schema_mock(mode="both")+ files = {+ self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(3),+ self._key(schema, build_buffer_file_name(200, 300, 1)): _parquet_bytes(2),+ }+ # scd2 lane keeps one row per event: exact match. consolidated deduped down to 4.+ legacy = {(str(schema.id), "scd2"): 5, (str(schema.id), "consolidated"): 4}+ self._run(schema, files, legacy)++ def test_fails_on_scd2_mismatch(self):+ schema = _schema_mock(mode="cdc_only")+ files = {self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(3)}+ with pytest.raises(CommandError, match="violation"):+ self._run(schema, files, {(str(schema.id), "scd2"): 5})++ def test_scd2_mismatch_downgrades_to_warning_with_multiple_runs(self):+ # Legacy re-inserts replayed rows on activity retry while buffer files+ # overwrite, so with >1 run in the window the exact match only warns.+ schema = _schema_mock(mode="cdc_only")+ files = {self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(3)}+ self._run(schema, files, {(str(schema.id), "scd2"): 5}, runs={str(schema.id): 2})++ def test_fails_when_buffer_below_consolidated(self):+ schema = _schema_mock(mode="consolidated")+ files = {self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(2)}+ with pytest.raises(CommandError, match="violation"):+ self._run(schema, files, {(str(schema.id), "consolidated"): 5})++ def test_fails_on_overlapping_ranges(self):+ schema = _schema_mock(mode="consolidated")+ files = {+ self._key(schema, build_buffer_file_name(100, 250, 0)): _parquet_bytes(1),+ self._key(schema, build_buffer_file_name(200, 300, 0)): _parquet_bytes(1),+ }+ with pytest.raises(CommandError, match="violation"):+ self._run(schema, files, {})++ def test_fails_on_inverted_range(self):+ schema = _schema_mock(mode="consolidated")+ # build_buffer_file_name refuses inverted ranges, so name it by hand.+ name = f"{300:020d}-{200:020d}-{0:06d}.parquet"+ files = {self._key(schema, name): _parquet_bytes(1)}+ with pytest.raises(CommandError, match="violation"):+ self._run(schema, files, {})++ def test_shared_boundary_is_legal(self):+ # A split transaction's batches share its commit position — not an overlap.+ schema = _schema_mock(mode="consolidated")+ files = {+ self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(1),+ self._key(schema, build_buffer_file_name(200, 200, 1)): _parquet_bytes(1),+ }+ self._run(schema, files, {(str(schema.id), "consolidated"): 2})++ def test_buffered_rows_with_no_legacy_dispatches_is_a_violation(self):+ # Streaming flushes dispatch legacy immediately: buffer rows with zero legacy+ # rows means the legacy lane stalled — absence must not skip the comparison.+ schema = _schema_mock(mode="both")+ files = {self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(3)}+ with pytest.raises(CommandError, match="violation"):+ self._run(schema, files, {(str(schema.id), "scd2"): 3}) # scd2 fine, consolidated lane absent++ def test_snapshot_schema_skips_row_reconciliation(self):+ # Snapshot phase defers legacy dispatch, so counts legitimately diverge.+ schema = _schema_mock(mode="cdc_only", cdc_mode="snapshot")+ files = {self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(3)}+ self._run(schema, files, {(str(schema.id), "scd2"): 99})++ def test_empty_buffer_with_legacy_rows_is_a_violation_not_a_crash(self):+ # Day-one state: shadow just enabled, no files yet, legacy still dispatching.+ schema = _schema_mock(mode="cdc_only")+ with pytest.raises(CommandError, match="violation"):+ self._run(schema, {}, {(str(schema.id), "scd2"): 5})++ def test_files_older_than_window_are_excluded(self):+ schema = _schema_mock(mode="cdc_only")+ old = datetime.now(UTC) - timedelta(hours=48)+ files = {+ self._key(schema, build_buffer_file_name(1, 50, 0)): (_parquet_bytes(7), old),+ self._key(schema, build_buffer_file_name(100, 200, 0)): (_parquet_bytes(3), None),+ }+ # Reconciles against only the in-window file (3 rows); counting the stale+ # 7 rows would make the exact match pass at the wrong sum.+ self._run(schema, files, {(str(schema.id), "scd2"): 3})++ def test_unreadable_file_is_a_violation_not_a_crash(self):+ schema = _schema_mock(mode="consolidated")+ files = {self._key(schema, build_buffer_file_name(100, 200, 0)): b"not a parquet file"}+ with pytest.raises(CommandError, match="violation"):+ self._run(schema, files, {})++ def test_fails_on_foreign_file(self):+ schema = _schema_mock(mode="consolidated")+ files = {self._key(schema, "part-0000.parquet"): _parquet_bytes(1)}+ with pytest.raises(CommandError, match="violation"):+ self._run(schema, files, {})++[email protected]_db(transaction=True)+class TestFetchLegacyRowSums:+ """DB-backed: the SQL must count only sync_type='cdc' dispatches — snapshots+ (full_refresh) share the sourcebatch table and would otherwise inflate the+ consolidated lane into a guaranteed false violation during onboarding."""++ @pytest.fixture(autouse=True)+ def _tables(self):+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.test_jobs_db import (+ _ensure_tables,+ _get_test_database_url,+ _truncate_tables,+ )++ url = _get_test_database_url()+ with psycopg.Connection.connect(url, autocommit=True) as conn:+ _ensure_tables(conn)+ _truncate_tables(conn)+ self._url = url+ yield++ def _seed(self, rows: list[dict]) -> None:+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.test_jobs_db import (+ _insert_batch,+ )++ async def seed() -> None:+ async with await psycopg.AsyncConnection.connect(self._url, autocommit=True) as conn:+ for row in rows:+ await _insert_batch(conn, **row)++ asyncio.run(seed())++ def test_counts_only_cdc_dispatches_and_distinct_runs(self):+ command_module = __import__(_CMD, fromlist=["Command"])+ source = MagicMock()+ source.id = "source-1"+ schema_id = "schema-1"++ self._seed(+ [+ {+ "schema_id": schema_id,+ "sync_type": "cdc",+ "resource_name": "users",+ "row_count": 10,+ "run_uuid": "r1",+ },+ {+ "schema_id": schema_id,+ "sync_type": "cdc",+ "resource_name": "users_cdc",+ "row_count": 7,+ "run_uuid": "r1",+ "batch_index": 1,+ },+ # Snapshot dispatch for the same schema: must NOT count.+ {+ "schema_id": schema_id,+ "sync_type": "full_refresh",+ "resource_name": "users",+ "row_count": 9999,+ "run_uuid": "r2",+ "batch_index": 2,+ },+ # Second cdc run: bumps the distinct-run count.+ {+ "schema_id": schema_id,+ "sync_type": "cdc",+ "resource_name": "users",+ "row_count": 5,+ "run_uuid": "r3",+ "batch_index": 3,+ },+ ]+ )++ with patch.object(command_module, "WAREHOUSE_SOURCES_DATABASE_URL", self._url):+ sums, run_counts = command_module.Command()._fetch_legacy_row_sums(+ source, datetime.now(UTC) - timedelta(hours=1)+ )++ assert sums == {(schema_id, "consolidated"): 15, (schema_id, "scd2"): 7}+ assert run_counts[schema_id] == 2