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): serve cdc_only and both table modes from the buffer (#91006)

Daniel RC271ceb161ffc
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.md
index 92f72566fa30..c3d475f1451f 100644
--- a/docs/internal/cdc-buffered-ingress-runbook.md
+++ b/docs/internal/cdc-buffered-ingress-runbook.md
@@ -13,32 +13,129 @@ other source.
The point is that a stalled load can no longer hold the customer's WAL. It spends our S3 retention
instead.
-**Only consolidated schemas move.** `cdc_only` and `both` schemas produce two tables per run, which
-one pipeline run cannot express, so they stay on legacy extraction. A source with a mix runs
-hybrid — some schemas buffered, the rest unchanged — and keeps its backpressure guard for the
-legacy ones.
+**Every streaming table mode moves.** A run reads the buffer once and writes every table the mode
+feeds, so `both` keeps its two tables at the same freshness as `consolidated` keeps its one.
+
+**Each table gets its own job.** A `both` run creates a second `ExternalDataJob` for the `_cdc`
+table, exactly as the legacy CDC extraction already does, and writes both from one read. That is
+what keeps the load queue out of it: a job is where batch idempotency, S3 staging paths, claim
+ordering and completion all hang, so two tables under one job would collide on every one of them,
+while two jobs are two ordinary single-table runs the loader already knows how to finish.
+
+The companion job carries no `workflow_run_id` and is not billable. The schema's own job owns the
+v3 pipeline lock, and a second holder releasing it would free the lock while the run is still
+writing; one read of a change stream is one sync however many tables it keeps, so only the
+consolidated table's rows count towards usage. Its `schema_snapshot` records `cdc_write_mode` and
+`companion_of`, which name the run it belongs to. If extraction fails, the activity marks its own
+companion jobs failed — the stranded sweep finds runs by their queued batches, so a companion that
+failed before staging anything has none to be found by.
+
+Only a source that declares lanes runs the lane code. Every other source runs `PipelineV3` as it
+was: the base class is the single-table path with extract-method seams, and `LanedPipelineV3` in
+`pipeline_v3/lanes.py` overrides those seams. The activity picks the class from
+`SourceResponse.lanes`. The load queue, the producer and the loader carry nothing about lanes at
+all, so a single-table run finalizes exactly as before.
+
+Schemas still snapshotting stay on legacy extraction until their first sync completes. A source
+with a mix runs hybrid — some schemas buffered, the rest unchanged — and keeps its backpressure
+guard for the legacy ones.
+
+**Buffer files are deleted at the start of the next run**, before they are read, so the run that
+proves a file consumed is never the run that deletes it. A file goes when it is strictly below the
+floor — the lowest position any of the schema's tables holds — or when it sits exactly at the floor
+and predates a listing by a run that went on to complete every table it writes. The floor alone is
+not enough at its own boundary: capture flushes a transaction bigger than its budget across several
+files that all carry that transaction's commit position, so a file at the floor may be the unread
+tail of one. A completed listing is what proves otherwise. For a `both` run, both jobs have to have
+completed, or a file could be deleted while the history table still owed it.
+
+**A lane resumes from its own table.** A failed run can leave one table holding rows the other does
+not, so each reads back the highest commit position it holds. The merge lane drops only what is
+below that position: re-applying a row it holds is a no-op upsert, and dropping a row AT the
+position would lose a later event for a key the table happens to hold at that same commit.
+
+The append (`_cdc`) lane has no upsert, so a row written twice stays twice. It also reads back the
+rows its table holds at that exact position, keyed by primary key and operation, and drops a batch
+row only when that identity is one of them. A multiset, not a set: one transaction can change the
+same key more than once and history keeps every version, so each match spends one. This is what
+tells a row a previous run wrote from one nothing has seen — including a file capture wrote after
+that run listed the buffer, which a bare count of rows at the position would have silently skipped.
+
+Reading it back rather than recording it beside the table is what removes the crash window: a value
+kept anywhere else can be lost between the write landing and the record of it, which either loses
+changes or writes them twice. Nothing about a run is written to `sync_type_config`.
+
+Delta keeps per-file min/max for its first 32 columns only, and the position column sits past that
+on any real table. So every table a buffered lane writes declares `delta.dataSkippingStatsColumns`
+naming the position column, its primary keys, and for the history table its SCD2 `valid_to`.
+
+Naming any column replaces the default window rather than extending it, so the declaration repeats
+the table's own first 32 columns ahead of those. Without that repetition a schema flip would strip
+the min/max off every column the customer queries, and this property is the only thing that sets
+them. Legacy CDC tables never reach the lane build, so the property is never declared on them.
+
+A merge table whose files carry no statistic for the position column reports no position and
+re-applies rows as upserts, which is a no-op. A history table cannot afford that, since a replay it
+does not recognise is a second copy of every row, so it falls back to scanning the position column
+once and logs `cdc_position_scanned`. The next write lands with the statistic and the scan stops.
+One such log line after a repartition is expected; the same line on every tick means the property
+is not being accepted, and `cdc_position_stats_property_not_set` alongside it says why. Alert on
+the pair: that table is paying a full column read every five minutes.
+
+A repartition carries the live table's properties onto the rebuilt one, so its files keep the
+statistic and nothing pauses.
+
+The history lane reads back every row at its position, with its content, to tell a replay from a
+new change. One bulk transaction can put millions of rows at one position, and reading them all
+back every tick until the next change lands would exhaust memory before that change could be
+staged. The rows are read a batch at a time, and only the rows _at the position_ count — a
+compacted file holds most of the table, but the read filters it. Past `MAX_POSITION_ROWS` rows or
+`MAX_POSITION_BYTES` of Arrow memory the lane keeps only the key columns from then on, logs
+`cdc_position_identity_degraded`, and matches on key and operation alone for that tick; a bulk
+change touches each key once, so nothing is lost by it. One such line per bulk change is expected.
+The same line on every tick means the table's newest transaction is huge and nothing has landed
+since — look at the source.
+
+A **merge** table whose files never gain the statistic replays safely but never advances the
+floor: no file is deleted, and the buffer is re-merged and re-billed every tick. It logs
+`cdc_position_unreadable` each tick. Alert on it; the writer is not honoring the property.
+
+**First run after this deploys.** Every already-flipped `consolidated` table declares the
+statistics property on its first run, and a table wider than 32 columns reports no position on that
+run, since none of its files carries the statistic yet. Its residual buffer is merged once more and
+billed once; the next write lands with the statistic and the position reads normally from then on.
+
+**A run stands down while any delivery for the schema is still in the queue** — a legacy one, or a
+previous attempt of this same job. Both would write alongside whatever this run reads, and on the
+append lane that is a second copy of the same history. Two scheduled runs cannot overlap on their
+own: the v3 pipeline lock is held from the start of the workflow until the loader completes the
+job. The window is a retried activity, which runs under the lock its own workflow already holds,
+and a lock takeover, which hands the lock to a new job while the old one's batches are still
+queued. The run returns an empty response, which no-ops the tick and keeps the schedule alive. Nothing is
+listed, so nothing is read, nothing is deleted, and the tick never counts as proof that a file was
+consumed. The next scheduled run picks the buffer up once the queue has drained.
Nothing is re-snapshotted. The slot, the Delta tables, and `initial_sync_complete` are all
preserved, so there is no WAL gap and no re-sync.
## Before flipping
-0. 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
+0. Pipeline version needs no preparation: the scheduled sync forces the v3 pipeline for every
+ buffered schema, because only the v3 loader deletes the buffer files a completed job read. 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
- changes. That is unrecoverable loss, not a stall. Rollback does not require the flag.
- **The flag must also stay on after the flip** — turning it off later freezes the load position,
- and the symptom is a frozen `cdc_load_position` with buffer files aging toward the TTL.
+ 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** —
the name is reserved for change ordering, and capture hard-errors on the collision rather than
- writing files whose ordering and retry cleanup derive from customer data. A schema that already
- consumed the buffer carries the column for our own reasons, and its recorded load position tells
- the check apart from a real collision, so a re-flip after a rollback is not blocked by it.
+ writing files whose ordering and retry cleanup derive from customer data. A source already on
+ buffered carries the column for our own reasons, so the check only applies to a source still on
+ legacy 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
when an eligible schema is off cadence — consumption paces to the schema's own schedule.
4. Buffer validation is clean over a busy window:
@@ -47,6 +144,12 @@ preserved, so there is no WAL gap and no re-sync.
python manage.py validate_cdc_buffer --source-id <uuid> --since-hours 40
```
+ Capture stops writing shadow copies the moment a source is buffered: a schema not yet served
+ would otherwise accumulate files the consumer merges the day it turns eligible, on top of what
+ the 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.
+
5. Check what will move:
```bash
@@ -57,6 +160,20 @@ 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.
+
```bash
python manage.py migrate_cdc_source_to_buffered --source-id <uuid>
```
@@ -64,9 +181,10 @@ 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,
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.
+`sourcebatch` batches to reach a terminal state, retires any companion job a hard kill left
+Running, 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
@@ -89,9 +207,8 @@ deferred backlog lands.
- Capture writes files under the schema's prefix and advances the slot (`cdc_last_log_position`
moves).
-- The next scheduled sync merges and advances `sync_type_config["cdc_load_position"]`.
-- Consumed files disappear on the run **after** the one that read them — deletion follows the
- committed position, not the read.
+- The next scheduled sync writes every table the mode feeds, from one read.
+- The files that run read disappear at the start of a later run, once every table is past them.
- Row counts track the pre-flip day.
- `warehouse_load_cdc_delete_enrichment_violations_total` stays at zero.
- The schema's status in the Syncs UI now comes from the scheduled sync alone — capture heartbeats
@@ -99,6 +216,13 @@ deferred backlog lands.
## Rollback
+> [!IMPORTANT]
+> Roll the source back to legacy **before** rolling the code back, and flip a `cdc_only` or `both`
+> schema only once a deploy has finished rolling. A worker on the previous release does not treat
+> those modes as buffered: it routes the schema into `CDCHandledExternally`, which pauses the
+> per-schema schedule permanently. Capture keeps filling the buffer and advancing the slot while
+> nothing consumes it, until the files age out of S3 retention.
+
```bash
python manage.py migrate_cdc_source_to_buffered --source-id <uuid> --rollback
```
@@ -112,12 +236,16 @@ The order matters, and the command enforces it:
3. **Wait for the consumer to drain the buffer.** The buffer's tail holds WAL the slot has already
advanced past — it exists nowhere else, and flipping to legacy before it is applied loses it for
good. The command refuses to proceed (extraction left paused, consumer left running) until every
- remaining file sits strictly below the schema's load position. A file ending exactly at the
- position does not count: one transaction shares a commit position across its events, so that file
- can still be the unread tail of a transaction split across files. The consumer settles it by
- deleting the file once a completed run proves it read it, which takes a tick or two.
-4. Pause the per-schema schedules and wait for running sync jobs, so no in-flight merge of old
- buffered rows can land after legacy delivery resumes and overwrite newer rows.
+ file is gone. The consumer deletes a file at the start of a run once every table the mode
+ feeds is past it, so an empty prefix is its own proof that every change reached every table.
+ The last file needs two completed runs after it was written: one to list it, and the next to
+ find that listing older than the file by the deletion margin. At the 5-minute cadence that
+ fits inside the drain timeout; a schema whose schedule is paused or slower than that holds
+ the drain open, and the command says which schema is behind when it gives up.
+4. Pause the per-schema schedules, wait for running sync jobs and for in-flight `sourcebatch`
+ batches, then retire any companion job a hard kill left Running — nothing else can, once the
+ schedules are paused. No in-flight merge of old buffered rows can then land after legacy
+ delivery resumes and overwrite newer rows.
5. Set the mode to `legacy` and unpause the extraction schedule.
The buffer-drain check covers every schema the buffered lane serves, including ones disabled after
@@ -126,10 +254,16 @@ schema so its sync can catch up first. It skips the schemas that stayed on legac
lane on, their prefixes hold validation copies no consumer reads, so scanning them would block the
rollback forever with capture paused.
-Fully-applied buffer files are **not** purged: the position guard makes a replay a no-op, and the
-14-day S3 TTL clears them. Rows already merged stay merged — the same rows the legacy lane would
+Fully-applied buffer files are **not** purged: the completed job already deleted them, and the
+14-day S3 TTL clears anything left. Rows already merged stay merged — the same rows the legacy lane would
have written.
+**If the command dies partway, re-run it.** Every step is idempotent, and the mode flips in the last
+one, so an interrupted rollback leaves the source on `buffered` with some or all of its schedules
+paused. That state moves no data and raises no alert of its own: capture is not running, so nothing
+reports a stall. Re-running walks the same steps and finishes them. A source paused with
+`cdc_ingest_mode` still `buffered` and no failing job is the signature to look for.
+
## Buffer expiry — no partial recovery
Buffer files expire after 14 days (`expire-cdc-producer-buffer`). If a schema stops consuming —
@@ -161,12 +295,19 @@ a retry-heavy period is the signal to revisit. Candidate fixes are costed in the
## Billing
-Consume runs are ordinary jobs: `billable=True`, `rows_synced` = consumed rows. A consolidated
-source bills the same change events once per run, so the flip is billing-neutral by construction.
-One bounded exception: the trailing file of a burst is re-read for a tick or two until a completed
-run proves it consumed and it is deleted — rows at the recorded position re-apply as no-op upserts
-in that window, never perpetually.
+Consume runs are ordinary jobs: `billable=True`, `rows_synced` = consumed rows.
+
+**One read of the change stream bills once, whatever it feeds.** A run counts one table's rows
+towards usage: the `_cdc` table for `cdc_only`, and the consolidated table for `consolidated` and
+`both`. So `both` bills the same as `consolidated`, and keeping a history table alongside the merged
+one costs nothing extra.
+
+This changes what `both` used to cost. Legacy extraction writes the two tables from two
+`ExternalDataJob` rows and counts each event twice; buffered writes them from one and counts once.
+Sources on `both` will see their synced-row count roughly halve when they flip.
-Note for later: `both`-mode schemas create two `ExternalDataJob` rows per run, each carrying
-`rows_synced`, so those customers are double-billed today. Buffered ingress halves it. That lands
-with the companion lane, not this flip.
+**The merge lane re-bills the rows at its position until the file holding them is deleted.** It
+keeps every row at its position deliberately, since dropping one would lose a later event for the
+same key at that same commit, and a kept row is a staged row. That is one transaction's rows, for
+the tick or two until the completed-listing proof clears the file. The history lane matches those
+rows by content and bills none of them.
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 53608567ba3b..84438e02f722 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
@@ -1,7 +1,7 @@
"""Flip one CDC source between legacy extraction and buffered ingress.
In place: the slot, the tables, and `initial_sync_complete` are all preserved, so there is no
-re-snapshot and no WAL gap. Only consolidated schemas move — see `cdc/source_manager.py`.
+re-snapshot and no WAL gap. Which schemas move is `serves_buffered_lane` — see `cdc/source_manager.py`.
"""
from __future__ import annotations
@@ -18,7 +18,10 @@ import structlog
from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_schema import (
+ ExternalDataSchema,
+ update_sync_type_config_keys,
+)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN
from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import (
@@ -26,13 +29,15 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import
parse_buffer_file_name,
purge_buffer_prefix,
)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.companion_jobs import retire_orphaned_companions
from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import (
WRITE_RESOLUTION_FLAG,
is_cdc_write_resolution_enabled,
- read_load_position,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
- consolidated_resource_name,
+ 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 (
@@ -50,8 +55,25 @@ DRAIN_POLL_SECONDS = 10
EXPECTED_SYNC_INTERVAL = dt.timedelta(minutes=5)
+def _ineligible_reason(schema: ExternalDataSchema) -> str:
+ """Why this schema stays on legacy — the condition that failed, not its table mode.
+
+ Every table mode is served now, so printing the mode says nothing about why a schema was
+ skipped.
+ """
+ if not schema.should_sync:
+ return "disabled"
+ if not schema.is_cdc:
+ return "not cdc"
+ if schema.cdc_mode != "streaming":
+ return f"cdc_mode={schema.cdc_mode}"
+ if not schema.initial_sync_complete:
+ return "initial sync incomplete"
+ return f"table mode {schema.cdc_table_mode}"
+
+
class Command(BaseCommand):
- help = "Move a CDC source onto buffered ingress (or back). Consolidated schemas only."
+ help = "Move a CDC source onto buffered ingress (or back)."
def add_arguments(self, parser: Any) -> None:
parser.add_argument("--source-id", required=True, help="ExternalDataSource UUID")
@@ -82,23 +104,36 @@ 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.
- eligible = [s for s in cdc_schemas if s.should_sync and serves_buffered_lane(s)]
- ineligible = [s for s in cdc_schemas if s not in eligible]
current_mode = (source.job_inputs or {}).get("cdc_ingest_mode", "legacy")
+ 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]
- self._report(source, current_mode, target_mode, eligible, ineligible)
+ self._report(source, current_mode, target_mode, eligible, ineligible, already_served)
if 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.")
+ )
+ return
raise CommandError(
"No schema on this source serves the buffered lane — nothing to flip. "
- "Buffered ingress covers consolidated streaming schemas whose initial sync is done."
+ "Buffered ingress covers streaming schemas whose initial sync is done, in any table mode."
)
- if current_mode == target_mode:
- self.stdout.write(self.style.WARNING(f"Already {target_mode}; nothing to do."))
+ if rollback and current_mode == target_mode:
+ self.stdout.write(self.style.WARNING("Already legacy; nothing to do."))
return
if not rollback:
# No pipeline-version gate: the scheduled sync forces the v3 pipeline for
- # buffered-consolidated schemas (scheduled_sync_consumes_buffer), so the flip does
+ # 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)
@@ -109,7 +144,7 @@ class Command(BaseCommand):
if rollback:
self._roll_back(source, eligible, cdc_schemas, options["drain_timeout"])
else:
- self._flip_to_buffered(source, eligible, options["drain_timeout"])
+ 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.
@@ -121,9 +156,9 @@ class Command(BaseCommand):
if is_cdc_write_resolution_enabled(source.team_id, str(eligible[0].id), f"preflight-{source.id}"):
return
raise CommandError(
- f"{WRITE_RESOLUTION_FLAG} is off for team {source.team_id}. Buffered ingress needs it: "
- "without it no load position is recorded, consumed files are never deleted, and they "
- "expire at the S3 TTL with the slot already advanced past them."
+ 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:
@@ -132,16 +167,28 @@ class Command(BaseCommand):
The collision stops the batcher stamping the engine position, and capture hard-errors on it
(CDCReservedColumnError) — catching it here keeps the source out of a flip-then-break loop.
- The buffered lane writes its own `_ph_cdc_seq` into the warehouse table, so the column alone
- proves nothing once a schema has consumed the buffer. A recorded load position is proof the
- column is ours: capture would have hard-errored on a real collision before any file existed.
+ The buffered lane writes its own `_ph_cdc_seq` into the warehouse table, so the column
+ proves nothing once a source has been buffered — capture would have hard-errored on a real
+ collision before any file existed, and a rollback leaves the column behind. Only on a
+ source that has never been buffered can the column be the source's own, and only there is
+ this check able to tell the two apart.
"""
+ if not eligible:
+ return
+ # Waived per schema: one this lane wrote to before carries its own `_ph_cdc_seq`. A
+ # consolidated schema flipped before the per-schema marker existed has only the source's
+ # marker (stored through `job_inputs`, which stringifies, so "False" is never written).
+ source_buffered_before = bool((eligible[0].source.job_inputs or {}).get("cdc_buffered_before"))
+
+ def waived(s: ExternalDataSchema) -> bool:
+ return bool(s.sync_type_config.get(BUFFERED_BEFORE_KEY)) or (
+ source_buffered_before and s.cdc_table_mode == "consolidated"
+ )
+
conflicted = [
s.name
for s in eligible
- if s.table is not None
- and CDC_SEQ_COLUMN in (s.table.columns or {})
- and read_load_position(s.sync_type_config, consolidated_resource_name(s)) is None
+ if not waived(s) and s.table is not None and CDC_SEQ_COLUMN in (s.table.columns or {})
]
if conflicted:
raise CommandError(
@@ -156,9 +203,14 @@ 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(
@@ -168,9 +220,7 @@ class Command(BaseCommand):
)
)
if ineligible:
- detail = ", ".join(
- f"{s.name} [{'disabled' if not s.should_sync else s.cdc_table_mode}]" for s in ineligible
- )
+ detail = ", ".join(f"{s.name} [{_ineligible_reason(s)}]" for s in ineligible)
self.stdout.write(self.style.WARNING(f" staying on legacy ({len(ineligible)}): {detail}"))
self.stdout.write(
self.style.WARNING(
@@ -179,7 +229,11 @@ class Command(BaseCommand):
)
def _flip_to_buffered(
- self, source: ExternalDataSource, eligible: list[ExternalDataSchema], drain_timeout: int
+ self,
+ source: ExternalDataSource,
+ eligible: list[ExternalDataSchema],
+ cdc_schemas: list[ExternalDataSchema],
+ drain_timeout: int,
) -> None:
from products.data_warehouse.backend.facade.api import (
pause_cdc_extraction_schedule,
@@ -207,21 +261,35 @@ class Command(BaseCommand):
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._retire_orphaned_companions(eligible)
+
+ # Pre-flip files were already delivered by the legacy lane, whose rows carry no position,
+ # so nothing in the table could tell a replay of them from new changes. Every CDC schema is
+ # purged, not just the eligible ones: a schema still snapshotting today becomes eligible on
+ # its first completed sync, and would otherwise inherit whatever the shadow lane left here.
+ # On a source already buffered, the schemas it serves hold files the consumer still owes,
+ # so only the schemas moving now are purged.
+ already_buffered = (source.job_inputs or {}).get("cdc_ingest_mode") == "buffered"
+ to_purge = eligible if already_buffered else cdc_schemas
self.stdout.write("5/7 purging pre-flip buffer files")
- for schema in eligible:
+ for schema in to_purge:
purge_buffer_prefix(source.team_id, str(schema.id), logger)
- self._verify_prefixes_empty(source.team_id, eligible)
+ self._verify_prefixes_empty(source.team_id, to_purge)
# 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"}
+ self.stdout.write("6/7 setting cdc_ingest_mode=buffered and marking the schemas served")
+ source.job_inputs = {
+ **(source.job_inputs or {}),
+ "cdc_ingest_mode": "buffered",
+ # 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.
+ "cdc_buffered_before": True,
+ }
source.save(update_fields=["job_inputs"])
+ self._mark_schemas(eligible, served=True)
self.stdout.write("7/7 unpausing schedules")
unpause_cdc_extraction_schedule(source_id)
@@ -229,8 +297,8 @@ class Command(BaseCommand):
self.stdout.write(self.style.SUCCESS(f"Source {source_id} is now buffered."))
self.stdout.write(
- "Verify: capture writes buffer files and advances the slot; the next sync merges and "
- 'advances sync_type_config["cdc_load_position"]; consumed files disappear on the run after.'
+ "Verify: capture writes buffer files and advances the slot; the next sync writes every "
+ "table the mode feeds; a later sync deletes the files once every table is past them."
)
def _roll_back(
@@ -269,9 +337,19 @@ class Command(BaseCommand):
self.stdout.write("4/6 pausing per-schema schedules")
self._pause_schema_schedules_strict(eligible)
self._wait_for_running_sync_jobs(source.team_id, [str(s.id) for s in eligible], drain_timeout)
-
- self.stdout.write("5/6 setting cdc_ingest_mode=legacy")
- source.job_inputs = {**(source.job_inputs or {}), "cdc_ingest_mode": "legacy"}
+ self._wait_for_sourcebatch_drain(source.team_id, [str(s.id) for s in eligible], drain_timeout)
+ self._retire_orphaned_companions(eligible)
+
+ self.stdout.write("5/6 setting cdc_ingest_mode=legacy and unmarking the schemas")
+ self._mark_schemas(eligible, served=False)
+ source.job_inputs = {
+ **(source.job_inputs or {}),
+ "cdc_ingest_mode": "legacy",
+ # 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.
+ "cdc_buffered_before": True,
+ }
source.save(update_fields=["job_inputs"])
# Leftover fully-applied files stay: the position guard no-ops a replay, the S3 TTL clears them.
@@ -280,6 +358,27 @@ class Command(BaseCommand):
self.stdout.write(self.style.SUCCESS(f"Source {source_id} is now legacy."))
+ 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.
+
+ Merged under the row lock: the runs this command waited out wrote their own keys into the
+ same 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],
+ )
+
+ def _retire_orphaned_companions(self, schemas: list[ExternalDataSchema]) -> None:
+ """A companion left Running by a hard kill is retired only at a run's start, and the
+ schedules are paused by now — so retire it here, once nothing can still be writing to it."""
+ for schema in schemas:
+ for job_id in retire_orphaned_companions(schema):
+ self.stdout.write(f" retired orphaned companion job {job_id} ({schema.name})")
+
def _wait_for_extraction_idle(self, source_id: str, timeout: int) -> None:
from products.data_warehouse.backend.facade.api import cdc_extraction_schedule_has_running_action
@@ -294,14 +393,13 @@ class Command(BaseCommand):
time.sleep(DRAIN_POLL_SECONDS)
def _wait_for_buffer_drain(self, team_id: int, schemas: list[ExternalDataSchema], timeout: int) -> None:
- """Block until every remaining buffer file sits strictly below the schema's load position.
-
- A file AT the position is not proof of consumption: one Postgres transaction shares a commit
- position across every event, so a transaction split across files leaves an unread tail whose
- `end_seq` already equals the floor, and `drop_superseded_rows` keeps rows at the watermark
- precisely so that tail can still land. The consumer settles it by deleting the file once a
- completed run proves it read it, so waiting for the deletion is the same proof the consumer
- uses — a couple of ticks on an idle schema.
+ """Block until no buffer file is left for any schema.
+
+ The consumer deletes a file at the start of a run once every table this schema feeds is
+ past it, so an empty prefix is the consumer's own proof that every change in it landed
+ everywhere. Extraction is already paused by this point, so nothing refills the prefix while
+ this waits — but the last file needs two more completed runs to clear: the first lists it
+ and the second finds that listing older than the file by the deletion margin.
"""
from products.data_warehouse.backend.facade.api import get_s3_client
@@ -310,26 +408,21 @@ class Command(BaseCommand):
while True:
behind: list[str] = []
for schema in schemas:
- schema.refresh_from_db(fields=["sync_type_config"])
- floor = read_load_position(schema.sync_type_config, consolidated_resource_name(schema)) or 0
prefix = strip_s3_protocol(get_buffer_prefix(team_id, str(schema.id)))
try:
keys = s3.ls(prefix, detail=False, refresh=True)
except FileNotFoundError:
continue
- for key in keys:
- parsed = parse_buffer_file_name(key.rsplit("/", 1)[-1])
- if parsed is not None and parsed.end_seq >= floor:
- behind.append(schema.name)
- break
+ if any(parse_buffer_file_name(key.rsplit("/", 1)[-1]) is not None for key in keys):
+ behind.append(schema.name)
if not behind:
return
if time.monotonic() >= deadline:
raise CommandError(
- f"Buffered changes not yet proven applied for: {', '.join(sorted(behind))} after "
+ f"Buffered changes not yet applied for: {', '.join(sorted(behind))} after "
f"{timeout}s. Rolling back now could lose them — the slot already advanced past that "
- "WAL, and the consumer deletes each file only once it proves it read it. Extraction "
- "is left paused; let the scheduled syncs catch up, then re-run."
+ "WAL, and the consumer deletes each file only once the job that read it completes. "
+ "Extraction is left paused; let the scheduled syncs catch up, then re-run."
)
self.stdout.write(f" waiting, buffer not drained for: {', '.join(sorted(behind))}")
time.sleep(DRAIN_POLL_SECONDS)
@@ -402,9 +495,14 @@ class Command(BaseCommand):
deadline = time.monotonic() + timeout
while True:
+ # A companion row outlives its run only as an orphan, which nothing here can finish
+ # and the drain step retires; the run it belongs to is the row waited on.
running = list(
ExternalDataJob.objects.filter(
- team_id=team_id, schema_id__in=schema_ids, status=ExternalDataJob.Status.RUNNING
+ team_id=team_id,
+ schema_id__in=schema_ids,
+ status=ExternalDataJob.Status.RUNNING,
+ schema_snapshot__companion_of__isnull=True,
).values_list("id", "created_at")
)
if not running:
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
index 5b9f81c63eb0..c38720f3a091 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
@@ -339,6 +339,10 @@ _CDC_EXPOSED_JOB_INPUT_KEYS = {
# Set by migrate_cdc_source_to_buffered, never by the API. Losing it on an unrelated PATCH
# would resume legacy delivery from an advanced slot and strand the unread buffer.
"cdc_ingest_mode",
+ # Also set only by that command. It is what lets a rolled-back source be flipped again: without
+ # it the reserved-column check reads the `_ph_cdc_seq` the buffered lane wrote as the source's
+ # own and refuses every later flip.
+ "cdc_buffered_before",
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
index 74bf25ee775a..d3adfc3ba562 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -46,10 +46,10 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.adapters impor
get_cdc_adapter,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (
- CDC_COMPANION_SUFFIX,
CDC_SEQ_COLUMN,
ChangeEventBatcher,
build_scd2_table,
+ companion_resource_name,
deduplicate_table,
enrich_delete_rows,
enrich_toast_omitted_rows,
@@ -760,7 +760,7 @@ class CDCExtractActivity:
batch_writes.append(
(
build_scd2_table(enriched_table, key_columns),
- f"{schema.name}{CDC_COMPANION_SUFFIX}",
+ companion_resource_name(schema.name),
"scd2_append",
)
)
@@ -772,7 +772,7 @@ class CDCExtractActivity:
batch_writes.append(
(
build_scd2_table(enriched_table, key_columns),
- f"{schema.name}{CDC_COMPANION_SUFFIX}",
+ companion_resource_name(schema.name),
"scd2_append",
)
)
@@ -938,13 +938,21 @@ 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)
+ # Shadow writes validate the buffer *before* a source is flipped. Past the flip they are
+ # a hazard: a schema not yet serving the lane (mid-snapshot, say) would accumulate shadow
+ # files under its own prefix, and the consumer would merge them the moment the schema
+ # turns eligible — re-delivering rows the legacy lane already wrote, which an append lane
+ # cannot absorb. The flip command purges the prefix once; nothing purges it again.
+ cdc_config = self.adapter.parse_cdc_config(self.source)
+ self._shadow_enabled = is_shadow_write_enabled(self.inputs.team_id, self.log) and (
+ cdc_config.ingest_mode != "buffered"
+ )
- if self.adapter.parse_cdc_config(self.source).ingest_mode == "buffered":
+ if cdc_config.ingest_mode == "buffered":
# A schema with deferred runs pending stays legacy this tick, so the flush and any new
# events travel one lane. Deferred batches carry no position column, so nothing orders
# them against buffered writes — mixing lanes lets an older deferred row land after a
- # newer buffered one. The consumer holds off too (has_pending_legacy_backlog).
+ # newer buffered one. The consumer holds off too (has_batches_in_flight).
self._buffered_table_names = {
s.name
for s in self.cdc_schemas
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py
index b06cece1adbf..568b9e13e9a9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py
@@ -5,6 +5,7 @@ from collections.abc import Callable
import pyarrow as pa
+from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCReservedColumnError
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent
# CDC metadata column names — database-agnostic
@@ -25,6 +26,18 @@ CDC_SEQ_PROVENANCE = {b"posthog_cdc": b"engine_position"}
# 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"
+
+
+def companion_resource_name(schema_name: str) -> str:
+ """Storage name for a schema's `_cdc` companion table.
+
+ Keyed on the schema's `name`, never its resolved folder: the companion is CDC-only and stays
+ self-consistent with its `name`-keyed snapshot seed. Capture, the snapshot seed and the
+ buffered consumer all write the same table, so they all resolve the name here.
+ """
+ return f"{schema_name}{CDC_COMPANION_SUFFIX}"
+
+
# 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
@@ -427,7 +440,21 @@ def build_scd2_table(pa_table: pa.Table, pk_columns: list[str]) -> pa.Table:
A two-step merge + append in the load processor closes previous "current"
rows (sets valid_to) when a new batch is written for the same PK.
"""
- ts_type = pa.timestamp("us", tz="UTC")
+ taken = {SCD2_VALID_FROM_COLUMN, SCD2_VALID_TO_COLUMN} & set(pa_table.column_names)
+ if taken:
+ # Delta refuses a duplicate column name at write time; failing here names the column and
+ # keeps a half-built batch out of the writer.
+ raise CDCReservedColumnError(
+ f"Source column(s) {sorted(taken)} collide with the history table's validity columns"
+ )
+ # Taken from the batch rather than assumed: `valid_from` is the timestamp column's own values,
+ # and declaring a type it does not have makes pyarrow reject the append outright. The buffered
+ # path normalizes timestamps to naive before this runs, the legacy path does not.
+ ts_type = (
+ pa_table.schema.field(CDC_TIMESTAMP_COLUMN).type
+ if CDC_TIMESTAMP_COLUMN in pa_table.column_names
+ else pa.timestamp("us", tz="UTC")
+ )
if pa_table.num_rows == 0:
return pa_table.append_column(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/companion_jobs.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/companion_jobs.py
new file mode 100644
index 000000000000..04d5c77c557d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/companion_jobs.py
@@ -0,0 +1,87 @@
+"""The second job row a `both` schema's run opens for its history table.
+
+Kept apart from the pipeline and the source manager so both can retire one without importing
+each other.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from django.db import transaction
+from django.utils import timezone
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+# On the schema's own job row: the companion job ids this run opened, so the listing proof can
+# check them by primary key rather than by an unindexed JSON predicate over the schema's history.
+COMPANION_JOB_IDS_KEY = "cdc_companion_job_ids"
+
+COMPANION_RETIRED_ERROR = "Extraction ended before this table's changes were written"
+
+
+def retire_companion_job(job_id: str) -> None:
+ """Take one Running companion job terminal, touching nothing else.
+
+ Written straight onto the row, as the legacy CDC path retires its own companions: the shared
+ status helper would repaint the customer's schema FAILED and fire a failure digest for a row
+ that is not the schema's own.
+ """
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+
+ ExternalDataJob.objects.filter(id=job_id, status=ExternalDataJob.Status.RUNNING).update(
+ status=ExternalDataJob.Status.FAILED,
+ latest_error=COMPANION_RETIRED_ERROR,
+ finished_at=timezone.now(),
+ )
+
+
+def retire_orphaned_companions(schema: ExternalDataSchema) -> list[str]:
+ """Retire this schema's Running companion jobs that no run owns any more.
+
+ A companion is opened by the run that needs it, and that run's `finally` retires it when
+ extraction fails — but a hard kill (OOM, SIGKILL) runs no `finally`. Nothing else knows the
+ row exists: the loader completes a job only on its final batch, which a dead run never sent;
+ the stranded sweep finds runs by their non-terminal batches, and the loader drains those to
+ `succeeded`. Left alone the row stays Running for good and blocks every flip and rollback.
+
+ Safe to call once `has_batches_in_flight` is false: no batch of any earlier run can still be
+ executing, so nothing is mid-write on a job this retires. That includes a companion an
+ earlier attempt of the caller's own job opened — the caller opens its own lazily, after
+ this runs, so any Running companion at this point belongs to a run that is gone.
+ """
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+
+ orphans = list(
+ ExternalDataJob.objects.filter(
+ team_id=schema.team_id,
+ pipeline_id=schema.source_id,
+ schema_id=schema.id,
+ status=ExternalDataJob.Status.RUNNING,
+ schema_snapshot__companion_of__isnull=False,
+ ).values_list("id", flat=True)
+ )
+ for job_id in orphans:
+ retire_companion_job(str(job_id))
+ return [str(j) for j in orphans]
+
+
+def record_companion_job(parent_job_id: str, team_id: int, companion_job_id: str, *, first_of_attempt: bool) -> None:
+ """Add a companion's id to its parent's row, so the parent's completion can vouch for it.
+
+ A new attempt starts the list over: an earlier attempt's companion was retired or drained by
+ the time this attempt reads, and leaving it listed would have the listing proof reject this
+ run for good.
+
+ Under the row lock, like every writer of this snapshot: the listing stamp shares the JSON,
+ and an attempt still alive past its timeout can write it between this read and this write.
+ """
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+
+ with transaction.atomic():
+ parent = ExternalDataJob.objects.select_for_update().get(id=parent_job_id, team_id=team_id)
+ snapshot = dict(parent.schema_snapshot or {})
+ earlier = [] if first_of_attempt else snapshot.get(COMPANION_JOB_IDS_KEY, [])
+ snapshot[COMPANION_JOB_IDS_KEY] = [*earlier, companion_job_id]
+ ExternalDataJob.objects.filter(id=parent.id).update(schema_snapshot=snapshot)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py
index 1d81c569b041..57ee8ede73e1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py
@@ -67,14 +67,19 @@ class CDCSlotNotConfiguredError(Exception):
class CDCReservedColumnError(Exception):
- """A source table carries a column whose name PostHog reserves for change ordering.
+ """A source table carries a column whose name PostHog stamps onto change rows.
Non-retryable: the collision is a property of the customer's table, so replaying re-fails.
- Raised only on the buffered-ingress path — buffer files derive their name, ordering, and
- retry cleanup from the engine position column, and a same-named source column means the
- batcher could not append it. Writing anyway would order and clean up by customer data,
- which can silently delete unconsumed buffer files. The legacy path is unaffected: it
- passes the customer's column through untouched.
+
+ For the engine position column it is raised only on the buffered-ingress path — buffer
+ files derive their name, ordering, and retry cleanup from it, and a same-named source column
+ means the batcher could not append it. Writing anyway would order and clean up by customer
+ data, which can silently delete unconsumed buffer files. The legacy path passes the
+ customer's column through untouched.
+
+ For the history table's validity columns it is raised on every path, from the SCD2 stamp
+ itself: Delta refuses the duplicate name at write time anyway, and failing before the writer
+ names the column instead of a qualified field in a schema error.
"""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/lane_position.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/lane_position.py
new file mode 100644
index 000000000000..db4477c8a334
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/lane_position.py
@@ -0,0 +1,354 @@
+"""How far a CDC lane's table already goes, read back from the table itself.
+
+A run that re-reads the buffer after a failed one must not write a change its predecessor already
+wrote. Where a lane stops is a fact about what its table holds, so it is read from the table rather
+than recorded beside it: a value kept anywhere else has a window where the write landed and the
+record of it did not, and a crash in that window either loses changes or writes them twice.
+
+Reading it is a statistics lookup. A merge table whose files carry no statistic reports no position
+and re-applies rows as upserts, which is harmless. A history table cannot afford that — a replay it
+cannot recognize is a second copy of every row — so it falls back to scanning the column once, until
+the next write carries the statistic again.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from collections import Counter, defaultdict
+from collections.abc import Callable
+from functools import partial
+from typing import TYPE_CHECKING, Any, cast
+from urllib.parse import unquote
+
+import pyarrow as pa
+import structlog
+import pyarrow.compute as pc
+import pyarrow.dataset as pa_ds
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (
+ CDC_SEQ_COLUMN,
+ SCD2_VALID_FROM_COLUMN,
+ SCD2_VALID_TO_COLUMN,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import normalize_column_name
+
+if TYPE_CHECKING:
+ import deltalake
+
+logger = structlog.get_logger(__name__)
+
+# The position column is appended after the source's own, so on a wide table it falls outside the
+# window Delta indexes by default. Naming it here is what makes the resume point a stats lookup
+# rather than a scan of the whole column.
+STATS_COLUMNS_PROPERTY = "delta.dataSkippingStatsColumns"
+
+# Delta's own default for `delta.dataSkippingNumIndexedCols`, restated because naming any column
+# at all overrides it.
+_DEFAULT_INDEXED_COLUMNS = 32
+
+# Rows at one position above which the history lane matches on key and operation alone. Each
+# row is read back as a Python dict of every content column; on a wide table this is the point
+# where that stops fitting alongside the batch being staged.
+MAX_POSITION_ROWS = 100_000
+
+# The same cutoff by the Arrow memory those rows occupy as they are read, since the row cap alone
+# lets a wide, JSON-heavy transaction read back gigabytes. The Python objects built from them run
+# several times larger, which is what this number allows for.
+MAX_POSITION_BYTES = 64 * 1024 * 1024
+
+# Rows per batch as the position is read: the caps are checked between batches, so this is how
+# far past them one read can go.
+_POSITION_BATCH_ROWS = 8_192
+
+_MAX_STAT = f"max.{CDC_SEQ_COLUMN}"
+_NULL_COUNT_STAT = f"null_count.{CDC_SEQ_COLUMN}"
+
+
+@frozen
+class LanePosition:
+ """Where a lane's table stops, and which rows it holds at that exact position.
+
+ One Postgres transaction stamps every event it carries with the same commit position, and a
+ transaction bigger than the flush budget spans several buffer files. So the position alone
+ cannot say whether that transaction finished — `applied` is what tells a row the table already
+ holds from one it has never seen, and it is a multiset because the same key can change more
+ than once inside one transaction.
+ """
+
+ position: int | None
+ # Rows the table holds AT the position, grouped by `(pk…, op)`, each as its own content. The
+ # group is what a batch row is matched against, and the content is what tells two changes to
+ # one key inside one transaction apart: they share every key, and only their values differ.
+ applied: dict[tuple[Any, ...], list[dict[str, Any]]]
+ # The columns `applied` is grouped by, in order. Carried with it so the filter that spends it
+ # keys its batch rows exactly the same way, even when the table lacks one of them.
+ key_columns: tuple[str, ...] = ()
+ # Arrow types of the content columns as the table stores them, so a batch is cast to them
+ # before its values are compared. `None` when there is nothing to compare against.
+ content_schema: pa.Schema | None = None
+ # False above the position-row cap: `applied` then carries keys only, and a batch row is
+ # matched on key and operation alone.
+ content_matched: bool = True
+ # Reads the rows at the position into a resolved copy of this. Deferred so a tick whose
+ # buffer holds nothing at the position — every idle tick — never reads them at all.
+ load_applied: Callable[[], LanePosition] | None = None
+
+
+EMPTY_POSITION = LanePosition(position=None, applied={}, key_columns=())
+
+# Columns that never take part in a content comparison: the position and operation are the key,
+# the SCD2 pair is stamped after replay, and the TOAST marker names columns to leave out per row.
+NON_CONTENT_COLUMNS = frozenset({SCD2_VALID_FROM_COLUMN, SCD2_VALID_TO_COLUMN})
+
+
+def content_columns(names: list[str]) -> list[str]:
+ return [n for n in names if not n.startswith("_ph_") and n not in NON_CONTENT_COLUMNS]
+
+
+def _has_position_column(delta_table: deltalake.DeltaTable) -> bool:
+ return any(field.name == CDC_SEQ_COLUMN for field in delta_table.schema().fields)
+
+
+def _stats_max(add_actions: pa.Table) -> int | None:
+ """The highest position the per-file statistics prove, or None if no file carries one."""
+ if _MAX_STAT not in add_actions.column_names:
+ return None
+ known = [value for value in add_actions.column(_MAX_STAT).to_pylist() if value is not None]
+ return max(known) if known else None
+
+
+async def read_lane_position(
+ delta_table: deltalake.DeltaTable | None, *, key_columns: list[str] | None = None
+) -> LanePosition:
+ """Where this lane's table stops. `key_columns` asks for the rows at that position too.
+
+ Only the append lane needs them: a merge writes a row it already holds as a no-op, while a
+ history table would keep a second copy. Those rows are read from the files whose statistic
+ says they hold the position, never from the table at large.
+ """
+ if delta_table is None or not _has_position_column(delta_table):
+ return EMPTY_POSITION
+
+ add_actions = pa.table(await asyncio.to_thread(delta_table.get_add_actions, flatten=True))
+ if add_actions.num_rows == 0:
+ return EMPTY_POSITION
+
+ highest = _stats_max(add_actions)
+ if highest is None and not key_columns:
+ # The merge lane can replay from nothing, but a table that never gains the statistic
+ # never advances the floor either: no file is deleted and the buffer is re-merged and
+ # re-billed every tick. That is an alert, not a silent state.
+ logger.warning("cdc_position_unreadable", files=add_actions.num_rows)
+ if highest is None and key_columns:
+ # No file carries the statistic — the property was lost to a rewrite, or never took. A
+ # merge lane can replay from nothing; an append lane would write every row again. Scan
+ # once; the next write lands with the statistic and this path goes quiet.
+ highest = await asyncio.to_thread(_scan_position, delta_table)
+ logger.warning("cdc_position_scanned", position=highest, files=add_actions.num_rows)
+ if highest is None or not key_columns:
+ return LanePosition(position=highest, applied={}, key_columns=())
+
+ present = {field.name for field in delta_table.schema().fields}
+ columns = [name for name in key_columns if name in present]
+ candidates = _files_at_position(add_actions, highest)
+ return LanePosition(
+ position=highest,
+ applied={},
+ key_columns=tuple(columns),
+ load_applied=partial(_load_applied, delta_table, add_actions, highest, candidates, columns),
+ )
+
+
+def _load_applied(
+ delta_table: deltalake.DeltaTable,
+ add_actions: pa.Table,
+ highest: int,
+ candidates: dict[str, int],
+ columns: list[str],
+) -> LanePosition:
+ """The rows the table holds at `highest`, read from the candidate files a batch at a time.
+
+ One bulk transaction stamps every row it touched with one position, and reading them all
+ back as Python objects would exhaust memory before anything could be staged — the schema
+ would never move again. Past either cap the lane keeps only the key columns from then on and
+ matches on key and operation alone: a bulk change touches each key once, so the content is
+ not needed to tell its rows apart, and a replay still spends the stored row rather than
+ appending a copy.
+ """
+ scanner = _rows_at_position(delta_table, add_actions, highest, list(candidates))
+ schema = scanner.projected_schema
+ batches: list[pa.RecordBatch] = []
+ # Past a cap, each batch is folded into these counts and dropped: what stays in memory is
+ # one entry per distinct identity, which is the least a replay can be matched against.
+ counts: Counter[tuple[Any, ...]] = Counter()
+ rows = 0
+ held_bytes = 0
+ degraded = False
+ for batch in scanner.to_batches():
+ if batch.num_rows == 0:
+ continue
+ rows += batch.num_rows
+ if not degraded:
+ held_bytes += batch.nbytes
+ if rows > MAX_POSITION_ROWS or held_bytes > MAX_POSITION_BYTES:
+ degraded = True
+ logger.warning("cdc_position_identity_degraded", position=highest, rows=rows, held_bytes=held_bytes)
+ for held in batches:
+ counts.update(_identities(pa.Table.from_batches([held]), columns))
+ batches = []
+ if degraded:
+ counts.update(_identities(pa.Table.from_batches([batch]), columns))
+ else:
+ batches.append(batch)
+ if degraded:
+ # One shared placeholder per identity: the filter only reads these, and pops one per match.
+ placeholder: dict[str, Any] = {}
+ return LanePosition(
+ position=highest,
+ applied={key: [placeholder] * count for key, count in counts.items()},
+ key_columns=tuple(columns),
+ content_matched=False,
+ )
+ at_position = pa.Table.from_batches(batches, schema=schema)
+ return LanePosition(
+ position=highest,
+ applied=_group_by_identity(at_position, columns),
+ key_columns=tuple(columns),
+ content_schema=at_position.select(content_columns(at_position.column_names)).schema,
+ )
+
+
+def _scan_position(delta_table: deltalake.DeltaTable) -> int | None:
+ """The column's maximum, folded one batch at a time so a large table costs O(batch) memory."""
+ highest: int | None = None
+ scanner = delta_table.to_pyarrow_dataset().scanner(columns=[CDC_SEQ_COLUMN])
+ for batch in scanner.to_batches():
+ if batch.num_rows == 0:
+ continue
+ batch_max = pc.max(batch.column(0)).as_py()
+ if batch_max is not None and (highest is None or batch_max > highest):
+ highest = batch_max
+ return highest
+
+
+def _files_at_position(add_actions: pa.Table, highest: int) -> dict[str, int]:
+ """Paths of the files that can hold a row at `highest`, with their row counts.
+
+ A file's `max` is its highest position, so a row at `highest` sits in a file whose statistic
+ says exactly that. A file with no statistic may hold one too — a rewrite the statistic did
+ not survive — unless its null count says every position in it is null, which is what a seed
+ file rewritten by schema evolution reports.
+ """
+ paths = add_actions.column("path").to_pylist()
+ counts = add_actions.column("num_records").to_pylist()
+ maxes = add_actions.column(_MAX_STAT).to_pylist() if _MAX_STAT in add_actions.column_names else [None] * len(paths)
+ all_null = _all_null(add_actions)
+ return {
+ str(path): int(count or 0)
+ for path, count, value in zip(paths, counts, maxes)
+ if path is not None and (value == highest or (value is None and path not in all_null))
+ }
+
+
+def _rows_at_position(
+ delta_table: deltalake.DeltaTable,
+ add_actions: pa.Table,
+ highest: int,
+ candidates: list[str],
+) -> pa_ds.Scanner:
+ """A scan over every row at `highest`, touching only the candidate files.
+
+ A candidate with no statistic is opened only as far as its footer: one that lacks the column
+ at all cannot hold the row and is skipped without a read.
+
+ `DeltaTable.to_pyarrow_table(filters=…)` would not do this. Its filter reaches pyarrow after
+ the dataset is built over every active file, so it prunes by parquet footers alone, and a
+ seed file's key columns would be read in full on every tick just to be filtered away.
+ """
+ # The add action escapes a partition value once more than the fragment does, so a value with
+ # a space or an equals sign would never match by raw string.
+ wanted = {_unescaped(path) for path in candidates}
+ dataset = cast(pa_ds.FileSystemDataset, delta_table.to_pyarrow_dataset())
+ fragments = [
+ fragment
+ for fragment in dataset.get_fragments()
+ if _unescaped(fragment.path) in wanted and CDC_SEQ_COLUMN in fragment.physical_schema.names
+ ]
+ logger.info(
+ "cdc_position_rows_read", position=highest, files_read=len(fragments), files_active=add_actions.num_rows
+ )
+ selected = pa_ds.FileSystemDataset(fragments, dataset.schema, dataset.format, dataset.filesystem)
+ return selected.scanner(filter=pc.field(CDC_SEQ_COLUMN) == highest, batch_size=_POSITION_BATCH_ROWS)
+
+
+def _unescaped(path: str) -> str:
+ while (decoded := unquote(path)) != path:
+ path = decoded
+ return path
+
+
+def _identities(rows: pa.Table, key_columns: list[str]) -> list[tuple[Any, ...]]:
+ return list(zip(*(rows.column(name).to_pylist() for name in key_columns)))
+
+
+def _all_null(add_actions: pa.Table) -> set[str]:
+ if _NULL_COUNT_STAT not in add_actions.column_names:
+ return set()
+ paths = add_actions.column("path").to_pylist()
+ nulls = add_actions.column(_NULL_COUNT_STAT).to_pylist()
+ rows = add_actions.column("num_records").to_pylist()
+ return {
+ str(path)
+ for path, null_count, row_count in zip(paths, nulls, rows)
+ if path is not None and null_count is not None and null_count == row_count
+ }
+
+
+def _group_by_identity(rows: pa.Table, key_columns: list[str]) -> dict[tuple[Any, ...], list[dict[str, Any]]]:
+ if not key_columns or not rows.num_rows:
+ return {}
+ keys = _identities(rows, key_columns)
+ contents = rows.select(content_columns(rows.column_names)).to_pylist()
+ grouped: defaultdict[tuple[Any, ...], list[dict[str, Any]]] = defaultdict(list)
+ for key, content in zip(keys, contents):
+ grouped[key].append(content)
+ return dict(grouped)
+
+
+async def ensure_position_stats(delta_table: deltalake.DeltaTable, keep_stats_for: list[str] | None = None) -> None:
+ """Keep per-file min/max for the position column, so reading the resume point stays a lookup.
+
+ Naming columns REPLACES Delta's default of indexing the first `_DEFAULT_INDEXED_COLUMNS`, so
+ those are named again ahead of ours. Otherwise every column the customer queries loses its
+ min/max the moment a schema flips, and this property is the only thing that would have taken
+ it away — nothing sets it on a warehouse table today.
+
+ The position column is named even before the table has it. A snapshot-seeded companion does
+ not carry it until its first buffered write, and that write is the one that has to land with
+ the statistic: without it the next run reads no position at all and appends every row again.
+ delta-rs accepts a column the table lacks. Every other name is filtered by presence, since one
+ that never arrives would buy no pruning while still displacing the defaults.
+ """
+ fields = delta_table.schema().fields
+ present = {field.name for field in fields}
+ # Deduplicated, and normalized to match how the writer stores them: the caller passes raw source
+ # names, so `userId` would otherwise be dropped and the merge key would lose its pruning.
+ candidates = dict.fromkeys(
+ [
+ *(field.name for field in fields[:_DEFAULT_INDEXED_COLUMNS]),
+ CDC_SEQ_COLUMN,
+ *(normalize_column_name(n) for n in keep_stats_for or []),
+ ]
+ )
+ wanted = ",".join(name for name in candidates if name == CDC_SEQ_COLUMN or name in present)
+ if (delta_table.metadata().configuration or {}).get(STATS_COLUMNS_PROPERTY) == wanted:
+ return
+ try:
+ await asyncio.to_thread(delta_table.alter.set_table_properties, {STATS_COLUMNS_PROPERTY: wanted})
+ except Exception:
+ # The lane then reports no position. The merge lane re-applies rows as upserts, but the
+ # append lane would append them a second time, so this warning is an alert condition —
+ # see the runbook. Still never worth failing a sync that has already written its data.
+ logger.warning("cdc_position_stats_property_not_set", exc_info=True)
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.py
index 493a0cf9d6f7..e1531e2860d5 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
@@ -7,7 +7,7 @@ ordering and delete safety have to be settled on the batch rather than in merge
from __future__ import annotations
from functools import lru_cache
-from typing import Any
+from typing import Final
import pyarrow as pa
@@ -22,21 +22,16 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import
WRITE_RESOLUTION_FLAG = "dwh-cdc-write-resolution"
-# Highest position applied, per lane resource name. Sibling of `cdc_last_log_position`, which
-# tracks capture — buffered ingress lets the two diverge, since capture runs ahead of load.
-LOAD_POSITION_CONFIG_KEY = "cdc_load_position"
-
# Verification is a diagnostic; cap it so a delete-heavy batch can't dominate the write path.
MAX_VERIFIED_DELETE_ROWS = 1_000
MAX_REPORTED_COLUMNS = 10
# The companion lane. Its table is append-only history, so deduping it would delete versions.
-SCD2_APPEND_MODE = "scd2_append"
+SCD2_APPEND_MODE: Final = "scd2_append"
@frozen
class ResolutionStats:
- superseded: int
duplicate_key: int
@@ -74,26 +69,20 @@ def has_engine_seq(table: pa.Table) -> bool:
return (field.metadata or {}).get(b"posthog_cdc") == CDC_SEQ_PROVENANCE[b"posthog_cdc"]
-def batch_max_seq(table: pa.Table) -> int | None:
- if not has_engine_seq(table) or table.num_rows == 0:
- return None
- values = [v for v in table.column(CDC_SEQ_COLUMN).to_pylist() if v is not None]
- return max(values) if values else None
-
-
-def drop_superseded_rows(table: pa.Table, watermark: int | None) -> tuple[pa.Table, int]:
- """Drop rows strictly below `watermark`.
+def drop_superseded_rows(table: pa.Table, position: int | None) -> tuple[pa.Table, int]:
+ """Drop rows strictly below `position` — everything the lane's table already holds.
Rows exactly at it stay: one Postgres transaction shares a commit LSN across every event, and a
- transaction bigger than the flush budget spans batches, so dropping equality would truncate it.
- Re-applying is cheap by comparison — the write is a primary-key upsert.
+ transaction bigger than the flush budget spans files, so dropping equality would truncate it.
+ What to do with those is the lane's own business — a merge re-applies them as upserts, while an
+ append has to tell the ones it wrote from the ones it did not.
"""
- if watermark is None or not has_engine_seq(table) or table.num_rows == 0:
+ if position is None or not has_engine_seq(table) or table.num_rows == 0:
return table, 0
seqs = table.column(CDC_SEQ_COLUMN).to_pylist()
# A null position can't be proven stale, so it survives.
- keep = [i for i, s in enumerate(seqs) if s is None or s >= watermark]
+ keep = [i for i, seq in enumerate(seqs) if seq is None or seq >= position]
if len(keep) == table.num_rows:
return table, 0
return table.take(pa.array(keep, type=pa.int64())), table.num_rows - len(keep)
@@ -128,46 +117,22 @@ def dedupe_keep_highest_seq(table: pa.Table, primary_keys: list[str]) -> tuple[p
return table.take(pa.array(keep, type=pa.int64())), table.num_rows - len(keep)
-def read_load_position(sync_type_config: dict | None, resource_name: str) -> int | None:
- positions = (sync_type_config or {}).get(LOAD_POSITION_CONFIG_KEY) or {}
- value = positions.get(resource_name)
- return int(value) if isinstance(value, int) or (isinstance(value, str) and value.isdigit()) else None
-
-
-def persist_load_position(schema_id: Any, team_id: int, resource_name: str, position: int) -> None:
- """Record the position — only ever after the commit lands.
-
- That ordering is the safety argument: this value can then only lag the table, never lead it.
- Lagging re-applies rows, which the upsert makes a no-op; leading would skip rows that were never
- written. The locked merge keeps capture's concurrent write to the same JSON column intact.
- """
- from products.warehouse_sources.backend.models.external_data_schema import update_sync_type_config_keys
-
- def _merge(config: dict[str, Any]) -> None:
- positions = config.setdefault(LOAD_POSITION_CONFIG_KEY, {})
- current = positions.get(resource_name)
- # Monotonic, so a retried older batch can't rewind the guard for later ones.
- if current is None or int(current) < position:
- positions[resource_name] = position
-
- update_sync_type_config_keys(schema_id, team_id, mutate=_merge)
-
-
def resolve_batch(
table: pa.Table,
primary_keys: list[str],
*,
- watermark: int | None,
cdc_write_mode: str | None,
) -> tuple[pa.Table, ResolutionStats]:
- """Resolve one lane's batch. Only the consolidated lane dedupes — see SCD2_APPEND_MODE."""
- table, superseded = drop_superseded_rows(table, watermark)
+ """Resolve one lane's batch. Only the consolidated lane dedupes — see SCD2_APPEND_MODE.
+ Replay is settled upstream, as the buffer is read: only the reader knows how far into a
+ position's rows the last run got, and it reads them in one canonical order.
+ """
duplicates = 0
if cdc_write_mode != SCD2_APPEND_MODE:
table, duplicates = dedupe_keep_highest_seq(table, primary_keys)
- return table, ResolutionStats(superseded=superseded, duplicate_key=duplicates)
+ return table, ResolutionStats(duplicate_key=duplicates)
def verify_delete_enrichment(
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 624b1c9ccf29..b7c392b6a6d6 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
@@ -4,20 +4,23 @@ The egress half of buffered CDC: capture writes position-named Parquet files (se
this reads them back as an ordinary source, so change events reach the loader through the same path
every other source uses.
-Files are deleted once the persisted load position proves their rows are committed, never on yield —
-the v3 batcher buffers across generator yields, so a yielded table can still be in memory when the
-generator resumes.
+Files are deleted at the start of the next run, once every table the schema feeds is proven past
+them, never on yield — the v3 batcher buffers across generator yields, so a yielded table can still
+be in memory when the generator resumes.
"""
from __future__ import annotations
-import uuid
import datetime as dt
-from collections.abc import AsyncGenerator
-from typing import TYPE_CHECKING
+from collections.abc import AsyncGenerator, Callable
+from typing import TYPE_CHECKING, Any, Final, Literal
+
+from django.db import transaction
+from django.utils import timezone
import psycopg
import pyarrow as pa
+import pyarrow.compute as pc
import pyarrow.parquet as pq
from structlog.types import FilteringBoundLogger
@@ -26,14 +29,38 @@ from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
from posthog.sync import database_sync_to_async_pool
from products.data_warehouse.backend.facade.api import aget_s3_client
+from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (
+ CDC_OP_COLUMN,
+ CDC_SEQ_COLUMN,
+ SCD2_VALID_TO_COLUMN,
+ TOAST_OMITTED_COLUMN,
+ build_scd2_table,
+ companion_resource_name,
+)
from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import (
BufferFileSpan,
get_buffer_prefix,
parse_buffer_file_name,
)
-from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import read_load_position
+from products.warehouse_sources.backend.temporal.data_imports.cdc.companion_jobs import COMPANION_JOB_IDS_KEY
+from products.warehouse_sources.backend.temporal.data_imports.cdc.lane_position import (
+ LanePosition,
+ content_columns,
+ ensure_position_stats,
+ read_lane_position,
+)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import (
+ SCD2_APPEND_MODE,
+ drop_superseded_rows,
+ has_engine_seq,
+)
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import parse_ingest_mode
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import normalize_column_name
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef
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.load.metrics import (
+ CDC_SEQ_GUARD_ROWS_DROPPED_TOTAL,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
BatchQueue,
)
@@ -43,66 +70,306 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bat
TableBatcher,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.db import db_read_with_retry
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import OutputLane, SourceInputs
if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
-# The only lane this manager serves. `cdc_only` and `both` need a second output per run, which one
-# pipeline run cannot express — those schemas stay on the legacy extraction path.
CONSOLIDATED_TABLE_MODE = "consolidated"
+CDC_ONLY_TABLE_MODE = "cdc_only"
+BOTH_TABLE_MODE = "both"
-# The loader's write mode for this lane, and the flag that tells the pipeline a run carries change
+# The loader's write mode per lane, and the flag that tells the pipeline a run carries change
# events rather than rows read from a table.
-CONSOLIDATED_WRITE_MODE = "incremental_merge"
+CDCWriteMode = Literal["incremental_merge", "scd2_append"]
+CONSOLIDATED_WRITE_MODE: Final = "incremental_merge"
+COMPANION_WRITE_MODE: Final = SCD2_APPEND_MODE
+# The tables each mode's change stream feeds, as the write mode the loader uses for each — in the
+# order the legacy extraction path writes them. A mode absent here is one this module cannot write.
+_LANE_WRITE_MODES: dict[str, tuple[CDCWriteMode, ...]] = {
+ CONSOLIDATED_TABLE_MODE: (CONSOLIDATED_WRITE_MODE,),
+ CDC_ONLY_TABLE_MODE: (COMPANION_WRITE_MODE,),
+ BOTH_TABLE_MODE: (CONSOLIDATED_WRITE_MODE, COMPANION_WRITE_MODE),
+}
-# Slack when comparing an S3 mtime against a listing timestamp from our clock, so skew between the
-# two can never make a file look older than a listing that in fact never saw it.
-_CONSUMED_MTIME_MARGIN = dt.timedelta(minutes=5)
-# The last buffer listing, `{"listed_at": iso, "job_id": str}` — a sibling of `cdc_load_position`.
-# It matures into a deletion proof only if that job COMPLETES (see _completed_listing_time).
-BUFFER_LISTING_CONFIG_KEY = "cdc_buffer_listing"
+@frozen
+class CDCLane:
+ """One warehouse table this schema's change stream feeds, and how the loader writes it."""
+ resource_name: str
+ write_mode: CDCWriteMode
-def serves_buffered_lane(schema: ExternalDataSchema) -> bool:
- """Schema-side conditions for buffered ingress; the source's `ingest_mode` is the other half.
- Fails closed on every axis: a lane this manager cannot write, or a schema with no table yet,
- stays on the legacy extraction path.
- """
+# 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"
+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."""
return bool(
schema.is_cdc
and schema.cdc_mode == "streaming"
- and schema.cdc_table_mode == CONSOLIDATED_TABLE_MODE
+ and schema.cdc_table_mode in _LANE_WRITE_MODES
and schema.initial_sync_complete
)
-def is_buffered_consolidated(schema: ExternalDataSchema, *, ingest_mode: str) -> 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)
+def served_lanes(schema: ExternalDataSchema) -> list[CDCLane]:
+ """The tables this schema's change stream feeds.
+
+ One entry per Delta table the mode writes, in the order the legacy extraction path writes them.
+ An unrecognized mode returns nothing, which reads as "not a lane the buffer serves".
+ """
+ return [
+ CDCLane(
+ resource_name=(
+ companion_resource_name(schema.name)
+ if mode == COMPANION_WRITE_MODE
+ else consolidated_resource_name(schema)
+ ),
+ write_mode=mode,
+ )
+ for mode in _LANE_WRITE_MODES.get(schema.cdc_table_mode, ())
+ ]
+
+
+# Slack when comparing an S3 mtime against a listing timestamp from our clock, so skew between the
+# two can never make a file look older than a listing that in fact never saw it.
+_CONSUMED_MTIME_MARGIN = dt.timedelta(minutes=5)
+
+# When a run listed the buffer, kept on that run's own job. Proof only once the job completes.
+BUFFER_LISTED_AT_KEY = "cdc_buffer_listed_at"
+
+
+def read_completed_listing_proof(schema: ExternalDataSchema) -> dt.datetime | None:
+ """When the buffer was last listed by a run that went on to complete every table it writes.
+
+ Completion is what proves consumption: it means the generator drained every listed file and
+ every staged batch committed. A `both` run completes two jobs, so both have to be COMPLETED —
+ the schema's own and its companion — or a file at the floor could be deleted while the history
+ table still owed it.
+
+ Both queries are bounded by `created_at`. `externaldatajob` is one of the largest tables in
+ this database and a 5-minute schema adds a row every tick, so an unbounded sort over its
+ history — or a JSONB predicate with no index across it — would cost more every day it ran.
+ A proof older than the window is no loss: it only ever deletes fewer files.
+ """
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+
+ since = timezone.now() - _PROOF_WINDOW
+ jobs = (
+ # `pipeline_id` is redundant with `schema_id` but is what lets the planner use
+ # `idx_extdatajob_latest_run` (team, pipeline, status, -created_at); without it the read
+ # walks every job the schema ever had, every tick.
+ ExternalDataJob.objects.filter(
+ team_id=schema.team_id,
+ pipeline_id=schema.source_id,
+ schema_id=schema.id,
+ status=ExternalDataJob.Status.COMPLETED,
+ created_at__gte=since,
+ )
+ .order_by("-created_at")
+ .values_list("schema_snapshot", flat=True)[:_PROOF_SEARCH_DEPTH]
+ )
+ for snapshot in jobs:
+ listed_at = (snapshot or {}).get(BUFFER_LISTED_AT_KEY)
+ if not listed_at:
+ continue
+ try:
+ stamped = dt.datetime.fromisoformat(listed_at)
+ except (TypeError, ValueError):
+ continue
+ if stamped.tzinfo is None:
+ continue
+ if _companions_completed((snapshot or {}).get(COMPANION_JOB_IDS_KEY) or []):
+ return stamped
+ return None
+
+
+async def completed_listing_proof(schema: ExternalDataSchema) -> dt.datetime | None:
+ """`read_completed_listing_proof`, off the event loop."""
+ return await database_sync_to_async_pool(db_read_with_retry)(lambda: read_completed_listing_proof(schema))
+
+
+def clear_listing(job_id: str, team_id: int) -> None:
+ """Drop the listing stamp from a job that a retry is about to hand back without draining.
+
+ An earlier attempt of the same job listed the buffer and stamped it; this attempt stood down
+ for its in-flight batches, and the workflow will now complete the job anyway. If one of those
+ batches then fails in the loader, the job stays Completed, and a stamp still on it would prove
+ a listing nothing drained — and delete a file at the floor whose rows never landed.
+ """
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+
+ with transaction.atomic():
+ job = (
+ ExternalDataJob.objects.select_for_update()
+ .filter(id=job_id, team_id=team_id)
+ .only("id", "schema_snapshot")
+ .first()
+ )
+ stamped = dict(job.schema_snapshot or {}) if job is not None else {}
+ if job is None or not stamped.get(BUFFER_LISTED_AT_KEY):
+ return
+ snapshot = {k: v for k, v in stamped.items() if k != BUFFER_LISTED_AT_KEY}
+ ExternalDataJob.objects.filter(id=job.id).update(schema_snapshot=snapshot)
+
+
+def _companions_completed(companion_job_ids: list[str]) -> bool:
+ """Whether every companion table this run also wrote finished with it."""
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+
+ if not companion_job_ids:
+ return True
+ statuses = ExternalDataJob.objects.filter(id__in=companion_job_ids).values_list("status", flat=True)
+ return len(statuses) == len(companion_job_ids) and all(
+ status == ExternalDataJob.Status.COMPLETED for status in statuses
+ )
+
+
+# A run whose companion failed proves nothing, so look past it — but never far: an older listing
+# only ever deletes fewer files, and the floor is what does the real work.
+_PROOF_SEARCH_DEPTH = 10
+
+# How far back a usable proof can sit. A schema that has not completed a run in this long has a
+# bigger problem than an undeleted buffer file.
+_PROOF_WINDOW = dt.timedelta(days=2)
+
+
+def _history_transform(replay: ReplayFilter, key_columns: list[str]) -> Callable[[pa.Table], pa.Table]:
+ """Replay first, then stamp the SCD2 validity columns onto what is left.
+
+ Derived here rather than in the loader so the staged parquet is complete on its own: a loader
+ on the previous release has no SCD2 step, and would append these rows with no validity at all.
+ The legacy extraction path stamps them at the same point for the same reason.
+
+ Replay runs first because `valid_to` points at the next event for the same key. Rows this lane
+ already wrote carry their own, and the writer closes them against what arrives next, so
+ including them here would both duplicate the row and mis-chain the one that follows it.
+
+ Applied to the coalesced batch the pipeline hands over, never per yield: a key changed in two
+ yields of one batch would otherwise leave two rows open.
+ """
+
+ def _apply(table: pa.Table) -> pa.Table:
+ table = replay.apply(table)
+ if not table.num_rows:
+ return table
+ # No guard on the columns already being there: a source that owns `valid_from` fails
+ # loudly inside `build_scd2_table`, where a skip would let the writer close rows against
+ # customer data.
+ return build_scd2_table(table, key_columns)
+
+ return _apply
+
+
+async def build_output_lanes(
+ schema: ExternalDataSchema, job: ExternalDataJob, logger: FilteringBoundLogger
+) -> tuple[list[OutputLane], int | None]:
+ """Every table this run writes, and the position below which the buffer is settled.
+
+ One run serves them all from one read of the buffer. Each carries its own replay filter, built
+ from its own table, because a failed run can leave one lane ahead of the other.
+
+ The first lane is the billable one: a change stream feeding two tables is one stream, and
+ charging it twice would price the history table as a second sync.
+
+ The floor is the lowest position any lane holds — a file below it is settled for every table.
+ A lane whose table reports no position holds the floor open, so nothing is deleted until every
+ lane can prove where it stops.
+ """
+ lanes: list[OutputLane] = []
+ positions: list[int | None] = []
+ for index, lane in enumerate(served_lanes(schema)):
+ delta_table = await DeltaTableRef(lane.resource_name, job, logger).get_delta_table()
+ is_append = lane.write_mode == COMPANION_WRITE_MODE
+ keys = [normalize_column_name(name) for name in schema.primary_key_columns or []]
+ if delta_table is not None:
+ # Before the read, so this run's own write is the one that carries the statistic.
+ await ensure_position_stats(delta_table, [*keys, *([SCD2_VALID_TO_COLUMN] if is_append else [])])
+ # Without primary keys an identity is just the operation, which matches rows the table
+ # has never held. Ask for none instead: the lane then replays, which duplicates history
+ # rather than losing it, and duplication is the direction that can be repaired.
+ key_columns = [*keys, CDC_OP_COLUMN] if keys else None
+ position = await read_lane_position(delta_table, key_columns=key_columns if is_append else None)
+ positions.append(position.position)
+ replay = ReplayFilter(position, team_id=job.team_id)
+ lanes.append(
+ OutputLane(
+ name=lane.resource_name,
+ cdc_write_mode=lane.write_mode,
+ billable=index == 0,
+ transform=_history_transform(replay, keys) if is_append else replay.apply,
+ )
+ )
+ floor = None if any(p is None for p in positions) else min(p for p in positions if p is not None)
+ return lanes, floor
+
+
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.
+ because only the v3 loader stamps the position each row landed at, which is what the next
+ run reads back from the table, and only it 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))
+ return consumes_buffer(schema, ingest_mode=parse_ingest_mode(schema.source.job_inputs))
+
+
+def has_batches_in_flight(schema: ExternalDataSchema) -> bool:
+ """Whether any delivery for this schema is still working through the queue.
+
+ Two kinds, and the consumer must stand down for both.
+
+ Legacy deliveries carry no position column, so nothing orders them against buffered writes — a
+ consumer merge racing them lets an older legacy row land after a newer buffered one.
+ A previous attempt of THIS job is the other kind, and it is why the check has to cover buffered
+ batches too. It sees an attempt only once that attempt has staged a batch: one timed out by
+ its heartbeat but still alive inside the listing can stage after this check passed. The busy
+ gate keeps the two loads apart, but the history lane then holds both copies. Legacy has the
+ same window; fencing batches by attempt in the producer is the follow-up.
-def has_pending_legacy_backlog(schema: ExternalDataSchema) -> bool:
- """Whether legacy-lane deliveries for this schema are still in flight.
+ The v3 pipeline lock keeps two scheduled runs apart — it is held from the start of
+ the workflow until the loader completes the job — but a retried activity runs under the lock its
+ own workflow already holds, and a takeover hands the lock to a new job while the old one's
+ batches are still queued. Attempts are superseded only when the loader shows no recent
+ progress, and the claim gates are scoped per run, so an attempt that died with batches still
+ staged has them claimed and written alongside whatever a new attempt reads. The merge lane
+ absorbs that as upserts; the append lane writes it as a second copy of the same history.
- Deferred runs and sourcebatch batches carry no position column, so nothing orders them against
- buffered writes — a consumer merge racing them lets an older legacy row land after a newer
- buffered one. The consumer no-ops until both are drained; buffer files just wait.
+ Batches only reach a terminal state after their position is recorded, so "nothing in flight"
+ is also what makes the resume point safe to read: every commit before it is already visible.
+
+ Runs holding a failed batch are excluded by the query, matching the loader's claim gate — their
+ remaining batches can never be claimed, so they cannot write anything to collide with.
"""
if schema.sync_type_config.get("cdc_deferred_runs"):
return True
@@ -133,74 +400,219 @@ class _BufferFile:
modified: dt.datetime | None
-class CDCSourceManager:
- """Reads one schema's buffered change events in position order."""
-
- def __init__(self, inputs: SourceInputs, logger: FilteringBoundLogger) -> None:
- self._inputs = inputs
- self._logger = logger
-
- async def _read_consume_state(self, resource_name: str) -> tuple[int | None, dict | None]:
- """The lane's committed floor and the last listing stamp, read once per run.
+class ReplayFilter:
+ """Drops from each batch what this lane's table already holds, as the run re-reads the buffer.
+
+ Rows below the position are settled for either lane: the position is a commit's highest row,
+ so everything beneath it landed in that commit or an earlier one.
+
+ Rows AT the position are one transaction the previous run may have applied only part of, and
+ the two lanes want different things from them. A merge rewrites them as upserts, so it asks
+ for no identity, `applied` is empty, and every row at the position is kept — dropping one
+ would lose a later event for a key the table happens to hold at that same commit. A history
+ table would keep a second copy instead, so it asks for the rows its table holds there and
+ drops a batch row whose identity is one of them.
+
+ Matched on content, not on key alone: one transaction can change the same key more than once,
+ and history keeps every version. Two such changes share every key column and the position,
+ so a batch row spends a table row only when their values agree — on every column the batch
+ row actually carries, since a TOAST-omitted column is unset in the batch and real in the
+ table. A row nothing matches has never been written, including one in a file capture wrote
+ after the last run listed the buffer, and including the second change to a key whose first
+ change is all the table holds.
+
+ One case content cannot settle: two changes to one key in one transaction with identical
+ content — an idempotent second update. If the file holding the first was consumed and
+ deleted before the second arrived, the second spends the single stored row and is dropped.
+ It is one row of history that adds nothing to the current state; a per-row ordinal from
+ capture would close it, and is the follow-up.
+ """
- The floor decides which files are still needed, not correctness — `drop_superseded_rows` is
- that, and it re-reads the config per batch on the load side. Reading a stale value here
- costs one redundant file read whose rows the guard then drops.
+ def __init__(self, position: LanePosition, *, team_id: int | None = None) -> None:
+ self._position = position.position
+ self._applied = {key: list(rows) for key, rows in position.applied.items()}
+ # Taken from the position itself, so the batch is keyed exactly as the table was read.
+ self._key_columns = list(position.key_columns)
+ self._content_schema = position.content_schema
+ self._content_matched = position.content_matched
+ self._load_applied = position.load_applied
+ self._team_id = team_id
+ self.rows_skipped = 0
+
+ def apply(self, table: pa.Table) -> pa.Table:
+ table, dropped = drop_superseded_rows(table, self._position)
+ self._count_skipped(dropped, "superseded")
+ if self._position is None or not table.num_rows or (not self._applied and self._load_applied is None):
+ return table
+ return self._drop_already_written(table)
+
+ def _resolve_applied(self) -> None:
+ # Deferred to the first batch that holds a row at the position: on an idle tick there is
+ # none, and the table's rows there are never read.
+ if self._load_applied is None:
+ return
+ resolved = self._load_applied()
+ self._load_applied = None
+ self._applied = {key: list(rows) for key, rows in resolved.applied.items()}
+ self._content_schema = resolved.content_schema
+ self._content_matched = resolved.content_matched
+
+ def _count_skipped(self, dropped: int, reason: str) -> None:
+ # `superseded` is the series the loader raised while the position lived there. It now
+ # comes from the extraction workers, so a dashboard filtered to the load fleet loses it.
+ self.rows_skipped += dropped
+ if dropped and self._team_id is not None:
+ CDC_SEQ_GUARD_ROWS_DROPPED_TOTAL.labels(team_id=str(self._team_id), reason=reason).inc(dropped)
+
+ def _drop_already_written(self, table: pa.Table) -> pa.Table:
+ # A source column of the same name is customer data, so comparing it against this lane's
+ # position would drop rows nothing has written. `drop_superseded_rows` refuses it too.
+ if not has_engine_seq(table):
+ return table
+ if any(name not in table.column_names for name in self._key_columns):
+ # The batch cannot be keyed the way the table was, so nothing can be proven applied.
+ return table
+ # Only rows at the position can match anything, and they sit in a run's first batch;
+ # materializing the rest as Python objects would cost every batch for nothing.
+ mask = pc.equal(table.column(CDC_SEQ_COLUMN), pa.scalar(self._position, pa.int64()))
+ if not pc.any(mask).as_py():
+ return table
+ candidates = [i for i, hit in enumerate(mask.to_pylist()) if hit]
+ self._resolve_applied()
+ if not self._applied:
+ return table
+ at_position = table.take(pa.array(candidates, type=pa.int64()))
+ identities = list(zip(*(at_position.column(name).to_pylist() for name in self._key_columns)))
+ # Above the position-row cap the table side carried no content, so none is read here.
+ contents, stringly = (
+ self._batch_contents(at_position) if self._content_matched else ([{}] * at_position.num_rows, set())
+ )
+ omitted = (
+ at_position.column(TOAST_OMITTED_COLUMN).to_pylist()
+ if TOAST_OMITTED_COLUMN in at_position.column_names
+ else [None] * at_position.num_rows
+ )
+ ops = at_position.column(CDC_OP_COLUMN).to_pylist() if CDC_OP_COLUMN in at_position.column_names else []
+ dropped: set[int] = set()
+ for local, row_index in enumerate(candidates):
+ held = self._applied.get(identities[local])
+ if not held:
+ continue
+ skip = set(omitted[local] or ())
+ if ops and ops[local] == "D":
+ # A delete carries only its key under the default replica identity; the loader
+ # filled the rest from the table before storing it. Those nulls are unknowns,
+ # not values, the same as a TOAST-omitted column.
+ skip |= {name for name, value in contents[local].items() if value is None}
+ match = next((j for j, row in enumerate(held) if _same_content(contents[local], row, skip, stringly)), None)
+ if match is None:
+ continue
+ held.pop(match)
+ if not held:
+ del self._applied[identities[local]]
+ dropped.add(row_index)
+ if not dropped:
+ return table
+ self._count_skipped(len(dropped), "already_written")
+ keep = [i for i in range(table.num_rows) if i not in dropped]
+ return table.take(pa.array(keep, type=pa.int64()))
+
+ def _batch_contents(self, table: pa.Table) -> tuple[list[dict[str, Any]], set[str]]:
+ """The batch's content columns as the table stores them, so values compare as equals.
+
+ The batch carries the source's own arrow types and the table the loader's evolved ones;
+ a date widened to a timestamp reads back as a different Python value. A column that will
+ not cast is compared by its string form instead, so two changes that differ only there
+ still compare different: dropping it would make a wrong match likelier, and a wrong match
+ is a lost change where a missed one is only a copy.
"""
- from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+ names = content_columns(table.column_names)
+ if self._content_schema is None:
+ return table.select(names).to_pylist(), set()
+ columns: list[pa.ChunkedArray] = []
+ stringly: set[str] = set()
+ for name in names:
+ column = table.column(name)
+ if name in self._content_schema.names:
+ try:
+ column = column.cast(self._content_schema.field(name).type)
+ except (pa.ArrowInvalid, pa.ArrowNotImplementedError):
+ stringly.add(name)
+ columns.append(column)
+ return pa.table(columns, names=names).to_pylist(), stringly
+
+
+def _same_content(batch_row: dict[str, Any], held_row: dict[str, Any], skip: set[str], stringly: set[str]) -> bool:
+ """Whether a batch row and a stored row agree on every column the batch row carries."""
+ for name, value in batch_row.items():
+ if name in skip or name not in held_row:
+ continue
+ held = held_row[name]
+ if name in stringly:
+ if str(value) != str(held):
+ return False
+ elif held != value:
+ return False
+ return True
- sync_type_config = await database_sync_to_async_pool(db_read_with_retry)(
- lambda: ExternalDataSchema.objects.values_list("sync_type_config", flat=True).get(
- id=self._inputs.schema_id, team_id=self._inputs.team_id
- )
- )
- listing = (sync_type_config or {}).get(BUFFER_LISTING_CONFIG_KEY)
- return read_load_position(sync_type_config, resource_name), listing if isinstance(listing, dict) else None
- async def _stamp_listing(self, listed_at: dt.datetime) -> None:
- """Record that this run listed the buffer, before any file is read.
+class CDCSourceManager:
+ """Reads one schema's buffered change events in position order, deleting what is settled."""
- The stamp becomes a deletion proof only once this run's job COMPLETES — see
- `_completed_listing_time`. Crashing after the stamp leaves the job un-completed, so a
- partial run can never prove anything.
- """
- from products.warehouse_sources.backend.models.external_data_schema import update_sync_type_config_keys
+ def __init__(
+ self,
+ inputs: SourceInputs,
+ logger: FilteringBoundLogger,
+ *,
+ deletion_floor: int | None = None,
+ proof_time: dt.datetime | None = None,
+ ) -> None:
+ self._inputs = inputs
+ self._logger = logger
+ self._deletion_floor = deletion_floor
+ self._proof_time = proof_time
- stamp = {"listed_at": listed_at.isoformat(), "job_id": str(self._inputs.job_id)}
+ def _is_consumed(self, end_seq: int, modified: dt.datetime | None) -> bool:
+ """Whether every table this schema feeds already holds this file's rows.
- def _merge(config: dict) -> None:
- config[BUFFER_LISTING_CONFIG_KEY] = stamp
+ Strictly below the floor is position-proof: the lowest-placed lane holds a commit above it,
+ and lanes apply their batches in order, so every row beneath landed everywhere.
- await database_sync_to_async_pool(db_read_with_retry)(
- lambda: update_sync_type_config_keys(self._inputs.schema_id, self._inputs.team_id, mutate=_merge)
- )
+ AT the floor, position alone cannot tell a consumed file from the unread tail of a
+ transaction split across files — they all carry one commit position. A file that already
+ existed when a run listed the buffer, and that run then COMPLETED, was read and written by
+ it. The margin absorbs clock skew between S3 and our own clock.
+ """
+ floor = self._deletion_floor
+ if floor is None or end_seq > floor:
+ return False
+ if end_seq < floor:
+ return True
+ if modified is None or modified.tzinfo is None or self._proof_time is None:
+ return False
+ return modified < self._proof_time - _CONSUMED_MTIME_MARGIN
- async def _completed_listing_time(self, listing: dict | None) -> dt.datetime | None:
- """When the buffer was last listed by a run that went on to COMPLETE, or None.
+ async def stamp_listing(self, listed_at: dt.datetime) -> None:
+ """Record on this run's own job that it listed the buffer, before any file is read.
- Only a completed run proves consumption: completion means the generator drained every
- listed file and every staged batch committed. A job-status check on the stamped job is what
- keeps a no-op run (the legacy-backlog gate returns an empty response without listing) or a
- crashed run from ever serving as proof.
+ Kept on the job rather than beside the schema's settings: it describes one run, and it is
+ that run's completion which turns it into proof. A crash leaves the job un-completed, so a
+ partial run can never prove anything, and a no-op tick never lists and never stamps.
"""
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
- if not listing:
- return None
- try:
- listed_at = dt.datetime.fromisoformat(listing["listed_at"])
- job_id = uuid.UUID(str(listing["job_id"]))
- except (KeyError, TypeError, ValueError):
- return None
- if listed_at.tzinfo is None:
- return None
-
- completed = await database_sync_to_async_pool(db_read_with_retry)(
- lambda: ExternalDataJob.objects.filter(
- id=job_id, team_id=self._inputs.team_id, status=ExternalDataJob.Status.COMPLETED
- ).exists()
- )
- return listed_at if completed else None
+ def _stamp() -> None:
+ # Field-scoped: job completion writes status and finished_at, never the snapshot. The
+ # row lock keeps the companion ids a writer on the same JSON puts there.
+ with transaction.atomic():
+ job = ExternalDataJob.objects.select_for_update().get(
+ id=self._inputs.job_id, team_id=self._inputs.team_id
+ )
+ snapshot = dict(job.schema_snapshot or {})
+ snapshot[BUFFER_LISTED_AT_KEY] = listed_at.isoformat()
+ ExternalDataJob.objects.filter(id=job.id).update(schema_snapshot=snapshot)
+
+ await database_sync_to_async_pool(db_read_with_retry)(_stamp)
async def _list_buffer_files(self) -> list[_BufferFile]:
"""Buffer files under this schema's prefix, in position order.
@@ -239,62 +651,41 @@ class CDCSourceManager:
await self._logger.adebug("cdc_buffer_files_listed", prefix=prefix, file_count=len(files))
return files
- def _is_consumed(
- self,
- end_seq: int,
- modified: dt.datetime | None,
- floor: int | None,
- proof_time: dt.datetime | None,
- ) -> bool:
- """Whether a file's rows are all proven committed, so the file can be deleted.
-
- Strictly below the floor is position-proof: the load-side guard would drop every row anyway.
- AT the floor, position alone cannot tell a consumed file from the unread tail of a
- transaction split across files (all its rows share one commit position) — but a file that
- already existed at `proof_time` (a completed run's listing) was listed, drained, and
- committed by that run. The margin absorbs clock skew between S3 and our DB; an idle schema's
- trailing file clears it within a couple of ticks instead of being re-merged and re-billed
- forever.
- """
- if floor is None or end_seq > floor:
- return False
- if end_seq < floor:
- return True
- if modified is None or modified.tzinfo is None or proof_time is None:
- return False
- return modified < proof_time - _CONSUMED_MTIME_MARGIN
-
async def get_items(
self,
- resource_name: str,
+ *,
batch_row_limit: int = DEFAULT_BATCH_ROW_LIMIT,
batch_byte_limit: int = DEFAULT_BATCH_BYTE_LIMIT,
) -> AsyncGenerator[pa.Table]:
+ """Every buffered change, once, in position order — for all of this schema's lanes.
+
+ One read serves every lane. What each lane already holds is dropped per lane afterwards,
+ by the filter `build_output_lanes` gave it, because a failed run can leave one lane ahead
+ of the other.
+
+ Files every table has settled are deleted here, before they are read, so the run that
+ proves them consumed is never the one that deletes them.
+ """
listed_at = dt.datetime.now(tz=dt.UTC)
files = await self._list_buffer_files()
- floor, prior_listing = await self._read_consume_state(resource_name)
- # Proof comes from the PRIOR stamp, resolved before this run overwrites it.
- proof_time = await self._completed_listing_time(prior_listing) if floor is not None else None
- await self._stamp_listing(listed_at)
-
+ await self.stamp_listing(listed_at)
batch: TableBatcher[str] = TableBatcher(row_limit=batch_row_limit, byte_limit=batch_byte_limit)
async with aget_s3_client() as s3:
for file in files:
- key = file.key
- # The only place a buffer file is deleted — see _is_consumed for the proof.
- if self._is_consumed(file.span.end_seq, file.modified, floor, proof_time):
- await s3._rm(key)
+ # The only place a buffer file is deleted — see `_is_consumed` for the proof.
+ if self._is_consumed(file.span.end_seq, file.modified):
+ await s3._rm(file.key)
continue
try:
- async with await s3.open_async(key, "rb") as f:
+ async with await s3.open_async(file.key, "rb") as f:
data = await f.read()
table = pq.read_table(pa.BufferReader(data))
except FileNotFoundError:
# A concurrent run, or a retry of this activity, can have deleted the file
# between the listing and this open — the listing is a snapshot, not a lease.
- await self._logger.adebug("cdc_buffer_file_already_consumed", key=key)
+ await self._logger.adebug("cdc_buffer_file_already_consumed", key=file.key)
continue
if table.num_rows == 0:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_batcher.py
index d8818487f461..c8e2d2f2255b 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
@@ -3,6 +3,8 @@ from collections.abc import Mapping
from datetime import UTC, datetime
from typing import Literal
+import pytest
+
import pyarrow as pa
from parameterized import parameterized
@@ -22,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import
enrich_delete_rows,
enrich_toast_omitted_rows,
)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCReservedColumnError
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent
@@ -751,3 +754,48 @@ class TestSeqColumn:
# 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"
+
+
+class TestScd2TimestampType:
+ """`valid_from` carries the timestamp column's own values, so it must carry its type too.
+
+ The buffered path normalizes timestamps to naive before the loader derives SCD2; the legacy
+ path derives it in the extraction activity, where they are still UTC-aware. Declaring a fixed
+ type made pyarrow reject the whole batch on the buffered path.
+ """
+
+ @parameterized.expand([("naive", None), ("utc_aware", "UTC")])
+ def test_scd2_columns_match_the_timestamp_column(self, _name, tz):
+ ts = pa.timestamp("us", tz=tz)
+ table = pa.table(
+ {
+ "id": pa.array([1, 1], pa.int64()),
+ CDC_TIMESTAMP_COLUMN: pa.array([0, 1], ts),
+ }
+ )
+
+ result = build_scd2_table(table, ["id"])
+
+ assert result.schema.field(SCD2_VALID_FROM_COLUMN).type == ts
+ assert result.schema.field(SCD2_VALID_TO_COLUMN).type == ts
+ assert result.column(SCD2_VALID_TO_COLUMN).to_pylist()[0] is not None
+
+
+class TestScd2ReservedColumns:
+ @parameterized.expand([(SCD2_VALID_FROM_COLUMN,), (SCD2_VALID_TO_COLUMN,)])
+ def test_a_source_column_named_like_the_stamp_fails_before_the_writer(self, taken):
+ # Delta refuses the duplicate name at write time, but by then a batch is half built and
+ # the error names a qualified field, not the customer's column. A silent skip here is
+ # worse still: the writer would close rows against the customer's own values.
+ table = pa.table(
+ {
+ "id": pa.array([1], pa.int64()),
+ taken: pa.array([datetime(2020, 1, 1)], pa.timestamp("us")),
+ CDC_SEQ_COLUMN: pa.array([5], pa.int64()),
+ CDC_OP_COLUMN: pa.array(["U"], pa.string()),
+ CDC_TIMESTAMP_COLUMN: pa.array([datetime(2026, 1, 1)], pa.timestamp("us")),
+ }
+ )
+
+ with pytest.raises(CDCReservedColumnError, match=taken):
+ build_scd2_table(table, ["id"])
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 a4408505a5cf..d1caf0271537 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,7 +1,8 @@
import pytest
-from unittest.mock import MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.temporal.data_imports.cdc.lane_position import LanePosition
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
@@ -9,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.s
_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"
+_COMPANIONS = "products.warehouse_sources.backend.temporal.data_imports.cdc.companion_jobs"
def _schema(ingest_mode: str = "buffered", **overrides) -> MagicMock:
@@ -18,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 = {}
+ schema.sync_type_config = {} if schema.cdc_table_mode == "consolidated" else {"cdc_buffered_lane": True}
schema.schema_metadata = {}
schema.resolved_s3_folder_name = None
schema.primary_key_columns = ["id"]
@@ -43,17 +45,31 @@ def _inputs(reset_pipeline: bool = False) -> SourceInputs:
)
+def _delta_ref() -> MagicMock:
+ ref = MagicMock()
+ ref.return_value.get_delta_table = AsyncMock(return_value=MagicMock())
+ return ref
+
+
def _dispatch(
schema: MagicMock,
inputs: SourceInputs,
- backlog: bool = False,
+ in_flight: bool = False,
job_version: str | None = ExternalDataJob.PipelineVersion.V3,
+ clear_listing: MagicMock | None = None,
+ retire_orphans: MagicMock | None = None,
):
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(f"{_MANAGER}.clear_listing", clear_listing or MagicMock()),
+ patch(f"{_COMPANIONS}.retire_orphaned_companions", retire_orphans or MagicMock(return_value=[])),
+ patch(f"{_MANAGER}.has_batches_in_flight", return_value=in_flight),
+ patch(f"{_MANAGER}.DeltaTableRef", _delta_ref()),
+ patch(f"{_MANAGER}.read_lane_position", AsyncMock(return_value=LanePosition(position=None, applied={}))),
+ patch(f"{_MANAGER}.ensure_position_stats", AsyncMock()),
+ patch(f"{_MANAGER}.completed_listing_proof", AsyncMock(return_value=None)),
patch.object(PostgresSource, "make_ssh_tunnel_func", return_value=MagicMock()),
):
objects.select_related.return_value.get.return_value = schema
@@ -72,7 +88,7 @@ class TestBufferedDispatch:
"overrides,ingest_mode",
[
({}, "legacy"),
- ({"cdc_table_mode": "cdc_only"}, "buffered"),
+ ({"cdc_table_mode": "something_new"}, "buffered"),
({"initial_sync_complete": False}, "buffered"),
],
)
@@ -80,21 +96,64 @@ class TestBufferedDispatch:
with pytest.raises(CDCHandledExternally):
_dispatch(_schema(ingest_mode, **overrides), _inputs())
+ def test_a_cdc_only_schema_is_consumed_into_its_companion_table(self):
+ response = _dispatch(_schema(cdc_table_mode="cdc_only"), _inputs())
+
+ assert response.name == "users_cdc"
+ assert response.cdc_write_mode == "scd2_append"
+
+ def test_both_writes_each_table_on_every_run(self):
+ response = _dispatch(_schema(cdc_table_mode="both"), _inputs())
+
+ assert [lane.name for lane in response.lanes or []] == ["users", "users_cdc"]
+
+ def test_each_table_carries_the_write_mode_its_loader_needs(self):
+ response = _dispatch(_schema(cdc_table_mode="both"), _inputs())
+
+ modes = [lane.cdc_write_mode for lane in response.lanes or []]
+ assert modes == ["incremental_merge", "scd2_append"]
+
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)
+ def test_a_missing_job_row_fails_the_run(self):
+ # Every lane reads its resume point off its own Delta table, which needs the job row.
+ with pytest.raises(ValueError, match="no job row"):
+ _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)
+ def test_a_delivery_still_in_flight_no_ops_the_tick(self):
+ # Reading now would stage rows alongside batches that are still landing. An empty response
+ # keeps the schedule alive and declares no lanes, so nothing is listed, read or deleted.
+ response = _dispatch(_schema(cdc_table_mode="both"), _inputs(), in_flight=True)
assert list(response.items()) == []
+ assert response.lanes is None
+
+ def test_a_no_op_tick_takes_an_earlier_attempts_listing_off_the_job(self):
+ # Attempt 1 of this same job listed and stamped, then died with batches staged. This
+ # attempt hands back an empty response and the workflow completes the job on it. If a
+ # staged batch later fails in the loader, the job stays Completed — and a stamp still on
+ # it would prove a listing nothing drained.
+ clear, retire = MagicMock(), MagicMock()
+ inputs = _inputs()
+
+ _dispatch(_schema(cdc_table_mode="both"), inputs, in_flight=True, clear_listing=clear, retire_orphans=retire)
+
+ clear.assert_called_once_with(inputs.job_id, inputs.team_id)
+ retire.assert_not_called()
+
+ def test_a_run_retires_companions_no_run_owns_before_it_reads(self):
+ # Once nothing is in flight, a companion still Running belongs to a run that died without
+ # its `finally`. Nothing else ever closes it, and one such row blocks every flip.
+ retire = MagicMock(return_value=["orphan"])
+ inputs = _inputs()
+
+ _dispatch(_schema(cdc_table_mode="both"), inputs, retire_orphans=retire)
+
+ retire.assert_called_once()
def test_a_reset_on_a_streaming_buffered_schema_is_refused(self):
with pytest.raises(ValueError, match="cdc_mode='snapshot'"):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py
index 5dec8e963726..00d8d9c83870 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
@@ -3711,10 +3711,12 @@ class TestBufferedIngressCapture:
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
def test_an_ineligible_schema_on_a_flipped_source_keeps_the_legacy_path(self, MockBufferWriter):
source = _make_source()
- companion = _make_schema("events", cdc_mode="streaming", cdc_table_mode="cdc_only", source=source)
+ # No table yet, so the buffer has nothing to merge its changes into.
+ seeding = _make_schema("events", cdc_mode="streaming", source=source)
+ seeding.initial_sync_complete = False
events = [_make_event(op="I", position="0/100", table="events", columns={"id": 1})]
- _reader, mock_s3, mock_producer = self._run(MockBufferWriter, events, [companion], source)
+ _reader, mock_s3, mock_producer = self._run(MockBufferWriter, events, [seeding], source)
MockBufferWriter.return_value.write_batch.assert_not_called()
mock_s3.write_batch.assert_called_once()
@@ -3756,7 +3758,8 @@ class TestBufferedIngressCapture:
# tick would erase a failing consumer run within a minute and hide a buffer backlog.
source = _make_source()
buffered = _make_schema("users", cdc_mode="streaming", source=source)
- legacy = _make_schema("events", cdc_mode="streaming", cdc_table_mode="cdc_only", source=source)
+ legacy = _make_schema("events", cdc_mode="streaming", source=source)
+ legacy.initial_sync_complete = False
events = [
_make_event(op="I", position="0/100", columns={"id": 1}),
_make_event(op="I", position="0/100", table="events", columns={"id": 1}),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_lane_position.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_lane_position.py
new file mode 100644
index 000000000000..3bc218144156
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_lane_position.py
@@ -0,0 +1,330 @@
+import pytest
+from unittest.mock import patch
+
+import pyarrow as pa
+import deltalake
+import pyarrow.dataset as pa_ds
+
+from products.warehouse_sources.backend.temporal.data_imports.cdc import lane_position
+from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_OP_COLUMN, CDC_SEQ_COLUMN
+from products.warehouse_sources.backend.temporal.data_imports.cdc.lane_position import (
+ STATS_COLUMNS_PROPERTY,
+ ensure_position_stats,
+ read_lane_position,
+)
+
+# Past the 32 columns Delta keeps stats for by default, which is where a real source table sits.
+_WIDE = 40
+
+
+def _rows(seqs: list[int], *, wide: bool = True, ids: list[int] | None = None) -> pa.Table:
+ columns: dict[str, pa.Array] = {"id": pa.array(ids or list(range(len(seqs))), pa.int64())}
+ if wide:
+ columns |= {f"c{i}": pa.array([0] * len(seqs), pa.int64()) for i in range(_WIDE)}
+ columns[CDC_SEQ_COLUMN] = pa.array(seqs, pa.int64())
+ columns[CDC_OP_COLUMN] = pa.array(["I"] * len(seqs), pa.string())
+ return pa.table(columns)
+
+
+def _content(row_id: int, *, wide: bool = True) -> dict:
+ return {"id": row_id, **({f"c{i}": 0 for i in range(_WIDE)} if wide else {})}
+
+
+def _write(
+ path, seqs: list[int], *, stats: bool = True, wide: bool = True, ids: list[int] | None = None
+) -> deltalake.DeltaTable:
+ deltalake.write_deltalake(
+ str(path),
+ _rows(seqs, wide=wide, ids=ids),
+ mode="overwrite",
+ configuration={STATS_COLUMNS_PROPERTY: CDC_SEQ_COLUMN} if stats else None,
+ )
+ return deltalake.DeltaTable(str(path))
+
+
+def _append(
+ path, seqs: list[int], *, wide: bool = True, ids: list[int] | None = None, evolve: bool = False
+) -> deltalake.DeltaTable:
+ deltalake.write_deltalake(
+ str(path), _rows(seqs, wide=wide, ids=ids), mode="append", schema_mode="merge" if evolve else None
+ )
+ return deltalake.DeltaTable(str(path))
+
+
+async def _resolved(table, key_columns=("id", CDC_OP_COLUMN)):
+ position = await read_lane_position(table, key_columns=list(key_columns))
+ assert position.load_applied is not None
+ return position.load_applied()
+
+
+class TestReadLanePosition:
+ async def test_a_lane_with_no_table_has_no_position(self):
+ assert (await read_lane_position(None)).position is None
+
+ async def test_a_table_without_the_position_column_has_no_position(self, tmp_path):
+ deltalake.write_deltalake(str(tmp_path / "t"), pa.table({"id": pa.array([1], pa.int64())}), mode="overwrite")
+
+ assert (await read_lane_position(deltalake.DeltaTable(str(tmp_path / "t")))).position is None
+
+ async def test_an_empty_table_has_no_position(self, tmp_path):
+ assert (await read_lane_position(_write(tmp_path / "t", []))).position is None
+
+ async def test_the_position_is_the_highest_the_table_holds(self, tmp_path):
+ position = await read_lane_position(_write(tmp_path / "t", [10, 20, 30]))
+
+ assert position.position == 30
+
+ async def test_the_rows_at_the_position_come_back_keyed_by_identity(self, tmp_path):
+ # One transaction stamps every row it carries with its commit position. Which of those
+ # rows a table already holds is what tells a resumed read where the transaction got to.
+ table = _write(tmp_path / "t", [10, 30, 30], ids=[1, 2, 3])
+
+ position = await _resolved(table)
+
+ assert position.position == 30
+ assert position.applied == {(2, "I"): [_content(2)], (3, "I"): [_content(3)]}
+
+ async def test_the_same_key_written_twice_keeps_both_rows_content(self, tmp_path):
+ # History keeps every version. A key changed twice inside one transaction holds two rows
+ # that share every key column, and only their content tells a third change from a replay.
+ table = _write(tmp_path / "t", [30, 30], ids=[1, 1])
+
+ position = await _resolved(table)
+
+ assert position.applied == {(1, "I"): [_content(1), _content(1)]}
+ assert position.content_schema is not None
+ assert position.content_schema.names == ["id", *(f"c{i}" for i in range(_WIDE))]
+
+ async def test_rows_at_the_position_are_gathered_across_the_files_holding_them(self, tmp_path):
+ path = tmp_path / "t"
+ _write(path, [10, 30], ids=[1, 2])
+ table = _append(path, [30, 30], ids=[3, 4])
+
+ position = await _resolved(table)
+
+ assert position.applied == {(2, "I"): [_content(2)], (3, "I"): [_content(3)], (4, "I"): [_content(4)]}
+
+ async def test_a_lane_that_does_not_ask_for_them_reads_no_rows(self, tmp_path, mocker):
+ # The merge lane needs only the position: it rewrites rows at it as upserts.
+ table = _write(tmp_path / "t", [10, 30])
+ read = mocker.spy(table, "to_pyarrow_table")
+
+ position = await read_lane_position(table)
+
+ assert position.position == 30
+ assert position.applied == {}
+ read.assert_not_called()
+
+ async def test_a_merge_table_whose_files_carry_no_statistic_reports_no_position(self, tmp_path, mocker):
+ # The merge lane replays as upserts, so nothing is lost by knowing nothing, and a scan of
+ # the column would cost more than the replay.
+ table = _write(tmp_path / "t", [10, 30], stats=False)
+ read = mocker.spy(table, "to_pyarrow_table")
+
+ position = await read_lane_position(table)
+
+ assert position.position is None
+ read.assert_not_called()
+
+ async def test_a_history_table_whose_files_carry_no_statistic_scans_the_column_once(self, tmp_path):
+ # A repartition rewrites every file without the statistic. Reporting no position here
+ # would replay the whole buffer into an append-only table; the scan is the price of not.
+ table = _write(tmp_path / "t", [10, 30], stats=False)
+
+ position = await _resolved(table)
+
+ assert position.position == 30
+ assert set(position.applied) == {(1, "I")}
+
+ async def test_only_the_files_that_can_hold_the_position_are_read(self, tmp_path, mocker):
+ # A snapshot seed has no position column at all, and a 50M-row seed read in full on every
+ # tick just to be filtered away is the cost this avoids. The seed file is opened only as
+ # far as its footer.
+ path = tmp_path / "t"
+ seed = pa.table({"id": pa.array(range(1000), pa.int64())})
+ deltalake.write_deltalake(str(path), seed, mode="overwrite")
+ deltalake.DeltaTable(str(path)).alter.set_table_properties({STATS_COLUMNS_PROPERTY: CDC_SEQ_COLUMN})
+ _append(path, [10, 10], wide=False, ids=[1, 2], evolve=True)
+ table = _append(path, [30], wide=False, ids=[3], evolve=True)
+ real = pa_ds.FileSystemDataset
+ built = mocker.patch.object(pa_ds, "FileSystemDataset", side_effect=real)
+
+ position = await _resolved(table)
+
+ assert position.applied == {(3, "I"): [_content(3, wide=False)]}
+ assert len(built.call_args.args[0]) == 1
+
+ async def test_a_seed_file_the_schema_evolution_rewrote_is_not_read_either(self, tmp_path, mocker):
+ # Adding the position column can rewrite a seed file with it present and every value null.
+ # Its `max` statistic is then null — the same as no statistic — and only its null count
+ # says the file cannot hold a position. Without that check every such file is read in full.
+ path = tmp_path / "t"
+ rewritten_seed = pa.table(
+ {
+ "id": pa.array(range(500), pa.int64()),
+ CDC_SEQ_COLUMN: pa.array([None] * 500, pa.int64()),
+ CDC_OP_COLUMN: pa.array(["I"] * 500, pa.string()),
+ }
+ )
+ deltalake.write_deltalake(str(path), rewritten_seed, mode="overwrite")
+ deltalake.DeltaTable(str(path)).alter.set_table_properties({STATS_COLUMNS_PROPERTY: CDC_SEQ_COLUMN})
+ table = _append(path, [30], wide=False, ids=[3])
+ real = pa_ds.FileSystemDataset
+ built = mocker.patch.object(pa_ds, "FileSystemDataset", side_effect=real)
+
+ position = await _resolved(table)
+
+ assert position.position == 30
+ assert len(built.call_args.args[0]) == 1
+
+ async def test_the_rows_at_the_position_are_not_read_until_a_batch_needs_them(self, tmp_path, mocker):
+ # An idle tick has nothing at the position to match, so the table's rows there — a whole
+ # bulk transaction, on the tick after one — must not be read just to be discarded.
+ table = _write(tmp_path / "t", [10, 30], ids=[1, 2])
+ read = mocker.spy(lane_position, "_rows_at_position")
+
+ position = await read_lane_position(table, key_columns=["id", CDC_OP_COLUMN])
+
+ assert position.position == 30
+ read.assert_not_called()
+ assert position.load_applied is not None
+ assert position.load_applied().applied == {(2, "I"): [_content(2)]}
+
+ async def test_a_partition_value_with_escaped_characters_is_still_read(self, tmp_path):
+ # The add action escapes a partition value once more than the dataset fragment does, so
+ # matching them as raw strings skipped the file and replayed its rows into history.
+ rows = _rows([10, 30], ids=[1, 2]).append_column("part", pa.array(["a b=c", "a b=c"], pa.string()))
+ deltalake.write_deltalake(
+ str(tmp_path / "t"),
+ rows,
+ mode="overwrite",
+ partition_by=["part"],
+ configuration={STATS_COLUMNS_PROPERTY: CDC_SEQ_COLUMN},
+ )
+
+ position = await _resolved(deltalake.DeltaTable(str(tmp_path / "t")))
+
+ assert position.applied == {(2, "I"): [{**_content(2), "part": "a b=c"}]}
+
+ async def test_a_stat_bearing_file_decides_without_reading_the_column(self, tmp_path):
+ # Positions only ever increase and the property follows the first write, so a file
+ # without the statistic cannot hold a higher position than one that has it.
+ path = tmp_path / "t"
+ _write(path, [10, 10], stats=False)
+ deltalake.DeltaTable(str(path)).alter.set_table_properties({STATS_COLUMNS_PROPERTY: CDC_SEQ_COLUMN})
+ table = _append(path, [30, 30])
+
+ assert (await read_lane_position(table)).position == 30
+
+
+class TestPositionRowCap:
+ @pytest.mark.parametrize("cap,limit", [("MAX_POSITION_ROWS", 2), ("MAX_POSITION_BYTES", 1)])
+ async def test_above_the_cap_the_lane_keeps_keys_and_operations_only(self, cap, limit, tmp_path, mocker):
+ # One bulk transaction stamps every row it touched with one position. Reading them all
+ # back as dicts would exhaust memory before the write that moves the position could ever
+ # happen — and the row count alone says nothing about how wide those rows are.
+ mocker.patch(f"products.warehouse_sources.backend.temporal.data_imports.cdc.lane_position.{cap}", limit)
+ table = _write(tmp_path / "t", [30, 30, 30], ids=[1, 1, 2])
+
+ position = await _resolved(table)
+
+ assert position.position == 30
+ assert position.applied == {(1, "I"): [{}, {}], (2, "I"): [{}]}
+ assert position.content_schema is None
+
+ @pytest.mark.parametrize("cap", ["MAX_POSITION_ROWS", "MAX_POSITION_BYTES"])
+ async def test_a_big_file_with_few_rows_at_the_position_does_not_degrade(self, cap, tmp_path, mocker):
+ # After compaction the file holding the newest position holds most of the table. Its row
+ # count is not the count at the position, nor are its bytes, and degrading on either would
+ # switch content matching off for every history table of any size.
+ table = _write(tmp_path / "t", [10, 10, 10, 30], ids=[1, 2, 3, 4])
+ file_bytes = int(pa.table(table.get_add_actions(flatten=True)).column("size_bytes").to_pylist()[0] or 0)
+ limit = {"MAX_POSITION_ROWS": 2, "MAX_POSITION_BYTES": file_bytes // 2}[cap]
+ mocker.patch(f"products.warehouse_sources.backend.temporal.data_imports.cdc.lane_position.{cap}", limit)
+
+ position = await _resolved(table)
+
+ assert position.applied == {(4, "I"): [_content(4)]}
+ assert position.content_schema is not None
+
+ async def test_a_merge_table_that_never_gains_the_statistic_is_an_alert(self, tmp_path):
+ # It replays safely, but never advances the floor: nothing is deleted and the buffer is
+ # re-merged and re-billed every tick. Silence there is the failure.
+ table = _write(tmp_path / "t", [10, 30], stats=False)
+ with patch.object(lane_position.logger, "warning") as warned:
+ await read_lane_position(table)
+
+ assert warned.call_args.args[0] == "cdc_position_unreadable"
+
+
+class TestEnsurePositionStats:
+ async def test_it_names_the_position_column_so_later_reads_are_a_lookup(self, tmp_path):
+ table = _write(tmp_path / "t", [10], stats=False)
+
+ await ensure_position_stats(table)
+
+ declared = deltalake.DeltaTable(str(tmp_path / "t")).metadata().configuration[STATS_COLUMNS_PROPERTY]
+ assert CDC_SEQ_COLUMN in declared.split(",")
+
+ async def test_it_names_the_position_column_before_the_table_has_one(self, tmp_path):
+ # A snapshot-seeded companion has no position column until its first buffered write, and
+ # that write is the one that has to carry the statistic. Without it the next run reads no
+ # position and the append lane writes every row a second time.
+ deltalake.write_deltalake(str(tmp_path / "t"), pa.table({"id": pa.array([1], pa.int64())}), mode="overwrite")
+ table = deltalake.DeltaTable(str(tmp_path / "t"))
+
+ await ensure_position_stats(table, ["id"])
+
+ declared = deltalake.DeltaTable(str(tmp_path / "t")).metadata().configuration[STATS_COLUMNS_PROPERTY]
+ assert CDC_SEQ_COLUMN in declared.split(",")
+
+ async def test_it_does_not_rewrite_a_table_that_already_has_it(self, tmp_path):
+ # Runs on every lane build, so a second call has to be free.
+ table = _write(tmp_path / "t", [10], stats=False)
+ await ensure_position_stats(table, ["id"])
+ settled = deltalake.DeltaTable(str(tmp_path / "t"))
+
+ await ensure_position_stats(settled, ["id"])
+
+ assert deltalake.DeltaTable(str(tmp_path / "t")).version() == settled.version()
+
+ async def test_a_table_that_refuses_the_property_does_not_fail_the_sync(self, tmp_path, mocker):
+ table = _write(tmp_path / "t", [10], stats=False)
+ mocker.patch.object(type(table.alter), "set_table_properties", side_effect=RuntimeError("no"), create=True)
+
+ await ensure_position_stats(table)
+
+
+pytestmark = pytest.mark.asyncio
+
+
+class TestStatsColumnList:
+ async def test_the_columns_delta_already_indexed_keep_their_statistics(self, tmp_path):
+ # Naming any column replaces Delta's default window, and nothing sets this property on a
+ # warehouse table today. Naming only ours would strip the min/max off every column the
+ # customer queries the moment their schema flips.
+ table = _write(tmp_path / "t", [10], stats=False)
+ indexed_by_default = [field.name for field in table.schema().fields][:32]
+
+ await ensure_position_stats(table, ["id"])
+
+ wanted = deltalake.DeltaTable(str(tmp_path / "t")).metadata().configuration[STATS_COLUMNS_PROPERTY]
+ assert set(indexed_by_default) <= set(wanted.split(","))
+
+ async def test_the_merge_key_keeps_its_pruning(self, tmp_path):
+ # The merge key can sit past the default window on a wide table, so it is named outright.
+ table = _write(tmp_path / "t", [10], stats=False, wide=False)
+
+ await ensure_position_stats(table, ["id", "id"])
+
+ wanted = deltalake.DeltaTable(str(tmp_path / "t")).metadata().configuration[STATS_COLUMNS_PROPERTY]
+ assert wanted.split(",").count("id") == 1
+ assert CDC_SEQ_COLUMN in wanted.split(",")
+
+ async def test_a_column_the_table_lacks_is_not_declared(self, tmp_path):
+ table = _write(tmp_path / "t", [10], stats=False)
+
+ await ensure_position_stats(table, ["nope"])
+
+ wanted = deltalake.DeltaTable(str(tmp_path / "t")).metadata().configuration[STATS_COLUMNS_PROPERTY]
+ assert "nope" not in wanted.split(",")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_listing_proof.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_listing_proof.py
new file mode 100644
index 000000000000..05d2a56046b2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_listing_proof.py
@@ -0,0 +1,199 @@
+import datetime as dt
+
+from posthog.test.base import BaseTest
+
+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.temporal.data_imports.cdc.companion_jobs import (
+ record_companion_job,
+ retire_orphaned_companions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
+ BUFFER_LISTED_AT_KEY,
+ clear_listing,
+ read_completed_listing_proof,
+)
+
+
+class TestCompletedListingProof(BaseTest):
+ """The proof that authorises deleting a buffer file, which is the one irreversible step here."""
+
+ def _proof(self, schema):
+ # The synchronous entry point, so the query runs on this test's own connection.
+ return read_completed_listing_proof(schema)
+
+ def _schema(self) -> ExternalDataSchema:
+ source = ExternalDataSource.objects.create(
+ team=self.team, source_id="s", connection_id="c", status="Running", source_type="Postgres"
+ )
+ return ExternalDataSchema.objects.create(team=self.team, source=source, name="users")
+
+ def _job(self, schema, *, status, listed_at=None, companion_of=None, billable=True) -> ExternalDataJob:
+ snapshot: dict = {}
+ if listed_at is not None:
+ snapshot[BUFFER_LISTED_AT_KEY] = listed_at.isoformat()
+ if companion_of is not None:
+ snapshot["companion_of"] = str(companion_of)
+ job = ExternalDataJob.objects.create(
+ team=self.team,
+ pipeline=schema.source,
+ schema=schema,
+ status=status,
+ rows_synced=0,
+ billable=billable,
+ schema_snapshot=snapshot,
+ )
+ if companion_of is not None:
+ record_companion_job(str(companion_of), self.team.id, str(job.id), first_of_attempt=False)
+ return job
+
+ def test_a_completed_run_with_no_companion_proves_its_listing(self):
+ # A `consolidated` run, and a `both` run whose history lane had nothing to write, both
+ # leave no companion row. An empty companion set has to count as proof.
+ schema = self._schema()
+ listed = dt.datetime(2026, 1, 1, 12, 0, tzinfo=dt.UTC)
+ self._job(schema, status=ExternalDataJob.Status.COMPLETED, listed_at=listed)
+
+ assert self._proof(schema) == listed
+
+ def test_a_run_still_going_proves_nothing(self):
+ schema = self._schema()
+ self._job(schema, status=ExternalDataJob.Status.RUNNING, listed_at=dt.datetime(2026, 1, 1, tzinfo=dt.UTC))
+
+ assert self._proof(schema) is None
+
+ @parameterized.expand([("running", "Running"), ("failed", "Failed")])
+ def test_a_run_whose_history_lane_did_not_finish_proves_nothing(self, _name, companion_status):
+ # Deleting on this run's word would drop a file the history table still owed.
+ schema = self._schema()
+ parent = self._job(
+ schema, status=ExternalDataJob.Status.COMPLETED, listed_at=dt.datetime(2026, 1, 1, tzinfo=dt.UTC)
+ )
+ self._job(schema, status=companion_status, companion_of=parent.id, billable=False)
+
+ assert self._proof(schema) is None
+
+ def test_an_older_run_proves_it_when_the_newest_one_cannot(self):
+ schema = self._schema()
+ older = dt.datetime(2026, 1, 1, 10, 0, tzinfo=dt.UTC)
+ self._job(schema, status=ExternalDataJob.Status.COMPLETED, listed_at=older)
+ newer = self._job(
+ schema, status=ExternalDataJob.Status.COMPLETED, listed_at=dt.datetime(2026, 1, 1, 11, 0, tzinfo=dt.UTC)
+ )
+ self._job(schema, status=ExternalDataJob.Status.FAILED, companion_of=newer.id, billable=False)
+
+ assert self._proof(schema) == older
+
+ def test_a_run_that_never_listed_proves_nothing(self):
+ # The in-flight no-op tick returns an empty response without listing, so it must not count.
+ schema = self._schema()
+ self._job(schema, status=ExternalDataJob.Status.COMPLETED)
+
+ assert self._proof(schema) is None
+
+ def test_a_naive_timestamp_is_refused(self):
+ schema = self._schema()
+ self._job(schema, status=ExternalDataJob.Status.COMPLETED, listed_at=dt.datetime(2026, 1, 1, 12, 0))
+
+ assert self._proof(schema) is None
+
+
+class TestRecordCompanionJob(BaseTest):
+ def test_a_new_attempt_starts_the_list_over(self):
+ # An earlier attempt's companion was retired or drained by the time this attempt reads;
+ # leaving it listed would have the listing proof reject this run for good.
+ source = ExternalDataSource.objects.create(
+ team=self.team, source_id="s", connection_id="c", status="Running", source_type="Postgres"
+ )
+ schema = ExternalDataSchema.objects.create(team=self.team, source=source, name="users")
+ parent = ExternalDataJob.objects.create(
+ team=self.team, pipeline=source, schema=schema, status="Running", rows_synced=0
+ )
+
+ record_companion_job(str(parent.id), self.team.id, "attempt-1-companion", first_of_attempt=True)
+ record_companion_job(str(parent.id), self.team.id, "attempt-2-companion", first_of_attempt=True)
+ record_companion_job(str(parent.id), self.team.id, "attempt-2-second", first_of_attempt=False)
+
+ parent.refresh_from_db()
+ assert (parent.schema_snapshot or {})["cdc_companion_job_ids"] == ["attempt-2-companion", "attempt-2-second"]
+
+
+class TestClearListing(BaseTest):
+ def _job(self, schema, snapshot) -> ExternalDataJob:
+ return ExternalDataJob.objects.create(
+ team=self.team,
+ pipeline=schema.source,
+ schema=schema,
+ status="Running",
+ rows_synced=0,
+ schema_snapshot=snapshot,
+ )
+
+ def _schema(self) -> ExternalDataSchema:
+ source = ExternalDataSource.objects.create(
+ team=self.team, source_id="s", connection_id="c", status="Running", source_type="Postgres"
+ )
+ return ExternalDataSchema.objects.create(team=self.team, source=source, name="users")
+
+ def test_only_the_stamp_comes_off(self):
+ schema = self._schema()
+ job = self._job(schema, {BUFFER_LISTED_AT_KEY: "2026-01-01T00:00:00+00:00", "name": "users"})
+
+ clear_listing(str(job.id), self.team.id)
+
+ job.refresh_from_db()
+ assert job.schema_snapshot == {"name": "users"}
+
+ def test_a_job_that_never_stamped_is_left_alone(self):
+ schema = self._schema()
+ job = self._job(schema, {"name": "users"})
+ before = job.updated_at
+
+ clear_listing(str(job.id), self.team.id)
+
+ job.refresh_from_db()
+ assert job.updated_at == before
+
+
+class TestRetireOrphanedCompanions(BaseTest):
+ def _schema(self) -> ExternalDataSchema:
+ source = ExternalDataSource.objects.create(
+ team=self.team, source_id="s", connection_id="c", status="Running", source_type="Postgres"
+ )
+ return ExternalDataSchema.objects.create(team=self.team, source=source, name="users")
+
+ def _job(self, schema, *, status="Running", companion_of=None) -> ExternalDataJob:
+ snapshot = {"companion_of": str(companion_of)} if companion_of else {}
+ return ExternalDataJob.objects.create(
+ team=self.team,
+ pipeline=schema.source,
+ schema=schema,
+ status=status,
+ rows_synced=0,
+ billable=companion_of is None,
+ schema_snapshot=snapshot,
+ )
+
+ def test_only_running_companions_are_retired(self):
+ schema = self._schema()
+ me = self._job(schema)
+ mine = self._job(schema, companion_of=me.id)
+ dead_run = self._job(schema, status="Failed")
+ orphan = self._job(schema, companion_of=dead_run.id)
+ finished = self._job(schema, status="Completed", companion_of=dead_run.id)
+ plain_running = self._job(schema)
+
+ retired = retire_orphaned_companions(schema)
+
+ # `mine` was opened by an earlier attempt of the running job: this attempt opens its own
+ # lazily, later, so at run start it is an orphan like any other.
+ assert sorted(retired) == sorted([str(orphan.id), str(mine.id)])
+ for job in (me, mine, dead_run, finished, plain_running, orphan):
+ job.refresh_from_db()
+ # The customer's schema is untouched: only companion rows moved, and only to Failed.
+ assert orphan.status == "Failed" and mine.status == "Failed"
+ assert [j.status for j in (me, plain_running)] == ["Running"] * 2
+ assert finished.status == "Completed"
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.py
index 7003670ab799..9c5a1befcf1f 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,5 +1,3 @@
-from typing import Any
-
import pytest
from unittest.mock import MagicMock, patch
@@ -13,16 +11,12 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import
DELETED_COLUMN,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import (
- LOAD_POSITION_CONFIG_KEY,
MAX_VERIFIED_DELETE_ROWS,
SCD2_APPEND_MODE,
- batch_max_seq,
dedupe_keep_highest_seq,
drop_superseded_rows,
has_engine_seq,
is_cdc_write_resolution_enabled,
- persist_load_position,
- read_load_position,
resolve_batch,
verify_delete_enrichment,
)
@@ -50,76 +44,6 @@ def _existing(ids, names):
return pa.table({"id": pa.array(ids, pa.int64()), "name": pa.array(names, pa.string())})
-class TestBatchMaxSeq:
- def test_none_without_seq_column(self):
- assert batch_max_seq(_batch([1], ["a"], ["I"])) is None
-
- def test_none_when_empty(self):
- assert batch_max_seq(_batch([], [], [], seqs=[])) is None
-
- def test_ignores_nulls(self):
- table = _batch([1, 2, 3], ["a", "b", "c"], ["I", "I", "I"], seqs=[10, None, 30])
- assert batch_max_seq(table) == 30
-
-
-class TestDropSupersededRows:
- def test_passthrough_without_watermark(self):
- table = _batch([1, 2], ["a", "b"], ["I", "I"], seqs=[10, 20])
- result, dropped = drop_superseded_rows(table, None)
- assert dropped == 0
- assert result is table
-
- def test_passthrough_without_seq_column(self):
- table = _batch([1, 2], ["a", "b"], ["I", "I"])
- result, dropped = drop_superseded_rows(table, 99)
- assert dropped == 0
- assert result is table
-
- def test_drops_only_rows_strictly_below_watermark(self):
- table = _batch([1, 2, 3], ["a", "b", "c"], ["I", "I", "I"], seqs=[10, 20, 30])
- result, dropped = drop_superseded_rows(table, 20)
-
- assert dropped == 1
- assert result.column("id").to_pylist() == [2, 3]
-
- def test_keeps_later_chunks_of_a_split_transaction(self):
- # Every event in one Postgres transaction shares its commit LSN, and a transaction bigger
- # than the flush budget spans micro-batches. Dropping seq == watermark would discard the
- # rest of the transaction outright.
- table = _batch([3, 4], ["c", "d"], ["I", "I"], seqs=[20, 20])
- result, dropped = drop_superseded_rows(table, 20)
-
- assert dropped == 0
- assert result.column("id").to_pylist() == [3, 4]
-
- def test_keeps_null_positions(self):
- # An unknown position cannot be proven stale; dropping it would lose data.
- table = _batch([1, 2], ["a", "b"], ["I", "I"], seqs=[None, 5])
- result, dropped = drop_superseded_rows(table, 10)
-
- assert dropped == 1
- assert result.column("id").to_pylist() == [1]
-
- def test_drops_replayed_rows_below_the_watermark(self):
- table = _batch([1, 2], ["a", "b"], ["I", "I"], seqs=[10, 20])
- result, dropped = drop_superseded_rows(table, 30)
-
- assert dropped == 2
- assert result.num_rows == 0
-
- def test_ignores_a_source_owned_seq_column(self):
- # The batcher passes through a source column named _ph_cdc_seq untouched, so its values
- # are user data. Trusting them would let a source set a high value, poison the watermark,
- # and have its own later rows dropped.
- table = _batch([1, 2], ["a", "b"], ["I", "I"], seqs=[10, 20], engine_seq=False)
- result, dropped = drop_superseded_rows(table, 15)
-
- assert dropped == 0
- assert result is table
- assert not has_engine_seq(table)
- assert batch_max_seq(table) is None
-
-
class TestDedupeKeepHighestSeq:
def test_passthrough_without_seq_column(self):
table = _batch([1, 1], ["a", "b"], ["I", "U"])
@@ -171,11 +95,10 @@ class TestDedupeKeepHighestSeq:
class TestResolveBatch:
- def test_consolidated_lane_drops_superseded_and_dedupes(self):
+ def test_consolidated_lane_dedupes(self):
table = _batch([1, 1, 2], ["old", "new", "other"], ["I", "U", "I"], seqs=[10, 20, 30])
- result, stats = resolve_batch(table, ["id"], watermark=None, cdc_write_mode="incremental_merge")
+ result, stats = resolve_batch(table, ["id"], cdc_write_mode="incremental_merge")
- assert stats.superseded == 0
assert stats.duplicate_key == 1
assert result.column("name").to_pylist() == ["new", "other"]
@@ -183,31 +106,23 @@ class TestResolveBatch:
# The companion table is append-only history: deduping it would delete versions, not
# resolve a conflict.
table = _batch([1, 1], ["v1", "v2"], ["I", "U"], seqs=[10, 20])
- result, stats = resolve_batch(table, ["id"], watermark=None, cdc_write_mode=SCD2_APPEND_MODE)
+ result, stats = resolve_batch(table, ["id"], cdc_write_mode=SCD2_APPEND_MODE)
assert stats.duplicate_key == 0
assert result.column("name").to_pylist() == ["v1", "v2"]
- def test_history_lane_still_drops_already_applied_rows(self):
- # Replaying a buffer file into the companion is how duplicate history rows arise.
- table = _batch([1, 1], ["v1", "v2"], ["I", "U"], seqs=[10, 20])
- result, stats = resolve_batch(table, ["id"], watermark=15, cdc_write_mode=SCD2_APPEND_MODE)
-
- assert stats.superseded == 1
- assert result.column("name").to_pylist() == ["v2"]
-
def test_source_owned_seq_column_disables_resolution_entirely(self):
table = _batch([1, 1], ["old", "new"], ["I", "U"], seqs=[99, 1], engine_seq=False)
- result, stats = resolve_batch(table, ["id"], watermark=50, cdc_write_mode="incremental_merge")
+ result, stats = resolve_batch(table, ["id"], cdc_write_mode="incremental_merge")
- assert (stats.superseded, stats.duplicate_key) == (0, 0)
+ assert stats.duplicate_key == 0
assert result is table
def test_noop_on_batches_without_positions(self):
table = _batch([1, 2], ["a", "b"], ["I", "I"])
- result, stats = resolve_batch(table, ["id"], watermark=99, cdc_write_mode="incremental_merge")
+ result, stats = resolve_batch(table, ["id"], cdc_write_mode="incremental_merge")
- assert (stats.superseded, stats.duplicate_key) == (0, 0)
+ assert stats.duplicate_key == 0
assert result is table
@@ -266,54 +181,6 @@ class TestVerifyDeleteEnrichment:
assert report.delete_rows_checked == MAX_VERIFIED_DELETE_ROWS
-class TestLoadPosition:
- @parameterized.expand(
- [
- ("absent_config", None, None),
- ("empty_config", {}, None),
- ("other_lane_only", {LOAD_POSITION_CONFIG_KEY: {"users_cdc": 99}}, None),
- ("int_value", {LOAD_POSITION_CONFIG_KEY: {"users": 42}}, 42),
- # JSON round-trips can hand back strings; a bad value must read as "unknown", not 0.
- ("string_value", {LOAD_POSITION_CONFIG_KEY: {"users": "42"}}, 42),
- ("garbage_value", {LOAD_POSITION_CONFIG_KEY: {"users": "not-a-number"}}, None),
- ("null_value", {LOAD_POSITION_CONFIG_KEY: {"users": None}}, None),
- ]
- )
- def test_read(self, _name, config, expected):
- assert read_load_position(config, "users") == expected
-
- def test_persist_creates_the_key_and_leaves_siblings_alone(self):
- captured: dict[str, Any] = {"cdc_last_log_position": "0/ABC"}
-
- def fake_update(schema_id, team_id, *, mutate=None, **kwargs):
- mutate(captured)
-
- with patch(
- "products.warehouse_sources.backend.models.external_data_schema.update_sync_type_config_keys",
- side_effect=fake_update,
- ):
- persist_load_position("schema-1", 2, "users", 100)
-
- assert captured[LOAD_POSITION_CONFIG_KEY] == {"users": 100}
- # Capture's own position lives in the same JSON column and must survive.
- assert captured["cdc_last_log_position"] == "0/ABC"
-
- @parameterized.expand([("advances", 50, 100, 100), ("never_rewinds", 100, 50, 100), ("equal", 100, 100, 100)])
- def test_persist_is_monotonic(self, _name, existing, incoming, expected):
- captured = {LOAD_POSITION_CONFIG_KEY: {"users": existing}}
-
- def fake_update(schema_id, team_id, *, mutate=None, **kwargs):
- mutate(captured)
-
- with patch(
- "products.warehouse_sources.backend.models.external_data_schema.update_sync_type_config_keys",
- side_effect=fake_update,
- ):
- persist_load_position("schema-1", 2, "users", incoming)
-
- assert captured[LOAD_POSITION_CONFIG_KEY]["users"] == expected
-
-
class TestIsCdcWriteResolutionEnabled:
@pytest.fixture(autouse=True)
def _clear_cache(self):
@@ -365,3 +232,60 @@ class TestIsCdcWriteResolutionEnabled:
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])
+ result, dropped = drop_superseded_rows(table, None)
+ assert dropped == 0
+ assert result is table
+
+ def test_passthrough_without_seq_column(self):
+ table = _batch([1, 2], ["a", "b"], ["I", "I"])
+ result, dropped = drop_superseded_rows(table, 99)
+ assert dropped == 0
+ assert result is table
+
+ def test_drops_only_rows_strictly_below_watermark(self):
+ table = _batch([1, 2, 3], ["a", "b", "c"], ["I", "I", "I"], seqs=[10, 20, 30])
+ result, dropped = drop_superseded_rows(table, 20)
+
+ assert dropped == 1
+ assert result.column("id").to_pylist() == [2, 3]
+
+ def test_keeps_later_chunks_of_a_split_transaction(self):
+ # Every event in one Postgres transaction shares its commit LSN, and a transaction bigger
+ # than the flush budget spans micro-batches. Dropping seq == watermark would discard the
+ # rest of the transaction outright.
+ table = _batch([3, 4], ["c", "d"], ["I", "I"], seqs=[20, 20])
+ result, dropped = drop_superseded_rows(table, 20)
+
+ assert dropped == 0
+ assert result.column("id").to_pylist() == [3, 4]
+
+ def test_keeps_null_positions(self):
+ # An unknown position cannot be proven stale; dropping it would lose data.
+ table = _batch([1, 2], ["a", "b"], ["I", "I"], seqs=[None, 5])
+ result, dropped = drop_superseded_rows(table, 10)
+
+ assert dropped == 1
+ assert result.column("id").to_pylist() == [1]
+
+ def test_drops_replayed_rows_below_the_watermark(self):
+ table = _batch([1, 2], ["a", "b"], ["I", "I"], seqs=[10, 20])
+ result, dropped = drop_superseded_rows(table, 30)
+
+ assert dropped == 2
+ assert result.num_rows == 0
+
+ def test_ignores_a_source_owned_seq_column(self):
+ # The batcher passes through a source column named _ph_cdc_seq untouched, so its values
+ # are user data. Trusting them would let a source set a high value, poison the watermark,
+ # and have its own later rows dropped.
+ table = _batch([1, 2], ["a", "b"], ["I", "I"], seqs=[10, 20], engine_seq=False)
+ result, dropped = drop_superseded_rows(table, 15)
+
+ assert dropped == 0
+ assert result is table
+ assert not has_engine_seq(table)
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 c029646d39dd..853e71cfbf4b 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
@@ -8,13 +8,29 @@ import pyarrow as pa
import pyarrow.parquet as pq
from parameterized import parameterized
-from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN, CDC_SEQ_PROVENANCE
+from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (
+ CDC_OP_COLUMN,
+ CDC_SEQ_COLUMN,
+ CDC_SEQ_PROVENANCE,
+ CDC_TIMESTAMP_COLUMN,
+ SCD2_VALID_FROM_COLUMN,
+ SCD2_VALID_TO_COLUMN,
+ TOAST_OMITTED_COLUMN,
+)
from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import build_buffer_file_name
+from products.warehouse_sources.backend.temporal.data_imports.cdc.lane_position import LanePosition
from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
+ BUFFERED_LANE_KEY,
+ COMPANION_WRITE_MODE,
+ CONSOLIDATED_WRITE_MODE,
+ CDCLane,
CDCSourceManager,
- has_pending_legacy_backlog,
- is_buffered_consolidated,
+ ReplayFilter,
+ build_output_lanes,
+ consumes_buffer,
+ has_batches_in_flight,
scheduled_sync_consumes_buffer,
+ served_lanes,
serves_buffered_lane,
)
@@ -33,6 +49,44 @@ def _table(ids: list[int], seqs: list[int]) -> pa.Table:
)
+def _ops(
+ ids: list[int],
+ seqs: list[int],
+ ops: list[str] | None = None,
+ labels: list[str | None] | None = None,
+ omitted: list[list[str] | None] | None = None,
+) -> pa.Table:
+ """A batch as the lanes see it: keyed rows carrying the position, operation and commit time.
+
+ `label` is the one content column, so two changes to a key can differ. `omitted` is the TOAST
+ marker: the columns a row does not carry because the source left them unchanged.
+ """
+ stamps = pa.array([dt.datetime(2026, 1, 1, tzinfo=dt.UTC)] * len(ids), pa.timestamp("us", tz="UTC"))
+ table = (
+ _table(ids, seqs)
+ .append_column(pa.field("label", pa.string()), pa.array(labels or ["v1"] * len(ids), pa.string()))
+ .append_column(pa.field(CDC_OP_COLUMN, pa.string()), pa.array(ops or ["I"] * len(ids), pa.string()))
+ .append_column(pa.field(CDC_TIMESTAMP_COLUMN, stamps.type), stamps)
+ )
+ if omitted is not None:
+ table = table.append_column(
+ pa.field(TOAST_OMITTED_COLUMN, pa.list_(pa.string())), pa.array(omitted, pa.list_(pa.string()))
+ )
+ return table
+
+
+def _held(*rows: tuple[int, str] | tuple[int, str, str]) -> dict:
+ """Rows a history table holds at its position, as `read_lane_position` returns them."""
+ grouped: dict = {}
+ for row in rows:
+ row_id, op, label = (*row, "v1")[:3]
+ grouped.setdefault((row_id, op), []).append({"id": row_id, "label": label})
+ return grouped
+
+
+_NO_POSITION = LanePosition(position=None, applied={})
+
+
def _parquet_bytes(table: pa.Table) -> bytes:
buf = pa.BufferOutputStream()
pq.write_table(table, buf)
@@ -51,8 +105,11 @@ class _FakeS3:
files: dict[str, bytes],
missing_prefix: bool = False,
mtimes: dict[str, dt.datetime] | None = None,
+ missing_keys: set[str] | None = None,
) -> None:
self.files = dict(files)
+ # Listed but gone by the time the reader opens them, as a concurrent retry leaves things.
+ self.missing_keys = missing_keys or set()
self.removed: list[str] = []
self.opened: list[str] = []
self.missing_prefix = missing_prefix
@@ -72,7 +129,7 @@ class _FakeS3:
async def open_async(self, key, mode):
self.opened.append(key)
- if key not in self.files:
+ if key in self.missing_keys or key not in self.files:
raise FileNotFoundError(key)
data = self.files[key]
@@ -86,14 +143,11 @@ class _FakeS3:
@contextlib.contextmanager
-def _patched(s3: _FakeS3, load_position: int | None, proof_time: dt.datetime | None):
+def _patched(s3: _FakeS3):
with (
patch(
"products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.aget_s3_client"
) as mock_client,
- patch.object(CDCSourceManager, "_read_consume_state", AsyncMock(return_value=(load_position, None))),
- patch.object(CDCSourceManager, "_completed_listing_time", AsyncMock(return_value=proof_time)),
- patch.object(CDCSourceManager, "_stamp_listing", AsyncMock()) as mock_stamp,
patch(
"products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.get_buffer_prefix",
return_value=f"s3://{_PREFIX}",
@@ -101,25 +155,23 @@ def _patched(s3: _FakeS3, load_position: int | None, proof_time: dt.datetime | N
):
mock_client.return_value.__aenter__ = AsyncMock(return_value=s3)
mock_client.return_value.__aexit__ = AsyncMock(return_value=False)
- yield mock_stamp
+ yield
-def _manager() -> CDCSourceManager:
+def _manager(*, deletion_floor: int | None = None, proof_time: dt.datetime | None = None) -> CDCSourceManager:
inputs = MagicMock()
inputs.team_id = _TEAM_ID
inputs.schema_id = _SCHEMA_ID
inputs.reset_pipeline = False
- return CDCSourceManager(inputs=inputs, logger=AsyncMock())
+ return CDCSourceManager(inputs=inputs, logger=AsyncMock(), deletion_floor=deletion_floor, proof_time=proof_time)
async def _collect(
- s3: _FakeS3,
- load_position: int | None = None,
- proof_time: dt.datetime | None = None,
- **kwargs,
+ s3: _FakeS3, *, deletion_floor: int | None = None, proof_time: dt.datetime | None = None, **kwargs
) -> list[pa.Table]:
- with _patched(s3, load_position, proof_time):
- return [t async for t in _manager().get_items("users", **kwargs)]
+ manager = _manager(deletion_floor=deletion_floor, proof_time=proof_time)
+ with _patched(s3), patch.object(CDCSourceManager, "stamp_listing", AsyncMock()):
+ return [t async for t in manager.get_items(**kwargs)]
def _schema(**overrides) -> MagicMock:
@@ -128,8 +180,13 @@ 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)
- schema.sync_type_config = overrides.get("sync_type_config", {})
+ # 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.source.job_inputs = overrides.get("job_inputs", {})
+ schema.primary_key_columns = overrides.get("primary_key_columns", ["id"])
+ schema.name = overrides.get("name", "users")
+ schema.resolved_s3_folder_name = overrides.get("resolved_s3_folder_name", "users")
return schema
@@ -164,71 +221,6 @@ class TestCDCSourceManager:
assert tables[0].column("id").to_pylist() == [1, 2, 3]
- async def test_files_strictly_below_the_position_are_deleted_and_never_read(self):
- s3 = _FakeS3(
- {
- _key(100, 199): _parquet_bytes(_table([1], [100])),
- _key(200, 299): _parquet_bytes(_table([2], [200])),
- }
- )
-
- tables = await _collect(s3, load_position=250)
-
- assert s3.removed == [_key(100, 199)]
- assert s3.opened == [_key(200, 299)]
- assert tables[0].column("id").to_pylist() == [2]
-
- async def test_a_trailing_file_is_deleted_once_a_completed_listing_predates_it(self):
- # Position alone cannot prove the file at the floor consumed, so an idle schema would
- # otherwise re-merge and re-bill its trailing file on every sync forever.
- s3 = _FakeS3({_key(100, 200): _parquet_bytes(_table([1], [200]))})
-
- tables = await _collect(s3, load_position=200, proof_time=_OLD_MTIME + dt.timedelta(hours=1))
-
- assert s3.removed == [_key(100, 200)]
- assert tables == []
-
- @parameterized.expand(
- [
- # A file written after the proving run's listing was never in it — it can hold the
- # unread tail of a transaction split across files (all rows share one position).
- ("written_after_the_proving_listing", _NOW, _NOW - dt.timedelta(minutes=30)),
- # Within the clock-skew margin of the listing, existence in it is unproven.
- ("within_the_skew_margin", _NOW - dt.timedelta(minutes=32), _NOW - dt.timedelta(minutes=30)),
- ("no_completed_listing_yet", _OLD_MTIME, None),
- ]
- )
- async def test_a_file_at_the_position_is_kept_when_consumption_is_unproven(self, _name, mtime, proof_time):
- key = _key(100, 200)
- s3 = _FakeS3({key: _parquet_bytes(_table([1], [200]))}, mtimes={key: mtime})
-
- tables = await _collect(s3, load_position=200, proof_time=proof_time)
-
- assert s3.removed == []
- assert len(tables) == 1
-
- async def test_no_files_are_deleted_before_anything_is_committed(self):
- s3 = _FakeS3({_key(100, 199): _parquet_bytes(_table([1], [100]))})
-
- await _collect(s3, load_position=None, proof_time=_NOW)
-
- assert s3.removed == []
-
- async def test_files_are_not_deleted_on_yield(self):
- # The v3 batcher buffers across yields, so a yielded table can still be in memory. Only a
- # committed position may delete a file.
- s3 = _FakeS3(
- {
- _key(100, 199): _parquet_bytes(_table(list(range(6000)), [100] * 6000)),
- _key(200, 299): _parquet_bytes(_table([1], [200])),
- }
- )
-
- tables = await _collect(s3)
-
- assert len(tables) == 2
- assert s3.removed == []
-
async def test_names_that_do_not_match_the_contract_are_ignored(self):
s3 = _FakeS3(
{
@@ -269,38 +261,93 @@ class TestCDCSourceManager:
assert [t.num_rows for t in tables] == [800, 400]
+class TestServedLanes:
+ @parameterized.expand(
+ [
+ ("consolidated", "consolidated", [CDCLane(resource_name="users", write_mode="incremental_merge")]),
+ ("cdc_only", "cdc_only", [CDCLane(resource_name="users_cdc", write_mode="scd2_append")]),
+ (
+ "both",
+ "both",
+ [
+ CDCLane(resource_name="users", write_mode="incremental_merge"),
+ CDCLane(resource_name="users_cdc", write_mode="scd2_append"),
+ ],
+ ),
+ ]
+ )
+ def test_a_table_mode_names_the_tables_its_changes_feed(self, _name, table_mode, expected):
+ assert served_lanes(_schema(cdc_table_mode=table_mode)) == expected
+
+ def test_an_unrecognized_table_mode_feeds_nothing(self):
+ # Fail closed: a mode this module cannot write must not reach the buffer at all.
+ assert served_lanes(_schema(cdc_table_mode="something_new")) == []
+
+ def test_the_companion_is_named_off_the_schema_not_the_folder(self):
+ # The consolidated lane follows the snapshot's resolved folder, which diverges from `name`
+ # for a row renamed bare to qualified. Following it here would append history into a table
+ # no query reads — the companion is keyed on `name`, like its snapshot seed.
+ schema = _schema(name="public.users", resolved_s3_folder_name="users", cdc_table_mode="both")
+ 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(
[
("not_cdc", {"is_cdc": False}),
("still_snapshotting", {"cdc_mode": "snapshot"}),
- ("companion_lane", {"cdc_table_mode": "cdc_only"}),
- ("both_lanes", {"cdc_table_mode": "both"}),
+ ("unrecognized_table_mode", {"cdc_table_mode": "something_new"}),
("no_table_yet", {"initial_sync_complete": False}),
]
)
def test_ineligible_schemas_stay_on_the_legacy_path(self, _name, overrides):
assert serves_buffered_lane(_schema(**overrides)) is False
- def test_a_consolidated_streaming_schema_serves_the_buffered_lane(self):
- assert serves_buffered_lane(_schema()) is True
+ @parameterized.expand([("consolidated",), ("cdc_only",), ("both",)])
+ def test_every_streaming_table_mode_serves_the_buffered_lane(self, table_mode):
+ assert serves_buffered_lane(_schema(cdc_table_mode=table_mode)) is True
@parameterized.expand([("legacy",), ("",), ("nonsense",)])
def test_a_source_that_was_not_flipped_stays_on_the_legacy_path(self, ingest_mode):
- assert is_buffered_consolidated(_schema(), ingest_mode=ingest_mode) is False
+ assert consumes_buffer(_schema(), ingest_mode=ingest_mode) is False
- def test_a_flipped_consolidated_schema_consumes_the_buffer(self):
- assert is_buffered_consolidated(_schema(), ingest_mode="buffered") is True
+ @parameterized.expand([("consolidated",), ("cdc_only",), ("both",)])
+ def test_a_flipped_schema_consumes_the_buffer(self, table_mode):
+ assert consumes_buffer(_schema(cdc_table_mode=table_mode), 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([("consolidated",), ("cdc_only",), ("both",)])
+ def test_a_flipped_schema_forces_the_buffered_consumer_on_its_scheduled_sync(self, table_mode):
+ schema = _schema(job_inputs={"cdc_ingest_mode": "buffered"}, cdc_table_mode=table_mode)
+ assert scheduled_sync_consumes_buffer(schema) is True
@parameterized.expand(
[
("source_never_flipped", {}),
("no_job_inputs", {"job_inputs": None}),
+ (
+ "unrecognized_table_mode",
+ {"job_inputs": {"cdc_ingest_mode": "buffered"}, "cdc_table_mode": "something_new"},
+ ),
("job_inputs_not_a_mapping", {"job_inputs": "buffered"}),
- ("companion_lane", {"job_inputs": {"cdc_ingest_mode": "buffered"}, "cdc_table_mode": "cdc_only"}),
("still_snapshotting", {"job_inputs": {"cdc_ingest_mode": "buffered"}, "cdc_mode": "snapshot"}),
]
)
@@ -308,7 +355,8 @@ class TestBufferedGating:
assert scheduled_sync_consumes_buffer(_schema(**overrides)) is False
-class TestPendingLegacyBacklog:
+class TestBatchesInFlight:
# Legacy deliveries carry no position column, so a consumer merge racing them can be overwritten
# by an older row. These prove both backlog forms hold the consumer off.
@@ -316,7 +364,7 @@ class TestPendingLegacyBacklog:
with patch(
"products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.psycopg"
) as mock_psycopg:
- assert has_pending_legacy_backlog(_schema(sync_type_config={"cdc_deferred_runs": [{"x": 1}]})) is True
+ assert has_batches_in_flight(_schema(sync_type_config={"cdc_deferred_runs": [{"x": 1}]})) is True
mock_psycopg.Connection.connect.assert_not_called()
@parameterized.expand([("batches_pending", 12.5, True), ("queue_drained", None, False)])
@@ -331,45 +379,390 @@ class TestPendingLegacyBacklog:
return_value=age,
),
):
- assert has_pending_legacy_backlog(schema) is expected
+ assert has_batches_in_flight(schema) is expected
@pytest.mark.asyncio
-class TestListingProof:
- # The deletion proof must come only from a run that listed the buffer AND completed. A gated
- # no-op run (which never lists) or a crashed run (whose job never completes) must prove nothing.
+class TestReplayFilter:
+ """What each lane drops when a run re-reads a buffer its table has partly consumed.
- async def test_every_consuming_run_stamps_its_listing(self):
- s3 = _FakeS3({_key(100, 199): _parquet_bytes(_table([1], [100]))})
+ The two lanes differ only at the position itself: a merge rewrites those rows as upserts,
+ while history would keep a second copy, so only the append lane matches them, by content.
+ """
+
+ @staticmethod
+ def _append(position, applied):
+ return ReplayFilter(LanePosition(position=position, applied=applied, key_columns=("id", CDC_OP_COLUMN)))
+
+ def test_nothing_is_dropped_before_a_lane_has_written_anything(self):
+ table = _ops([1, 2], [10, 20], ["I", "U"])
+
+ assert self._append(None, {}).apply(table) is table
+ assert ReplayFilter(LanePosition(position=None, applied={}, key_columns=())).apply(table) is table
+
+ def test_the_table_rows_are_read_only_once_a_batch_holds_a_row_at_the_position(self):
+ loads = 0
+
+ def load():
+ nonlocal loads
+ loads += 1
+ return LanePosition(position=20, applied=_held((2, "I")), key_columns=("id", CDC_OP_COLUMN))
+
+ replay = ReplayFilter(
+ LanePosition(position=20, applied={}, key_columns=("id", CDC_OP_COLUMN), load_applied=load)
+ )
+
+ assert replay.apply(_ops([3], [30])).column("id").to_pylist() == [3]
+ assert loads == 0
+ assert replay.apply(_ops([2, 3], [20, 30])).column("id").to_pylist() == [3]
+ assert replay.apply(_ops([2], [20])).column("id").to_pylist() == [2]
+ assert loads == 1
+
+ def test_rows_below_the_position_are_dropped(self):
+ result = ReplayFilter(LanePosition(position=20, applied={}, key_columns=())).apply(
+ _ops([1, 2, 3], [10, 20, 30])
+ )
+
+ assert result.column(CDC_SEQ_COLUMN).to_pylist() == [20, 30]
+
+ def test_the_merge_lane_keeps_every_row_at_its_position(self):
+ result = ReplayFilter(LanePosition(position=20, applied={}, key_columns=())).apply(
+ _ops([1, 2, 3], [20, 20, 30])
+ )
+
+ assert result.column("id").to_pylist() == [1, 2, 3]
+
+ def test_the_append_lane_drops_only_the_rows_its_table_already_holds(self):
+ result = self._append(20, _held((1, "I"), (2, "U"))).apply(
+ _ops([1, 2, 3, 4], [20, 20, 20, 30], ["I", "U", "I", "U"])
+ )
+
+ assert result.column("id").to_pylist() == [3, 4]
+
+ def test_a_file_that_arrives_late_at_a_consumed_position_still_lands(self):
+ # The previous run read every file at position 20 and its table holds those two rows.
+ # Capture then wrote another file at the same position, carrying rows nothing has seen.
+ result = self._append(20, _held((1, "I"), (2, "I"))).apply(_ops([7, 8], [20, 20], ["I", "I"]))
+
+ assert result.column("id").to_pylist() == [7, 8]
+
+ def test_a_second_change_to_a_key_is_kept_when_the_table_holds_only_the_first(self):
+ # One transaction updated key 1 twice, across two buffer files. The first file was applied
+ # and then deleted; only the second is read now. Its row shares every key column with the
+ # one the table holds, and matching on the key alone would have dropped it for good.
+ result = self._append(20, _held((1, "U", "first"))).apply(_ops([1], [20], ["U"], labels=["second"]))
+
+ assert result.column("label").to_pylist() == ["second"]
+
+ def test_a_replayed_row_is_matched_by_its_content(self):
+ result = self._append(20, _held((1, "U", "first"))).apply(_ops([1], [20], ["U"], labels=["first"]))
+
+ assert result.num_rows == 0
+
+ def test_a_key_changed_twice_in_one_transaction_spends_one_row_per_match(self):
+ result = self._append(20, _held((1, "U", "a"))).apply(_ops([1, 1], [20, 20], ["U", "U"], labels=["a", "b"]))
+
+ assert result.column("label").to_pylist() == ["b"]
+
+ def test_a_delete_rows_nulls_are_unknowns_not_values(self):
+ # Under the default replica identity a delete carries only its key; the loader filled the
+ # rest from the table before storing it. Comparing the batch's nulls against those values
+ # would never match, and the delete would be appended again on every re-read of its file.
+ replay = self._append(20, _held((1, "D", "filled-in")))
+
+ result = replay.apply(_ops([1], [20], ["D"], labels=[None]))
+
+ assert result.num_rows == 0
- with _patched(s3, None, None) as mock_stamp:
- [t async for t in _manager().get_items("users")]
+ def test_a_deletes_non_null_column_still_has_to_match(self):
+ replay = self._append(20, _held((1, "D", "was-a")))
- mock_stamp.assert_awaited_once()
+ result = replay.apply(_ops([1], [20], ["D"], labels=["was-b"]))
- @parameterized.expand([("job_completed", True, True), ("job_not_completed", False, False)])
- async def test_a_stamp_proves_only_once_its_job_completes(self, _name, completed, expect_proof):
- listing = {"listed_at": _NOW.isoformat(), "job_id": "018f0000-0000-0000-0000-000000000001"}
- exists_qs = MagicMock()
- exists_qs.exists.return_value = completed
+ assert result.num_rows == 1
+
+ def test_a_column_that_will_not_cast_compares_by_its_string_form(self):
+ # Dropping the column would make a wrong match likelier, and a wrong match is a lost change.
+ held = {(1, "U"): [{"id": 1, "label": "v1", "amount": "9.5"}]}
+ stored = pa.table({"amount": pa.array(["9.5"], pa.string())})
+ schema = _ops([1], [20]).select(["id", "label"]).append_column("amount", stored.column("amount")).schema
+ replay = ReplayFilter(
+ LanePosition(position=20, applied=held, key_columns=("id", CDC_OP_COLUMN), content_schema=schema)
+ )
+ differs = _ops([1], [20], ["U"]).append_column("amount", pa.array([[9, 5]], pa.list_(pa.int64())))
+
+ assert replay.apply(differs).num_rows == 1
+
+ def test_above_the_cap_the_batch_content_is_never_materialized(self):
+ # The table side carried no content, so reading the batch's would cost what the cap avoids.
+ replay = ReplayFilter(
+ LanePosition(
+ position=20, applied={(1, "I"): [{}]}, key_columns=("id", CDC_OP_COLUMN), content_matched=False
+ )
+ )
+
+ with patch.object(ReplayFilter, "_batch_contents", side_effect=AssertionError("read content")):
+ result = replay.apply(_ops([1, 2], [20, 20], ["I", "I"]))
+
+ assert result.column("id").to_pylist() == [2]
+
+ def test_a_toast_omitted_column_is_left_out_of_the_comparison(self):
+ # The source left `label` unchanged, so the batch row does not carry it and the table's
+ # row does. Comparing it would never match, and the row would be appended a second time.
+ replay = self._append(20, _held((1, "U", "unchanged")))
+
+ result = replay.apply(_ops([1], [20], ["U"], labels=[None], omitted=[["label"]]))
+
+ assert result.num_rows == 0
+
+ def test_the_identity_is_spent_across_files_that_share_the_position(self):
+ replay = self._append(20, _held((1, "I"), (2, "I")))
+
+ first = replay.apply(_ops([1], [20], ["I"]))
+ second = replay.apply(_ops([2, 3], [20, 20], ["I", "I"]))
+
+ assert first.num_rows == 0
+ assert second.column("id").to_pylist() == [3]
+
+ def test_rows_past_the_position_are_never_matched(self):
+ replay = self._append(20, _held((1, "I")))
+ result = replay.apply(_ops([1, 2], [30, 40], ["I", "I"]))
+
+ assert result.column("id").to_pylist() == [1, 2]
+ assert replay.rows_skipped == 0
+
+ def test_a_table_missing_a_key_column_keys_the_batch_the_same_way(self):
+ # The position reports the columns it actually read. If the filter keyed batch rows by a
+ # wider tuple than the table was read with, nothing would ever match and every replayed
+ # row would be appended a second time.
+ replay = ReplayFilter(
+ LanePosition(position=20, applied={("I",): [{"id": 1, "label": "v1"}]}, key_columns=(CDC_OP_COLUMN,))
+ )
+
+ result = replay.apply(_ops([1, 2], [20, 20], ["I", "I"]))
+
+ assert result.num_rows == 1
+
+ def test_a_batch_is_cast_to_the_table_types_before_comparing(self):
+ # A column the loader widened from date to timestamp reads back as a datetime, and the
+ # batch's date is not equal to it. Left uncast, every replayed row would be appended again.
+ held = {(1, "I"): [{"id": 1, "label": "v1", "day": dt.datetime(2026, 1, 1)}]}
+ stored = pa.table({"day": pa.array([dt.datetime(2026, 1, 1)], pa.timestamp("us"))})
+ schema = _ops([1], [20]).select(["id", "label"]).append_column("day", stored.column("day")).schema
+ replay = ReplayFilter(
+ LanePosition(position=20, applied=held, key_columns=("id", CDC_OP_COLUMN), content_schema=schema)
+ )
+ batch = _ops([1], [20], ["I"]).append_column("day", pa.array([dt.date(2026, 1, 1)], pa.date32()))
+
+ assert replay.apply(batch).num_rows == 0
+
+ def test_a_source_owned_position_column_is_never_matched(self):
+ # The batcher passes a source column literally named _ph_cdc_seq through untouched, so its
+ # values are customer data. Matching them against this lane's position would drop rows
+ # nothing has written.
+ table = pa.table(
+ {
+ "id": pa.array([1, 2], pa.int64()),
+ CDC_SEQ_COLUMN: pa.array([20, 20], pa.int64()),
+ CDC_OP_COLUMN: pa.array(["I", "I"], pa.string()),
+ }
+ )
+ replay = self._append(20, _held((1, "I"), (2, "I")))
+
+ assert replay.apply(table) is table
+
+ def test_skipped_rows_are_counted(self):
+ replay = self._append(20, _held((2, "I")))
+ replay.apply(_ops([1, 2, 3], [10, 20, 20], ["I", "I", "I"]))
+
+ assert replay.rows_skipped == 2
+
+ def test_each_kind_of_drop_reports_its_own_reason(self):
+ # `superseded` is the series the loader raised while the position lived there. Reporting
+ # the identity drop under the same name would flatten a dashboard onto one number.
+ counter = MagicMock()
+ replay = ReplayFilter(
+ LanePosition(position=20, applied=_held((2, "I")), key_columns=("id", CDC_OP_COLUMN)), team_id=7
+ )
with patch(
- "products.warehouse_sources.backend.models.external_data_job.ExternalDataJob.objects.filter",
- return_value=exists_qs,
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager."
+ "CDC_SEQ_GUARD_ROWS_DROPPED_TOTAL",
+ counter,
):
- proof = await _manager()._completed_listing_time(listing)
+ replay.apply(_ops([1, 2, 3], [10, 20, 20], ["I", "I", "I"]))
- assert (proof == _NOW) is expect_proof
- assert (proof is None) is (not expect_proof)
+ assert [call.kwargs["reason"] for call in counter.labels.call_args_list] == ["superseded", "already_written"]
- @parameterized.expand(
- [
- ("no_stamp", None),
- ("malformed_date", {"listed_at": "not-a-date", "job_id": "018f0000-0000-0000-0000-000000000001"}),
- ("naive_timestamp", {"listed_at": "2026-08-14T12:00:00", "job_id": "018f0000-0000-0000-0000-000000000001"}),
- ("malformed_job_id", {"listed_at": "2026-08-14T12:00:00+00:00", "job_id": "not-a-uuid"}),
- ("missing_job", {"listed_at": "2026-08-14T12:00:00+00:00"}),
- ]
- )
- async def test_unusable_stamps_prove_nothing(self, _name, listing):
- assert await _manager()._completed_listing_time(listing) is None
+
+class TestFloorDeletion:
+ """Files every table has settled are deleted before they are read, never after."""
+
+ async def test_files_strictly_below_the_floor_are_deleted_and_never_read(self):
+ s3 = _FakeS3({_key(1, 10): _parquet_bytes(_table([1], [10])), _key(21, 30): _parquet_bytes(_table([2], [30]))})
+ await _collect(s3, deletion_floor=20)
+
+ assert s3.removed == [_key(1, 10)]
+ assert s3.opened == [_key(21, 30)]
+
+ async def test_a_file_at_the_floor_is_kept_until_a_completed_run_proves_it_read(self):
+ s3 = _FakeS3({_key(11, 20): _parquet_bytes(_table([1], [20]))})
+ await _collect(s3, deletion_floor=20)
+
+ assert s3.removed == []
+ assert s3.opened == [_key(11, 20)]
+
+ async def test_a_file_at_the_floor_goes_once_an_older_completed_listing_covers_it(self):
+ s3 = _FakeS3({_key(11, 20): _parquet_bytes(_table([1], [20]))})
+ await _collect(s3, deletion_floor=20, proof_time=_NOW)
+
+ assert s3.removed == [_key(11, 20)]
+
+ async def test_a_trailing_file_stops_being_re_read_once_a_completed_run_proves_it(self):
+ """The at-floor file has to go, or an idle merge lane re-stages it every tick.
+
+ Only the append lane drops those rows by identity. The merge lane keeps them on purpose,
+ so without this proof an idle schema re-writes and re-bills its last transaction forever.
+ """
+ s3 = _FakeS3({_key(11, 20): _parquet_bytes(_table([1], [20]))})
+ await _collect(s3, deletion_floor=20, proof_time=_NOW)
+
+ assert s3.removed == [_key(11, 20)]
+ assert s3.opened == []
+
+ async def test_nothing_is_deleted_before_every_lane_has_a_position(self):
+ s3 = _FakeS3({_key(1, 10): _parquet_bytes(_table([1], [10]))})
+ await _collect(s3, deletion_floor=None, proof_time=_NOW)
+
+ assert s3.removed == []
+
+
+class TestBuildOutputLanes:
+ @staticmethod
+ async def _build(schema, positions: list[LanePosition]):
+ delta_ref = MagicMock()
+ delta_ref.return_value.get_delta_table = AsyncMock(return_value=MagicMock())
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.DeltaTableRef", delta_ref
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.ensure_position_stats",
+ AsyncMock(),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.read_lane_position",
+ AsyncMock(side_effect=positions),
+ ),
+ ):
+ return await build_output_lanes(schema, MagicMock(), AsyncMock())
+
+ async def test_both_writes_two_tables_in_one_run(self):
+ lanes, _ = await self._build(_schema(cdc_table_mode="both"), [_NO_POSITION, _NO_POSITION])
+
+ assert [lane.name for lane in lanes] == ["users", "users_cdc"]
+ assert [lane.cdc_write_mode for lane in lanes] == [CONSOLIDATED_WRITE_MODE, COMPANION_WRITE_MODE]
+
+ @parameterized.expand([("consolidated", "consolidated", "users"), ("cdc_only", "cdc_only", "users_cdc")])
+ async def test_a_single_table_mode_bills_its_only_lane(self, _name, table_mode, expected):
+ lanes, _ = await self._build(_schema(cdc_table_mode=table_mode), [_NO_POSITION])
+
+ assert [(lane.name, lane.billable) for lane in lanes] == [(expected, True)]
+
+ async def test_both_bills_the_consolidated_lane_only(self):
+ lanes, _ = await self._build(_schema(cdc_table_mode="both"), [_NO_POSITION, _NO_POSITION])
+
+ assert [(lane.name, lane.billable) for lane in lanes] == [("users", True), ("users_cdc", False)]
+
+ async def test_only_the_append_lane_is_asked_for_identity(self):
+ # Asserted on the call, not on hand-fed positions: if both lanes asked for identity the
+ # merge lane would drop rows at its own position, and a test that feeds the positions in
+ # cannot see that.
+ reads = AsyncMock(side_effect=[_NO_POSITION, _NO_POSITION])
+ stats = AsyncMock()
+ delta_ref = MagicMock()
+ delta_ref.return_value.get_delta_table = AsyncMock(return_value=MagicMock())
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.DeltaTableRef", delta_ref
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.ensure_position_stats",
+ stats,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.read_lane_position", reads
+ ),
+ ):
+ await build_output_lanes(_schema(cdc_table_mode="both"), MagicMock(), AsyncMock())
+
+ merge_keys, append_keys = (call.kwargs["key_columns"] for call in reads.call_args_list)
+ assert merge_keys is None
+ assert append_keys == ["id", CDC_OP_COLUMN]
+ # The history table's own merge predicates on valid_to, so it keeps its pruning too.
+ assert SCD2_VALID_TO_COLUMN in stats.call_args_list[1].args[1]
+ assert SCD2_VALID_TO_COLUMN not in stats.call_args_list[0].args[1]
+
+ async def test_a_lane_with_no_primary_keys_asks_for_no_identity(self):
+ # Otherwise the identity is the operation alone, which matches rows the table never held.
+ reads = AsyncMock(side_effect=[_NO_POSITION])
+ delta_ref = MagicMock()
+ delta_ref.return_value.get_delta_table = AsyncMock(return_value=MagicMock())
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.DeltaTableRef", delta_ref
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.ensure_position_stats",
+ AsyncMock(),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.read_lane_position", reads
+ ),
+ ):
+ await build_output_lanes(
+ _schema(cdc_table_mode="cdc_only", primary_key_columns=[]), MagicMock(), AsyncMock()
+ )
+
+ assert reads.call_args.kwargs["key_columns"] is None
+
+ async def test_only_the_append_lane_matches_rows_at_the_position(self):
+ lanes, _ = await self._build(
+ _schema(cdc_table_mode="both"),
+ [
+ LanePosition(position=20, applied={}),
+ LanePosition(
+ position=20,
+ applied=_held((1, "I"), (2, "I"), (3, "I")),
+ key_columns=("id", CDC_OP_COLUMN),
+ ),
+ ],
+ )
+
+ batch = _ops([1, 2, 3, 4], [20, 20, 20, 30], ["I", "I", "I", "I"])
+ merged, history = (lane.transform(batch) for lane in lanes)
+
+ assert merged.column("id").to_pylist() == [1, 2, 3, 4]
+ assert history.column("id").to_pylist() == [4]
+ # Stamped by the lane, not the loader: a loader on the previous release has no SCD2 step
+ # and would append these rows with no validity at all.
+ assert SCD2_VALID_FROM_COLUMN in history.column_names
+ assert SCD2_VALID_TO_COLUMN in history.column_names
+ assert SCD2_VALID_FROM_COLUMN not in merged.column_names
+
+ async def test_the_floor_is_the_lowest_position_any_table_holds(self):
+ _, floor = await self._build(
+ _schema(cdc_table_mode="both"),
+ [LanePosition(position=50, applied={}), LanePosition(position=20, applied={})],
+ )
+
+ assert floor == 20
+
+ async def test_a_lane_with_no_position_holds_the_floor_open(self):
+ _, floor = await self._build(
+ _schema(cdc_table_mode="both"), [LanePosition(position=50, applied={}), _NO_POSITION]
+ )
+
+ assert floor is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
index 7d7b96773a15..9d2c9ed4ac8e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
@@ -165,6 +165,7 @@ async def _seed_cdc_companion_from_snapshot(
DELETED_COLUMN,
SCD2_VALID_FROM_COLUMN,
SCD2_VALID_TO_COLUMN,
+ companion_resource_name as build_companion_resource_name,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.writer import DeltaWriter
@@ -187,7 +188,7 @@ async def _seed_cdc_companion_from_snapshot(
}
read_columns = [c for c in dataset.schema.names if c not in cdc_meta_cols]
- companion_resource_name = f"{schema.name}_cdc"
+ companion_resource_name = build_companion_resource_name(schema.name)
companion_ref = DeltaTableRef(
resource_name=companion_resource_name,
job=job,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
index 9d833163e202..368d366dd6dc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
@@ -966,6 +966,10 @@ async def _rewrite_into_temp(
temp_uri=temp_uri,
)
+ # The live table's properties travel with its rows. A buffered CDC lane reads its resume
+ # point from a statistic one of them declares, and a rebuilt table that lost it would report
+ # no position at all.
+ table_configuration = dict(old_delta.metadata().configuration or {}) or None
dataset = await asyncio.to_thread(old_delta.to_pyarrow_dataset)
if skip_rows:
dataset, skip_rows = await asyncio.to_thread(_drop_copied_source_files, old_delta, dataset, skip_rows)
@@ -1049,6 +1053,7 @@ async def _rewrite_into_temp(
mode="append",
schema_mode="merge",
storage_options=storage_options,
+ configuration=table_configuration,
)
rows_written += combined.num_rows
commits += 1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
index 760de8eb592c..22a2ea3fff48 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
@@ -592,6 +592,37 @@ class TestRewriteIntoTemp:
for key in new_sizes:
assert key is not None and len(key) == len("2024-01-05")
+ def test_the_live_tables_properties_travel_with_its_rows(self, tmp_path):
+ # A buffered CDC history table reads its resume point from a statistic one property
+ # declares. A rebuilt table that lost it reports no position and replays the buffer into
+ # an append-only table.
+ rows = [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 2, 2))]
+ old_delta = _write_month_partitioned(str(tmp_path / "src"), rows)
+ old_delta.alter.set_table_properties({"delta.dataSkippingStatsColumns": "id"})
+ old_delta = deltalake.DeltaTable(str(tmp_path / "src"))
+ temp_uri = str(tmp_path / "tmp")
+
+ asyncio.run(
+ _rewrite_into_temp(
+ old_delta=old_delta,
+ temp_uri=temp_uri,
+ storage_options={},
+ target=RepartitionTarget(
+ partition_keys=["created_at"],
+ trigger_reason="test",
+ partition_mode="datetime",
+ partition_format="day",
+ ),
+ batch_size=1,
+ logger=logger,
+ )
+ )
+
+ rebuilt = deltalake.DeltaTable(temp_uri)
+ assert rebuilt.metadata().configuration.get("delta.dataSkippingStatsColumns") == "id"
+ # And the statistic itself is on the rewritten files, not just the declaration.
+ assert "max.id" in rebuilt.get_add_actions(flatten=True).column_names
+
def test_reports_buffered_bytes_to_the_workload_reporter(self, tmp_path):
# Dropping this hook makes rewrites invisible to the OOM classifier's culprit rule.
rows = [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 1, 20))]
@@ -1050,6 +1081,7 @@ class TestRewriteIntoTemp:
return self._batches.pop(0)
old_delta = SimpleNamespace(
+ metadata=lambda: SimpleNamespace(configuration={}),
to_pyarrow_dataset=lambda: SimpleNamespace(
scanner=lambda **kwargs: SimpleNamespace(to_reader=lambda: _FakeReader(batch_table))
),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/__init__.py
index a9e880abb25c..9ccfab6c9a21 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/__init__.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/__init__.py
@@ -1,3 +1,4 @@
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.lanes import LanedPipelineV3
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline import PipelineV3
-__all__ = ["PipelineV3"]
+__all__ = ["LanedPipelineV3", "PipelineV3"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.py
new file mode 100644
index 000000000000..eb11dff21a41
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.py
@@ -0,0 +1,310 @@
+"""A run that writes every table its source feeds, from one read of that source.
+
+Kept apart from `PipelineV3` on purpose: every other source runs the base class, whose code is
+the single-table path it has always been. Only a source that declares `SourceResponse.lanes`
+gets this subclass, so nothing in here can change what a single-table run does.
+
+Each table beyond the first gets its own `ExternalDataJob`, the way the legacy CDC extraction
+already writes a `both` schema (see `cdc/activities.py`). That is what keeps the queue out of it:
+a job is where batch idempotency, staging paths, claim ordering and completion all hang, so two
+tables under one job would collide on every one of them, while two jobs are two ordinary
+single-table runs the loader already knows how to finish.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import TYPE_CHECKING
+
+import pyarrow as pa
+from structlog.types import FilteringBoundLogger
+
+from posthog.sync import database_sync_to_async_pool
+from posthog.temporal.common.shutdown import ShutdownMonitor
+
+from products.warehouse_sources.backend.temporal.data_imports.cdc.companion_jobs import (
+ record_companion_job,
+ retire_companion_job,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline import PipelineV3
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer import (
+ PostgresProducer,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3 import (
+ BatchWriteResult,
+ S3BatchWriter,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
+ OutputLane,
+ ResumableData,
+ SourceResponse,
+)
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+ from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
+ ImportJobModels,
+ )
+
+
+class _LaneWriter:
+ """One table this run writes: its own job, its own staged files, its own count."""
+
+ def __init__(
+ self,
+ lane: OutputLane,
+ s3_batch_writer: S3BatchWriter,
+ pg_producer: PostgresProducer,
+ batch_results: list[BatchWriteResult] | None = None,
+ job: ExternalDataJob | None = None,
+ ) -> None:
+ self.lane = lane
+ self.s3_batch_writer = s3_batch_writer
+ self.pg_producer = pg_producer
+ self.batch_results: list[BatchWriteResult] = batch_results if batch_results is not None else []
+ self.row_count = 0
+ # None for the first lane, which writes the job the workflow already created for this run.
+ self.job = job
+
+
+class LanedPipelineV3(PipelineV3[ResumableData]):
+ """`PipelineV3` for a source whose one stream lands in several tables."""
+
+ _output_lanes: list[OutputLane]
+ _lane_writers: list[_LaneWriter]
+ # Keyed by the lane's index in `_output_lanes`, which is stable for the run.
+ _writers_by_lane: dict[int, _LaneWriter]
+ _companion_job_ids: list[str]
+
+ def __init__(
+ self,
+ source_response: SourceResponse,
+ logger: FilteringBoundLogger,
+ job_id: str,
+ reset_pipeline: bool,
+ shutdown_monitor: ShutdownMonitor,
+ resumable_source_manager: ResumableSourceManager[ResumableData] | None,
+ *,
+ models: ImportJobModels,
+ ) -> None:
+ if not source_response.lanes:
+ raise ValueError(f"{source_response.name} declares no lanes; run it on PipelineV3")
+ self._output_lanes = list(source_response.lanes)
+
+ super().__init__(
+ source_response, logger, job_id, reset_pipeline, shutdown_monitor, resumable_source_manager, models=models
+ )
+
+ # The base built the first lane; it shares the base's batch list so the two never disagree.
+ primary = _LaneWriter(self._output_lanes[0], self._s3_batch_writer, self._pg_producer, self._batch_results)
+ self._lane_writers = [primary]
+ # Companions are appended as they open; the primary is always here because the base built it.
+ self._writers_by_lane: dict[int, _LaneWriter] = {0: primary}
+ # Tracked apart from the writers, so a job row this run created is retired even when the
+ # writer built on top of it never came together.
+ self._companion_job_ids = []
+ # Companions whose final batch is queued: the loader owns them from there, and retiring
+ # one would have it discard a tail that lands on its own.
+ self._final_sent_job_ids: set[str] = set()
+
+ async def run(self) -> PipelineResult:
+ completed = False
+ try:
+ result = await super().run()
+ completed = True
+ return result
+ finally:
+ if not completed:
+ # Only lanes that opened have a job, and none of them will send a final batch now.
+ # Shielded because the failure may be a cancellation.
+ await asyncio.shield(self._fail_companion_jobs())
+
+ async def _writer_for(self, index: int) -> _LaneWriter:
+ """This lane's writer, opening its job on the first batch it actually has rows for.
+
+ Opened lazily on purpose. A job created before there is anything to write is a row nothing
+ owns: the loader finishes a job when its final batch lands, this activity's own workflow
+ only knows the schema's job, and the stranded sweep finds runs by their queued batches. A
+ crash between creating it and staging into it would leave it Running for good, and one such
+ row blocks the flip and the rollback for the whole source. Opening it here means every
+ companion job has at least one batch, so the sweep is its owner like any other run.
+ """
+ existing = self._writers_by_lane.get(index)
+ if existing is not None:
+ return existing
+ lane = self._output_lanes[index]
+
+ first_of_attempt = not self._companion_job_ids
+ job = await self._create_companion_job(lane, first_of_attempt=first_of_attempt)
+ # Recorded before the S3 client and the queue connect below, either of which can raise. A
+ # job row this run loses track of is a row nothing retires, and one of those blocks the
+ # flip and the rollback for the whole source.
+ self._companion_job_ids.append(str(job.id))
+
+ s3_batch_writer = self._build_s3_writer(self._companion_run_uuid())
+ producer = PostgresProducer(
+ **{
+ **self._producer_args(s3_batch_writer, resource_name=lane.name, cdc_write_mode=lane.cdc_write_mode),
+ "job_id": str(job.id),
+ "workflow_run_id": None,
+ # The history table has no destination mapping: delivery names the destination
+ # table from the schema, and SCD2 rows merged by key there would clobber the
+ # consolidated table's rows. Legacy never delivered companion batches either.
+ "destination_ids": [],
+ }
+ )
+ writer = _LaneWriter(lane, s3_batch_writer, producer, job=job)
+ self._writers_by_lane[index] = writer
+ self._lane_writers.append(writer)
+ return writer
+
+ def _companion_run_uuid(self) -> str | None:
+ return f"{self._run_uuid}-cdc" if self._run_uuid else None
+
+ async def _create_companion_job(self, lane: OutputLane, *, first_of_attempt: bool) -> ExternalDataJob:
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+ from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (
+ _build_schema_snapshot,
+ )
+
+ def _create() -> ExternalDataJob:
+ return ExternalDataJob.objects.create(
+ team_id=self._job.team_id,
+ pipeline_id=self._schema.source_id,
+ schema_id=self._schema.id,
+ status=ExternalDataJob.Status.RUNNING,
+ rows_synced=0,
+ workflow_id=self._job.workflow_id,
+ workflow_run_id=None,
+ pipeline_version=ExternalDataJob.PipelineVersion.V3,
+ billable=False,
+ schema_snapshot={
+ **_build_schema_snapshot(self._schema),
+ # Distinguishes the two rows a `both` run produces, and names the run they
+ # belong to so a reader can tell whether the whole run finished.
+ "cdc_write_mode": lane.cdc_write_mode,
+ "companion_of": str(self._job.id),
+ },
+ destination_ids=[],
+ )
+
+ job = await database_sync_to_async_pool(_create)()
+ await database_sync_to_async_pool(record_companion_job)(
+ str(self._job.id), self._job.team_id, str(job.id), first_of_attempt=first_of_attempt
+ )
+ await self._logger.ainfo(
+ "companion_job_created", companion_job_id=str(job.id), resource_name=lane.name, job_id=str(self._job.id)
+ )
+ return job
+
+ async def _fail_companion_jobs(self) -> None:
+ """Take this run's open companion jobs terminal when extraction did not finish.
+
+ Only the job row. Its batches are never marked failed here: a batch the loader is
+ mid-write on still lands (the pre-commit check is a lease, not a status read), and a
+ failed mark would drop the run out of the in-flight guard, so the retry would read a
+ position the straggler is about to move past and stage the same rows again. The loader
+ itself discards the batches it has not yet claimed once it sees the job Failed; the next
+ run re-reads those files from the table's position, so nothing is lost, only re-staged.
+
+ Written directly, the way the legacy CDC path retires its own companion jobs. Going
+ through `update_external_job_status` would repaint the customer's schema FAILED and fire a
+ failure digest, and this runs from a `finally` on every attempt — including ones Temporal
+ retries and succeeds.
+ """
+ for job_id in self._companion_job_ids:
+ if job_id in self._final_sent_job_ids:
+ continue
+ try:
+ await database_sync_to_async_pool(retire_companion_job)(job_id)
+ except Exception:
+ await self._logger.awarning("companion_job_fail_write_failed", companion_job_id=job_id, exc_info=True)
+
+ async def _stage_batch(self, pa_table: pa.Table, batch_index: int, row_count: int) -> int:
+ # Each lane writes the same batch to its own job. A lane that already holds these rows
+ # contributes nothing for this index, which leaves a gap in its batch indexes — the claim
+ # gate orders on "no earlier index still running", so gaps are harmless.
+ billable_rows = 0
+ for index, lane in enumerate(self._output_lanes):
+ # The history lane's first match reads the table's rows at its position; keep that
+ # off the event loop the heartbeat runs on.
+ lane_table = await asyncio.to_thread(lane.transform, pa_table) if lane.transform is not None else pa_table
+ # A companion opens its job on its first rows, so an empty batch gives it nothing to
+ # stage and no reason to exist yet.
+ if index > 0 and not lane_table.num_rows:
+ continue
+ # Only a lane that filtered the batch away sits this index out. A batch that arrived
+ # empty is still staged, as it is on a single-table run.
+ #
+ # The primary lane keeps index 0 whatever it filtered: the producer supersedes a
+ # previous attempt's staged batches only on that index, so letting the merge lane skip
+ # it would leave a retried run unable to retire what the attempt before it staged.
+ filtered_away = pa_table.num_rows and not lane_table.num_rows
+ if filtered_away and not (index == 0 and batch_index == 0):
+ continue
+ writer = await self._writer_for(index)
+ writer.row_count += lane_table.num_rows
+ batch_result = await asyncio.to_thread(writer.s3_batch_writer.write_batch, lane_table, batch_index)
+ writer.batch_results.append(batch_result)
+ writer.pg_producer.send_batch_notification(
+ batch_result, is_final_batch=False, cumulative_row_count=writer.row_count
+ )
+ # One read of a change stream is one sync however many tables it keeps.
+ if lane.billable:
+ billable_rows += lane_table.num_rows
+ return billable_rows
+
+ def _total_batches(self) -> int:
+ return sum(len(writer.batch_results) for writer in self._lane_writers)
+
+ def _consumer_finalizes_this_run(self) -> bool:
+ # Only the primary lane's batches carry the schema's own job, and that job is the one the
+ # workflow hands over. A companion's final batch completes a different job and releases no
+ # lock, so counting it here would leave the schema's job Running and its lock held.
+ return len(self._batch_results) > 0
+
+ async def _send_final_batches(self, total_batches: int, row_count: int) -> str | None:
+ schema_path = None
+ for writer in self._lane_writers:
+ if not writer.batch_results:
+ continue
+ lane_schema_path = await asyncio.to_thread(writer.s3_batch_writer.write_schema)
+ schema_path = schema_path or lane_schema_path
+ writer.pg_producer.send_batch_notification(
+ writer.batch_results[-1],
+ is_final_batch=True,
+ total_batches=len(writer.batch_results),
+ total_rows=writer.row_count,
+ data_folder=writer.s3_batch_writer.get_data_folder(),
+ schema_path=lane_schema_path,
+ cumulative_row_count=writer.row_count,
+ )
+ if writer.job is not None:
+ self._final_sent_job_ids.add(str(writer.job.id))
+ await self._record_companion_rows(writer)
+ return schema_path
+
+ async def _record_companion_rows(self, writer: _LaneWriter) -> None:
+ """Count what a companion wrote onto its own job, as the workflow does for the first."""
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+
+ assert writer.job is not None
+ job_id, rows = writer.job.id, writer.row_count
+ try:
+ await database_sync_to_async_pool(
+ lambda: ExternalDataJob.objects.filter(id=job_id).update(rows_synced=rows)
+ )()
+ except Exception:
+ # Bookkeeping for rows already written; never worth failing the run over.
+ await self._logger.awarning("companion_job_rows_not_recorded", companion_job_id=str(job_id), exc_info=True)
+
+ def _mark_first_ever_sync(self) -> None:
+ # The schema's own table only. A companion is append-only history the loader never
+ # overwrites, and its own first write creates it.
+ self._pg_producer.is_first_ever_sync = True
+
+ def _close_producers(self) -> None:
+ for writer in self._lane_writers:
+ writer.pg_producer.close()
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.py
index 2b33c0c55d15..7d3426dbc1c2 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
@@ -34,11 +34,8 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import
enrich_toast_omitted_rows,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import (
- batch_max_seq,
has_engine_seq,
is_cdc_write_resolution_enabled,
- persist_load_position,
- read_load_position,
resolve_batch,
verify_delete_enrichment,
)
@@ -241,33 +238,23 @@ def _enrich_cdc_rows(
def _resolve_cdc_positions(
pa_table: pa.Table,
*,
- sync_type_config: dict | None,
- resource_name: str,
primary_keys: list[str],
cdc_write_mode: str | None,
team_id: str,
-) -> tuple[pa.Table, int | None]:
- """Drop rows this lane's table has already applied.
-
- Returns the batch and the position to record, which the caller persists only once the write
- commits — a position ahead of the table would skip rows that never landed.
- """
+) -> pa.Table:
+ """Collapse a merge batch to one row per key — the write engine rejects duplicates."""
if not has_engine_seq(pa_table):
- return pa_table, None
-
- watermark = read_load_position(sync_type_config, resource_name)
+ return pa_table
pa_table, stats = resolve_batch(
pa_table,
primary_keys,
- watermark=watermark,
cdc_write_mode=cdc_write_mode,
)
- for reason, dropped in (("superseded", stats.superseded), ("duplicate_key", stats.duplicate_key)):
- if dropped:
- CDC_SEQ_GUARD_ROWS_DROPPED_TOTAL.labels(team_id=team_id, reason=reason).inc(dropped)
+ if stats.duplicate_key:
+ CDC_SEQ_GUARD_ROWS_DROPPED_TOTAL.labels(team_id=team_id, reason="duplicate_key").inc(stats.duplicate_key)
- return pa_table, batch_max_seq(pa_table)
+ return pa_table
def _apply_partitioning(
@@ -974,12 +961,9 @@ def _process_message_reported(
team_id=team_id_str,
)
- pending_load_position: int | None = None
if resolution_enabled:
- pa_table, pending_load_position = _resolve_cdc_positions(
+ pa_table = _resolve_cdc_positions(
pa_table,
- sync_type_config=schema.sync_type_config,
- resource_name=export_signal.resource_name,
primary_keys=primary_keys or [],
cdc_write_mode=cdc_write_mode,
team_id=team_id_str,
@@ -1053,16 +1037,6 @@ def _process_message_reported(
DELTA_ROWS_WRITTEN_TOTAL.labels(team_id=team_id_str, schema_id=schema_id_str).inc(pa_table.num_rows)
- if pending_load_position is not None:
- # Best-effort: failing here would fail a batch that is already written, and the cost of
- # losing the position is re-applying rows next time, which is a no-op.
- try:
- persist_load_position(
- schema.id, export_signal.team_id, export_signal.resource_name, pending_load_position
- )
- except Exception: # noqa: BLE001 - bookkeeping must never fail a committed write
- logger.warning("cdc_load_position_persist_failed", exc_info=True)
-
internal_schema = HogQLSchema()
# Build from the Delta table schema first to cover all columns from
# all batches, then overlay the current batch for JSON detection.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
index d331b65118ad..25071bd9987a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
@@ -16,7 +16,6 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import
SCD2_VALID_TO_COLUMN,
TOAST_OMITTED_COLUMN,
)
-from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import LOAD_POSITION_CONFIG_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor import (
_apply_partitioning,
@@ -750,61 +749,34 @@ class TestEnrichCdcRows:
pa.field(CDC_SEQ_COLUMN, pa.int64(), metadata=CDC_SEQ_PROVENANCE), pa.array(seqs, pa.int64())
)
- def _resolve(self, table: pa.Table, *, watermark: int | None, cdc_write_mode: str = "incremental_merge"):
- config = {LOAD_POSITION_CONFIG_KEY: {"users": watermark}} if watermark is not None else {}
+ def _resolve(self, table: pa.Table, *, cdc_write_mode: str = "incremental_merge"):
return _resolve_cdc_positions(
table,
- sync_type_config=config,
- resource_name="users",
primary_keys=["id"],
cdc_write_mode=cdc_write_mode,
team_id="2",
)
- def test_resolution_drops_applied_rows_and_returns_the_new_position(self):
- table = self._stamped([1, 2, 3], ["I", "I", "I"], [10, 20, 30])
- result, position = self._resolve(table, watermark=20)
+ def test_the_merge_lane_collapses_a_key_to_its_latest_version(self):
+ # The write engine rejects duplicate keys outright.
+ table = self._stamped([1, 1, 2], ["I", "U", "I"], [10, 20, 30])
+ result = self._resolve(table)
- # Strictly-below only: 20 stays, because a split transaction shares its commit position.
- assert result.column("id").to_pylist() == [2, 3]
- assert position == 30
+ assert result.column(CDC_SEQ_COLUMN).to_pylist() == [20, 30]
def test_resolution_is_skipped_without_an_engine_stamped_position(self):
# A source column named _ph_cdc_seq must not drive the guard.
- table = self._stamped([1, 2], ["I", "I"], [10, 20]).drop_columns([CDC_SEQ_COLUMN])
+ table = self._stamped([1, 1], ["I", "U"], [10, 20]).drop_columns([CDC_SEQ_COLUMN])
table = table.append_column(pa.field(CDC_SEQ_COLUMN, pa.int64()), pa.array([10, 20], pa.int64()))
- result, position = self._resolve(table, watermark=99)
+ result = self._resolve(table)
assert result is table
- assert position is None
- def test_resolution_keeps_every_row_on_the_first_batch_ever(self):
- # No recorded position yet: nothing is provably applied, so nothing may be dropped.
- table = self._stamped([1, 2], ["I", "I"], [10, 20])
- result, position = self._resolve(table, watermark=None)
-
- assert result.column("id").to_pylist() == [1, 2]
- assert position == 20
-
- def test_resolution_reads_the_position_for_its_own_lane_only(self):
- # Consolidated and companion tables advance independently; one must not gate the other.
- table = self._stamped([1, 2], ["I", "I"], [10, 20])
- result, _ = _resolve_cdc_positions(
- table,
- sync_type_config={LOAD_POSITION_CONFIG_KEY: {"users_cdc": 99}},
- resource_name="users",
- primary_keys=["id"],
- cdc_write_mode="incremental_merge",
- team_id="2",
- )
-
- assert result.num_rows == 2
-
- def test_resolution_does_not_dedupe_the_history_lane(self):
+ def test_the_history_lane_keeps_every_version_of_a_key(self):
table = self._stamped([1, 1], ["I", "U"], [10, 20])
- result, _ = self._resolve(table, watermark=None, cdc_write_mode="scd2_append")
+ result = self._resolve(table, cdc_write_mode="scd2_append")
- assert result.num_rows == 2
+ assert result.column(CDC_SEQ_COLUMN).to_pylist() == [10, 20]
def _write_existing(self, path: str) -> None:
write_deltalake(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index dd5bd45cd21d..b17d6e716e8f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (
update_sync_type_config_keys,
)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import SCD2_APPEND_MODE
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
advance_xmin_state,
cleanup_memory,
@@ -152,12 +153,9 @@ class PipelineV3(Generic[ResumableData]):
self._delta_table_ref = DeltaTableRef(self._resource_name, self._job, self._logger)
attempt = current_activity_attempt()
- attempt_scoped_run_uuid = f"{self._job.workflow_run_id}-a{attempt}" if self._job.workflow_run_id else None
-
- self._s3_batch_writer = S3BatchWriter(
- self._logger, self._job, str(self._schema.id), attempt_scoped_run_uuid, compression=PARQUET_COMPRESSION
- )
self._attempt = attempt
+ self._run_uuid = f"{self._job.workflow_run_id}-a{attempt}" if self._job.workflow_run_id else None
+ self._s3_batch_writer = self._build_s3_writer(self._run_uuid)
sync_type: SyncTypeLiteral = "full_refresh"
if source_response.cdc_write_mode is not None:
@@ -198,30 +196,18 @@ class PipelineV3(Generic[ResumableData]):
is_resume = resumable_source_manager is not None and resumable_source_manager.can_resume()
- self._pg_producer = PostgresProducer(
- database_url=WAREHOUSE_SOURCES_DATABASE_URL,
- team_id=self._job.team_id,
- job_id=str(self._job.id),
- schema_id=str(self._schema.id),
- source_id=str(self._schema.source_id),
- resource_name=self._resource_name,
- sync_type=sync_type,
- run_uuid=self._s3_batch_writer.get_run_uuid(),
- logger=self._logger,
- primary_keys=self._resource.primary_keys,
- cdc_write_mode=self._resource.cdc_write_mode,
- is_resume=is_resume,
- partition_count=partition_count,
- partition_size=partition_size,
- partition_keys=partition_keys,
- partition_format=partition_format,
- partition_mode=partition_mode,
- is_first_ever_sync=is_first_ever_sync,
- workflow_id=current_workflow_id(),
- workflow_run_id=current_workflow_run_id(),
- # Snapshotted on the job when the run started. Empty for every run before
- # destinations, and every run of a team the flag is off for.
- destination_ids=list(self._job.destination_ids or []),
+ self._producer_kwargs: dict[str, Any] = {
+ "sync_type": sync_type,
+ "is_resume": is_resume,
+ "partition_count": partition_count,
+ "partition_size": partition_size,
+ "partition_keys": partition_keys,
+ "partition_format": partition_format,
+ "partition_mode": partition_mode,
+ "is_first_ever_sync": is_first_ever_sync,
+ }
+ self._pg_producer = self._build_producer(
+ self._s3_batch_writer, resource_name=self._resource_name, cdc_write_mode=self._resource.cdc_write_mode
)
self._resumable_source_manager = resumable_source_manager
@@ -251,12 +237,93 @@ class PipelineV3(Generic[ResumableData]):
is_incremental=self._is_incremental,
)
self._accumulated_pa_schema = None
+ self._batch_results = []
self._shutdown_monitor = shutdown_monitor
self._last_incremental_field_value: Any = None
self._earliest_incremental_field_value: Any = process_incremental_value(
models.schema.incremental_field_earliest_value, models.schema.incremental_field_type
)
- self._batch_results = []
+
+ # The seams below are where a run that writes several tables from one read plugs in (see
+ # `lanes.py`). Each default is exactly what a single-table run has always done.
+
+ def _build_s3_writer(self, run_uuid: str | None) -> S3BatchWriter:
+ return S3BatchWriter(self._logger, self._job, str(self._schema.id), run_uuid, compression=PARQUET_COMPRESSION)
+
+ def _producer_args(
+ self, s3_batch_writer: S3BatchWriter, *, resource_name: str, cdc_write_mode: str | None
+ ) -> dict[str, Any]:
+ return {
+ "database_url": WAREHOUSE_SOURCES_DATABASE_URL,
+ "team_id": self._job.team_id,
+ "job_id": str(self._job.id),
+ "schema_id": str(self._schema.id),
+ "source_id": str(self._schema.source_id),
+ "resource_name": resource_name,
+ "run_uuid": s3_batch_writer.get_run_uuid(),
+ "logger": self._logger,
+ "primary_keys": self._resource.primary_keys,
+ "cdc_write_mode": cdc_write_mode,
+ "workflow_id": current_workflow_id(),
+ "workflow_run_id": current_workflow_run_id(),
+ # Snapshotted on the job when the run started. Empty for every run before
+ # destinations, and every run of a team the flag is off for.
+ "destination_ids": list(self._job.destination_ids or []),
+ **self._producer_kwargs,
+ }
+
+ def _build_producer(
+ self, s3_batch_writer: S3BatchWriter, *, resource_name: str, cdc_write_mode: str | None
+ ) -> PostgresProducer:
+ return PostgresProducer(
+ **self._producer_args(s3_batch_writer, resource_name=resource_name, cdc_write_mode=cdc_write_mode)
+ )
+
+ async def _stage_batch(self, pa_table: pa.Table, batch_index: int, row_count: int) -> int:
+ """Write the batch and tell the queue. Returns the rows to count towards usage."""
+ batch_result = await asyncio.to_thread(self._s3_batch_writer.write_batch, pa_table, batch_index)
+ self._batch_results.append(batch_result)
+
+ self._pg_producer.send_batch_notification(batch_result, is_final_batch=False, cumulative_row_count=row_count)
+ return pa_table.num_rows
+
+ def _total_batches(self) -> int:
+ return len(self._batch_results)
+
+ def _consumer_finalizes_this_run(self) -> bool:
+ """Whether the load consumer will finalize THIS job, so the workflow must not."""
+ return self._total_batches() > 0
+
+ async def _send_final_batches(self, total_batches: int, row_count: int) -> str | None:
+ schema_path = await asyncio.to_thread(self._s3_batch_writer.write_schema)
+
+ final_batch = self._batch_results[-1]
+
+ self._pg_producer.send_batch_notification(
+ final_batch,
+ is_final_batch=True,
+ total_batches=total_batches,
+ total_rows=row_count,
+ data_folder=self._s3_batch_writer.get_data_folder(),
+ schema_path=schema_path,
+ cumulative_row_count=row_count,
+ )
+ return schema_path
+
+ def _mark_first_ever_sync(self) -> None:
+ self._pg_producer.is_first_ever_sync = True
+
+ def _maintains_companion_table(self) -> bool:
+ """Whether this run's own table is a `_cdc` history table, keyed under its own watermark.
+
+ Read off the resource rather than the lanes: a `cdc_only` run that stands down for
+ in-flight batches declares no lanes and runs this base class, and its table is the
+ history table all the same.
+ """
+ return self._resource.cdc_write_mode == SCD2_APPEND_MODE
+
+ def _close_producers(self) -> None:
+ self._pg_producer.close()
async def run(self) -> PipelineResult:
pa_memory_pool = pa.default_memory_pool()
@@ -338,13 +405,15 @@ class PipelineV3(Generic[ResumableData]):
is_fresh_sync = self._delta_table_ref.is_first_sync or self._schema.table is None
if is_fresh_sync:
- self._pg_producer.is_first_ever_sync = True
+ self._mark_first_ever_sync()
# Defensive pre-write compaction so a sync that arrived at a fragmented Delta
# target cleans up before adding more small files; see DeltaMaintenance.run_scheduled.
if not is_fresh_sync:
await DeltaMaintenance(self._delta_table_ref).run_scheduled(
- self._schema, partition_count_fallback=self._resource.partition_count
+ self._schema,
+ is_cdc_companion=self._maintains_companion_table(),
+ partition_count_fallback=self._resource.partition_count,
)
async for item in async_iterate(self._resource.items()):
@@ -404,7 +473,7 @@ class PipelineV3(Generic[ResumableData]):
# With zero batches, `_finalize` sent no final-batch notification, so the load
# consumer will never hear about this run and cannot finalize it — the workflow must.
# See the PipelineResult docstring for the full ownership contract.
- consumer_will_hear_about_this_run = len(self._batch_results) > 0
+ consumer_will_hear_about_this_run = self._consumer_finalizes_this_run()
return {
"should_trigger_cdp_producer": await self._sinks.cdp_producer.should_run(),
@@ -429,7 +498,7 @@ class PipelineV3(Generic[ResumableData]):
"sync_type": sync_type,
"status": status,
"duration_seconds": duration,
- "total_batches": len(self._batch_results),
+ "total_batches": self._total_batches(),
"total_rows": row_count if "row_count" in locals() else 0,
},
)
@@ -437,7 +506,7 @@ class PipelineV3(Generic[ResumableData]):
self._logger.debug("V3 Pipeline: Cleaning up resources")
del self._resource
del self._s3_batch_writer
- self._pg_producer.close()
+ self._close_producers()
del self._pg_producer
cleanup_memory(pa_memory_pool, py_table if "py_table" in locals() else None)
@@ -477,10 +546,7 @@ class PipelineV3(Generic[ResumableData]):
pa_table, self._accumulated_pa_schema, self._logger, protected_columns=cursor_columns
)
- batch_result = await asyncio.to_thread(self._s3_batch_writer.write_batch, pa_table, batch_index)
- self._batch_results.append(batch_result)
-
- self._pg_producer.send_batch_notification(batch_result, is_final_batch=False, cumulative_row_count=row_count)
+ tracked_rows = await self._stage_batch(pa_table, batch_index, row_count)
self._internal_schema.add_pyarrow_table(pa_table)
@@ -500,7 +566,7 @@ class PipelineV3(Generic[ResumableData]):
self._earliest_incremental_field_value = incremental_values.earliest_value
await update_row_tracking_after_batch(
- str(self._job.id), self._job.team_id, self._schema.id, pa_table.num_rows, self._logger
+ str(self._job.id), self._job.team_id, self._schema.id, tracked_rows, self._logger
)
async def _stamp_full_run(self) -> None:
@@ -536,7 +602,7 @@ class PipelineV3(Generic[ResumableData]):
except Exception:
await self._logger.aexception("V3 Pipeline: Failed to persist observed columns into schema_metadata")
- total_batches = len(self._batch_results)
+ total_batches = self._total_batches()
if total_batches == 0:
# A zero-batch run still ran the full extraction, which is what the fast-return
@@ -553,19 +619,7 @@ class PipelineV3(Generic[ResumableData]):
total_rows=row_count,
)
- schema_path = await asyncio.to_thread(self._s3_batch_writer.write_schema)
-
- final_batch = self._batch_results[-1]
-
- self._pg_producer.send_batch_notification(
- final_batch,
- is_final_batch=True,
- total_batches=total_batches,
- total_rows=row_count,
- data_folder=self._s3_batch_writer.get_data_folder(),
- schema_path=schema_path,
- cumulative_row_count=row_count,
- )
+ schema_path = await self._send_final_batches(total_batches, row_count)
await finalize_desc_sort_incremental_value(
self._resource,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
index a2ec372381fc..b5cf82412ff1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
@@ -3,11 +3,23 @@ from typing import cast
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
+import pyarrow as pa
+from asgiref.sync import async_to_sync
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.lanes import (
+ LanedPipelineV3,
+ _LaneWriter,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline import PipelineV3
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import OutputLane
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
ImportJobModels,
)
+_PIPELINE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline"
+_LANES = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.lanes"
+_CONSUMER = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer"
+
def _make_logger() -> MagicMock:
logger = MagicMock()
@@ -25,7 +37,7 @@ def _make_pipeline() -> PipelineV3:
with patch.object(PipelineV3, "__init__", return_value=None):
pipeline = PipelineV3.__new__(PipelineV3)
- pipeline._resource = MagicMock(name="test_table", primary_keys=["id"])
+ pipeline._resource = MagicMock(name="test_table", primary_keys=["id"], lanes=None)
pipeline._resource_name = "test_table"
pipeline._job = MagicMock(team_id=1, workflow_run_id="run-abc", billable=False)
pipeline._source = MagicMock(source_type="Postgres")
@@ -53,8 +65,8 @@ def _make_pipeline() -> PipelineV3:
pipeline._load_id = 1
pipeline._s3_batch_writer = MagicMock()
pipeline._pg_producer = MagicMock(sync_type="full_refresh")
- pipeline._accumulated_pa_schema = None
pipeline._batch_results = []
+ pipeline._accumulated_pa_schema = None
pipeline._shutdown_monitor = MagicMock()
pipeline._attempt = 1
pipeline._uses_delta_write_column_selection = False
@@ -98,6 +110,7 @@ class TestAttemptScopedRunUuid:
partition_format=None,
partition_mode=None,
cdc_write_mode=None,
+ lanes=None,
)
with (
@@ -227,6 +240,7 @@ class TestCDCSourceWiring:
partition_format=None,
partition_mode=None,
cdc_write_mode=cdc_write_mode,
+ lanes=None,
)
base = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline"
@@ -312,6 +326,437 @@ class TestCDCSeqProvenanceSurvivesStaging:
assert has_engine_seq(pq.read_table(buf))
+def _build_laned(lanes) -> LanedPipelineV3:
+ """A `LanedPipelineV3` over mocked collaborators, built the way the activity builds it."""
+ mock_job = MagicMock(
+ team_id=1, workflow_run_id="wfrun-abc", workflow_id="wf-1", billable=True, id="job-1", destination_ids=[]
+ )
+ mock_schema = MagicMock(
+ id="schema-1",
+ source_id="source-1",
+ is_incremental=False,
+ is_webhook=False,
+ is_xmin=False,
+ is_append=False,
+ table=None,
+ primary_key_columns=None,
+ partition_count=None,
+ partition_size=None,
+ partitioning_keys=None,
+ partition_format=None,
+ partition_mode=None,
+ incremental_field_earliest_value=None,
+ incremental_field_type=None,
+ )
+ mock_resource = MagicMock(
+ name="test",
+ primary_keys=["id"],
+ partition_count=None,
+ partition_size=None,
+ partition_keys=None,
+ partition_format=None,
+ partition_mode=None,
+ cdc_write_mode=lanes[0].cdc_write_mode,
+ lanes=lanes,
+ )
+ with (
+ patch(f"{_PIPELINE}.current_activity_attempt", return_value=3),
+ patch(f"{_PIPELINE}.current_workflow_id", return_value="wf-1"),
+ patch(f"{_PIPELINE}.current_workflow_run_id", return_value="wfrun-abc"),
+ patch(f"{_PIPELINE}.S3BatchWriter"),
+ patch(f"{_PIPELINE}.PostgresProducer"),
+ patch(f"{_PIPELINE}.DeltaTableRef"),
+ ):
+ return LanedPipelineV3(
+ source_response=mock_resource,
+ logger=_make_logger(),
+ job_id="job-1",
+ reset_pipeline=False,
+ shutdown_monitor=MagicMock(),
+ resumable_source_manager=None,
+ models=ImportJobModels(job=mock_job, schema=mock_schema, source=mock_source_stub(), table=None),
+ )
+
+
+def mock_source_stub() -> MagicMock:
+ return MagicMock()
+
+
+def _lane_writer(name: str, *, billable: bool = True, transform=None) -> _LaneWriter:
+ s3_batch_writer = MagicMock(
+ write_batch=MagicMock(side_effect=lambda t, i: MagicMock(batch_index=i)),
+ write_schema=MagicMock(return_value=f"s3://schema/{name}"),
+ get_data_folder=MagicMock(return_value=f"s3://data/{name}"),
+ )
+ return _LaneWriter(
+ lane=OutputLane(name=name, billable=billable, transform=transform),
+ s3_batch_writer=s3_batch_writer,
+ pg_producer=MagicMock(sync_type="cdc"),
+ )
+
+
+class TestLaneFanOut:
+ @staticmethod
+ def _pipeline(writers: list[_LaneWriter]) -> LanedPipelineV3:
+ """A laned pipeline whose companion lanes are already open.
+
+ Companions open lazily in production, on the first batch a lane has rows for. These tests
+ are about the fan-out itself, so they hand the writers over ready-made; `TestCompanionJob`
+ is what covers the opening.
+ """
+ base = _make_pipeline()
+ pipeline = LanedPipelineV3.__new__(LanedPipelineV3)
+ pipeline.__dict__.update(base.__dict__)
+ pipeline._output_lanes = [writer.lane for writer in writers]
+ pipeline._lane_writers = writers
+ pipeline._writers_by_lane = dict(enumerate(writers))
+ pipeline._s3_batch_writer = writers[0].s3_batch_writer
+ pipeline._pg_producer = writers[0].pg_producer
+ pipeline._batch_results = writers[0].batch_results
+ cast(MagicMock, pipeline._schema).configure_mock(incremental_field=None, enabled_columns=None)
+ pipeline._last_incremental_field_value = None
+ pipeline._earliest_incremental_field_value = None
+ return pipeline
+
+ async def _process(self, pipeline: PipelineV3, table) -> MagicMock:
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.update_incremental_field_values",
+ AsyncMock(return_value=MagicMock(last_value=None, earliest_value=None)),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.update_row_tracking_after_batch",
+ AsyncMock(),
+ ) as tracked,
+ ):
+ await pipeline._process_batch(pa_table=table, batch_index=0, row_count=table.num_rows)
+ return tracked
+
+ async def test_every_lane_writes_the_batch(self) -> None:
+ writers = [_lane_writer("users"), _lane_writer("users_cdc", billable=False)]
+ pipeline = self._pipeline(writers)
+
+ await self._process(pipeline, pa.table({"id": pa.array([1, 2], pa.int64())}))
+
+ assert [len(writer.batch_results) for writer in writers] == [1, 1]
+ for writer in writers:
+ cast(MagicMock, writer.pg_producer.send_batch_notification).assert_called_once()
+
+ async def test_only_the_billable_lane_counts_towards_usage(self) -> None:
+ # One read of a change stream is one sync however many tables it keeps.
+ writers = [_lane_writer("users"), _lane_writer("users_cdc", billable=False)]
+ pipeline = self._pipeline(writers)
+
+ tracked = await self._process(pipeline, pa.table({"id": pa.array([1, 2, 3], pa.int64())}))
+
+ assert tracked.call_args[0][3] == 3
+
+ async def test_a_lane_that_already_holds_the_rows_stages_nothing_for_that_index(self) -> None:
+ writers = [_lane_writer("users"), _lane_writer("users_cdc", transform=lambda t: t.slice(0, 0))]
+ pipeline = self._pipeline(writers)
+
+ await self._process(pipeline, pa.table({"id": pa.array([1, 2], pa.int64())}))
+
+ assert [len(writer.batch_results) for writer in writers] == [1, 0]
+ cast(MagicMock, writers[1].pg_producer.send_batch_notification).assert_not_called()
+
+ async def test_the_primary_lane_keeps_batch_zero_even_when_it_filters_it_away(self) -> None:
+ # The producer supersedes a previous attempt's staged batches only on index 0. If the
+ # merge lane could skip it, a retried run would never retire what the attempt before it
+ # left staged, and those batches would load alongside this one.
+ writers = [
+ _lane_writer("users", transform=lambda t: t.slice(0, 0)),
+ _lane_writer("users_cdc", billable=False),
+ ]
+ pipeline = self._pipeline(writers)
+
+ await self._process(pipeline, pa.table({"id": pa.array([1, 2], pa.int64())}))
+
+ assert [len(w.batch_results) for w in writers] == [1, 1]
+ assert writers[0].row_count == 0
+
+ async def test_a_batch_that_arrives_empty_is_staged_by_the_primary_lane_only(self) -> None:
+ # Every non-CDC source is one lane with no transform, and reaches here with an empty table
+ # whenever its source yields one. Skipping it would move job completion from the load
+ # consumer to the workflow for those syncs. A companion has no job until it holds rows,
+ # so staging the empty batch there would open one for nothing.
+ writers = [_lane_writer("users"), _lane_writer("users_cdc", billable=False)]
+ pipeline = self._pipeline(writers)
+
+ await self._process(pipeline, pa.table({"id": pa.array([], pa.int64())}))
+
+ assert [len(writer.batch_results) for writer in writers] == [1, 0]
+
+ async def test_each_lane_ends_with_its_own_final_batch(self) -> None:
+ writers = [_lane_writer("users"), _lane_writer("users_cdc", billable=False)]
+ pipeline = self._pipeline(writers)
+ await self._process(pipeline, pa.table({"id": pa.array([1], pa.int64())}))
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.finalize_desc_sort_incremental_value",
+ AsyncMock(),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.advance_xmin_state",
+ AsyncMock(),
+ ),
+ ):
+ await pipeline._finalize(row_count=1)
+
+ for writer in writers:
+ call = cast(MagicMock, writer.pg_producer.send_batch_notification).call_args
+ assert call.kwargs["is_final_batch"] is True
+
+ async def test_a_lane_with_nothing_to_write_sends_no_final_batch(self) -> None:
+ writers = [_lane_writer("users"), _lane_writer("users_cdc", transform=lambda t: t.slice(0, 0))]
+ pipeline = self._pipeline(writers)
+ await self._process(pipeline, pa.table({"id": pa.array([1], pa.int64())}))
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.finalize_desc_sort_incremental_value",
+ AsyncMock(),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.advance_xmin_state",
+ AsyncMock(),
+ ),
+ ):
+ await pipeline._finalize(row_count=1)
+
+ cast(MagicMock, writers[1].pg_producer.send_batch_notification).assert_not_called()
+
+
+class TestCompanionJob:
+ """A table beyond the first gets its own job, opened only when it has rows to write."""
+
+ @staticmethod
+ def _laned(lanes: list[OutputLane]) -> LanedPipelineV3:
+ return _build_laned(lanes)
+
+ @staticmethod
+ def _open(
+ pipeline: LanedPipelineV3, lane: OutputLane, created: MagicMock, recorded: MagicMock | None = None
+ ) -> MagicMock:
+ producer = MagicMock()
+ with (
+ patch(f"{_LANES}.PostgresProducer", producer),
+ patch(f"{_LANES}.record_companion_job", recorded or MagicMock()),
+ patch(
+ f"{_LANES}.database_sync_to_async_pool",
+ lambda fn: AsyncMock(side_effect=lambda *a, **k: fn(*a, **k)),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.workflow_activities."
+ "create_job_model._build_schema_snapshot",
+ return_value={"name": "users"},
+ ),
+ patch("products.warehouse_sources.backend.models.external_data_job.ExternalDataJob.objects", created),
+ ):
+ async_to_sync(pipeline._writer_for)(pipeline._output_lanes.index(lane))
+ return producer
+
+ @staticmethod
+ def _both() -> list[OutputLane]:
+ return [
+ OutputLane(name="users", cdc_write_mode="incremental_merge"),
+ OutputLane(name="users_cdc", cdc_write_mode="scd2_append"),
+ ]
+
+ def test_no_job_is_created_until_a_lane_has_rows(self) -> None:
+ # A job created before there is anything to write is a row nothing owns: the loader
+ # finishes a job on its final batch, and the stranded sweep finds runs by their batches.
+ pipeline = self._laned(self._both())
+
+ assert len(pipeline._lane_writers) == 1
+ assert pipeline._lane_writers[0].job is None
+
+ def test_the_companion_table_gets_its_own_job(self) -> None:
+ pipeline = self._laned(self._both())
+ created = MagicMock()
+
+ self._open(pipeline, pipeline._output_lanes[1], created)
+
+ fields = created.create.call_args.kwargs
+ # No workflow run id: the schema's own job owns the pipeline lock, and a second holder
+ # releasing it would free it while this run is still writing.
+ assert fields["workflow_run_id"] is None
+ # One read of a change stream is one sync however many tables it keeps.
+ assert fields["billable"] is False
+ assert fields["schema_snapshot"]["cdc_write_mode"] == "scd2_append"
+ assert fields["schema_snapshot"]["companion_of"] == "job-1"
+
+ def test_the_parent_job_records_its_companion(self) -> None:
+ # The listing proof checks companions by the ids on the parent's own row — a primary-key
+ # lookup, where a search by `companion_of` would walk the schema's whole job history.
+ pipeline = self._laned(self._both())
+ created = MagicMock()
+ created.create.return_value = MagicMock(id="companion-job")
+ recorded = MagicMock()
+
+ self._open(pipeline, pipeline._output_lanes[1], created, recorded)
+
+ recorded.assert_called_once_with("job-1", pipeline._job.team_id, "companion-job", first_of_attempt=True)
+
+ def test_the_companion_writes_under_its_own_job_and_run(self) -> None:
+ pipeline = self._laned(self._both())
+ created = MagicMock()
+ created.create.return_value = MagicMock(id="companion-job")
+
+ producer = self._open(pipeline, pipeline._output_lanes[1], created)
+
+ assert producer.call_args.kwargs["job_id"] == "companion-job"
+ assert producer.call_args.kwargs["workflow_run_id"] is None
+ companion = pipeline._lane_writers[1].job
+ assert companion is not None and companion.id == "companion-job"
+
+ def test_a_lane_opens_once_however_many_batches_it_writes(self) -> None:
+ pipeline = self._laned(self._both())
+ created = MagicMock()
+ created.create.return_value = MagicMock(id="companion-job")
+ lane = pipeline._output_lanes[1]
+
+ self._open(pipeline, lane, created)
+ self._open(pipeline, lane, created)
+
+ assert created.create.call_count == 1
+ assert len(pipeline._lane_writers) == 2
+
+ def test_the_schema_job_is_finalized_on_its_own_lane_alone(self) -> None:
+ # Counting the companion's batches here would hand the schema's job to a consumer that
+ # never hears about it, leaving the job Running and its pipeline lock held.
+ pipeline = self._laned(self._both())
+ companion = _lane_writer("users_cdc", billable=False)
+ companion.batch_results.append(MagicMock(batch_index=0))
+ pipeline._lane_writers.append(companion)
+
+ assert pipeline._total_batches() == 1
+ assert pipeline._consumer_finalizes_this_run() is False
+
+ def test_a_failed_run_retires_its_companion_job_rows_and_nothing_else(self) -> None:
+ # Keyed on the job id the run recorded, not on a writer: the row is created before the S3
+ # client and the queue connect, and a failure between them must still retire it. Its
+ # batches are left alone: failing one the loader is mid-write on does not stop the write,
+ # but it does drop the run out of the in-flight guard, and the retry then reads a position
+ # the straggler is about to move past and stages the same rows again.
+ pipeline = self._laned(self._both())
+ pipeline._companion_job_ids.append("companion-job")
+ retired = MagicMock()
+
+ with (
+ patch(f"{_LANES}.retire_companion_job", retired),
+ patch(
+ f"{_LANES}.database_sync_to_async_pool",
+ lambda fn: AsyncMock(side_effect=lambda *a, **k: fn(*a, **k)),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue."
+ "jobs_db.BatchQueue.fail_batches_for_job_sync"
+ ) as swept,
+ ):
+ async_to_sync(pipeline._fail_companion_jobs)()
+
+ retired.assert_called_once_with("companion-job")
+ swept.assert_not_called()
+
+ def test_a_companion_whose_final_batch_is_queued_is_not_retired(self) -> None:
+ # The loader owns it from there. Retiring it would have the loader discard a tail that
+ # lands on its own, and show the customer a Failed history row for a run that succeeded.
+ pipeline = self._laned(self._both())
+ pipeline._companion_job_ids.extend(["done", "open"])
+ pipeline._final_sent_job_ids.add("done")
+ retired = MagicMock()
+
+ with (
+ patch(f"{_LANES}.retire_companion_job", retired),
+ patch(
+ f"{_LANES}.database_sync_to_async_pool", lambda fn: AsyncMock(side_effect=lambda *a, **k: fn(*a, **k))
+ ),
+ ):
+ async_to_sync(pipeline._fail_companion_jobs)()
+
+ retired.assert_called_once_with("open")
+
+ @pytest.mark.asyncio
+ async def test_a_history_only_schema_maintains_its_table_under_the_companion_watermark(self) -> None:
+ # For `cdc_only` the schema's own table is the history table. The loader's post-load pass
+ # vacuums it under `last_vacuum_version_cdc`; the pre-write pass here must use the same
+ # one, or the two run on separate cadences against one table.
+ pipeline = self._laned([OutputLane(name="users_cdc", cdc_write_mode="scd2_append")])
+ pipeline._delta_table_ref = MagicMock(is_first_sync=False)
+ pipeline._schema.table = MagicMock()
+ pipeline._resource.items = MagicMock(return_value=iter([]))
+ pipeline._sinks = MagicMock(clear=AsyncMock(), cdp_producer=MagicMock(should_run=AsyncMock(return_value=False)))
+ maintenance = MagicMock()
+ maintenance.return_value.run_scheduled = AsyncMock()
+
+ with (
+ patch(f"{_PIPELINE}.reset_rows_synced_if_needed", new_callable=AsyncMock),
+ patch(f"{_PIPELINE}.validate_incremental_sync"),
+ patch(f"{_PIPELINE}.setup_row_tracking_with_billing_check", new_callable=AsyncMock),
+ patch(f"{_PIPELINE}.handle_reset_or_full_refresh", new_callable=AsyncMock),
+ patch(f"{_PIPELINE}.DeltaMaintenance", maintenance),
+ patch(f"{_PIPELINE}.activity") as mock_activity,
+ ):
+ mock_activity.in_activity.return_value = False
+ await pipeline.run()
+
+ assert maintenance.return_value.run_scheduled.call_args.kwargs["is_cdc_companion"] is True
+ assert self._laned(self._both())._maintains_companion_table() is False
+
+ def test_a_history_only_run_that_stands_down_still_maintains_under_the_companion_watermark(self) -> None:
+ # The in-flight no-op declares no lanes and runs the base class over the same history
+ # table. The answer has to come from the resource, not from the lanes.
+ pipeline = _make_pipeline()
+ pipeline._resource.cdc_write_mode = "scd2_append"
+
+ assert pipeline._maintains_companion_table() is True
+
+ def test_the_companion_delivers_to_no_destination(self) -> None:
+ # Delivery names the destination table from the schema, so history rows merged by key
+ # there would clobber the consolidated table's rows.
+ pipeline = self._laned(self._both())
+ pipeline._job.destination_ids = ["dest-1"]
+ created = MagicMock()
+ created.create.return_value = MagicMock(id="companion-job")
+
+ producer = self._open(pipeline, pipeline._output_lanes[1], created)
+
+ assert created.create.call_args.kwargs["destination_ids"] == []
+ assert producer.call_args.kwargs["destination_ids"] == []
+
+
+class TestSingleTableRunIsUntouched:
+ """The base class is every non-lane source. Its staging path must not depend on lanes at all."""
+
+ async def test_an_empty_batch_is_still_staged_and_counted(self) -> None:
+ # A source that yields an empty table still stages it, which is what makes the load
+ # consumer — not the workflow — complete the job.
+ pipeline = _make_pipeline()
+ pipeline._s3_batch_writer = MagicMock(write_batch=MagicMock(return_value=MagicMock(batch_index=0)))
+ pipeline._pg_producer = MagicMock()
+ pipeline._batch_results = []
+
+ staged = await pipeline._stage_batch(pa.table({"id": pa.array([], pa.int64())}), 0, 0)
+
+ assert staged == 0
+ pipeline._s3_batch_writer.write_batch.assert_called_once()
+ pipeline._pg_producer.send_batch_notification.assert_called_once()
+
+ def test_the_activity_runs_the_base_class_for_a_source_without_lanes(self) -> None:
+ # What keeps every other source off the subclass. `lanes=None` is what a source that
+ # never heard of lanes carries, and `[]` what a lane build that found nothing returns.
+ from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
+ v3_pipeline_class,
+ )
+
+ assert v3_pipeline_class(MagicMock(lanes=None)) is PipelineV3
+ assert v3_pipeline_class(MagicMock(lanes=[])) is PipelineV3
+ assert v3_pipeline_class(MagicMock(lanes=[OutputLane(name="users_cdc")])) is LanedPipelineV3
+
+
class TestZeroBatchRunStampsTheFullRunMarker:
@pytest.mark.asyncio
async def test_a_run_that_extracted_nothing_still_counts_as_a_full_run(self) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py
index 34bc282da541..59c492538930 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py
@@ -12,6 +12,7 @@ from structlog.types import FilteringBoundLogger
from products.warehouse_sources.backend.types import IncrementalFieldType
if TYPE_CHECKING:
+ import pyarrow as pa
from dlt.common.data_types.typing import TDataType
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import (
@@ -43,6 +44,26 @@ class _Dataclass(Protocol):
ResumableData = TypeVar("ResumableData", bound=_Dataclass)
[email protected](frozen=False)
+class OutputLane:
+ """One table a response's item stream feeds.
+
+ A source whose single stream lands in more than one table — a change stream feeding both a
+ merged table and its append-only history — declares one lane per table. The pipeline writes
+ every lane from the same read, so the source reads its origin once however many tables it
+ keeps.
+ """
+
+ name: str
+ cdc_write_mode: Optional[str] = None
+ billable: bool = True
+ """Whether this lane's rows count towards the team's synced-row usage. A source feeding two
+ tables from one stream bills the stream once."""
+ transform: Optional[Callable[[pa.Table], pa.Table]] = None
+ """Applied to each batch before this lane writes it. May drop rows and add columns; the lane's
+ own writer tracks the schema it ends up with."""
+
+
@dataclasses.dataclass(frozen=False) # callers mutate `primary_keys` after construction
class SourceResponse:
name: str
@@ -85,6 +106,9 @@ class SourceResponse:
"""xmin syncs: full 64-bit `xid8` ceiling, the durable wraparound-safe cursor."""
xmin_num_wraparound: Optional[int] = None
"""xmin syncs: epoch (high 32 bits of `xmin_ceiling_xid8`) at this run's ceiling."""
+ lanes: Optional[list[OutputLane]] = None
+ """Tables this response's items feed, when it feeds more than the one `name` alone describes.
+ None means the single lane built from `name` and `cdc_write_mode`."""
# Not frozen: nothing mutates it in place today, so freezing it is plausible, but every source
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 042ed6ad540e..bd2043ca38f0 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
@@ -1674,32 +1674,39 @@ 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 asgiref.sync import async_to_sync
+
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+ from products.warehouse_sources.backend.temporal.data_imports.cdc.companion_jobs import (
+ retire_orphaned_companions,
+ )
from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
- CONSOLIDATED_WRITE_MODE,
CDCSourceManager,
- consolidated_resource_name,
- has_pending_legacy_backlog,
- is_buffered_consolidated,
+ build_output_lanes,
+ clear_listing,
+ completed_listing_proof,
+ consumes_buffer,
+ has_batches_in_flight,
+ served_lanes,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.config import (
PostgresCDCConfig,
)
ingest_mode = PostgresCDCConfig.from_source(schema.source).ingest_mode
- if not is_buffered_consolidated(schema, ingest_mode=ingest_mode):
+ if not consumes_buffer(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.
+ # before the flip, or a worker one deploy behind, would consume this buffer on v2, which
+ # stamps no position on the rows it writes, so every later run would find nothing to resume
+ # from and re-merge the whole buffer. 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."
+ "Buffered consumption requires v3, whose loader stamps each row with the position "
+ "the next run resumes from."
)
# A CDC reset must travel through snapshot mode (which purges the buffer and re-seeds the
@@ -1712,26 +1719,51 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
"'streaming'. Reset it to snapshot (cdc_mode='snapshot') so the re-snapshot path runs."
)
- resource_name = consolidated_resource_name(schema)
-
- if has_pending_legacy_backlog(schema):
- # Legacy deliveries carry no position column, so merging buffered rows before they land
- # lets an older row overwrite a newer one. No-op this run — an empty response keeps the
- # schedule alive, unlike CDCHandledExternally, which would pause it for good.
- inputs.logger.info("cdc_buffered_waiting_for_legacy_backlog", schema_name=schema.name)
+ if has_batches_in_flight(schema):
+ # Reading now would stage rows alongside a delivery that is still landing: a legacy one
+ # carries no position to order against, and a previous attempt of this job holds staged
+ # batches that are still claimable, which the append lane would then write twice.
+ #
+ # An empty response no-ops this tick and keeps the schedule alive, unlike
+ # CDCHandledExternally, which would pause it for good. Nothing is listed and nothing is
+ # deleted. An earlier attempt of this same job may have stamped a listing, though, and
+ # the workflow completes the job on this response — so the stamp comes off, or a batch
+ # of that attempt failing later would leave a Completed job proving a listing nothing
+ # drained.
+ inputs.logger.info("cdc_buffered_waiting_for_in_flight_batches", schema_name=schema.name)
+ clear_listing(inputs.job_id, inputs.team_id)
+ first_lane = served_lanes(schema)[0]
return SourceResponse(
- name=resource_name,
+ name=first_lane.resource_name,
items=lambda: iter(()),
primary_keys=schema.primary_key_columns,
- cdc_write_mode=CONSOLIDATED_WRITE_MODE,
+ cdc_write_mode=first_lane.write_mode,
)
- manager = CDCSourceManager(inputs, inputs.logger)
+ if job is None:
+ raise ValueError(f"Buffered CDC schema {schema.name} has no job row for run {inputs.job_id}")
+
+ # Nothing of any earlier run is executing now, so a companion still Running belongs to a
+ # run that died without its `finally` and nothing else will ever close it.
+ retired = retire_orphaned_companions(schema)
+ if retired:
+ inputs.logger.warning("cdc_orphaned_companion_jobs_retired", schema_name=schema.name, job_ids=retired)
+
+ # Every table this schema's changes feed, written from one read of the buffer. Each lane
+ # carries where its own table stops, because a failed run can leave one ahead of the other.
+ lanes, deletion_floor = async_to_sync(build_output_lanes)(schema, job, inputs.logger)
+ manager = CDCSourceManager(
+ inputs,
+ inputs.logger,
+ deletion_floor=deletion_floor,
+ proof_time=async_to_sync(completed_listing_proof)(schema),
+ )
return SourceResponse(
- name=resource_name,
- items=lambda: manager.get_items(resource_name),
+ name=lanes[0].name,
+ items=manager.get_items,
primary_keys=schema.primary_key_columns,
- cdc_write_mode=CONSOLIDATED_WRITE_MODE,
+ cdc_write_mode=lanes[0].cdc_write_mode,
+ lanes=lanes,
)
def source_for_pipeline(self, config: PostgresSourceConfig, inputs: SourceInputs) -> SourceResponse:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
index 687c9b8919e3..b896abbab9b3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -3,7 +3,7 @@ import socket
import asyncio
import datetime as dt
import dataclasses
-from typing import Any, NoReturn, Optional
+from typing import TYPE_CHECKING, Any, NoReturn, Optional
from django.db import InterfaceError, InternalError, OperationalError
from django.db.models import Prefetch
@@ -150,6 +150,9 @@ WAREHOUSE_READABLE_PARENT_SYNC_TYPES = frozenset(
)
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3 import PipelineV3
+
# Opening the parent's Delta table costs a few seconds that paging the vendor listing does not:
# resolve the table, read the transaction log, start the scan. That cost is fixed, while the
# listing it replaces grows with the parent, so a small parent pays more than it saves. Measured
@@ -318,6 +321,17 @@ async def _probe_found_new_data(
return True
+def v3_pipeline_class(source_response: SourceResponse) -> "type[PipelineV3]":
+ """A source feeding several tables from one read declares lanes; everything else runs the
+ base class untouched."""
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3 import (
+ LanedPipelineV3,
+ PipelineV3,
+ )
+
+ return LanedPipelineV3 if source_response.lanes else PipelineV3
+
+
@activity.defn
async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> PipelineResult:
bind_contextvars(team_id=inputs.team_id)
@@ -918,7 +932,7 @@ async def _run(
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3 import PipelineV3
logger.info("Running V3 pipeline (persisted job.pipeline_version is V3)")
- pipeline: PipelineV3 | PipelineNonDLT = PipelineV3(
+ pipeline: PipelineV3 | PipelineNonDLT = v3_pipeline_class(source_response)(
source_response,
logger,
job_inputs.run_id,
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 28a33f55533b..26d4382f0a66 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
@@ -11,12 +11,15 @@ 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_schema import (
+ ExternalDataSchema,
+ update_sync_type_config_keys,
+)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN
from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import build_buffer_file_name
-from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import consolidated_resource_name
+from products.warehouse_sources.backend.temporal.data_imports.cdc.companion_jobs import COMPANION_RETIRED_ERROR
_CMD = "products.warehouse_sources.backend.management.commands.migrate_cdc_source_to_buffered"
@@ -161,41 +164,32 @@ class TestMigrateCDCSourceToBuffered(BaseTest):
# Consumer schedules must still be live so they can catch up for the re-run.
mocks["pause_schema"].assert_not_called()
- def _record_load_position(self, schema: ExternalDataSchema, position: int) -> None:
- schema.sync_type_config = {
- **schema.sync_type_config,
- "cdc_load_position": {consolidated_resource_name(schema): position},
- }
- schema.save(update_fields=["sync_type_config"])
-
def test_rollback_ignores_prefixes_the_buffered_lane_never_served(self):
# A legacy schema's prefix holds shadow copies no consumer ever reads, so scanning it would
# wedge every rollback of a hybrid source with capture left paused.
source = self._source(ingest_mode="buffered")
self._schema(source, "users")
- companion = self._schema(source, "events", table_mode="cdc_only")
+ snapshotting = self._schema(source, "events", cdc_mode="snapshot")
shadow = f"bucket/cdc_producer/x/{build_buffer_file_name(100, 200, 0)}"
- with _mocked_side_effects(buffer_keys_by_schema={str(companion.id): [shadow]}):
+ with _mocked_side_effects(buffer_keys_by_schema={str(snapshotting.id): [shadow]}):
self._run(source, rollback=True, drain_timeout=0)
source.refresh_from_db()
assert source.job_inputs["cdc_ingest_mode"] == "legacy"
- @parameterized.expand([("at_the_position", 200, True), ("below_the_position", 199, False)])
- def test_rollback_waits_for_the_consumer_to_delete_the_file_at_the_position(
- self, _name, end_seq: int, blocks: bool
- ):
- # One transaction shares a commit position across its events, so a file ending AT the
- # position can still be an unread tail. Only the consumer's deletion proves it landed.
+ @parameterized.expand([("a_file_remains", True), ("prefix_is_empty", False)])
+ def test_rollback_waits_until_the_consumer_has_deleted_every_file(self, _name, blocks: bool):
+ # The consumer deletes a file once the job that read it completes, so an empty prefix is
+ # its own proof that every change reached every table the mode feeds. A file that is still
+ # there can be an unread tail — one transaction shares its commit position across files.
source = self._source(ingest_mode="buffered")
- schema = self._schema(source, "users")
- self._record_load_position(schema, 200)
- remaining = f"bucket/cdc_producer/x/{build_buffer_file_name(100, end_seq, 0)}"
+ self._schema(source, "users")
+ remaining = [f"bucket/cdc_producer/x/{build_buffer_file_name(100, 200, 0)}"] if blocks else []
- with _mocked_side_effects(buffer_keys=[remaining]):
+ with _mocked_side_effects(buffer_keys=remaining):
if blocks:
- with pytest.raises(CommandError, match="not yet proven applied"):
+ with pytest.raises(CommandError, match="not yet applied"):
self._run(source, rollback=True, drain_timeout=0)
else:
self._run(source, rollback=True, drain_timeout=0)
@@ -203,10 +197,57 @@ class TestMigrateCDCSourceToBuffered(BaseTest):
source.refresh_from_db()
assert source.job_inputs["cdc_ingest_mode"] == ("buffered" if blocks else "legacy")
+ def test_a_rollback_records_that_the_source_has_been_buffered(self):
+ # A source flipped before this marker existed only gains it here, and that is exactly the
+ # source that would otherwise be refused its next flip.
+ source = self._source(ingest_mode="buffered")
+ self._schema(source, "users")
+
+ with _mocked_side_effects():
+ self._run(source, rollback=True)
+
+ source.refresh_from_db()
+ assert source.job_inputs["cdc_ingest_mode"] == "legacy"
+ assert source.job_inputs["cdc_buffered_before"]
+
+ def test_a_flip_after_a_rollback_is_not_refused_for_our_own_column(self):
+ # Rollback leaves `_ph_cdc_seq` in the warehouse table and puts the source back on legacy,
+ # so the column looks exactly like a source-owned one. Refusing here would strand the
+ # source for good, telling the operator to rename a column the source does not have.
+ source = self._source(ingest_mode="legacy")
+ source.job_inputs = {**source.job_inputs, "cdc_buffered_before": True}
+ source.save(update_fields=["job_inputs"])
+ table = DataWarehouseTable.objects.create(
+ team_id=self.team.pk,
+ name="users",
+ format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,
+ url_pattern="https://bucket/users/*",
+ external_data_source=source,
+ columns={"id": {"hogql": "IntegerDatabaseField"}, CDC_SEQ_COLUMN: {"hogql": "IntegerDatabaseField"}},
+ )
+ self._schema(source, "users", table=table)
+
+ with _mocked_side_effects():
+ self._run(source)
+
+ source.refresh_from_db()
+ assert source.job_inputs["cdc_ingest_mode"] == "buffered"
+
+ def test_a_first_flip_records_that_the_source_has_been_buffered(self):
+ source = self._source(ingest_mode="legacy")
+ self._schema(source, "users")
+
+ with _mocked_side_effects():
+ self._run(source)
+
+ source.refresh_from_db()
+ assert source.job_inputs["cdc_buffered_before"]
+
def test_a_reflip_is_allowed_once_the_reserved_column_is_ours(self):
- # The buffered lane writes `_ph_cdc_seq` into the warehouse table, so after a rollback the
- # column is there for our own reasons — a recorded position proves capture never collided.
- source = self._source()
+ # The buffered lane writes `_ph_cdc_seq` into the warehouse table, so on a source already
+ # buffered the column is there for our own reasons — capture would have hard-errored on a
+ # real collision before any file existed.
+ source = self._source(ingest_mode="buffered")
table = DataWarehouseTable.objects.create(
team_id=self.team.pk,
name="users",
@@ -215,8 +256,7 @@ class TestMigrateCDCSourceToBuffered(BaseTest):
external_data_source=source,
columns={"id": {"hogql": "IntegerDatabaseField"}, CDC_SEQ_COLUMN: {"hogql": "IntegerDatabaseField"}},
)
- schema = self._schema(source, "users", table=table)
- self._record_load_position(schema, 42)
+ self._schema(source, "users", table=table)
with _mocked_side_effects():
self._run(source)
@@ -224,31 +264,33 @@ class TestMigrateCDCSourceToBuffered(BaseTest):
source.refresh_from_db()
assert source.job_inputs["cdc_ingest_mode"] == "buffered"
- def test_a_hybrid_source_flips_only_its_consolidated_schemas(self):
+ def test_every_streaming_table_mode_flips_together(self):
source = self._source()
consolidated = self._schema(source, "users")
companion = self._schema(source, "events", table_mode="cdc_only")
+ both = self._schema(source, "orders", table_mode="both")
with _mocked_side_effects() as mocks:
- output = self._run(source)
+ self._run(source)
- assert "staying on legacy" in output
- assert "events [cdc_only]" in output
purged = [call.args[1] for call in mocks["purge"].call_args_list]
- assert purged == [str(consolidated.id)]
- mocks["unpause_schema"].assert_called_once_with(str(consolidated.id))
- assert str(companion.id) not in str(mocks["unpause_schema"].call_args_list)
+ assert sorted(purged) == sorted([str(consolidated.id), str(companion.id), str(both.id)])
+ assert mocks["unpause_schema"].call_count == 3
- def test_a_source_with_no_eligible_schema_is_refused(self):
+ def test_a_hybrid_source_leaves_its_ineligible_schemas_on_legacy(self):
source = self._source()
- self._schema(source, "events", table_mode="both")
+ eligible = self._schema(source, "users")
+ snapshotting = self._schema(source, "events", cdc_mode="snapshot")
- with _mocked_side_effects():
- with pytest.raises(CommandError, match="No schema on this source serves the buffered lane"):
- self._run(source)
+ with _mocked_side_effects() as mocks:
+ output = self._run(source)
- source.refresh_from_db()
- assert "cdc_ingest_mode" not in source.job_inputs
+ assert "staying on legacy" in output
+ # Every CDC prefix is purged, not just the eligible ones: a schema still snapshotting
+ # becomes eligible on its first completed sync and would inherit whatever it left behind.
+ purged = [call.args[1] for call in mocks["purge"].call_args_list]
+ assert sorted(purged) == sorted([str(eligible.id), str(snapshotting.id)])
+ mocks["unpause_schema"].assert_called_once_with(str(eligible.id))
def test_a_still_snapshotting_schema_is_not_eligible(self):
source = self._source()
@@ -258,6 +300,10 @@ class TestMigrateCDCSourceToBuffered(BaseTest):
with pytest.raises(CommandError, match="No schema on this source serves the buffered lane"):
self._run(source)
+ # Refusing must leave the source wholly on legacy, not half-flipped.
+ source.refresh_from_db()
+ assert "cdc_ingest_mode" not in source.job_inputs
+
def test_dry_run_changes_nothing_and_reports_the_cadence(self):
source = self._source()
self._schema(source, "users")
@@ -294,6 +340,122 @@ 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):
+ 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
+ )
+
+ with _mocked_side_effects():
+ self._run(source, rollback=True)
+ history.refresh_from_db()
+ assert "cdc_buffered_lane" not in history.sync_type_config
+ assert 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):
+ # 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)
+ 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}]})
+
+ with (
+ _mocked_side_effects(),
+ patch(f"{_CMD}.Command._wait_for_extraction_idle", side_effect=run_writes_during_the_wait),
+ ):
+ self._run(source, rollback=rollback)
+
+ 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)
+
+ @parameterized.expand([("flip", None, False), ("rollback", "buffered", True)])
+ def test_an_orphaned_companion_job_is_retired_instead_of_blocking(self, _name, ingest_mode, rollback):
+ # A hard kill leaves the companion row Running; only a run's start retires it, and the
+ # command has just paused the schedules — so waiting on it would never end.
+ source = self._source(ingest_mode)
+ schema = self._schema(source, "users", table_mode="both")
+ if rollback:
+ update_sync_type_config_keys(schema.id, self.team.pk, updates={"cdc_buffered_lane": True})
+ parent = ExternalDataJob.objects.create(
+ team_id=self.team.pk,
+ pipeline_id=source.id,
+ schema_id=schema.id,
+ status=ExternalDataJob.Status.COMPLETED,
+ rows_synced=0,
+ )
+ companion = ExternalDataJob.objects.create(
+ team_id=self.team.pk,
+ pipeline_id=source.id,
+ schema_id=schema.id,
+ status=ExternalDataJob.Status.RUNNING,
+ rows_synced=0,
+ workflow_run_id=None,
+ schema_snapshot={"companion_of": str(parent.id)},
+ )
+
+ with _mocked_side_effects():
+ self._run(source, rollback=rollback, drain_timeout=0)
+
+ companion.refresh_from_db()
+ source.refresh_from_db()
+ 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.