: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): start new postgres cdc sources on buffered ingress (#104738)
Daniel RCcf3e820ab9f5
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.mdindex 4019827aef4f..1c090a53c906 100644--- a/docs/internal/cdc-buffered-ingress-runbook.md+++ b/docs/internal/cdc-buffered-ingress-runbook.md@@ -3,6 +3,11 @@How to move a Postgres CDC source from legacy extraction onto the S3 change buffer, and how to moveit back.+A source that turns on CDC starts on the buffer: setting up the slot also writes+`cdc_ingest_mode = "buffered"`. Recreating a lost slot does the same, through "Repair CDC" or the+automatic recovery when capture finds its slot invalidated, so a repaired legacy source comes back+buffered. Only a healthy source that enabled CDC before that needs the flip.+## What changesCapture stops transforming and dispatching change events. It decodes WAL, writes Parquet to@@ -125,20 +130,14 @@ preserved, so there is no WAL gap and no re-sync.team's `warehouse-pipelines-v3` rollout flag neither enables norblocks the flip, and narrowing it later does not affect flipped sources. Do not flip while adeploy is rolling out, so every worker already runs the forcing.-1. `dwh-cdc-write-resolution` is on for the team. **The command refuses to flip without it.**- The flag gates ordering resolution: dropping rows the table already applied, collapsing repeated- keys within a batch, and checking that a DELETE is not about to erase columns the target still- holds. Without it a buffered merge lane still lands every row, but out of order across a retry.- Rollback does not require the flag. Neither deletion nor either lane's resume point depends on- it: both come from the tables themselves.-2. No source table has a column named `_ph_cdc_seq`. **The command refuses to flip if one does** —+1. 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 thanwriting files whose ordering and retry cleanup derive from customer data. A source already onbuffered carries the column for our own reasons, so the check only applies to a source still onlegacy and 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+2. Every CDC schema on the source is at `sync_frequency_interval = 5min`. The command warnswhen an eligible schema is off cadence — consumption paces to the schema's own schedule.-4. Buffer validation is clean over a busy window:+3. Buffer validation is clean over a busy window:```bashpython manage.py validate_cdc_buffer --source-id <uuid> --since-hours 40@@ -147,10 +146,9 @@ preserved, so there is no WAL gap and no re-sync.Capture stops writing shadow copies the moment a source is buffered: a schema not yet servedwould otherwise accumulate files the consumer merges the day it turns eligible, on top of whatthe legacy lane already wrote. So this window exists only before the first flip. A schema- added to a buffered source later, or one left on legacy by an earlier flip, moves on the re-run- without one.+ added to a buffered source later joins the buffer after its first sync, without one.-5. Check what will move:+4. Check what will move:```bashpython manage.py migrate_cdc_source_to_buffered --source-id <uuid> --dry-run@@ -160,19 +158,11 @@ preserved, so there is no WAL gap and no re-sync.## Flip-Eligibility is opt-in per schema. The command writes `cdc_buffered_lane: true` into each moved-schema's `sync_type_config`, and capture and the scheduled sync serve only marked schemas — plus-`consolidated` schemas on an already-buffered source, which predate the marker. A `cdc_only` or-`both` schema is never picked up by a deploy on its own: a source flipped before those modes were-served left them on legacy with their per-schema schedules paused, and routing their changes into-the buffer with nothing scheduled to consume would have lost them to the S3 retention.--To move such a schema, or one added since, **re-run the flip on the already-buffered source**. It-processes only the schemas not yet served: pauses extraction, quiesces those schedules, purges only-their prefixes (the served schemas' buffers hold files the consumer still owes), runs the-reserved-column check on them, marks them, and unpauses. A schema whose own table carries a-`_ph_cdc_seq` this lane wrote is waived by its own `cdc_buffered_before` marker; a schema never-buffered before is checked.+Every schema that is streaming and has finished its first sync is served, in any table mode. A+schema added to a buffered source later joins the buffer after its first sync, with no re-run. The+loader always resolves write ordering for CDC batches: it drops rows the table already applied,+collapses repeated keys within a batch, and checks that a DELETE is not about to erase columns the+target still holds.```bashpython manage.py migrate_cdc_source_to_buffered --source-id <uuid>diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.pyindex 1f26e4405bcd..c0e98059ec3c 100644--- a/products/warehouse_sources/backend/facade/source_management.py+++ b/products/warehouse_sources/backend/facade/source_management.py@@ -23,6 +23,7 @@ _LAZY = {"CDCRepairInProgress": "cdc.repair","repair_cdc_source": "cdc.repair","purge_buffer_prefix": "cdc.buffer",+ "CDC_SEQ_COLUMN": "cdc.batcher","ClickHouseConnectionError": "sources.clickhouse.clickhouse","ClickHouseSource": "sources.clickhouse.source","AnySource": "sources.common.base",diff --git a/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.py b/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.pyindex 0b8bd27a107e..12b67adf8009 100644--- a/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.py+++ b/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.py@@ -31,14 +31,8 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer importpurge_buffer_prefix,)from products.warehouse_sources.backend.temporal.data_imports.cdc.companion_jobs import retire_orphaned_companions-from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import (- WRITE_RESOLUTION_FLAG,- is_cdc_write_resolution_enabled,-)from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (BUFFERED_BEFORE_KEY,- BUFFERED_LANE_KEY,- buffered_lane_candidate,serves_buffered_lane,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (@@ -106,37 +100,23 @@ class Command(BaseCommand):# Mirror capture's _get_cdc_schemas: a user-disabled schema must not be flipped — the last# step would unpause its schedule, reversing the disable.current_mode = (source.job_inputs or {}).get("cdc_ingest_mode", "legacy")- candidates = [s for s in cdc_schemas if s.should_sync and buffered_lane_candidate(s)]- already_served: list[ExternalDataSchema] = []- if rollback:- eligible = [s for s in candidates if serves_buffered_lane(s)]- else:- # On a source already buffered, only the schemas not yet served move: a history-mode- # schema left on legacy by a flip that predates them, or one added since.- already_served = [s for s in candidates if current_mode == "buffered" and serves_buffered_lane(s)]- eligible = [s for s in candidates if s not in already_served]- ineligible = [s for s in cdc_schemas if s not in eligible and s not in already_served]+ 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]- self._report(source, current_mode, target_mode, eligible, ineligible, already_served)+ self._report(source, current_mode, target_mode, eligible, ineligible)+ if current_mode == target_mode:+ self.stdout.write(self.style.WARNING(f"Already {target_mode}; nothing to do."))+ returnif not eligible and not rollback:- if current_mode == "buffered":- self.stdout.write(- self.style.WARNING("Already buffered and every eligible schema is served; nothing to do.")- )- returnraise CommandError("No schema on this source serves the buffered lane — nothing to flip. ""Buffered ingress covers streaming schemas whose initial sync is done, in any table mode.")- if rollback and current_mode == target_mode:- self.stdout.write(self.style.WARNING("Already legacy; nothing to do."))- returnif not rollback:# No pipeline-version gate: the scheduled sync forces the v3 pipeline for# schemas that consume the buffer (scheduled_sync_consumes_buffer), so the flip does# not depend on the team's general rollout flag.- 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."))@@ -147,21 +127,6 @@ class Command(BaseCommand):else:self._flip_to_buffered(source, eligible, cdc_schemas, options["drain_timeout"])- 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 to "- "resolve write ordering: without it a retried batch can land rows the table already "- "holds back over newer ones, and a DELETE can erase columns the target still has."- )-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`.@@ -204,14 +169,9 @@ class Command(BaseCommand):target_mode: str,eligible: list[ExternalDataSchema],ineligible: list[ExternalDataSchema],- already_served: 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 '—'}")- if already_served:- self.stdout.write(- f" already buffered ({len(already_served)}): {', '.join(s.name for s in already_served)}"- )off_cadence = [s.name for s in eligible if s.sync_frequency_interval != EXPECTED_SYNC_INTERVAL]if off_cadence:self.stdout.write(@@ -296,19 +256,16 @@ class Command(BaseCommand):# have created its row yet. By now it has, so one more wait closes the straddle window.self._wait_for_running_sync_jobs(source.team_id, [str(s.id) for s in eligible], drain_timeout)- # Still inside the recovery boundary: `_mark_schemas` writes one schema at a time, so a- # failure partway through it would otherwise leave the mode buffered with only some- # schemas marked served and every schedule still paused — the same silent outage this- # command exists to fix. The atomic block makes the two writes fail together, so a- # failure here rolls `job_inputs` back to legacy too, and the `except` below restores- # the schedules onto a state that is genuinely unchanged, not a half-flipped one.- self.stdout.write("6/7 setting cdc_ingest_mode=buffered and marking the schemas served")+ # Still inside the recovery boundary, and atomic, so a failure partway through the+ # per-schema writes rolls `job_inputs` back to legacy too and the `except` below restores+ # the schedules onto a state that is genuinely unchanged.+ self.stdout.write("6/7 setting cdc_ingest_mode=buffered")with transaction.atomic():# `cdc_buffered_before` is kept across a rollback: it is what tells a later flip# that a `_ph_cdc_seq` column on the warehouse table may be one this lane wrote,# not one the source owns.self._write_job_inputs(source, cdc_ingest_mode="buffered", cdc_buffered_before=True)- self._mark_schemas(eligible, served=True)+ self._mark_buffered_before(eligible)except BaseException:self.stdout.write(self.style.WARNING("flip aborted, restoring per-schema schedules"))self._restore_schema_schedules(eligible)@@ -369,18 +326,14 @@ class Command(BaseCommand):self._wait_for_sourcebatch_drain(source.team_id, [str(s.id) for s in eligible], drain_timeout)self._retire_orphaned_companions(eligible)- # Still inside the recovery boundary, for the same reason as the flip: `_mark_schemas`- # writes one schema at a time, and the atomic block makes it fail together with the- # `job_inputs` write so a failure here leaves the source genuinely still buffered- # rather than half-rolled-back, which is what the `except` below assumes.- self.stdout.write("5/6 setting cdc_ingest_mode=legacy and unmarking the schemas")+ self.stdout.write("5/6 setting cdc_ingest_mode=legacy")+ # `cdc_buffered_before` is set here as well as on the flip, on the source and on each+ # served table: a source that started buffered, or was flipped before these markers+ # existed, would otherwise be refused a second flip over a `_ph_cdc_seq` column the+ # buffered lane wrote itself.with transaction.atomic():- self._mark_schemas(eligible, served=False)- # `cdc_buffered_before` is set here as well as on the flip, so a source flipped- # before this marker existed still carries it once it rolls back — which is the- # population that would otherwise be refused a second flip over a `_ph_cdc_seq`- # column the buffered lane wrote itself.self._write_job_inputs(source, cdc_ingest_mode="legacy", cdc_buffered_before=True)+ self._mark_buffered_before([s for s in cdc_schemas if serves_buffered_lane(s)])except BaseException:# The mode is still buffered, so the schemas go back to consuming the buffer, which is# what they were doing before this command ran. Leaving them paused instead would stop@@ -415,18 +368,15 @@ class Command(BaseCommand):job_inputs=source.job_inputs, updated_at=dt.datetime.now(dt.UTC))- def _mark_schemas(self, schemas: list[ExternalDataSchema], *, served: bool) -> None:- """The per-schema opt-in `serves_buffered_lane` reads. `cdc_buffered_before` is never cleared.+ def _mark_buffered_before(self, schemas: list[ExternalDataSchema]) -> None:+ """Record that the buffered lane wrote to these tables; never cleared, see the reserved-column check.Merged under the row lock: the runs this command waited out wrote their own keys into thesame JSON, and saving the copy loaded at the start would put them back the way they were."""for schema in schemas:schema.sync_type_config = update_sync_type_config_keys(- schema.id,- schema.team_id,- updates={BUFFERED_LANE_KEY: True, BUFFERED_BEFORE_KEY: True} if served else None,- removes=None if served else [BUFFERED_LANE_KEY],+ schema.id, schema.team_id, updates={BUFFERED_BEFORE_KEY: True})def _retire_orphaned_companions(self, schemas: list[ExternalDataSchema]) -> None:diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.pyindex 30c8e455f648..0d343da0e8ba 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py@@ -55,6 +55,7 @@ from products.warehouse_sources.backend.facade.models import ()from products.warehouse_sources.backend.facade.pipelines import finish_row_trackingfrom products.warehouse_sources.backend.facade.source_management import (+ CDC_SEQ_COLUMN,AnySource,RowFilterValidationError,SourceRegistry,@@ -309,6 +310,20 @@ def _apply_primary_key_columns()+def _refuse_reserved_cdc_column(instance: ExternalDataSchema) -> None:+ """Capture stamps each change with this column, so a source column of the same name would fail+ the source's sync. Checked against the columns discovery recorded, which are the source's own."""+ metadata = instance.schema_metadata or {}+ columns = metadata.get("columns") if isinstance(metadata, dict) else None+ if isinstance(columns, list) and any(+ isinstance(column, dict) and column.get("name") == CDC_SEQ_COLUMN for column in columns+ ):+ raise ValidationError(+ "Change data capture can't sync a column named _ph_cdc_seq, because PostHog uses that name. "+ "Rename the column on your database, or choose another sync method for this table."+ )++def schema_display_status(schema: ExternalDataSchema) -> str | None:"""The user-facing sync status, mapping the two billing-limit statuses to friendly labels.Shared by the full and list schema serializers so the labels stay identical."""@@ -1037,6 +1052,8 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers# CDC needs a PK for UPDATE/DELETE merges. Accept the caller's PK or reuse what# discovery already stored; refuse the switch when neither is set._apply_primary_key_columns(data, payload, instance, "CDC")+ if instance.sync_type != ExternalDataSchema.SyncType.CDC:+ _refuse_reserved_cdc_column(instance)validated_data["sync_type_config"] = payloadelif sync_type == ExternalDataSchema.SyncType.XMIN:diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.pyindex b2df97840339..86ca40dfc3e9 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py@@ -47,6 +47,7 @@ from products.warehouse_sources.backend.facade.models import (sync_old_schemas_with_new_schemas,)from products.warehouse_sources.backend.facade.source_management import (+ CDC_SEQ_COLUMN,PREVIEW_DEFAULT_ROWS,PREVIEW_MAX_ROWS,AnySource,@@ -1369,6 +1370,32 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):},)+ # Capture stamps each change with this column, so a source column of the same name would+ # fail the source's first sync. Refuse before any replication state exists.+ tables_with_reserved_column = sorted(+ {+ schema["name"]+ for schema in payload_schemas+ if schema.get("sync_type") == "cdc"+ and schema.get("should_sync", False)+ and isinstance(schema.get("name"), str)+ and CDC_SEQ_COLUMN+ in {column[0] for column in getattr(source_schemas_by_name.get(schema["name"]), "columns", [])}+ }+ )+ if tables_with_reserved_column:+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": (+ "Change data capture can't sync a column named _ph_cdc_seq, because PostHog uses "+ "that name. Rename the column on your database, or choose another sync method for "+ f"these tables: {', '.join(tables_with_reserved_column)}."+ )+ },+ )+# Engine-side CDC resource setup runs after PK validation so we don't leave# replication state on the source for a config we're about to refuse.if cdc_enabled:diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.pyindex fa34fa52b98a..089c1fc436d0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py@@ -178,9 +178,8 @@ _CATEGORY_DEFAULTS: dict[CDCErrorCategory, tuple[str, bool]] = {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.",+ "A source table has a column named _ph_cdc_seq, which PostHog uses for change data capture. "+ "Rename the column on your database, or choose another sync method for that table.",False,),CDCErrorCategory.UNKNOWN: (diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/load_resolution.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/load_resolution.pyindex e1531e2860d5..1add8c110040 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/load_resolution.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/load_resolution.py@@ -6,7 +6,6 @@ ordering and delete safety have to be settled on the batch rather than in mergefrom __future__ import annotations-from functools import lru_cachefrom typing import Finalimport pyarrow as pa@@ -20,8 +19,6 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher importCDC_SEQ_PROVENANCE,)-WRITE_RESOLUTION_FLAG = "dwh-cdc-write-resolution"-# Verification is a diagnostic; cap it so a delete-heavy batch can't dominate the write path.MAX_VERIFIED_DELETE_ROWS = 1_000MAX_REPORTED_COLUMNS = 10@@ -192,34 +189,3 @@ def verify_delete_enrichment(rows_with_nulled_columns=rows_with_nulls,columns=tuple(sorted(columns)[:MAX_REPORTED_COLUMNS]),)---@lru_cache(maxsize=2048)-def is_cdc_write_resolution_enabled(team_id: int, schema_id: str, run_uuid: str) -> bool:- """Per-team rollout gate, resolved once per schema per run.-- Keyed on `run_uuid` to keep a flags round trip off every batch's write path. Fails closed: a- flags blip must not start dropping rows.- """- import posthoganalytics-- from posthog.models import Team-- try:- team = Team.objects.only("uuid", "organization_id").get(id=team_id)- return bool(- posthoganalytics.feature_enabled(- WRITE_RESOLUTION_FLAG,- str(team.uuid),- groups={"organization": str(team.organization_id), "project": str(team_id)},- person_properties={"team_id": str(team_id), "schema_id": str(schema_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: # noqa: BLE001- return Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.pyindex db9ac4b97450..c254fec30915 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py@@ -4,7 +4,8 @@ Recovery counterpart of ``broken.mark_cdc_broken``: once the change-stream resourecreated (the safety net dropped the slot, or someone dropped it on the source database),repair recreates the engine-side resources against the stored CDC config, resets everyactive CDC schema to snapshot mode so it re-syncs from current table state, clears the-``cdc_broken`` markers, and resumes the paused schedules.+``cdc_broken`` markers, and resumes the paused schedules. The new slot starts on buffered+ingress, so a repaired legacy source comes back buffered.WAL between the old slot's last confirmed position and the new slot's consistent point isgone — the re-snapshot covers current rows, but intermediate changes in that gap (including@@ -26,6 +27,7 @@ Safeguards, in order:from __future__ import annotationsimport typing+import datetime as dtimport structlog@@ -38,6 +40,7 @@ from products.warehouse_sources.backend.models.external_data_schema import ()from products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.temporal.data_imports.cdc.adapters import CDCSourceAdapter, get_cdc_adapter+from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import purge_buffer_prefixfrom products.warehouse_sources.backend.temporal.data_imports.cdc.naming import cdc_qualified_table_namelogger = structlog.get_logger(__name__)@@ -99,22 +102,37 @@ def _repair_locked(source: ExternalDataSource) -> int:raise CDCRepairError("There are no active CDC schemas on this source to repair.")_require_broken_evidence(source, adapter, cdc_schemas)- _cancel_running_cdc_jobs(source, cdc_schemas, log)+ _mark_repair_in_progress(source, cdc_schemas)++ # Every CDC table, including those with sync off: the new slot cannot replay what the dead one+ # lost, so a table turned back on later must re-snapshot too.+ all_cdc_schemas = list(+ ExternalDataSchema.objects.filter(+ team_id=source.team_id, source=source, sync_type=ExternalDataSchema.SyncType.CDC+ ).exclude(deleted=True)+ )+ all_cdc_schema_ids = [schema.id for schema in all_cdc_schemas]+ _cancel_running_cdc_jobs(source, all_cdc_schemas, log)# Reset schemas before touching the slot (same ordering as the extraction activity's# slot-invalidation recovery): if recreation fails below, a re-run repeats idempotently# and no schema keeps streaming across the gap unnoticed. Deferred runs are dropped —# they reference WAL from the dead slot and the re-snapshot supersedes them. The# `cdc_broken` markers deliberately survive this step: they are the retry gate.- for schema in cdc_schemas:+ for schema_id in all_cdc_schema_ids:update_sync_type_config_keys(- schema.id,+ schema_id,source.team_id,updates={"cdc_mode": "snapshot", "reset_pipeline": True},removes=["cdc_last_log_position", "cdc_deferred_runs"],extra_model_fields={"initial_sync_complete": False},)+ # Before the new slot exists, so no change it captures can be purged, and a failure here leaves+ # the slot missing, which is the evidence a retry needs.+ for schema_id in all_cdc_schema_ids:+ purge_buffer_prefix(source.team_id, str(schema_id), log, strict=True)+default_schema = (source.job_inputs or {}).get("schema")resource_fields = adapter.recreate_slot(source, tables=[cdc_qualified_table_name(schema, default_schema) for schema in cdc_schemas]@@ -129,9 +147,9 @@ def _repair_locked(source: ExternalDataSource) -> int:# Only now that the new slot exists and the schedules are resumed: clear the broken# evidence. A failure before this point leaves the markers for the retry gate; a# failure inside this loop leaves some markers, which also re-opens the gate.- for schema in cdc_schemas:+ for schema_id in all_cdc_schema_ids:update_sync_type_config_keys(- schema.id,+ schema_id,source.team_id,removes=["cdc_broken", "cdc_extraction_paused"],extra_model_fields={"latest_error": None},@@ -143,6 +161,18 @@ def _repair_locked(source: ExternalDataSource) -> int:return len(cdc_schemas)+def _mark_repair_in_progress(source: ExternalDataSource, cdc_schemas: list[ExternalDataSchema]) -> None:+ """Leave a marker on schemas that have none, so a repair allowed by a live probe alone keeps+ its retry evidence once the new slot exists. Cleared with the other markers when repair ends."""+ marker = {"reason": "repair_in_progress", "at": dt.datetime.now(tz=dt.UTC).isoformat()}++ def _mark(config: dict[str, typing.Any]) -> None:+ config.setdefault("cdc_broken", marker)++ for schema in cdc_schemas:+ update_sync_type_config_keys(schema.id, source.team_id, mutate=_mark)++def _require_broken_evidence(source: ExternalDataSource, adapter: CDCSourceAdapter, cdc_schemas: list[ExternalDataSchema]) -> None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/source_manager.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/source_manager.pyindex d536e788256e..da2691193eb2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/source_manager.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/source_manager.py@@ -106,15 +106,17 @@ class CDCLane:write_mode: CDCWriteMode-# In `sync_type_config`. Set by the flip command on each schema it moves to the buffer, cleared by-# its rollback. `cdc_buffered_before` stays after a rollback, so a later flip can tell the-# `_ph_cdc_seq` the buffered lane wrote from a column the source owns.-BUFFERED_LANE_KEY = "cdc_buffered_lane"+# In `sync_type_config`. Set by the flip command on each schema it moves to the buffer and never+# cleared, so a later flip can tell the `_ph_cdc_seq` the buffered lane wrote from a column the+# source owns.BUFFERED_BEFORE_KEY = "cdc_buffered_before"-def buffered_lane_candidate(schema: ExternalDataSchema) -> bool:- """Whether the flip command may move this schema to the buffer: streaming, seeded, with lanes."""+def serves_buffered_lane(schema: ExternalDataSchema) -> bool:+ """Schema-side conditions for buffered ingress: streaming, seeded, and in a table mode with lanes.++ The source's `ingest_mode` is the other half.+ """return bool(schema.is_cdcand schema.cdc_mode == "streaming"@@ -123,20 +125,6 @@ def buffered_lane_candidate(schema: ExternalDataSchema) -> bool:)-def serves_buffered_lane(schema: ExternalDataSchema) -> bool:- """Schema-side conditions for buffered ingress; the source's `ingest_mode` is the other half.-- Eligibility is opt-in per schema, by the marker the flip command writes. A source flipped- before history modes were served left its `cdc_only` and `both` schemas on legacy with- their schedules paused; widening this predicate by mode alone would have capture route- those schemas into the buffer on deploy, with nothing scheduled to consume it. Consolidated- schemas on an already-buffered source predate the marker and stay served without it.- """- if not buffered_lane_candidate(schema):- return False- return schema.cdc_table_mode == "consolidated" or bool(schema.sync_type_config.get(BUFFERED_LANE_KEY))--def consumes_buffer(schema: ExternalDataSchema, *, ingest_mode: str) -> bool:"""Whether this schema's changes are delivered through the buffer."""return ingest_mode == "buffered" and serves_buffered_lane(schema)diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.pyindex d1caf0271537..6d760f0b77b2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py@@ -20,7 +20,7 @@ def _schema(ingest_mode: str = "buffered", **overrides) -> MagicMock: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 = {} if schema.cdc_table_mode == "consolidated" else {"cdc_buffered_lane": True}+ schema.sync_type_config = {}schema.schema_metadata = {}schema.resolved_s3_folder_name = Noneschema.primary_key_columns = ["id"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_load_resolution.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_load_resolution.pyindex 9c5a1befcf1f..94c2331528f1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_load_resolution.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_load_resolution.py@@ -1,6 +1,3 @@-import pytest-from unittest.mock import MagicMock, patch-import pyarrow as pafrom parameterized import parameterized@@ -16,7 +13,6 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolutiodedupe_keep_highest_seq,drop_superseded_rows,has_engine_seq,- is_cdc_write_resolution_enabled,resolve_batch,verify_delete_enrichment,)@@ -181,59 +177,6 @@ class TestVerifyDeleteEnrichment:assert report.delete_rows_checked == MAX_VERIFIED_DELETE_ROWS-class TestIsCdcWriteResolutionEnabled:- @pytest.fixture(autouse=True)- def _clear_cache(self):- # The helper memoizes per run; tests reuse ids, so a stale entry would leak between them.- is_cdc_write_resolution_enabled.cache_clear()- yield- is_cdc_write_resolution_enabled.cache_clear()-- def _team(self):- team = MagicMock()- team.uuid = "team-uuid"- team.organization_id = "org-id"- return team-- @parameterized.expand([("on", True), ("off", False)])- def test_follows_the_flag(self, _name, flag_value):- with (- patch("posthog.models.Team.objects") as objects,- patch("posthoganalytics.feature_enabled", return_value=flag_value) as feature_enabled,- ):- objects.only.return_value.get.return_value = self._team()- assert is_cdc_write_resolution_enabled(2, "schema-1", "run-1") is flag_value-- assert feature_enabled.call_args.kwargs["person_properties"] == {"team_id": "2", "schema_id": "schema-1"}-- def test_evaluates_once_per_run_then_again_on_the_next_run(self):- with (- patch("posthog.models.Team.objects") as objects,- patch("posthoganalytics.feature_enabled", return_value=True) as feature_enabled,- ):- objects.only.return_value.get.return_value = self._team()- for _ in range(5):- assert is_cdc_write_resolution_enabled(2, "schema-1", "run-1") is True- assert feature_enabled.call_count == 1-- # A new run re-reads it, so a flag flip lands within one run rather than one pod.- assert is_cdc_write_resolution_enabled(2, "schema-1", "run-2") is True- assert feature_enabled.call_count == 2-- def test_fails_closed_when_flag_service_raises(self):- with (- patch("posthog.models.Team.objects") as objects,- patch("posthoganalytics.feature_enabled", side_effect=Exception("flags down")),- ):- objects.only.return_value.get.return_value = self._team()- assert is_cdc_write_resolution_enabled(2, "schema-1", "run-1") is False-- def test_fails_closed_when_team_is_missing(self):- with patch("posthog.models.Team.objects") as objects:- objects.only.return_value.get.side_effect = Exception("no such team")- assert is_cdc_write_resolution_enabled(2, "schema-1", "run-1") is False--class TestDropSupersededRows:def test_passthrough_without_watermark(self):table = _batch([1, 2], ["a", "b"], ["I", "I"], seqs=[10, 20])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.pyindex 87054a1fc460..39749af5eb57 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py@@ -20,7 +20,6 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher importfrom products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import build_buffer_file_namefrom products.warehouse_sources.backend.temporal.data_imports.cdc.lane_position import LanePositionfrom products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (- BUFFERED_LANE_KEY,COMPANION_WRITE_MODE,CONSOLIDATED_WRITE_MODE,CDCLane,@@ -181,9 +180,7 @@ def _schema(**overrides) -> MagicMock: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)- # A flipped schema carries the opt-in marker; consolidated is served without it.- default_config = {} if schema.cdc_table_mode == "consolidated" else {BUFFERED_LANE_KEY: True}- schema.sync_type_config = overrides.get("sync_type_config", default_config)+ schema.sync_type_config = overrides.get("sync_type_config", {})schema.source.job_inputs = overrides.get("job_inputs", {})schema.primary_key_columns = overrides.get("primary_key_columns", ["id"])schema.name = overrides.get("name", "users")@@ -292,25 +289,6 @@ class TestServedLanes:assert [lane.resource_name for lane in served_lanes(schema)] == ["users", "public.users_cdc"]-class TestBufferedLaneOptIn:- @parameterized.expand(- [- ("consolidated", False, True),- ("cdc_only", False, False),- ("both", False, False),- ("cdc_only", True, True),- ("both", True, True),- ]- )- def test_history_modes_serve_only_once_the_flip_marked_them(self, mode, marked, served):- # A source flipped before history modes were served left those schemas on legacy with their- # schedules paused. Widening by mode alone would have capture route them into the buffer on- # deploy, with nothing scheduled to consume it. Consolidated predates the marker.- schema = _schema(cdc_table_mode=mode, sync_type_config={BUFFERED_LANE_KEY: True} if marked else {})-- assert serves_buffered_lane(schema) is served--class TestBufferedGating:@parameterized.expand([diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.pyindex f8470c86a33a..f6f5bb1cb199 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py@@ -35,7 +35,6 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import)from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import (has_engine_seq,- is_cdc_write_resolution_enabled,resolve_batch,verify_delete_enrichment,)@@ -959,9 +958,7 @@ def _process_message_reported("batch_index": str(export_signal.batch_index),}- resolution_enabled = cdc_write_mode is not None and is_cdc_write_resolution_enabled(- export_signal.team_id, schema_id_str, export_signal.run_uuid- )+ resolution_enabled = cdc_write_mode is not Nonepa_table = _enrich_cdc_rows(pa_table,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 21fe9d683e50..29854026f614 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@@ -213,7 +213,9 @@ class PostgresCDCAdapter:# customer-owned publication) don't match the predicate and re-raise immediately.consistent_point = _retry_on_connection_dropped(_recreate, _retry_logger)- return {"cdc_consistent_point": consistent_point}+ # Every schema is reset to snapshot before this runs, so no change from the dead slot is owed+ # to the legacy lane: the new slot starts on the buffer, as a new source does.+ return {"cdc_consistent_point": consistent_point, "cdc_ingest_mode": "buffered"}def setup_resources(self,@@ -239,6 +241,9 @@ class PostgresCDCAdapter:"cdc_management_mode": management_mode,"cdc_slot_name": slot_name,"cdc_publication_name": pub_name,+ # Written with the slot, before capture first runs, so no change reaches the buffer that a+ # legacy batch already delivered.+ "cdc_ingest_mode": "buffered",}if management_mode == "posthog":diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.pyindex 847343d1f26b..45976666fbdd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py@@ -94,6 +94,7 @@ class TestSetupResourcesPreflight:"cdc_management_mode": "posthog","cdc_slot_name": "posthog_019ef4e83bfd","cdc_publication_name": "posthog_pub_019ef4e83bfd",+ "cdc_ingest_mode": "buffered",}mock_create_slot.assert_not_called()mock_create_publication.assert_not_called()@@ -214,7 +215,7 @@ class TestRecreateSlot:fields = PostgresCDCAdapter().recreate_slot(source, tables=["users", "orders"])- assert fields == {"cdc_consistent_point": "0/AA"}+ assert fields == {"cdc_consistent_point": "0/AA", "cdc_ingest_mode": "buffered"}mock_drop.assert_called_once()assert mock_drop.call_args.args[1] == "posthog_slot"mock_create.assert_called_once()@@ -249,7 +250,7 @@ class TestRecreateSlot:fields = PostgresCDCAdapter().recreate_slot(source, tables=tables)- assert fields == {"cdc_consistent_point": "0/BB"}+ assert fields == {"cdc_consistent_point": "0/BB", "cdc_ingest_mode": "buffered"}mock_create_slot_and_pub.assert_called_once()assert mock_create_slot_and_pub.call_args.args[1:3] == ("posthog_slot", "posthog_pub")assert mock_create_slot_and_pub.call_args.kwargs["tables"] == expected_pairs@@ -304,7 +305,7 @@ class TestRecreateSlot:fields = PostgresCDCAdapter().recreate_slot(source, tables=["users"])- assert fields == {"cdc_consistent_point": "0/CC"}+ assert fields == {"cdc_consistent_point": "0/CC", "cdc_ingest_mode": "buffered"}assert mock_create_slot.call_count == 2assert mock_drop.call_count == 2diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py b/products/warehouse_sources/backend/tests/api/test_external_data_schema.pyindex d1ec725ce709..2da8a4bb55ca 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py@@ -1095,6 +1095,18 @@ class TestExternalDataSchema(APIBaseTest):ExternalDataSchema.SyncType.FULL_REFRESH,None,),+ (+ "rejects_a_source_column_named_like_the_position_column",+ {+ "primary_key_columns": ["id"],+ "schema_metadata": {"columns": [{"name": "id"}, {"name": "_ph_cdc_seq"}]},+ },+ None,+ status.HTTP_400_BAD_REQUEST,+ ExternalDataSchema.SyncType.FULL_REFRESH,+ None,+ "_ph_cdc_seq",+ ),])def test_update_schema_to_cdc(@@ -1105,6 +1117,7 @@ class TestExternalDataSchema(APIBaseTest):expected_status: int,expected_sync_type: str,expected_pk_columns: list[str] | None,+ expected_error: str = "primary key",):source = ExternalDataSource.objects.create(team=self.team,@@ -1144,7 +1157,7 @@ class TestExternalDataSchema(APIBaseTest):assert response.status_code == expected_status, response.contentif expected_status == status.HTTP_400_BAD_REQUEST:- assert "primary key" in str(response.json()).lower()+ assert expected_error in str(response.json()).lower()schema.refresh_from_db()assert schema.sync_type == expected_sync_typeif expected_pk_columns is not None: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 2d7fa585c9a2..8566befa67ce 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@@ -4600,6 +4600,17 @@ class TestExternalDataSource(APIBaseTest):mock_add_table.assert_called_once()assert mock_add_table.call_args.args[1:] == ("analytics", "events")+ @parameterized.expand(+ [+ ("no_primary_key", [("id", "uuid", False)], {}, "primary key"),+ (+ "reserved_column",+ [("id", "uuid", False), ("_ph_cdc_seq", "bigint", True)],+ {"tracking_link": ["id"]},+ "_ph_cdc_seq",+ ),+ ]+ )@patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,@@ -4613,8 +4624,12 @@ class TestExternalDataSource(APIBaseTest):@patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.get_primary_key_columns")@patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.cdc_pg_connection")@patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")- def test_create_postgres_cdc_rejects_table_without_primary_key(+ def test_create_postgres_cdc_rejects_a_table_it_cannot_capture(self,+ _name,+ columns,+ primary_keys,+ expected_in_message,mock_get_source,mock_cdc_pg_connection,mock_get_primary_key_columns,@@ -4647,7 +4662,7 @@ class TestExternalDataSource(APIBaseTest):supports_incremental=False,supports_append=False,supports_cdc=False,- columns=[("id", "uuid", False)],+ columns=columns,foreign_keys=[],source_schema="public",source_table_name="tracking_link",@@ -4656,8 +4671,7 @@ class TestExternalDataSource(APIBaseTest):mock_cdc_pg_connection.return_value.__enter__.return_value = object()mock_cdc_pg_connection.return_value.__exit__.return_value = None- # Source DB reports no PK for the table.- mock_get_primary_key_columns.return_value = {}+ mock_get_primary_key_columns.return_value = primary_keysresponse = self.client.post(f"/api/environments/{self.team.pk}/external_data_sources/",@@ -4680,7 +4694,7 @@ class TestExternalDataSource(APIBaseTest):)assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content- assert "primary key" in response.json()["message"].lower()+ assert expected_in_message in response.json()["message"].lower()assert "tracking_link" in response.json()["message"]# No source row left behind on validation failure.assert ExternalDataSource.objects.filter(team_id=self.team.pk).count() == 0@@ -11581,6 +11595,7 @@ class TestRepairCDC(APIBaseTest):source_id=source.pk,sync_type=ExternalDataSchema.SyncType.CDC,should_sync=False,+ initial_sync_complete=True,sync_type_config={"cdc_mode": "streaming"},)non_cdc_schema = ExternalDataSchema.objects.create(@@ -11613,7 +11628,8 @@ class TestRepairCDC(APIBaseTest):assert schema.latest_error is Nonedisabled_cdc_schema.refresh_from_db()- assert disabled_cdc_schema.sync_type_config == {"cdc_mode": "streaming"}+ assert disabled_cdc_schema.sync_type_config == {"cdc_mode": "snapshot", "reset_pipeline": True}+ assert disabled_cdc_schema.initial_sync_complete is Falsenon_cdc_schema.refresh_from_db()assert non_cdc_schema.sync_type_config == {}@@ -11717,6 +11733,47 @@ class TestRepairCDC(APIBaseTest):assert response.status_code == 200, response.contentmock_recreate.assert_called_once()+ @patch("products.data_warehouse.backend.logic.data_load.service.sync_cdc_extraction_schedule")+ @patch("products.data_warehouse.backend.logic.data_load.service.unpause_cdc_extraction_schedule")+ @patch("products.data_warehouse.backend.logic.data_load.service.trigger_external_data_workflow")+ @patch(+ "products.data_warehouse.backend.logic.data_load.service.unpause_external_data_schedule",+ side_effect=[RuntimeError("temporal down"), None],+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.recreate_slot",+ return_value={"cdc_consistent_point": "0/AABBCC"},+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.get_status",+ side_effect=[+ {"slot_exists": False, "publication_exists": True, "lag_bytes": None},+ {"slot_exists": True, "publication_exists": True, "lag_bytes": 0},+ ],+ )+ def test_repair_cdc_retry_is_allowed_after_a_failure_once_the_new_slot_exists(+ self, _status, mock_recreate, _unpause, _trigger, _unpause_ext, _sync_ext+ ) -> None:+ source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)+ schema = ExternalDataSchema.objects.create(+ name="orders",+ team_id=self.team.pk,+ source_id=source.pk,+ sync_type=ExternalDataSchema.SyncType.CDC,+ should_sync=True,+ sync_type_config={"cdc_mode": "streaming"},+ )++ assert self._repair(source).status_code != 200+ schema.refresh_from_db()+ assert schema.sync_type_config["cdc_broken"]["reason"] == "repair_in_progress"++ response = self._repair(source)+ assert response.status_code == 200, response.content+ schema.refresh_from_db()+ assert "cdc_broken" not in schema.sync_type_config+ assert mock_recreate.call_count == 2+@patch("products.data_warehouse.backend.logic.data_load.service.cancel_external_data_workflow")@patch("products.data_warehouse.backend.logic.data_load.service.sync_cdc_extraction_schedule")@patch("products.data_warehouse.backend.logic.data_load.service.unpause_cdc_extraction_schedule")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.pyindex 3b7e78a60326..7f6ee61f08e4 100644--- a/products/warehouse_sources/backend/tests/management/test_migrate_cdc_source_to_buffered.py+++ b/products/warehouse_sources/backend/tests/management/test_migrate_cdc_source_to_buffered.py@@ -27,7 +27,6 @@ _CMD = "products.warehouse_sources.backend.management.commands.migrate_cdc_sourc@contextmanagerdef _mocked_side_effects(oldest_batch_age: float | None = None,- write_resolution: bool = True,buffer_keys: list[str] | None = None,buffer_keys_by_schema: dict[str, list[str]] | None = None,extraction_running: bool = False,@@ -55,7 +54,6 @@ def _mocked_side_effects(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}.purge_buffer_prefix") as mock_purge,patch("products.data_warehouse.backend.facade.api.get_s3_client", return_value=s3),patch(@@ -273,6 +271,10 @@ class TestMigrateCDCSourceToBuffered(BaseTest):# source that would otherwise be refused its next flip.source = self._source(ingest_mode="buffered")self._schema(source, "users")+ history = self._schema(source, "events", table_mode="cdc_only")+ disabled_history = self._schema(source, "audit", table_mode="both")+ disabled_history.should_sync = False+ disabled_history.save()with _mocked_side_effects():self._run(source, rollback=True)@@ -280,6 +282,9 @@ class TestMigrateCDCSourceToBuffered(BaseTest):source.refresh_from_db()assert source.job_inputs["cdc_ingest_mode"] == "legacy"assert source.job_inputs["cdc_buffered_before"]+ for schema in (history, disabled_history):+ schema.refresh_from_db()+ assert schema.sync_type_config["cdc_buffered_before"] is Truedef test_rollback_restores_schedules_even_when_the_extraction_unpause_fails(self):# The per-schema restore runs before the single Temporal call that unpauses extraction, so@@ -426,32 +431,25 @@ class TestMigrateCDCSourceToBuffered(BaseTest):source.refresh_from_db()assert "cdc_ingest_mode" not in source.job_inputs- def test_flipping_marks_each_schema_and_rollback_unmarks_it(self):+ def test_flipping_records_the_buffered_lane_and_rollback_keeps_the_record(self):source = self._source()history = self._schema(source, "events", table_mode="cdc_only")with _mocked_side_effects():self._run(source)history.refresh_from_db()- assert (- history.sync_type_config["cdc_buffered_lane"] is True- and history.sync_type_config["cdc_buffered_before"] is True- )+ assert history.sync_type_config["cdc_buffered_before"] is Truewith _mocked_side_effects():self._run(source, rollback=True)history.refresh_from_db()- assert "cdc_buffered_lane" not in history.sync_type_configassert history.sync_type_config["cdc_buffered_before"] is True- @parameterized.expand([("flip", None, False), ("rollback", "buffered", True)])- def test_marking_keeps_the_keys_a_run_wrote_while_the_command_waited(self, _name, ingest_mode, rollback):+ def test_marking_keeps_the_keys_a_run_wrote_while_the_command_waited(self):# The command waits out an in-flight capture run, and that run appends to the same JSON —# under backpressure, the only record of batches it deferred. Saving the copy loaded before# the wait would put the JSON back the way it was.- source = self._source(ingest_mode)+ source = self._source()schema = self._schema(source, "users")- if rollback:- update_sync_type_config_keys(schema.id, self.team.pk, updates={"cdc_buffered_lane": True})def run_writes_during_the_wait(*_args):update_sync_type_config_keys(schema.id, self.team.pk, updates={"cdc_deferred_runs": [{"run": 1}]})@@ -460,11 +458,11 @@ class TestMigrateCDCSourceToBuffered(BaseTest):_mocked_side_effects(),patch(f"{_CMD}.Command._wait_for_extraction_idle", side_effect=run_writes_during_the_wait),):- self._run(source, rollback=rollback)+ self._run(source)schema.refresh_from_db()assert schema.sync_type_config["cdc_deferred_runs"] == [{"run": 1}]- assert schema.sync_type_config.get("cdc_buffered_lane") is (None if rollback else True)+ assert schema.sync_type_config["cdc_buffered_before"] is True@parameterized.expand([("flip", None, False), ("rollback", "buffered", True)])def test_an_orphaned_companion_job_is_retired_instead_of_blocking(self, _name, ingest_mode, rollback):@@ -499,73 +497,6 @@ class TestMigrateCDCSourceToBuffered(BaseTest):assert (companion.status, companion.latest_error) == (ExternalDataJob.Status.FAILED, COMPANION_RETIRED_ERROR)assert source.job_inputs["cdc_ingest_mode"] == ("legacy" if rollback else "buffered")- def test_rerunning_on_a_buffered_source_moves_only_the_unserved_schemas(self):- # A source flipped before history modes were served left its `cdc_only` schema on legacy.- # Re-running moves that schema, marks it, and purges only its prefix — the served schema's- # buffer holds files the consumer still owes.- source = self._source()- source.job_inputs = {**(source.job_inputs or {}), "cdc_ingest_mode": "buffered", "cdc_buffered_before": True}- source.save(update_fields=["job_inputs"])- served = self._schema(source, "users")- left_behind = self._schema(source, "events", table_mode="cdc_only")-- with _mocked_side_effects() as mocks:- out = self._run(source)-- assert "buffered lane (1): events" in out- assert "already buffered (1): users" in out- assert "staying on legacy" not in out- left_behind.refresh_from_db()- served.refresh_from_db()- assert left_behind.sync_type_config.get("cdc_buffered_lane") is True- assert "cdc_buffered_lane" not in served.sync_type_config- purged = {call.args[1] for call in mocks["purge"].call_args_list}- assert purged == {str(left_behind.id)}-- def test_a_reserved_column_on_a_schema_added_since_the_flip_is_still_refused(self):- # The source-level marker waives only the consolidated schemas that predate the per-schema- # one; a history schema never buffered before can only own that column itself.- source = self._source()- source.job_inputs = {**(source.job_inputs or {}), "cdc_ingest_mode": "buffered", "cdc_buffered_before": True}- source.save(update_fields=["job_inputs"])- table = DataWarehouseTable.objects.create(- team_id=self.team.pk,- name="events",- format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,- url_pattern="https://bucket/events/*",- external_data_source=source,- columns={"id": {"hogql": "IntegerDatabaseField"}, CDC_SEQ_COLUMN: {"hogql": "IntegerDatabaseField"}},- )- self._schema(source, "events", table_mode="cdc_only", table=table)-- with _mocked_side_effects():- with pytest.raises(CommandError, match="reserved for change ordering"):- self._run(source)-- 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_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")