Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse-sources): force the v3 pipeline for buffered CDC consumption (#90152)

Daniel RC6adc769249b1
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.md
index 8d5350837df8..92f72566fa30 100644
--- a/docs/internal/cdc-buffered-ingress-runbook.md
+++ b/docs/internal/cdc-buffered-ingress-runbook.md
@@ -23,10 +23,11 @@ preserved, so there is no WAL gap and no re-sync.
## Before flipping
-0. The team runs the v3 pipeline for this source type. **The command refuses to flip a v2 team.**
- Position resolution lives only in the v3 loader; on v2 nothing records a load position, so every
- scheduled sync re-merges the entire buffer and no file is ever deleted — per-run row counts grow
- with the buffer on every tick.
+0. Pipeline version needs no preparation: the scheduled sync forces the v3 pipeline for
+ buffered-consolidated schemas, because only the v3 loader records the load position that proves
+ buffer files consumed. The team's `warehouse-pipelines-v3` rollout flag neither enables nor
+ blocks the flip, and narrowing it later does not affect flipped sources. Do not flip while a
+ deploy 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.**
Without the flag the loader records no load position, so no consumed file is ever proven safe to
delete; the buffer then fills until the S3 TTL expires it, with the slot long advanced past those
@@ -60,10 +61,12 @@ preserved, so there is no WAL gap and no re-sync.
python manage.py migrate_cdc_source_to_buffered --source-id <uuid>
```
-The command pauses the extraction schedule, waits for the in-flight extraction run to finish, waits
-for in-flight `sourcebatch` batches to reach a terminal state, purges pre-flip buffer files **and
-aborts if any file survives the purge**, sets `job_inputs.cdc_ingest_mode = "buffered"`, then
-unpauses the extraction schedule and each eligible schema's own schedule.
+The command pauses the extraction schedule, waits for the in-flight extraction run to finish,
+pauses each eligible schema's schedule and waits for running sync jobs (a sync that started legacy
+resolved its pipeline version then, and must not straddle the mode change), waits for in-flight
+`sourcebatch` batches to reach a terminal state, purges pre-flip buffer files **and aborts if any
+file survives the purge**, sets `job_inputs.cdc_ingest_mode = "buffered"`, then unpauses the
+extraction schedule and each eligible schema's own schedule.
If a batch is still working after the drain timeout the command aborts with the source **left
paused**. That is deliberate — flipping on top of a stuck load lets that batch land against a table
diff --git a/posthog/temporal/tests/external_data/test_external_data_job.py b/posthog/temporal/tests/external_data/test_external_data_job.py
index d638607bd39c..d727e683be20 100644
--- a/posthog/temporal/tests/external_data/test_external_data_job.py
+++ b/posthog/temporal/tests/external_data/test_external_data_job.py
@@ -44,6 +44,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.con
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.settings import (
ENDPOINTS as STRIPE_ENDPOINTS,
)
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.acquire_v3_lock import (
+ check_pipeline_version_activity,
+)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.calculate_table_size import (
calculate_table_size_activity,
)
@@ -1017,6 +1020,7 @@ async def test_external_data_job_workflow_with_schema(team, **kwargs):
task_queue=settings.DATA_WAREHOUSE_TASK_QUEUE,
workflows=[ExternalDataJobWorkflow],
activities=[
+ check_pipeline_version_activity,
create_external_data_job_model_activity,
update_external_data_job_model,
import_data_activity_sync,
diff --git a/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.py b/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.py
index 64ec8d991404..53608567ba3b 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
@@ -39,9 +39,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
BatchQueue,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common import strip_s3_protocol
-from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (
- is_pipeline_v3_enabled,
-)
logger = structlog.get_logger(__name__)
@@ -100,7 +97,9 @@ class Command(BaseCommand):
self.stdout.write(self.style.WARNING(f"Already {target_mode}; nothing to do."))
return
if not rollback:
- self._require_pipeline_v3(source)
+ # No pipeline-version gate: the scheduled sync forces the v3 pipeline for
+ # buffered-consolidated schemas (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:
@@ -112,21 +111,6 @@ class Command(BaseCommand):
else:
self._flip_to_buffered(source, eligible, options["drain_timeout"])
- def _require_pipeline_v3(self, source: ExternalDataSource) -> None:
- """Refuse to flip a team that still runs the v2 pipeline.
-
- Position resolution lives only in the v3 loader; on v2 nothing records a load position, so
- every scheduled sync re-merges the entire buffer and no file is ever deleted — a snowballing
- re-merge on every tick, observed live before this guard existed.
- """
- if is_pipeline_v3_enabled(source.team_id, source.source_type):
- return
- raise CommandError(
- f"Team {source.team_id} runs the v2 pipeline for {source.source_type}. Buffered ingress "
- "requires v3: v2 has no position resolution, so the buffer re-merges in full on every "
- "sync and consumed files are never deleted."
- )
-
def _require_write_resolution(self, source: ExternalDataSource, eligible: list[ExternalDataSchema]) -> None:
"""Refuse to flip a team whose write resolution is off.
@@ -204,30 +188,42 @@ class Command(BaseCommand):
source_id = str(source.id)
- self.stdout.write("1/6 pausing extraction schedule")
+ self.stdout.write("1/7 pausing extraction schedule")
pause_cdc_extraction_schedule(source_id)
# Pausing the schedule stops future firings, not a workflow already running. A legacy run
# with the shadow lane on keeps writing buffer files, and one landing after the purge would
# be merged by the consumer even though the legacy lane already delivered those rows.
- self.stdout.write("2/6 waiting for the in-flight extraction run to finish")
+ self.stdout.write("2/7 waiting for the in-flight extraction run to finish")
self._wait_for_extraction_idle(source_id, drain_timeout)
- self.stdout.write("3/6 draining sourcebatch")
+ # A scheduled sync that started before the mode change resolved its pipeline version while
+ # the source was still legacy. If it reads the source again after the change, it consumes
+ # the buffer on that stale version, which records no load position, so nothing it read is
+ # ever proven consumed. Quiesce the schedules so no run straddles the mode change.
+ self.stdout.write("3/7 pausing per-schema schedules")
+ self._pause_schema_schedules_strict(eligible)
+ self._wait_for_running_sync_jobs(source.team_id, [str(s.id) for s in eligible], drain_timeout)
+
+ self.stdout.write("4/7 draining sourcebatch")
self._wait_for_sourcebatch_drain(source.team_id, [str(s.id) for s in eligible], drain_timeout)
# Pre-flip files were already delivered by the legacy lane, and replaying them would
# re-apply rows against a position the guard has no watermark for yet.
- self.stdout.write("4/6 purging pre-flip buffer files")
+ self.stdout.write("5/7 purging pre-flip buffer files")
for schema in eligible:
purge_buffer_prefix(source.team_id, str(schema.id), logger)
self._verify_prefixes_empty(source.team_id, eligible)
- self.stdout.write("5/6 setting cdc_ingest_mode=buffered")
+ # The step-3 wait sees job rows only; a workflow fired just before the pause may not 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)
+
+ self.stdout.write("6/7 setting cdc_ingest_mode=buffered")
source.job_inputs = {**(source.job_inputs or {}), "cdc_ingest_mode": "buffered"}
source.save(update_fields=["job_inputs"])
- self.stdout.write("6/6 unpausing schedules")
+ self.stdout.write("7/7 unpausing schedules")
unpause_cdc_extraction_schedule(source_id)
self._set_schema_schedules(eligible, paused=False)
@@ -346,8 +342,8 @@ class Command(BaseCommand):
pause_external_data_schedule(str(schema.id))
except Exception as exc:
raise CommandError(
- f"Could not pause the schedule for {schema.name}; a sync starting mid-rollback "
- f"could overwrite newer legacy rows. Mode unchanged — fix and re-run. ({exc})"
+ f"Could not pause the schedule for {schema.name}; a sync straddling the mode "
+ f"change would consume with stale settings. Mode unchanged — fix and re-run. ({exc})"
)
def _verify_prefixes_empty(self, team_id: int, eligible: list[ExternalDataSchema]) -> None:
@@ -406,17 +402,25 @@ class Command(BaseCommand):
deadline = time.monotonic() + timeout
while True:
- running = ExternalDataJob.objects.filter(
- team_id=team_id, schema_id__in=schema_ids, status=ExternalDataJob.Status.RUNNING
- ).count()
- if running == 0:
+ running = list(
+ ExternalDataJob.objects.filter(
+ team_id=team_id, schema_id__in=schema_ids, status=ExternalDataJob.Status.RUNNING
+ ).values_list("id", "created_at")
+ )
+ if not running:
return
if time.monotonic() >= deadline:
+ now = dt.datetime.now(dt.UTC)
+ # Ages let the operator tell a live sync from a stale stuck-RUNNING row, which
+ # never finishes on its own and needs unsticking before the flip can proceed.
+ detail = ", ".join(
+ f"{job_id} ({(now - created_at).total_seconds():.0f}s old)" for job_id, created_at in running
+ )
raise CommandError(
- f"{running} sync job(s) still running after {timeout}s. Schedules are left "
- "paused and the mode unchanged — wait for them to finish, then re-run."
+ f"{len(running)} sync job(s) still running after {timeout}s: {detail}. Schedules "
+ "are left paused and the mode unchanged — wait for them to finish, then re-run."
)
- self.stdout.write(f" waiting, {running} sync job(s) running")
+ self.stdout.write(f" waiting, {len(running)} sync job(s) running")
time.sleep(DRAIN_POLL_SECONDS)
def _set_schema_schedules(self, schemas: list[ExternalDataSchema], *, paused: bool) -> 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.py
index 7f1d26540ed6..624b1c9ccf29 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
@@ -32,6 +32,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import
parse_buffer_file_name,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import read_load_position
+from products.warehouse_sources.backend.temporal.data_imports.cdc.types import parse_ingest_mode
from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import resolve_table_and_folder_names
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
BatchQueue,
@@ -84,6 +85,18 @@ def is_buffered_consolidated(schema: ExternalDataSchema, *, ingest_mode: str) ->
return ingest_mode == "buffered" and serves_buffered_lane(schema)
+def scheduled_sync_consumes_buffer(schema: ExternalDataSchema) -> bool:
+ """Whether this schema's scheduled sync consumes the S3 change buffer.
+
+ Doubles as the pipeline-version override: buffered consumption must run the v3 pipeline,
+ because only the v3 loader records the load position that proves buffer files consumed and
+ resolves versions and deletes. The team's general rollout flag cannot make that call (it can
+ neither see individual sources nor be trusted to stay wide after a flip), so the version
+ check consults this predicate before the flag.
+ """
+ return is_buffered_consolidated(schema, ingest_mode=parse_ingest_mode(schema.source.job_inputs))
+
+
def has_pending_legacy_backlog(schema: ExternalDataSchema) -> bool:
"""Whether legacy-lane deliveries for this schema are still in flight.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py
index dbc41b149c17..a4408505a5cf 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
@@ -1,11 +1,13 @@
import pytest
from unittest.mock import MagicMock, patch
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import CDCHandledExternally
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSource
_SCHEMA_MODEL = "products.warehouse_sources.backend.models.external_data_schema.ExternalDataSchema"
+_JOB_MODEL = "products.warehouse_sources.backend.models.external_data_job.ExternalDataJob"
_MANAGER = "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager"
@@ -41,13 +43,21 @@ def _inputs(reset_pipeline: bool = False) -> SourceInputs:
)
-def _dispatch(schema: MagicMock, inputs: SourceInputs, backlog: bool = False):
+def _dispatch(
+ schema: MagicMock,
+ inputs: SourceInputs,
+ backlog: bool = False,
+ job_version: str | None = ExternalDataJob.PipelineVersion.V3,
+):
+ job = None if job_version is None else MagicMock(pipeline_version=job_version)
with (
patch(f"{_SCHEMA_MODEL}.objects") as objects,
+ patch(f"{_JOB_MODEL}.objects") as job_objects,
patch(f"{_MANAGER}.has_pending_legacy_backlog", return_value=backlog),
patch.object(PostgresSource, "make_ssh_tunnel_func", return_value=MagicMock()),
):
objects.select_related.return_value.get.return_value = schema
+ job_objects.filter.return_value.first.return_value = job
return PostgresSource().source_for_pipeline(MagicMock(), inputs)
@@ -70,6 +80,17 @@ class TestBufferedDispatch:
with pytest.raises(CDCHandledExternally):
_dispatch(_schema(ingest_mode, **overrides), _inputs())
+ def test_a_v2_run_reaching_the_buffered_lane_fails_loudly(self):
+ # The forcing keeps this unreachable; if a race or deploy skew gets past it, the run must
+ # fail rather than consume without recording a load position.
+ with pytest.raises(ValueError, match="requires v3"):
+ _dispatch(_schema(), _inputs(), job_version="v2-non-dlt")
+
+ def test_a_missing_job_row_does_not_block_buffered_consumption(self):
+ response = _dispatch(_schema(), _inputs(), job_version=None)
+
+ assert response.name == "users"
+
def test_a_pending_legacy_backlog_yields_an_empty_run_rather_than_pausing_the_schedule(self):
response = _dispatch(_schema(), _inputs(), backlog=True)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py
index 308091e1acc4..c49417590c64 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
@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager
CDCSourceManager,
has_pending_legacy_backlog,
is_buffered_consolidated,
+ scheduled_sync_consumes_buffer,
serves_buffered_lane,
)
@@ -128,6 +129,7 @@ def _schema(**overrides) -> MagicMock:
schema.cdc_table_mode = overrides.get("cdc_table_mode", "consolidated")
schema.initial_sync_complete = overrides.get("initial_sync_complete", True)
schema.sync_type_config = overrides.get("sync_type_config", {})
+ schema.source.job_inputs = overrides.get("job_inputs", {})
return schema
@@ -290,6 +292,20 @@ class TestBufferedGating:
def test_a_flipped_consolidated_schema_consumes_the_buffer(self):
assert is_buffered_consolidated(_schema(), ingest_mode="buffered") is True
+ def test_a_flipped_schema_forces_the_buffered_consumer_on_its_scheduled_sync(self):
+ assert scheduled_sync_consumes_buffer(_schema(job_inputs={"cdc_ingest_mode": "buffered"})) is True
+
+ @parameterized.expand(
+ [
+ ("source_never_flipped", {}),
+ ("no_job_inputs", {"job_inputs": None}),
+ ("companion_lane", {"job_inputs": {"cdc_ingest_mode": "buffered"}, "cdc_table_mode": "cdc_only"}),
+ ("still_snapshotting", {"job_inputs": {"cdc_ingest_mode": "buffered"}, "cdc_mode": "snapshot"}),
+ ]
+ )
+ def test_the_scheduled_sync_is_not_forced_off_the_flag_for(self, _name, overrides):
+ assert scheduled_sync_consumes_buffer(_schema(**overrides)) is False
+
class TestPendingLegacyBacklog:
# Legacy deliveries carry no position column, so a consumer merge racing them can be overwritten
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py
index fef7da2febfe..6fa799181e21 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py
@@ -14,6 +14,12 @@ ManagementMode = Literal["posthog", "self_managed"]
IngestMode = Literal["legacy", "buffered"]
+def parse_ingest_mode(job_inputs: Mapping[str, Any] | None) -> IngestMode:
+ """Anything unrecognized reads as legacy: an unknown value must not route a source onto a
+ path it was never flipped to."""
+ return "buffered" if (job_inputs or {}).get("cdc_ingest_mode") == "buffered" else "legacy"
+
+
@dataclass(frozen=True)
class CDCConfig:
"""Base class for engine-specific CDC configs returned by ``parse_cdc_config``.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
index 2f4c16d4884b..84151fa8ad62 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
@@ -53,6 +53,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_h
from products.warehouse_sources.backend.temporal.data_imports.metrics import (
get_data_import_finished_metric,
get_v3_lock_skipped_metric,
+ get_version_check_skipped_metric,
)
from products.warehouse_sources.backend.temporal.data_imports.post_import_job import (
PostImportWorkflow,
@@ -554,12 +555,24 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
CheckPipelineVersionActivityInputs(
team_id=inputs.team_id,
source_id=inputs.external_data_source_id,
+ schema_id=inputs.external_data_schema_id,
),
start_to_close_timeout=dt.timedelta(minutes=1),
- retry_policy=RetryPolicy(maximum_attempts=1),
+ retry_policy=RetryPolicy(maximum_attempts=3),
)
is_v3 = version_result.is_v3
except Exception:
+ # Guessing the version is not safe: a buffered CDC schema consumed on v2 records no
+ # load position, so the buffer re-merges in full and nothing is ever deleted. Skip
+ # the run and let the schedule fire again, matching the lock-not-acquired path.
+ # patched() keeps in-flight pre-patch executions replaying their recorded fall-through.
+ if workflow.patched("data-imports-skip-run-on-version-check-failure-v1"):
+ workflow.logger.error(
+ "Failed to check pipeline version, skipping run",
+ extra={"schema_id": str(inputs.external_data_schema_id)},
+ )
+ get_version_check_skipped_metric().add(1)
+ return
workflow.logger.warning(
"Failed to check pipeline version, defaulting to V2",
extra={"schema_id": str(inputs.external_data_schema_id)},
diff --git a/products/warehouse_sources/backend/temporal/data_imports/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
index d7263befae32..00aa0314a060 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
@@ -56,6 +56,14 @@ def get_v3_lock_skipped_metric() -> MetricCounter:
)
+def get_version_check_skipped_metric() -> MetricCounter:
+ # Same visibility gap as the lock metric: the skip leaves no job row, so a persistently
+ # failing version check silently costs a schema every scheduled slot.
+ return workflow.metric_meter().create_counter(
+ "data_import_version_check_skipped", "Scheduled runs skipped because the pipeline version check failed."
+ )
+
+
def emit_data_import_app_metrics(job: "ExternalDataJob") -> None:
"""Emit app_metrics2 rows for a data import job that just reached terminal state.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py
index 2dbd513dcc7b..8ee9e4b099e3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py
@@ -13,7 +13,11 @@ from typing import TYPE_CHECKING
from posthog.utils import str_to_bool
-from products.warehouse_sources.backend.temporal.data_imports.cdc.types import CDCConfig, IngestMode, ManagementMode
+from products.warehouse_sources.backend.temporal.data_imports.cdc.types import (
+ CDCConfig,
+ ManagementMode,
+ parse_ingest_mode,
+)
if TYPE_CHECKING:
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -38,9 +42,7 @@ class PostgresCDCConfig(CDCConfig):
management_mode: ManagementMode = (
"self_managed" if ji.get("cdc_management_mode") == "self_managed" else "posthog"
)
- # Anything unrecognized reads as legacy: an unknown value must not route a source onto a
- # path it was never flipped to.
- ingest_mode: IngestMode = "buffered" if ji.get("cdc_ingest_mode") == "buffered" else "legacy"
+ ingest_mode = parse_ingest_mode(ji)
return cls(
enabled=str_to_bool(ji.get("cdc_enabled", False)),
slot_name=ji.get("cdc_slot_name") or "",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
index be65c9ac1b00..b2b7859c0251 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
@@ -1316,6 +1316,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
Returning None keeps the caller on the legacy `CDCHandledExternally` path, so a source that
was never flipped — or a lane the buffer doesn't serve — behaves exactly as before.
"""
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
CONSOLIDATED_WRITE_MODE,
CDCSourceManager,
@@ -1331,6 +1332,18 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
if not is_buffered_consolidated(schema, ingest_mode=ingest_mode):
return None
+ # Defense in depth for the v3-forcing invariant: a run that resolved its pipeline version
+ # before the flip, or a worker one deploy behind, would consume this buffer on v2, record
+ # no load position, and re-merge the whole buffer on every tick. Fail the run loudly
+ # instead of degrading silently.
+ job = ExternalDataJob.objects.filter(id=inputs.job_id, team_id=inputs.team_id).first()
+ if job is not None and job.pipeline_version != ExternalDataJob.PipelineVersion.V3:
+ raise ValueError(
+ f"Buffered CDC schema {schema.name} reached a {job.pipeline_version} pipeline run. "
+ "Buffered consumption requires v3, whose loader records the load position that "
+ "proves buffer files consumed."
+ )
+
# A CDC reset must travel through snapshot mode (which purges the buffer and re-seeds the
# table); every reset writer does that. Standing down here instead would route into
# CDCHandledExternally, whose handler pauses this schedule — and nothing on a buffered
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
index 28aaed820d75..14187fd5a3ee 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
@@ -19,7 +19,9 @@ from posthog.temporal.common.logger import get_logger
from products.data_warehouse.backend.facade.api import update_external_job_status
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import scheduled_sync_consumes_buffer
from products.warehouse_sources.backend.temporal.data_imports.metrics import (
LOCK_TAKEOVER_LATEST_ERROR,
TERMINAL_JOB_STATUSES,
@@ -49,10 +51,12 @@ TAKEOVER_MAX_HOLD_SECONDS = 24 * 60 * 60
NO_JOB_ROW_TAKEOVER_GRACE_SECONDS = 900
[email protected](frozen=True)
class CheckPipelineVersionActivityInputs:
team_id: int
source_id: uuid.UUID
+ # Optional so payloads recorded before this field existed still deserialize on replay.
+ schema_id: uuid.UUID | None = None
@dataclasses.dataclass(frozen=True)
@@ -84,6 +88,18 @@ def check_pipeline_version_activity(inputs: CheckPipelineVersionActivityInputs)
bind_contextvars(team_id=inputs.team_id)
close_old_connections()
+ # Buffered CDC consumption requires the v3 loader, whose position resolution proves buffer
+ # files consumed, so it overrides the rollout flag: the same V3 the CDC extraction hardcodes
+ # for the jobs it creates.
+ if inputs.schema_id is not None:
+ schema = (
+ ExternalDataSchema.objects.filter(id=inputs.schema_id, team_id=inputs.team_id)
+ .select_related("source")
+ .first()
+ )
+ if schema is not None and scheduled_sync_consumes_buffer(schema):
+ return CheckPipelineVersionActivityOutputs(is_v3=True)
+
try:
source = ExternalDataSource.objects.get(id=inputs.source_id)
except ExternalDataSource.DoesNotExist:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
index 847738ea6ea7..11516d27fb9c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
@@ -67,6 +67,66 @@ class TestCheckPipelineVersionActivity:
assert result.is_v3 is expected_is_v3
mock_v3_check.assert_called_once_with(TEAM_ID, "Stripe")
+ @pytest.mark.parametrize(
+ "ingest_mode, expected_is_v3",
+ [
+ ("buffered", True),
+ ("legacy", False),
+ ],
+ ids=["flipped_forces_v3", "unflipped_follows_flag"],
+ )
+ @patch(f"{MODULE}.is_pipeline_v3_enabled", return_value=False)
+ @patch(f"{MODULE}.ExternalDataSchema")
+ @patch(f"{MODULE}.ExternalDataSource")
+ @patch(f"{MODULE}.close_old_connections")
+ @patch(f"{MODULE}.bind_contextvars")
+ def test_buffered_cdc_consumption_overrides_the_flag(
+ self,
+ _bind: MagicMock,
+ _close: MagicMock,
+ mock_source_model: MagicMock,
+ mock_schema_model: MagicMock,
+ _mock_v3_check: MagicMock,
+ ingest_mode: str,
+ expected_is_v3: bool,
+ ) -> None:
+ schema = MagicMock()
+ schema.is_cdc = True
+ schema.cdc_mode = "streaming"
+ schema.cdc_table_mode = "consolidated"
+ schema.initial_sync_complete = True
+ schema.source.job_inputs = {"cdc_ingest_mode": ingest_mode}
+ mock_schema_model.objects.filter.return_value.select_related.return_value.first.return_value = schema
+ mock_source_model.objects.get.return_value = MagicMock(source_type="Postgres")
+
+ result = check_pipeline_version_activity(
+ CheckPipelineVersionActivityInputs(team_id=TEAM_ID, source_id=SOURCE_ID, schema_id=SCHEMA_ID)
+ )
+
+ assert result.is_v3 is expected_is_v3
+
+ @patch(f"{MODULE}.is_pipeline_v3_enabled", return_value=True)
+ @patch(f"{MODULE}.ExternalDataSchema")
+ @patch(f"{MODULE}.ExternalDataSource")
+ @patch(f"{MODULE}.close_old_connections")
+ @patch(f"{MODULE}.bind_contextvars")
+ def test_a_missing_schema_row_falls_back_to_the_flag(
+ self,
+ _bind: MagicMock,
+ _close: MagicMock,
+ mock_source_model: MagicMock,
+ mock_schema_model: MagicMock,
+ _mock_v3_check: MagicMock,
+ ) -> None:
+ mock_schema_model.objects.filter.return_value.select_related.return_value.first.return_value = None
+ mock_source_model.objects.get.return_value = MagicMock(source_type="Postgres")
+
+ result = check_pipeline_version_activity(
+ CheckPipelineVersionActivityInputs(team_id=TEAM_ID, source_id=SOURCE_ID, schema_id=SCHEMA_ID)
+ )
+
+ assert result.is_v3 is True
+
@patch(f"{MODULE}.ExternalDataSource")
@patch(f"{MODULE}.close_old_connections")
@patch(f"{MODULE}.bind_contextvars")
diff --git a/products/warehouse_sources/backend/tests/management/test_migrate_cdc_source_to_buffered.py b/products/warehouse_sources/backend/tests/management/test_migrate_cdc_source_to_buffered.py
index 303bee7489a8..28a33f55533b 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
@@ -10,6 +10,7 @@ from django.core.management.base import CommandError
from parameterized import parameterized
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
@@ -24,7 +25,6 @@ _CMD = "products.warehouse_sources.backend.management.commands.migrate_cdc_sourc
def _mocked_side_effects(
oldest_batch_age: float | None = None,
write_resolution: bool = True,
- pipeline_v3: bool = True,
buffer_keys: list[str] | None = None,
buffer_keys_by_schema: dict[str, list[str]] | None = None,
extraction_running: bool = False,
@@ -53,7 +53,6 @@ def _mocked_side_effects(
patch(f"{_CMD}.psycopg.Connection.connect") as mock_connect,
patch(f"{_CMD}.BatchQueue.get_oldest_non_terminal_batch_age_seconds", return_value=oldest_batch_age),
patch(f"{_CMD}.is_cdc_write_resolution_enabled", return_value=write_resolution),
- patch(f"{_CMD}.is_pipeline_v3_enabled", return_value=pipeline_v3),
patch(f"{_CMD}.purge_buffer_prefix") as mock_purge,
patch("products.data_warehouse.backend.facade.api.get_s3_client", return_value=s3),
patch(
@@ -309,20 +308,6 @@ class TestMigrateCDCSourceToBuffered(BaseTest):
assert "cdc_ingest_mode" not in source.job_inputs
mocks["pause"].assert_not_called()
- def test_flipping_a_v2_pipeline_team_is_refused(self):
- # v2 has no position resolution: nothing records a load position, so the consumer re-merges
- # the whole buffer on every sync and never deletes a file.
- source = self._source()
- self._schema(source, "users")
-
- with _mocked_side_effects(pipeline_v3=False) as mocks:
- with pytest.raises(CommandError, match="requires v3"):
- self._run(source)
-
- source.refresh_from_db()
- assert "cdc_ingest_mode" not in source.job_inputs
- mocks["pause"].assert_not_called()
-
def test_rollback_does_not_need_write_resolution(self):
source = self._source(ingest_mode="buffered")
self._schema(source, "users")
@@ -348,6 +333,28 @@ class TestMigrateCDCSourceToBuffered(BaseTest):
mocks["pause"].assert_called_once()
mocks["unpause"].assert_not_called()
+ def test_the_flip_waits_out_a_running_scheduled_sync(self):
+ # A sync that started legacy resolves its pipeline version before the mode changes; letting
+ # it straddle the change would consume the buffer on that stale version.
+ source = self._source()
+ schema = self._schema(source, "users")
+ ExternalDataJob.objects.create(
+ team_id=self.team.pk,
+ pipeline_id=source.id,
+ schema_id=schema.id,
+ status=ExternalDataJob.Status.RUNNING,
+ rows_synced=0,
+ )
+
+ with _mocked_side_effects() as mocks:
+ with pytest.raises(CommandError, match="still running"):
+ self._run(source, drain_timeout=0)
+
+ source.refresh_from_db()
+ assert "cdc_ingest_mode" not in source.job_inputs
+ mocks["pause_schema"].assert_called_once_with(str(schema.id))
+ mocks["unpause"].assert_not_called()
+
def test_the_flip_waits_out_an_in_flight_extraction_run(self):
# A legacy run with the shadow lane on keeps writing buffer files after the schedule pauses;
# one landing after the purge would be merged on top of rows legacy already delivered.