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): remove the legacy cdc lane (#105912)

Daniel RCeac3751022f3
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.md
index f010926c39b3..e8ad1b701f24 100644
--- a/docs/internal/cdc-buffered-ingress-runbook.md
+++ b/docs/internal/cdc-buffered-ingress-runbook.md
@@ -1,16 +1,10 @@
-# CDC buffered ingress — flip runbook
+# CDC buffered ingress — runbook
-How to move a Postgres CDC source from legacy extraction onto the S3 change buffer, and how to move
-it back.
+How a Postgres, Supabase or Neon CDC source delivers its changes through the S3 change buffer, and how to operate it.
-A source that turns on CDC starts on the buffer: setting up the slot also writes
-`cdc_ingest_mode = "buffered"`. Recreating a lost slot does the same, through "Repair CDC" or the
-automatic recovery when capture finds its slot invalidated, so a repaired legacy source comes back
-buffered. Only a healthy source that enabled CDC before that needs the flip.
+## How it works
-## What changes
-
-Capture stops transforming and dispatching change events. It decodes WAL, writes Parquet to
+Capture decodes WAL, writes Parquet to
`s3://{DATAWAREHOUSE_BUCKET}/cdc_producer/{team_id}/{schema_id}/`, and advances the replication slot
as soon as those files are durable. The normal per-schema scheduled sync then consumes them like any
other source.
@@ -18,11 +12,11 @@ other source.
The point is that a stalled load can no longer hold the customer's WAL. It spends our S3 retention
instead.
-**Every streaming table mode moves.** A run reads the buffer once and writes every table the mode
+**Every table mode is served.** 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
+table 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.
@@ -41,17 +35,19 @@ was: the base class is the single-table path with extract-method seams, and `Lan
`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.
-A table taking its snapshot keeps its changes on legacy deferred runs, as before, unless its snapshot runs in the buffer.
-A snapshot runs in the buffer when capture starts it there, which needs the `dwh-cdc-buffered-snapshot` flag and no deferred runs, or when a streaming table on a buffered source is reset to snapshot with the flag on.
-Either path records `cdc_snapshot_lane: "buffer"` in the schema's `sync_type_config`, and that marker, not the flag, routes the table until the snapshot hands over to streaming.
-So one snapshot never splits between the buffer and deferred runs, even when the flag changes or fails to evaluate.
-Turning the flag off only stops new snapshots from starting in the buffer.
-Turn the flag on only after a deploy has fully rolled, because an older worker ignores the marker.
+A table taking its snapshot has its changes captured to the buffer too, and the consumer reads them once the snapshot completes.
+A marker on the schema, `cdc_snapshot_lane: "buffer"` in `sync_type_config`, records that the buffer carries the current snapshot.
+Capture sets it, after emptying the table's buffer, the first time it sees the snapshotting table, before it reads the WAL, which drops files left from before a gap in capture such as a re-enable.
+A request that resets a table the buffer already serves (a resync, a table-mode switch, an admin re-snapshot) sets it directly, because that buffer already holds an unbroken run of the table's changes.
+A reset in capture (a TRUNCATE, or slot-invalidation recovery) empties the table's buffer first, because a file from before the reset would bring back rows, and then sets the marker, so the changes captured after the reset carry through the hand-over.
+The flip to streaming clears it.
-While the marker holds, the buffer carries an unbroken run of the table's changes, and the hand-over deletes none of them.
+While the marker holds, the hand-over deletes no buffer file.
The consumer replays all of them over the snapshot, including changes the snapshot already contains.
Replaying an unbroken run in order converges on the source's state, because the merge is an upsert by primary key.
-A gap would break that, so capture empties the table's buffer when it starts a snapshot there, which drops files left from before a re-enable.
+A gap would break that, which is why the buffer is emptied when capture starts a snapshot there.
+A snapshot that completes without the marker, because capture never ran for the table while it snapshotted, purges the whole buffer at the hand-over.
+
A TRUNCATE resets the table, empties its buffer, and drops that run's pending changes for it.
The reset also pauses the table's schedule and cancels its running sync, so a snapshot that began before a repeated reset cannot hand over without the changes the reset drops.
A cancel only asks the workflow to stop, and the loader still applies batches the sync queued, so while either is in progress the reset waits (`cdc_reset_waits_for_running_sync`).
@@ -66,9 +62,7 @@ Each write that stages a reset gives the key a new `generation`, so capture drop
The admin resync refuses instead, because it starts its own non-billable run, so it asks the operator to retry once the sync stops.
Turning a table's sync off, or adding it back to capture, drops its marker, because capture skipped the table in between and its buffer has a gap.
Capture handles a TRUNCATE only after every change of its transaction has been read, so no pre-TRUNCATE change can land in the buffer after the purge.
-Without the marker, the hand-over purges the whole buffer, as legacy always did.
-A source with a mix runs hybrid, some schemas buffered and the rest unchanged, and keeps its backpressure guard for the legacy ones.
-The rollback command restarts any snapshot the buffer carries as a legacy snapshot, because only the buffer holds those changes and legacy's hand-over would purge them.
+A table whose data was deleted is still streaming but not seeded; its next sync runs a full refresh and the buffer replays over it.
**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
@@ -100,9 +94,9 @@ on any real table. So every table a buffered lane writes declares `delta.dataSki
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 table's own first 32 columns ahead of those. Without that repetition the declaration 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.
+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
@@ -130,14 +124,15 @@ A **merge** table whose files never gain the statistic replays safely but never
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 table's first buffered run** declares the statistics property, 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
+**A run stands down while any delivery for the schema is still in the queue**: a previous attempt
+of this same job, or a batch the retired legacy lane queued before its source was converted. Either
+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
@@ -145,157 +140,31 @@ queued. The run returns an empty response, which no-ops the tick and keeps the s
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 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. 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 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.
-2. 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.
-3. Buffer validation is clean over a busy window:
-
- ```bash
- 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 joins the buffer after its first sync, without one.
-
-4. Check what will move:
-
- ```bash
- python manage.py migrate_cdc_source_to_buffered --source-id <uuid> --dry-run
- ```
+## Leftover legacy state
- Anything reported under "staying on legacy" keeps today's behavior.
+Capture used to deliver some tables' changes itself, on what is now the retired legacy lane.
+That lane paused each such table's schedule while it streamed, held a snapshotting table's changes as deferred runs in `sync_type_config["cdc_deferred_runs"]`, marked its source `cdc_ingest_mode: legacy`, and created job rows of its own.
+Capture converts that state before every read (`cdc/legacy_conversion.py`), so nothing needs doing by hand:
-## Flip
+- **A source still marked legacy** has every CDC table's buffer emptied, since it holds only copies of changes the legacy lane already delivered.
+ Each table is stamped `cdc_legacy_converted_at`, because it is current as of the conversion: without the stamp, its first sync would find no run that ever listed the buffer, take the buffer for expired, and re-snapshot the table (see "Buffer expiry — no partial recovery").
+ Each syncing table's schedule is rebuilt unpaused, because it is now the table's consumer.
+ A table set slower than its source's fastest table is sped up to it (`cdc_legacy_table_frequency_raised`), because that is how often the legacy lane delivered its changes.
+ The source is then marked `cdc_ingest_mode: buffered`, last, so a failure repeats the whole conversion on the next run.
+ Legacy batches still in the load queue land first, because the consumer stands down while any are in flight.
+ Until then, a scheduled run of one of its tables, such as one a sync frequency change unpaused, no-ops the tick (`cdc_buffered_waiting_for_legacy_conversion`), because reading those copies would load them a second time.
+- **A table with deferred runs** snapshots again in the buffer, through the same pending reset a resync hands to capture (`cdc_legacy_deferred_runs_handed_to_reset`).
+ Nothing merges deferred runs anymore, so the reset pauses the table's schedule and cancels its running sync, and waits while either can still hand over (`cdc_reset_waits_for_running_sync`).
+ Then it resets the table, drops the deferred runs, empties its buffer, and starts the new snapshot.
+ Capture gives the table no buffered snapshot of its own before that, because the old sync could hand over into it without the deferred changes.
+- **A job row a legacy capture run left Running** is failed once it is 30 minutes old and has no batches in the queue.
-Every schema that is streaming and has finished its first sync is served, in any table mode. A
-schema added to a buffered source later joins the buffer after its first sync, with no re-run. The
-loader always resolves write ordering for CDC batches: it drops rows the table already applied,
-collapses repeated keys within a batch, and checks that a DELETE is not about to erase columns the
-target still holds.
+A rebuilt schedule is skipped where the pause is deliberate: the schema's status is `Paused`, an admin-triggered run holds it, the schema is halted and waits for Repair CDC, a pending reset holds it, or it has no sync frequency.
+Every step logs (`cdc_legacy_source_converted`, `cdc_legacy_deferred_runs_handed_to_reset`, `cdc_stranded_capture_jobs_closed`); once none of them appears across the fleet, the module can go.
-```bash
-python manage.py migrate_cdc_source_to_buffered --source-id <uuid>
-```
-
-The command pauses the extraction schedule, waits for the in-flight extraction run to finish,
-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, 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. **Extraction is left
-paused and the per-schema schedules are restored.** Extraction stays down deliberately, because
-flipping on top of a stuck load lets that batch land against a table the buffered lane has already
-started writing. The per-schema schedules come back because the mode never changed: the source is
-the legacy source it was before the command ran, and leaving its syncs down stops the customer's
-data with nothing to report it. Investigate the stuck load, then re-run.
-
-The restore covers every failure from the pause at step 3 to the mode change at step 6, including a
-pause that fails partway through the batch. Unpausing a schedule that was never paused is a no-op,
-so the whole eligible set is restored on any failure. A schema that stopped syncing while the
-command waited stays paused, because the restore re-reads `should_sync` rather than trusting the
-copy it loaded at the start.
-
-Pre-flip buffer files are purged because the legacy lane already delivered those rows, and the load
-position has no watermark for them yet.
-
-The wait for the extraction run matters because pausing a Temporal schedule does not stop a workflow
-already running. With the shadow lane on — the normal state before a flip, since validation needs
-it — that run keeps writing buffer files, and one landing after the purge would be merged by the
-consumer even though the legacy lane already delivered those rows.
-
-The consumer also no-ops while any legacy delivery for the schema is in flight (deferred runs or
-unfinished `sourcebatch` batches), so a legacy batch that lands late still lands before the first
-buffered merge. The same gate holds the consumer off during a post-flip re-snapshot until the
-deferred backlog lands.
-
-### Verify
-
-- Capture writes files under the schema's prefix and advances the slot (`cdc_last_log_position`
- moves).
-- The next scheduled sync 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
- but never repaints a buffered schema COMPLETED, so a failing consumer run stays visible.
-
-## 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
-```
+A source whose slot is gone does not capture at all, so it converts only after Repair CDC, which already resets every table and marks the source buffered.
-The order matters, and the command enforces it:
-
-1. Pause the extraction schedule, so no new capture run starts.
-2. Wait for the in-flight extraction run to finish — pausing a schedule does not stop a running
- workflow, and a run still executing would keep writing files and advancing the slot behind the
- drain check. Then restart every snapshot the buffer carries: cancel its running sync, empty its
- buffer, and reset it to snapshot without the marker. The new snapshot starts after capture
- stopped, so it covers every change up to there, and legacy capture defers the rest.
-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
- 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`, then unpause the per-schema schedules that step 4 paused, then the
- extraction schedule. Both halves matter: legacy delivery needs capture running to produce the
- changes, and the per-schema syncs running to load them. The per-schema restore goes first
- because it degrades gracefully per schema, while unpausing extraction is a single Temporal
- call that can raise and strand them again.
-
-The buffer-drain check covers every schema the buffered lane serves, including ones disabled after
-the flip — a disabled schema's unconsumed files still block, and draining them means re-enabling the
-schema so its sync can catch up first. It skips the schemas that stayed on legacy: with the shadow
-lane on, their prefixes hold validation copies no consumer reads, so scanning them would block the
-rollback forever with capture paused.
-
-Fully-applied buffer files are **not** purged: the 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 extraction paused. A clean
-abort restores the per-schema schedules on its way out; a process killed outright does not, so
-check them. 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.
-
-Capture is not running in that state, so it reports nothing itself. What reports it is
-`sweep_stalled_schema_schedules`, described below, which reads the schemas rather than capture.
+`cdc_ingest_mode` must survive every API write. A PATCH that dropped it would make capture read the source as legacy and empty its unconsumed buffer.
## When a schedule stops firing
@@ -326,6 +195,8 @@ a schedule that went missing. It triggers no run, so it bills nothing and each s
own next tick. It stops at 100 schemas by default and refuses a wider match rather than acting on
it; raise `--max-schemas` deliberately.
+A CDC table's schedule is the one that consumes its change buffer, so a stall there also lets the buffer age toward its 14-day expiry.
+
### What it will not touch, and where those go instead
A paused schedule is normal in more cases than it looks, so the command repairs only what it can
@@ -333,21 +204,16 @@ prove is the outage above. It re-checks every exclusion against a freshly loaded
time, because minutes can pass between the sweep finding a schema and an operator confirming the
prompt, and reports those as skips rather than repairs.
-| Excluded | Why | Where it goes |
-| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
-| Streaming CDC schema | A paused schedule is its steady state. `CDCExtractionWorkflow` owns the schedule and re-pauses it on its own next tick, so unpausing only races that workflow. | The source's `repair_cdc` action |
-| `cdc_halted` schema | The marker exists to keep everything else off the schema until the halt clears. | The source's `repair_cdc` action |
-| Buffered CDC source | Its schedule paces buffer consumption, so restarting it out of sequence merges files against a table the buffered lane already writes. | Re-run the flip or the rollback, and let it reach its own step 6 or 7 |
-| `admin_unpause_schedule_after_run` set | The pause may belong to an in-flight admin-triggered run that clears the marker itself. | Wait for that run |
-| No `sync_frequency_interval` | The schedule builder cannot turn a null interval into a cadence. | Set an interval first |
-
-Two of those five matter most on a CDC source. A streaming schema and a halted one are both
-expected to sit with a paused schedule, so neither is evidence of this outage, and unpausing either
-one is at best wasted and at worst a race.
+| Excluded | Why | Where it goes |
+| -------------------------------------- | --------------------------------------------------------------------------------------- | -------------------------------- |
+| `cdc_halted` schema | The marker exists to keep everything else off the schema until the halt clears. | The source's `repair_cdc` action |
+| `admin_unpause_schedule_after_run` set | The pause may belong to an in-flight admin-triggered run that clears the marker itself. | Wait for that run |
+| No `sync_frequency_interval` | The schedule builder cannot turn a null interval into a cadence. | Set an interval first |
## Buffer expiry — no partial recovery
-Buffer files expire after 14 days (`expire-cdc-producer-buffer`). If a schema stops consuming —
+Buffer files expire after 14 days (`expire-cdc-producer-buffer`). The API therefore rejects a CDC
+sync frequency slower than `7day`. If a schema stops consuming —
paused, erroring, or wedged — its oldest unconsumed file ages toward that limit while the slot has
long since advanced past those changes.
@@ -368,19 +234,20 @@ and does not count.
Watch the age of the oldest unconsumed file per schema, not the file count. A schema with few files
that are all thirteen days old is in trouble; one with thousands of fresh files is fine.
-**The billing limit is the usual cause, and the sweeper stops it.** Capture has no billing check, so it
-keeps reading the slot and writing the buffer while the limit blocks every consume run. Once a table
-has been blocked by the billing limit for longer than the buffer keeps files, and the team is still
-over the limit, the slot sweeper (`cleanup_orphan_slots_activity`) marks the source broken with reason
-`billing_limit_expired`. A PostHog-managed slot with auto-drop on is dropped and the schedules are
-paused, on the same terms as the critical-lag safety net. If that drop is refused — an active slot,
-a missing grant — the source is left running and the next sweep retries it, because pausing capture
-behind a live slot is what makes WAL grow. Any other slot is left to its owner and capture keeps
-advancing it, so the customer's WAL does not grow. Once the team is back under the limit, a dropped
-slot needs Repair CDC, which recreates it and re-snapshots every table. A kept slot needs nothing: the
-sweeper lifts its marker, and each table's next sync finds its buffer expired and re-snapshots on its
-own. Only a table's own sync runs count toward the 14 days. Capture records a Failed job on every table
-when it fails, and those rows do not restart the count.
+A team over its billing limit is the usual cause.
+The consumer is a scheduled sync, so it stops at the billing check, while capture keeps reading the WAL and writing the buffer, as webhook sources keep writing their events.
+Once the limit lifts, the next sync loads the backlog, as long as none of it has expired.
+Unlike the webhook prefix, `cdc_producer/` expires after 14 days.
+
+**The sweeper stops a source blocked for longer than that.**
+Once a table has been blocked by the billing limit for longer than the buffer keeps files, and the team is still over the limit, the slot sweeper (`cleanup_orphan_slots_activity`) marks the source broken with reason `billing_limit_expired`.
+A PostHog-managed slot with auto-drop on is dropped and the schedules are paused, on the same terms as the critical-lag safety net.
+If that drop is refused, such as by an active slot or a missing grant, the source is left running and the next sweep retries it, because pausing capture behind a live slot is what makes WAL grow.
+Any other slot is left to its owner and capture keeps advancing it, so the customer's WAL does not grow.
+Once the team is back under the limit, a dropped slot needs Repair CDC, which recreates it and re-snapshots every table.
+A kept slot needs nothing: the sweeper lifts its marker, and each table's next sync finds its buffer expired and re-snapshots on its own.
+Only a table's own sync runs count toward the 14 days.
+Capture records a Failed job on every table when it fails, and those rows do not restart the count.
## Retried capture attempts
@@ -417,8 +284,8 @@ rows then exist nowhere, and the slot has advanced past them.
This is an accepted risk, not a fixed one. It needs a retry **and** a transaction spanning a flush
boundary **and** the boundary to shift between attempts.
-There is no detector. `validate_cdc_buffer`'s continuity check compares adjacent filename ranges,
-and in this failure the ranges stay contiguous — rows go missing inside a range.
+There is no detector. Adjacent filename ranges stay contiguous in this failure — rows go missing
+inside a range.
Track `cdc_extract_retried_attempts_total` as the exposure proxy. A quiet counter bounds the risk;
a retry-heavy period is the signal to revisit. Candidate fixes are costed in the plan doc
@@ -433,9 +300,8 @@ towards usage: the `_cdc` table for `cdc_only`, and the consolidated table for `
`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.
+The retired legacy lane wrote the two tables from two `ExternalDataJob` rows and counted each event
+twice, so a `both` source's synced-row count roughly halved when it moved to the buffer.
**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
diff --git a/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html b/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html
index b36dbc11ea61..6ea45a6072c3 100644
--- a/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html
+++ b/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html
@@ -419,8 +419,8 @@
<a href="{{ temporal_ui_host }}/namespaces/{{ temporal_namespace }}/schedules/{{ cdc_extraction_schedule_id }}"
target="_blank">View CDC extraction schedule in Temporal</a>
<p class="help">
- For CDC schemas, the per-schema schedule above is paused once streaming starts.
- This source-level schedule is what drives the actual change capture.
+ For CDC schemas, this source-level schedule captures changes into the buffer,
+ and the per-schema schedule above loads them into the table.
</p>
</div>
{% endif %}
diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.py
index dfb557b31458..506638123038 100644
--- a/products/data_warehouse/backend/facade/api.py
+++ b/products/data_warehouse/backend/facade/api.py
@@ -31,7 +31,7 @@ _LAZY = {
"is_any_external_data_schema_paused": "logic.data_load.service",
"is_cdc_enabled_for_team": "logic.data_load.service",
"cdc_extraction_schedule_exists": "logic.data_load.service",
- "cdc_extraction_schedule_has_running_action": "logic.data_load.service",
+ "cdc_min_interval": "logic.data_load.service",
"is_cdc_extraction_schedule_paused": "logic.data_load.service",
"is_external_data_schedule_paused": "logic.data_load.service",
"is_custom_source_ai_builder_enabled_for_team": "logic.data_load.service",
diff --git a/products/data_warehouse/backend/logic/data_load/service.py b/products/data_warehouse/backend/logic/data_load/service.py
index 555623eab0e3..61230acd4555 100644
--- a/products/data_warehouse/backend/logic/data_load/service.py
+++ b/products/data_warehouse/backend/logic/data_load/service.py
@@ -684,25 +684,6 @@ async def is_cdc_extraction_schedule_paused(source_id: str) -> bool:
return desc.schedule.state.paused
-@async_to_sync
-async def cdc_extraction_schedule_has_running_action(source_id: str) -> bool:
- """Whether an extraction run started by the source's schedule is still executing.
-
- Pausing a schedule stops future firings but not a workflow already running — anything that
- must not race an in-flight extraction (the buffered-ingress rollback) has to wait on this
- after pausing. A missing schedule has nothing running.
- """
- schedule_id = _get_cdc_extraction_schedule_id(source_id)
- temporal = await async_connect()
- try:
- desc = await a_describe_schedule(temporal, schedule_id=schedule_id)
- except temporalio.service.RPCError as e:
- if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:
- return False
- raise
- return bool(desc.info.running_actions)
-
-
@async_to_sync
async def bulk_sync_cdc_extraction_schedules(
source_intervals: list[tuple[ExternalDataSource, timedelta]],
diff --git a/products/data_warehouse/backend/logic/data_load/test/test_service.py b/products/data_warehouse/backend/logic/data_load/test/test_service.py
index db2d96384668..fe04f81617cd 100644
--- a/products/data_warehouse/backend/logic/data_load/test/test_service.py
+++ b/products/data_warehouse/backend/logic/data_load/test/test_service.py
@@ -2,7 +2,6 @@ import uuid
import random
import logging
import datetime as dt
-from collections.abc import Callable
from typing import Any
import pytest
@@ -32,7 +31,6 @@ from products.data_warehouse.backend.logic.data_load.service import (
bulk_sync_cdc_extraction_schedules,
bulk_update_external_data_job_schedules,
cdc_extraction_schedule_exists,
- cdc_extraction_schedule_has_running_action,
cdc_min_interval,
get_discover_schemas_schedule,
get_sync_schedule,
@@ -386,22 +384,9 @@ def test_cdc_schedule_paused_reports_the_schedule_state(paused: bool) -> None:
assert is_cdc_extraction_schedule_paused("01a0393e-a79f-0000-0361-2cabb703888f") is paused
[email protected]("running_actions,expected", [([], False), ([MagicMock()], True)])
-def test_cdc_schedule_running_action_reports_an_executing_run(running_actions: list[MagicMock], expected: bool) -> None:
- desc = MagicMock()
- desc.info.running_actions = running_actions
-
- with _temporal_with_schedule(desc):
- assert cdc_extraction_schedule_has_running_action("01a0393e-a79f-0000-0361-2cabb703888f") is expected
-
-
- "read",
- [is_cdc_extraction_schedule_paused, cdc_extraction_schedule_has_running_action],
-)
-def test_a_missing_schedule_reads_as_neither_paused_nor_running(read: Callable[[str], bool]) -> None:
+def test_a_missing_schedule_reads_as_not_paused() -> None:
with _temporal_with_schedule(describe_side=_not_found()):
- assert read("01a0393e-a79f-0000-0361-2cabb703888f") is False
+ assert is_cdc_extraction_schedule_paused("01a0393e-a79f-0000-0361-2cabb703888f") is False
# --- bulk_sync_cdc_extraction_schedules (upsert: update, else create+trigger) ---
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
index 8ad14f87051c..5815be6d925a 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
@@ -46,6 +46,7 @@ import {
StatusTagSetting,
SyncFrequencyLabelMap,
SyncTypeLabelMap,
+ allowedCdcSyncFrequencies,
allowedSyncFrequencies,
defaultQuery,
syncAnchorIntervalToHumanReadable,
@@ -912,7 +913,9 @@ function ScheduleSection({
const { loadSchema } = useActions(schemaSceneLogic({ sourceId, schemaId: schema.id }))
const isCdc = schema.sync_type === 'cdc'
const supportsScheduledFullRefresh = SCHEDULED_FULL_REFRESH_SYNC_TYPES.includes(schema.sync_type)
- const frequencyOptions: LemonSelectOption<DataWarehouseSyncInterval>[] = allowedSyncFrequencies().map((value) => ({
+ const frequencyOptions: LemonSelectOption<DataWarehouseSyncInterval>[] = (
+ isCdc ? allowedCdcSyncFrequencies() : allowedSyncFrequencies()
+ ).map((value) => ({
value,
label: SyncFrequencyLabelMap[value],
}))
@@ -985,9 +988,9 @@ function ScheduleSection({
<div className="flex flex-col gap-1">
<span>Sync frequency</span>
<span className="text-xs text-muted max-w-md">
- How often PostHog pulls new data from the source. Shorter intervals mean fresher data but more
- load on the source database
- {isCdc ? ' — CDC supports sub-minute replication for near-real-time syncs.' : '.'}
+ {isCdc
+ ? 'How often PostHog loads the changes it captured for this table. Shorter intervals mean fresher data.'
+ : 'How often PostHog pulls new data from the source. Shorter intervals mean fresher data but more load on the source database.'}
</span>
<LemonSelect
fullWidth
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts
index 045c596913d5..50096fd38b14 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts
@@ -1,7 +1,7 @@
import type { ExternalDataSource, ExternalDataSourceSchema } from '~/types'
import type { SourceFieldConfig } from 'products/data_warehouse/frontend/types'
-import { clampSyncFrequency } from 'products/data_warehouse/frontend/utils'
+import { allowedCdcSyncFrequencies, clampSyncFrequency } from 'products/data_warehouse/frontend/utils'
import {
buildBulkEnablePayloads,
@@ -280,12 +280,19 @@ describe('effectiveLookbackDays', () => {
})
})
-describe('clampSyncFrequency', () => {
+describe('sync frequency limits', () => {
it('floors every schema at 5 minutes, CDC included', () => {
expect(clampSyncFrequency('1min')).toBe('5min')
expect(clampSyncFrequency('5min')).toBe('5min')
expect(clampSyncFrequency('1hour')).toBe('1hour')
})
+
+ it('offers a CDC table nothing slower than weekly, which the API rejects', () => {
+ const options = allowedCdcSyncFrequencies()
+ expect(options).toContain('7day')
+ expect(options).not.toContain('30day')
+ expect(options).not.toContain('1min')
+ })
})
describe('buildBulkEnablePayloads', () => {
diff --git a/products/data_warehouse/frontend/utils.ts b/products/data_warehouse/frontend/utils.ts
index 4ef758bcdfe6..8afd5c6a3ad4 100644
--- a/products/data_warehouse/frontend/utils.ts
+++ b/products/data_warehouse/frontend/utils.ts
@@ -202,6 +202,12 @@ export function allowedSyncFrequencies(): DataWarehouseSyncInterval[] {
return SYNC_FREQUENCY_ORDER.filter((frequency) => !LEGACY_SUB_FLOOR_SYNC_FREQUENCIES.includes(frequency))
}
+// A CDC table's change buffer keeps files for 14 days, so the API rejects a CDC table slower than weekly.
+export function allowedCdcSyncFrequencies(): DataWarehouseSyncInterval[] {
+ const slowest = SYNC_FREQUENCY_ORDER.indexOf('7day')
+ return allowedSyncFrequencies().filter((frequency) => SYNC_FREQUENCY_ORDER.indexOf(frequency) <= slowest)
+}
+
// Raise a requested frequency to the fastest allowed one (e.g. a legacy 1min → 5min).
export function clampSyncFrequency(requested: DataWarehouseSyncInterval): DataWarehouseSyncInterval {
const allowed = allowedSyncFrequencies()
diff --git a/products/warehouse_sources/backend/ad_hoc_sync.py b/products/warehouse_sources/backend/ad_hoc_sync.py
index a4dc9cf63999..18587dfed960 100644
--- a/products/warehouse_sources/backend/ad_hoc_sync.py
+++ b/products/warehouse_sources/backend/ad_hoc_sync.py
@@ -15,7 +15,6 @@ from typing import Any
from django.conf import settings
-import structlog
from asgiref.sync import async_to_sync
from temporalio.client import Client
from temporalio.common import WorkflowIDReusePolicy
@@ -35,8 +34,6 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane
resnapshot_stays_in_buffer,
)
-logger = structlog.get_logger(__name__)
-
@frozen
class AdHocSyncTrigger:
@@ -123,16 +120,15 @@ def trigger_ad_hoc_sync(
extra_model_fields: dict[str, Any] = {}
if reset_pipeline:
updates["reset_pipeline"] = True
- # A streaming CDC schema no-ops a normal reset — CDCExtractionWorkflow owns it and the
- # per-schema run raises CDCHandledExternally. Flip it back to snapshot so this run does a
- # full re-snapshot. The job is created non-billable when the caller asks for that, and on
- # completion set_initial_sync_complete transitions it back to streaming, so ongoing CDC
- # stays billable. The save must precede the workflow start so the source reloads
- # cdc_mode="snapshot" instead of racing on stale "streaming".
+ # A streaming CDC schema's run consumes the change buffer, which a reset cannot restart. Flip it
+ # back to snapshot so this run does a full re-snapshot. The job is created non-billable when
+ # the caller asks for that, and on completion set_initial_sync_complete transitions it back to
+ # streaming, so ongoing CDC stays billable. The save must precede the workflow start so the
+ # source reloads cdc_mode="snapshot" instead of racing on stale "streaming".
if schema.is_cdc and schema.cdc_mode == "streaming":
# Decided while the table still streams. Without the marker, the next capture run would
# empty the buffer under the new snapshot, deleting changes an in-flight run wrote.
- if resnapshot_stays_in_buffer(schema, logger):
+ if resnapshot_stays_in_buffer(schema):
updates[CDC_SNAPSHOT_LANE_KEY] = BUFFER_LANE
updates["cdc_mode"] = "snapshot"
removes += ["cdc_last_log_position", "cdc_deferred_runs"]
diff --git a/products/warehouse_sources/backend/admin/external_data_schema_admin.py b/products/warehouse_sources/backend/admin/external_data_schema_admin.py
index 31a123b39601..fe8262df2a6c 100644
--- a/products/warehouse_sources/backend/admin/external_data_schema_admin.py
+++ b/products/warehouse_sources/backend/admin/external_data_schema_admin.py
@@ -535,8 +535,8 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):
"admin:external_data_schema_recreate_schedule", args=[obj.id]
)
- # CDC schemas stream via a source-level extraction schedule; the per-schema schedule
- # above is paused once streaming starts, so surface the real one too.
+ # CDC capture runs on a source-level extraction schedule; the per-schema schedule above
+ # loads what capture buffered, so surface both.
if obj.is_cdc:
extra_context["cdc_extraction_schedule_id"] = f"cdc-extraction-{obj.source_id}"
return super().change_view(request, object_id, form_url, extra_context=extra_context)
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
deleted file mode 100644
index 40206d47b3d5..000000000000
--- a/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.py
+++ /dev/null
@@ -1,602 +0,0 @@
-"""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. Which schemas move is `serves_buffered_lane` — see `cdc/source_manager.py`.
-"""
-
-from __future__ import annotations
-
-import time
-import datetime as dt
-from typing import Any
-
-from django.core.management.base import BaseCommand, CommandError
-from django.db import transaction
-
-import psycopg
-import structlog
-
-from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
-
-from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
-from products.warehouse_sources.backend.models.external_data_schema import (
- CDC_SNAPSHOT_LANE_KEY,
- 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 (
- get_buffer_prefix,
- 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.snapshot_lane import (
- cancel_running_sync,
- snapshot_in_buffer,
-)
-from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
- BUFFERED_BEFORE_KEY,
- serves_buffered_lane,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common import strip_s3_protocol
-from products.warehouse_sources_queue.backend.sdk import BatchQueue
-
-logger = structlog.get_logger(__name__)
-
-# How long to wait for in-flight work to reach a terminal state before giving up. Past this the
-# operator should investigate rather than flip on top of a stuck run.
-DRAIN_TIMEOUT_SECONDS = 15 * 60
-DRAIN_POLL_SECONDS = 10
-
-EXPECTED_SYNC_INTERVAL = dt.timedelta(minutes=5)
-
-
-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)."
-
- def add_arguments(self, parser: Any) -> None:
- parser.add_argument("--source-id", required=True, help="ExternalDataSource UUID")
- parser.add_argument("--rollback", action="store_true", help="Return the source to legacy extraction")
- parser.add_argument("--dry-run", action="store_true", help="Report what would change and exit")
- parser.add_argument(
- "--drain-timeout",
- type=int,
- default=DRAIN_TIMEOUT_SECONDS,
- help=f"Seconds to wait for in-flight work to drain (default {DRAIN_TIMEOUT_SECONDS})",
- )
-
- def handle(self, *args: Any, **options: Any) -> None:
- source_id = options["source_id"]
- rollback = options["rollback"]
- dry_run = options["dry_run"]
- target_mode = "legacy" if rollback else "buffered"
-
- try:
- source = ExternalDataSource.objects.get(id=source_id)
- except ExternalDataSource.DoesNotExist:
- raise CommandError(f"No source {source_id}")
-
- schemas = list(ExternalDataSchema.objects.filter(source_id=source.id, deleted=False))
- cdc_schemas = [s for s in schemas if s.is_cdc]
- if not cdc_schemas:
- raise CommandError(f"Source {source_id} has no CDC schemas")
-
- # Mirror capture's _get_cdc_schemas: a user-disabled schema must not be flipped — the last
- # step would unpause its schedule, reversing the disable.
- current_mode = (source.job_inputs or {}).get("cdc_ingest_mode", "legacy")
- eligible = [s for s in cdc_schemas if s.should_sync and serves_buffered_lane(s)]
- ineligible = [s for s in cdc_schemas if s not in eligible]
-
- self._report(source, current_mode, target_mode, eligible, ineligible)
-
- if current_mode == target_mode:
- self.stdout.write(self.style.WARNING(f"Already {target_mode}; nothing to do."))
- return
- if not eligible and not rollback:
- raise CommandError(
- "No schema on this source serves the buffered lane — nothing to flip. "
- "Buffered ingress covers streaming schemas whose initial sync is done, in any table mode."
- )
- if not rollback:
- # No pipeline-version gate: the scheduled sync forces the v3 pipeline for
- # schemas that consume the buffer (scheduled_sync_consumes_buffer), so the flip does
- # not depend on the team's general rollout flag.
- self._require_no_reserved_columns(eligible)
- if rollback:
- for schema in self._snapshots_in_buffer(source):
- self.stdout.write(f" {schema.name}: snapshot running in the buffer, will restart on legacy")
- if dry_run:
- self.stdout.write(self.style.WARNING("Dry run — no changes made."))
- return
-
- if rollback:
- self._roll_back(source, eligible, cdc_schemas, options["drain_timeout"])
- else:
- self._flip_to_buffered(source, eligible, cdc_schemas, options["drain_timeout"])
-
- def _snapshots_in_buffer(self, source: ExternalDataSource) -> list[ExternalDataSchema]:
- return sorted(
- (
- s
- for s in ExternalDataSchema.objects.filter(source_id=source.id, deleted=False)
- if s.is_cdc and snapshot_in_buffer(s)
- ),
- key=lambda s: s.name,
- )
-
- def _demote_snapshots_in_buffer(self, source: ExternalDataSource) -> None:
- """Restart every snapshot the buffer carries as a legacy snapshot.
-
- Only the buffer holds such a table's changes since its snapshot began, and legacy's hand-over
- purges the whole buffer. Capture is idle here, so a snapshot that starts after this point reads
- every change up to where capture stopped, and legacy capture defers the rest. The running
- snapshot is cancelled first, so it cannot hand over without those changes.
- """
- for schema in self._snapshots_in_buffer(source):
- cancel_running_sync(schema)
- purge_buffer_prefix(schema.team_id, str(schema.id), logger, strict=True)
- update_sync_type_config_keys(
- schema.id,
- schema.team_id,
- updates={"cdc_mode": "snapshot", "reset_pipeline": True},
- removes=[CDC_SNAPSHOT_LANE_KEY, "cdc_last_log_position"],
- extra_model_fields={"initial_sync_complete": False},
- )
- self.stdout.write(f" {schema.name}: snapshot restarted on legacy")
-
- def _require_no_reserved_columns(self, eligible: list[ExternalDataSchema]) -> None:
- """Refuse to flip a schema whose source table has a column named `_ph_cdc_seq`.
-
- The collision stops the batcher stamping the engine position, and capture hard-errors on it
- (CDCReservedColumnError) — catching it here keeps the source out of a flip-then-break loop.
-
- The buffered lane writes its own `_ph_cdc_seq` into the warehouse table, so the column
- 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 not waived(s) and s.table is not None and CDC_SEQ_COLUMN in (s.table.columns or {})
- ]
- if conflicted:
- raise CommandError(
- f"Schemas with a source column named {CDC_SEQ_COLUMN}: {', '.join(sorted(conflicted))}. "
- "That name is reserved for change ordering — rename the column or keep the source on legacy."
- )
-
- def _report(
- self,
- source: ExternalDataSource,
- current_mode: str,
- target_mode: str,
- eligible: list[ExternalDataSchema],
- ineligible: list[ExternalDataSchema],
- ) -> None:
- self.stdout.write(f"Source {source.id} (team {source.team_id}): {current_mode} → {target_mode}")
- self.stdout.write(f" buffered lane ({len(eligible)}): {', '.join(s.name for s in eligible) or '—'}")
- off_cadence = [s.name for s in eligible if s.sync_frequency_interval != EXPECTED_SYNC_INTERVAL]
- if off_cadence:
- self.stdout.write(
- self.style.WARNING(
- f" ⚠ not at the 5min platform cadence: {', '.join(sorted(off_cadence))} — "
- "consumption paces to the schema's schedule; set them to 5min first"
- )
- )
- if ineligible:
- detail = ", ".join(f"{s.name} [{_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(
- " → hybrid source: capture keeps its transforms and the backpressure guard for those schemas"
- )
- )
-
- def _flip_to_buffered(
- self,
- source: ExternalDataSource,
- eligible: list[ExternalDataSchema],
- cdc_schemas: list[ExternalDataSchema],
- drain_timeout: int,
- ) -> None:
- from products.data_warehouse.backend.facade.api import (
- pause_cdc_extraction_schedule,
- unpause_cdc_extraction_schedule,
- )
-
- source_id = str(source.id)
-
- self.stdout.write("1/7 pausing extraction schedule")
- pause_cdc_extraction_schedule(source_id)
-
- # Pausing the schedule stops future firings, not a workflow already running. A legacy run
- # with the shadow lane on keeps writing buffer files, and one landing after the purge would
- # be merged by the consumer even though the legacy lane already delivered those rows.
- self.stdout.write("2/7 waiting for the in-flight extraction run to finish")
- self._wait_for_extraction_idle(source_id, drain_timeout)
-
- # A scheduled sync that started before the mode change resolved its pipeline version while
- # the source was still legacy. If it reads the source again after the change, it consumes
- # the buffer on that stale version, which records no load position, so nothing it read is
- # ever proven consumed. Quiesce the schedules so no run straddles the mode change.
- #
- # The pause call itself is inside this same try: a schedule that fails to pause partway
- # through the batch must not leave the ones that did pause stranded. `_restore_schema_schedules`
- # unpausing a schedule that was never paused is a no-op, so restoring the whole eligible set
- # on any failure here is safe.
- try:
- self.stdout.write("3/7 pausing per-schema schedules")
- self._pause_schema_schedules_strict(eligible)
-
- # Everything from here to the mode change leaves the schemas quiesced, and every step in
- # between can abort: a drain that times out, a buffer file that survives the purge. The
- # mode does not change until step 6, so on an abort the source is still the legacy source
- # it was before the command ran. Leaving its schedules paused there stops the customer's
- # syncs for as long as nobody notices, and nothing reports that: no run starts, so there
- # is no job row and no error. Restore the schedules and let the abort surface. Extraction
- # stays paused on purpose, because an operator has to look at whatever stopped the drain
- # before capture writes again.
- self._wait_for_running_sync_jobs(source.team_id, [str(s.id) for s in eligible], drain_timeout)
-
- self.stdout.write("4/7 draining sourcebatch")
- self._wait_for_sourcebatch_drain(source.team_id, [str(s.id) for s in eligible], drain_timeout)
- 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 to_purge:
- purge_buffer_prefix(source.team_id, str(schema.id), logger)
- 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)
-
- # Still inside the recovery boundary, and atomic, so a failure partway through the
- # per-schema writes rolls `job_inputs` back to legacy too and the `except` below restores
- # the schedules onto a state that is genuinely unchanged.
- self.stdout.write("6/7 setting cdc_ingest_mode=buffered")
- with transaction.atomic():
- # `cdc_buffered_before` is kept across a rollback: it is what tells a later flip
- # that a `_ph_cdc_seq` column on the warehouse table may be one this lane wrote,
- # not one the source owns.
- self._write_job_inputs(source, cdc_ingest_mode="buffered", cdc_buffered_before=True)
- self._mark_buffered_before(eligible)
- except BaseException:
- self.stdout.write(self.style.WARNING("flip aborted, restoring per-schema schedules"))
- self._restore_schema_schedules(eligible)
- raise
-
- self.stdout.write("7/7 unpausing schedules")
- unpause_cdc_extraction_schedule(source_id)
- self._set_schema_schedules(eligible, paused=False)
-
- self.stdout.write(self.style.SUCCESS(f"Source {source_id} is now buffered."))
- self.stdout.write(
- "Verify: capture writes buffer files and advances the slot; the next sync writes every "
- "table the mode feeds; a later sync deletes the files once every table is past them."
- )
-
- def _roll_back(
- self,
- source: ExternalDataSource,
- eligible: list[ExternalDataSchema],
- cdc_schemas: list[ExternalDataSchema],
- drain_timeout: int,
- ) -> None:
- from products.data_warehouse.backend.facade.api import (
- pause_cdc_extraction_schedule,
- unpause_cdc_extraction_schedule,
- )
-
- source_id = str(source.id)
-
- # Pausing the schedule stops future firings, not a workflow already running — which can
- # keep writing buffer files and advancing the slot. The drain check below is meaningless
- # until capture is actually idle.
- self.stdout.write("1/6 pausing extraction schedule")
- pause_cdc_extraction_schedule(source_id)
- self.stdout.write("2/6 waiting for the in-flight extraction run to finish")
- self._wait_for_extraction_idle(source_id, drain_timeout)
- # Only once capture is idle, so no run can start another snapshot in the buffer afterwards.
- try:
- self._demote_snapshots_in_buffer(source)
- except BaseException:
- unpause_cdc_extraction_schedule(source_id)
- raise
-
- # The buffer's tail holds WAL the slot has already advanced past — it exists nowhere else.
- # The consumer must apply it BEFORE legacy delivery resumes, or it is lost for good. Capture
- # is idle so the buffer is static; the still-running scheduled sync drains it. Scanned over
- # every schema the buffered lane serves, which includes ones disabled after the flip — but
- # not the legacy ones, whose prefixes hold shadow copies no consumer will ever read.
- self.stdout.write("3/6 waiting for the consumer to drain the buffer")
- self._wait_for_buffer_drain(source.team_id, [s for s in cdc_schemas if serves_buffered_lane(s)], drain_timeout)
-
- # Consumer next: a sync merging old buffered rows AFTER legacy capture resumed would
- # overwrite newer legacy writes — legacy writes carry no position, so the guard can't
- # protect them. Strict: a schedule that failed to pause could start such a sync.
- #
- # The pause call is inside this same try: a schedule that fails to pause partway through
- # the batch must not leave the ones that did pause stranded. `_restore_schema_schedules`
- # unpausing a schedule that was never paused is a no-op, so restoring the whole eligible
- # set on any failure here is safe.
- try:
- 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._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")
- # `cdc_buffered_before` is set here as well as on the flip, on the source and on each
- # served table: a source that started buffered, or was flipped before these markers
- # existed, would otherwise be refused a second flip over a `_ph_cdc_seq` column the
- # buffered lane wrote itself.
- with transaction.atomic():
- self._write_job_inputs(source, cdc_ingest_mode="legacy", cdc_buffered_before=True)
- self._mark_buffered_before([s for s in cdc_schemas if serves_buffered_lane(s)])
- except BaseException:
- # The mode is still buffered, so the schemas go back to consuming the buffer, which is
- # what they were doing before this command ran. Leaving them paused instead would stop
- # the syncs silently and let the buffer age toward its TTL.
- self.stdout.write(self.style.WARNING("rollback aborted, restoring per-schema schedules"))
- self._restore_schema_schedules(eligible)
- raise
-
- # Leftover fully-applied files stay: the position guard no-ops a replay, the S3 TTL clears them.
- self.stdout.write("6/6 unpausing schedules")
- # Step 4 paused these, so the rollback has to hand them back. Without this the source ends
- # a successful rollback on legacy delivery with no schema scheduled to load it. Restored
- # before the extraction schedule: `_restore_schema_schedules` degrades gracefully per
- # schema, but `unpause_cdc_extraction_schedule` is a single Temporal call that can still
- # raise here, and doing this one first means a raise there does not also strand the
- # per-schema schedules a second time.
- self._restore_schema_schedules(eligible)
- unpause_cdc_extraction_schedule(source_id)
-
- self.stdout.write(self.style.SUCCESS(f"Source {source_id} is now legacy."))
-
- def _write_job_inputs(self, source: ExternalDataSource, **updates: Any) -> None:
- """A queryset update, never `source.save()`.
-
- Saving goes through the activity-log mixin, which diffs the instance against the row.
- A sync changing the source's status during the drain makes that diff read every job the
- source ever ran to describe the change: gigabytes on a busy source, and an OOM-killed
- worker mid-flip.
- """
- source.job_inputs = {**(source.job_inputs or {}), **updates}
- ExternalDataSource.objects.filter(id=source.id).update(
- job_inputs=source.job_inputs, updated_at=dt.datetime.now(dt.UTC)
- )
-
- def _mark_buffered_before(self, schemas: list[ExternalDataSchema]) -> None:
- """Record that the buffered lane wrote to these tables; never cleared, see the reserved-column check.
-
- Merged under the row lock: the runs this command waited out wrote their own keys into 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_BEFORE_KEY: True}
- )
-
- 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
-
- deadline = time.monotonic() + timeout
- while cdc_extraction_schedule_has_running_action(source_id):
- if time.monotonic() >= deadline:
- raise CommandError(
- f"An extraction run is still executing after {timeout}s. The schedule is left "
- "paused and the mode unchanged — wait for it to finish, then re-run."
- )
- self.stdout.write(" waiting, extraction run still executing")
- time.sleep(DRAIN_POLL_SECONDS)
-
- def _wait_for_buffer_drain(self, team_id: int, schemas: list[ExternalDataSchema], timeout: int) -> None:
- """Block until 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
-
- s3 = get_s3_client()
- deadline = time.monotonic() + timeout
- while True:
- behind: list[str] = []
- for schema in schemas:
- prefix = strip_s3_protocol(get_buffer_prefix(team_id, str(schema.id)))
- try:
- keys = s3.ls(prefix, detail=False, refresh=True)
- except FileNotFoundError:
- continue
- 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 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 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)
-
- def _pause_schema_schedules_strict(self, schemas: list[ExternalDataSchema]) -> None:
- from products.data_warehouse.backend.facade.api import pause_external_data_schedule
-
- for schema in schemas:
- try:
- pause_external_data_schedule(str(schema.id))
- except Exception as exc:
- raise CommandError(
- f"Could not pause the schedule for {schema.name}; a sync straddling the mode "
- f"change would consume with stale settings. Mode unchanged — fix and re-run. ({exc})"
- )
-
- def _verify_prefixes_empty(self, team_id: int, eligible: list[ExternalDataSchema]) -> None:
- """Abort if any buffer file survived the purge.
-
- The purge itself is best-effort, but a leftover file here means the first buffered sync
- replays rows the legacy lane already delivered, against a lane with no watermark yet —
- silently. The source is still paused and the mode unset, so aborting is clean.
- """
- from products.data_warehouse.backend.facade.api import get_s3_client
-
- s3 = get_s3_client()
- leftovers: list[str] = []
- for schema in eligible:
- prefix = strip_s3_protocol(get_buffer_prefix(team_id, str(schema.id)))
- try:
- keys = s3.ls(prefix, detail=False, refresh=True)
- except FileNotFoundError:
- continue
- leftovers.extend(k for k in keys if parse_buffer_file_name(k.rsplit("/", 1)[-1]) is not None)
- if leftovers:
- raise CommandError(
- f"{len(leftovers)} buffer file(s) survived the purge (first: {leftovers[0]}). "
- "The source is left paused and the mode unchanged — clear the prefix and re-run."
- )
-
- def _wait_for_sourcebatch_drain(self, team_id: int, schema_ids: list[str], timeout: int) -> None:
- """Block until no sourcebatch batch for these schemas is still working.
-
- Flipping while a batch is mid-flight would leave it to land after the source stopped
- producing them, against a table the buffered lane has started writing.
- """
- if not schema_ids:
- return
-
- deadline = time.monotonic() + timeout
- conn = psycopg.Connection.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True)
- try:
- while True:
- age = BatchQueue.get_oldest_non_terminal_batch_age_seconds(conn, team_id=team_id, schema_ids=schema_ids)
- if age is None:
- return
- if time.monotonic() >= deadline:
- raise CommandError(
- f"sourcebatch still has a batch {age:.0f}s old after {timeout}s. "
- "The source is left paused — investigate the stuck load before flipping."
- )
- self.stdout.write(f" waiting, oldest batch {age:.0f}s old")
- time.sleep(DRAIN_POLL_SECONDS)
- finally:
- conn.close()
-
- def _wait_for_running_sync_jobs(self, team_id: int, schema_ids: list[str], timeout: int) -> None:
- if not schema_ids:
- return
-
- deadline = time.monotonic() + timeout
- while True:
- # 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,
- schema_snapshot__companion_of__isnull=True,
- ).values_list("id", "created_at")
- )
- if not running:
- return
- if time.monotonic() >= deadline:
- now = dt.datetime.now(dt.UTC)
- # Ages let the operator tell a live sync from a stale stuck-RUNNING row, which
- # never finishes on its own and needs unsticking before the flip can proceed.
- detail = ", ".join(
- f"{job_id} ({(now - created_at).total_seconds():.0f}s old)" for job_id, created_at in running
- )
- raise CommandError(
- f"{len(running)} sync job(s) still running after {timeout}s: {detail}. Schedules "
- "are left paused and the mode unchanged — wait for them to finish, then re-run."
- )
- self.stdout.write(f" waiting, {len(running)} sync job(s) running")
- time.sleep(DRAIN_POLL_SECONDS)
-
- def _restore_schema_schedules(self, schemas: list[ExternalDataSchema]) -> None:
- """Hand the schemas back their schedules, skipping any that stopped syncing meanwhile.
-
- `should_sync` is re-read rather than taken from the in-memory copies: a drain wait can run
- for minutes, and a schema disabled in that window must stay paused.
- """
- still_syncing = set(
- ExternalDataSchema.objects.filter(
- id__in=[s.id for s in schemas], should_sync=True, deleted=False
- ).values_list("id", flat=True)
- )
- self._set_schema_schedules([s for s in schemas if s.id in still_syncing], paused=False)
-
- def _set_schema_schedules(self, schemas: list[ExternalDataSchema], *, paused: bool) -> None:
- from products.data_warehouse.backend.facade.api import (
- pause_external_data_schedule,
- unpause_external_data_schedule,
- )
-
- for schema in schemas:
- try:
- if paused:
- pause_external_data_schedule(str(schema.id))
- else:
- unpause_external_data_schedule(str(schema.id))
- except Exception:
- # The mode is already persisted, so a failed schedule call is recoverable by hand;
- # aborting here would leave the source half-flipped instead.
- self.stdout.write(self.style.WARNING(f" could not set schedule for {schema.name} — do it manually"))
- logger.warning("cdc_flip_schedule_failed", schema_id=str(schema.id), exc_info=True)
diff --git a/products/warehouse_sources/backend/management/commands/repair_stalled_schema_schedules.py b/products/warehouse_sources/backend/management/commands/repair_stalled_schema_schedules.py
index 7bc88eb2c3c4..b366061d2e40 100644
--- a/products/warehouse_sources/backend/management/commands/repair_stalled_schema_schedules.py
+++ b/products/warehouse_sources/backend/management/commands/repair_stalled_schema_schedules.py
@@ -40,7 +40,7 @@ class Command(BaseCommand):
help = (
"Repair schemas whose Temporal schedule stopped firing: unpause or recreate the schedule "
"and clear a stale Running status. Skips schemas whose run is wedged (use "
- "unstick_external_data_jobs) and buffered CDC sources. Dry-run unless --live-run is given."
+ "unstick_external_data_jobs) and halted CDC schemas (use repair_cdc). Dry-run unless --live-run is given."
)
def add_arguments(self, parser: CommandParser) -> None:
@@ -61,21 +61,11 @@ class Command(BaseCommand):
default=MAX_SCHEMAS_DEFAULT,
help=f"Abort if more than this many schemas match (default {MAX_SCHEMAS_DEFAULT})",
)
- parser.add_argument(
- "--include-buffered",
- action="store_true",
- help=(
- "Also repair schemas on a buffered CDC source. Their schedule paces buffer "
- "consumption, so restarting it out of sequence can merge files against a table "
- "the buffered lane already writes. Prefer re-running migrate_cdc_source_to_buffered."
- ),
- )
parser.add_argument("--live-run", action="store_true", help="Apply changes (default is dry-run)")
parser.add_argument("--yes", action="store_true", help="Skip interactive confirmation")
def handle(self, *args: Any, **options: Any) -> None:
live_run: bool = options["live_run"]
- include_buffered: bool = options["include_buffered"]
max_schemas: int = options["max_schemas"]
# One over the cap, so an unexpectedly wide match is refused rather than loaded whole.
@@ -96,21 +86,7 @@ class Command(BaseCommand):
"Narrow the targeting or raise --max-schemas explicitly."
)
- # --include-buffered only overrides the buffered-CDC exclusion; every other exclusion in
- # repairable_here stays in force — none of them are what that flag is for.
- actionable = [
- s
- for s in stalled
- if s.repairable_here
- or (
- include_buffered
- and s.kind == "no_runs"
- and not s.admin_paused
- and s.has_sync_interval
- and not s.cdc_streaming
- and not s.cdc_halted
- )
- ]
+ actionable = [s for s in stalled if s.repairable_here]
actionable_ids = {s.schema_id for s in actionable}
skipped = [s for s in stalled if s.schema_id not in actionable_ids]
@@ -181,11 +157,7 @@ class Command(BaseCommand):
return "paused for an in-flight admin-triggered run"
if not schema.has_sync_interval:
return "no sync_frequency_interval set"
- if schema.cdc_streaming:
- return "streaming CDC schema, use repair_cdc"
- if schema.cdc_halted:
- return "CDC halted, use repair_cdc"
- return "buffered CDC source"
+ return "CDC halted, use repair_cdc"
def _confirm(self, prompt: str, yes: bool) -> None:
if yes:
diff --git a/products/warehouse_sources/backend/management/commands/validate_cdc_buffer.py b/products/warehouse_sources/backend/management/commands/validate_cdc_buffer.py
deleted file mode 100644
index 34cc5a61aa81..000000000000
--- a/products/warehouse_sources/backend/management/commands/validate_cdc_buffer.py
+++ /dev/null
@@ -1,229 +0,0 @@
-"""Validate CDC shadow-buffer files against the legacy sourcebatch lane.
-
-Read-only exit gate for the buffered-ingress flip: while the dwh-cdc-buffer-shadow
-flag is on, the legacy path stays authoritative and this command reconciles what the
-shadow wrote against what legacy dispatched over the same time window.
-
-Checks per CDC schema:
-- filename contract: every buffer file parses, start <= end, and ranges are
- non-overlapping in filename-sort order (a shared boundary is legal — a split
- transaction's batches share its commit position).
-- row reconciliation: the `{name}_cdc` (scd2_append) lane keeps one row per
- change event, so its sourcebatch row sum must equal the buffer's row sum
- exactly. The consolidated lane dedupes per PK, so it only bounds the buffer
- from below (buffer >= consolidated).
-
-Windows are aligned by timestamp (buffer LastModified vs sourcebatch created_at),
-so edge-of-window skew of one micro-batch is possible — treat single-batch-sized
-deltas near the window edge as noise and re-run with a wider --since-hours.
-
-Known windows where sums legitimately diverge:
-- Around the snapshot→streaming flip: shadow writes buffer files during the
- snapshot phase, but their legacy dispatches are deferred and inserted with
- created_at = flip time. Validate with a window that starts after the schema
- began streaming (or spans the entire snapshot phase).
-- After a mid-run activity retry: the legacy lane re-inserts the replayed prefix
- of an in-flight transaction (accepted duplicate scd2 rows) while the buffer's
- same-named files overwrite. A `(run_uuid, batch_index)` dispatched more than
- once in the window therefore downgrades the scd2 exact-match to a warning.
-"""
-
-from datetime import UTC, datetime, timedelta
-from typing import Any
-
-from django.core.management.base import BaseCommand, CommandError, CommandParser
-
-import psycopg
-import pyarrow.parquet as pq
-
-from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
-
-from products.data_warehouse.backend.facade.api import get_s3_client
-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
-from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
-from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_COMPANION_SUFFIX
-from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import (
- BufferFileSpan,
- get_buffer_prefix,
- parse_buffer_file_name,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common import strip_s3_protocol
-from products.warehouse_sources_queue.backend.sdk import BATCH_TABLE
-
-
-class Command(BaseCommand):
- help = "Validate CDC shadow-buffer files against legacy sourcebatch dispatches (read-only)"
-
- def add_arguments(self, parser: CommandParser) -> None:
- parser.add_argument("--source-id", required=True, help="ExternalDataSource id to validate")
- parser.add_argument("--since-hours", type=int, default=24, help="Comparison window (default 24)")
-
- def handle(self, *args: Any, **options: Any) -> None:
- source = ExternalDataSource.objects.get(id=options["source_id"])
- cutoff = datetime.now(UTC) - timedelta(hours=options["since_hours"])
-
- schemas = list(
- ExternalDataSchema.objects.filter(source=source, sync_type=ExternalDataSchema.SyncType.CDC, deleted=False)
- )
- if not schemas:
- raise CommandError(f"Source {source.id} has no CDC schemas")
-
- legacy_rows, retried_batches = self._fetch_legacy_row_sums(source, cutoff)
- s3 = get_s3_client()
- violations: list[str] = []
-
- for schema in schemas:
- buffer_rows, file_count, schema_violations = self._scan_buffer(s3, schema, cutoff)
- violations.extend(schema_violations)
-
- scd2_rows = legacy_rows.get((str(schema.id), "scd2"))
- consolidated_rows = legacy_rows.get((str(schema.id), "consolidated"))
-
- self.stdout.write(
- f"{schema.name} (mode={schema.cdc_table_mode}, cdc_mode={schema.cdc_mode}): "
- f"buffer={buffer_rows} rows in {file_count} files, "
- f"legacy scd2={scd2_rows}, legacy consolidated={consolidated_rows}"
- )
-
- # Snapshot-phase schemas defer legacy dispatch (cdc_deferred_runs), so
- # row reconciliation only means something once the schema streams.
- if schema.cdc_mode != "streaming":
- continue
-
- # A streaming flush dispatches legacy immediately, so buffered rows with
- # no legacy dispatches at all means the legacy lane is stalled — absence
- # must fail, not silently skip the comparison.
- required_lanes = {"consolidated": ["consolidated"], "cdc_only": ["scd2"], "both": ["scd2", "consolidated"]}
- if buffer_rows > 0:
- for lane in required_lanes.get(schema.cdc_table_mode, []):
- if legacy_rows.get((str(schema.id), lane)) is None:
- violations.append(
- f"{schema.name}: buffer has {buffer_rows} rows but no legacy {lane} dispatches "
- "in the window — legacy lane stalled or producer failing"
- )
-
- if scd2_rows is not None and scd2_rows != buffer_rows:
- # Legacy re-inserts replayed rows on activity retry while buffer
- # files overwrite, so a re-dispatched batch is expected to skew the
- # exact match — that case warns instead of failing.
- retried = retried_batches.get(str(schema.id), 0)
- if retried > 0:
- self.stdout.write(
- self.style.WARNING(
- f"WARNING: {schema.name}: scd2 rows ({scd2_rows}) != buffer rows ({buffer_rows}) "
- f"with {retried} re-dispatched batch(es) in the window — likely retry-replay skew, "
- "verify manually"
- )
- )
- else:
- violations.append(
- f"{schema.name}: scd2 lane rows ({scd2_rows}) != buffer rows ({buffer_rows}) — "
- "exact match expected"
- )
- if consolidated_rows is not None and buffer_rows < consolidated_rows:
- violations.append(
- f"{schema.name}: buffer rows ({buffer_rows}) < consolidated rows ({consolidated_rows}) — "
- "shadow is missing data (dedupe can only shrink, never grow, the legacy count)"
- )
-
- if violations:
- for violation in violations:
- self.stdout.write(self.style.ERROR(f"VIOLATION: {violation}"))
- raise CommandError(f"{len(violations)} violation(s) found")
-
- self.stdout.write(self.style.SUCCESS("Buffer validation passed"))
-
- def _scan_buffer(self, s3: Any, schema: ExternalDataSchema, cutoff: datetime) -> tuple[int, int, list[str]]:
- """Return (row_sum, file_count, violations) for one schema's buffer prefix."""
- prefix = strip_s3_protocol(get_buffer_prefix(schema.team_id, str(schema.id)))
- try:
- ls_result = s3.ls(prefix, detail=True)
- except FileNotFoundError:
- return 0, 0, []
- # Some fsspec ls implementations return a dict keyed by path.
- entries = ls_result.values() if isinstance(ls_result, dict) else ls_result
-
- violations: list[str] = []
- named: list[tuple[str, BufferFileSpan]] = []
- for entry in entries:
- if entry.get("type") == "directory":
- continue
- key = entry["Key"]
- file_name = key.rsplit("/", 1)[-1]
- parsed = parse_buffer_file_name(file_name)
- if parsed is None:
- violations.append(f"{schema.name}: foreign file in buffer prefix: {file_name}")
- continue
- modified = entry.get("LastModified")
- if modified is not None and modified < cutoff:
- continue
- named.append((key, parsed))
-
- # Filename sort must equal WAL order: ranges strictly ordered, overlap
- # only as a shared boundary (split transaction).
- named.sort(key=lambda item: item[0].rsplit("/", 1)[-1])
- row_sum = 0
- prev_end: int | None = None
- for key, span in named:
- if span.start_seq > span.end_seq:
- violations.append(f"{schema.name}: inverted range in {key}")
- if prev_end is not None and span.start_seq < prev_end:
- violations.append(f"{schema.name}: overlapping range in {key} (starts before previous end {prev_end})")
- prev_end = span.end_seq
-
- # A failed shadow write can leave a truncated object; report it as a
- # violation instead of crashing the whole validation run.
- try:
- with s3.open(key, "rb") as f:
- row_sum += pq.ParquetFile(f).metadata.num_rows
- except Exception as e:
- violations.append(f"{schema.name}: unreadable buffer file {key} ({type(e).__name__})")
-
- return row_sum, len(named), violations
-
- def _fetch_legacy_row_sums(
- self, source: ExternalDataSource, cutoff: datetime
- ) -> tuple[dict[tuple[str, str], int], dict[str, int]]:
- """Sum sourcebatch row_count per (schema_id, lane) since cutoff, plus the number of
- re-dispatched batches per schema (for retry-replay downgrades).
-
- Only `sync_type = 'cdc'` dispatches count: snapshots and resyncs flow into
- the same table as full_refresh/incremental and would otherwise inflate the
- consolidated lane into a guaranteed false violation. Lane is derived from
- resource_name via the shared companion suffix.
-
- A retry is a `(run_uuid, batch_index)` pair dispatched more than once — that is the
- replay the scd2 exact-match cannot survive. Counting distinct run_uuids instead (as this
- did originally) counts *scheduled ticks*: a healthy 5-min source mints a fresh run_uuid
- every tick, so any window longer than one tick looked like a retry and permanently
- downgraded the exact match to a warning, which is precisely the check this gate exists to
- make.
- """
- companion_pattern = "%" + CDC_COMPANION_SUFFIX.replace("_", r"\_")
- with psycopg.connect(WAREHOUSE_SOURCES_DATABASE_URL) as conn:
- rows = conn.execute(
- f"""
- SELECT schema_id, lane, COALESCE(SUM(batch_rows), 0), COUNT(*) FILTER (WHERE dispatches > 1)
- FROM (
- SELECT schema_id,
- CASE WHEN resource_name LIKE %(companion_pattern)s
- THEN 'scd2' ELSE 'consolidated' END AS lane,
- run_uuid,
- batch_index,
- SUM(row_count) AS batch_rows,
- COUNT(*) AS dispatches
- FROM {BATCH_TABLE}
- WHERE source_id = %(source_id)s AND created_at >= %(cutoff)s AND sync_type = 'cdc'
- GROUP BY schema_id, lane, run_uuid, batch_index
- ) per_batch
- GROUP BY schema_id, lane
- """,
- {"source_id": str(source.id), "cutoff": cutoff, "companion_pattern": companion_pattern},
- ).fetchall()
-
- sums: dict[tuple[str, str], int] = {}
- retried_batches: dict[str, int] = {}
- for schema_id, lane, total, retried in rows:
- sums[(str(schema_id), lane)] = int(total)
- retried_batches[str(schema_id)] = max(retried_batches.get(str(schema_id), 0), int(retried))
- return sums, retried_batches
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index e5cf50ff5687..0dba61349bca 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -1507,7 +1507,7 @@ def update_sync_type_config_keys(
committed value instead of clobbering it.
`updates` sets keys, `removes` pops keys, and `mutate` runs last for in-place edits of nested
- structures (e.g. appending to `cdc_deferred_runs`) that must happen inside the critical section.
+ structures that must happen inside the critical section.
Callers refresh their in-memory copy from the returned dict.
`extra_model_fields` saves additional model fields in the same transaction and row lock — use
@@ -1628,37 +1628,6 @@ def finalize_repartition_scheme(
return wrote
-def complete_schema_run(schema: ExternalDataSchema, *, last_synced_at: datetime) -> bool:
- """Mark a schema COMPLETED after a successful run, atomically with the broken-state check.
-
- The sweeper can mark the source broken at any moment; checking ``cdc_broken`` outside the
- row lock would let a stale instance repaint the schema healthy right after the sweeper wrote
- FAILED, hiding the breakage from the UI and the failure digest (the loader-side twin of this
- guard lives in jobs.update_external_job_status, which already checks under its own lock).
- Clears a stale ``cdc_extraction_paused`` marker — a successful run proves extraction resumed.
- Returns whether the repaint happened; the passed instance is refreshed either way.
- """
- with transaction.atomic():
- fresh = ExternalDataSchema.objects.select_for_update().get(id=schema.id, team_id=schema.team_id)
- config = fresh.sync_type_config or {}
- repainted = not config.get("cdc_broken")
- if repainted:
- config.pop("cdc_extraction_paused", None)
- fresh.sync_type_config = config
- fresh.status = ExternalDataSchema.Status.COMPLETED
- fresh.latest_error = None
- fresh.last_synced_at = last_synced_at
- fresh.save(
- update_fields=["sync_type_config", "status", "latest_error", "last_synced_at", "updated_at"],
- skip_activity_log=True,
- )
- schema.sync_type_config = fresh.sync_type_config
- schema.status = fresh.status
- schema.latest_error = fresh.latest_error
- schema.last_synced_at = fresh.last_synced_at
- return repainted
-
-
def mark_schema_running_unless_halted(schema: ExternalDataSchema) -> bool:
"""Paint a schema Running at the start of a run, unless a CDC halt marker holds.
@@ -1683,11 +1652,10 @@ def mark_initial_sync_complete(schema_id: str | uuid.UUID, team_id: int) -> None
On the False→True transition, a CDC schema still in snapshot mode moves to
``cdc_mode="streaming"`` in the same row lock. Callers must only invoke this once the
run's data has durably landed in the destination table — the streaming flip is what lets
- the CDC workflow start enqueuing (and flushing deferred) WAL merge runs, and merges
- against a half-loaded snapshot corrupt the table. Locked for the same reason as
- ``update_sync_type_config_keys``: the CDC extract activity appends ``cdc_deferred_runs``
- to ``sync_type_config`` concurrently, and an unlocked read-modify-write here could
- clobber a deferred run.
+ the scheduled sync start merging the change buffer, and merges against a half-loaded
+ snapshot corrupt the table. Locked for the same reason as ``update_sync_type_config_keys``:
+ the CDC extract activity writes ``sync_type_config`` concurrently, and an unlocked
+ read-modify-write here could clobber its keys.
"""
with transaction.atomic():
schema = ExternalDataSchema.objects.select_for_update().exclude(deleted=True).get(id=schema_id, team_id=team_id)
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
index b8f9b8360692..c722e65e1261 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -166,8 +166,8 @@ def _reset_cdc_for_full_resnapshot(instance: ExternalDataSchema) -> None:
While the cancelled sync could still hand over, the reset is left to capture instead.
- Must save before triggering: the workflow reloads the schema and bails via
- `CDCHandledExternally` if it sees `cdc_mode='streaming'`.
+ Must save before triggering: the workflow reloads the schema, and a stale
+ `cdc_mode='streaming'` sends it to the change buffer instead of the snapshot.
"""
if hand_reset_to_capture_if_sync_running(instance, logger):
return
@@ -177,7 +177,7 @@ def _reset_cdc_for_full_resnapshot(instance: ExternalDataSchema) -> None:
# column, leaving no second window for the merged config to be overwritten).
updates: dict[str, Any] = {"reset_pipeline": True, "cdc_mode": "snapshot"}
removes = ["cdc_last_log_position", "cdc_deferred_runs", CDC_RESET_PENDING_KEY]
- if resnapshot_stays_in_buffer(instance, logger):
+ if resnapshot_stays_in_buffer(instance):
updates[CDC_SNAPSHOT_LANE_KEY] = BUFFER_LANE
instance.sync_type_config = update_sync_type_config_keys(
instance.id, instance.team_id, updates=updates, removes=removes
@@ -206,6 +206,14 @@ NO_SYNC_FREQUENCY_ERROR = (
"This table has no sync frequency, so its sync cannot be scheduled. Set a sync frequency first."
)
+# A CDC table's own schedule loads its captured changes, and the change buffer expires them after 14
+# days, so a slower schedule would lose changes for good.
+CDC_MAX_SYNC_FREQUENCY_INTERVAL = dt.timedelta(days=7)
+CDC_SYNC_FREQUENCY_TOO_SLOW_ERROR = (
+ "Change data capture keeps captured changes for 14 days, so this table must sync at least weekly. "
+ "Choose Weekly or a shorter interval."
+)
+
SCHEDULED_FULL_REFRESH_SYNC_TYPE_ERROR = (
"Scheduled full refreshes are only available for incremental, append only, and xmin syncs. "
"Change the sync method first."
@@ -772,7 +780,7 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
super().update() does a full-instance save: every column goes back to the value it held in the
copy loaded at the start of the request. A PATCH that carries one field therefore reverts every
field anything else wrote in between — a concurrent CDC extract activity's sync_type_config keys
- (cdc_last_log_position, cdc_deferred_runs, cdc_mode), or the table_id, status, last_synced_at
+ (cdc_last_log_position, cdc_snapshot_lane, cdc_mode), or the table_id, status, last_synced_at
and initial_sync_complete that `delete_table()` clears. sync_type_config additionally merges,
because two writers own different keys of the same column. The lock is held across the save so
nothing interleaves.
@@ -1193,6 +1201,16 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
if should_sync is True or was_sync_time_of_day_updated:
raise ValidationError({"sync_frequency": NO_SYNC_FREQUENCY_ERROR})
+ # Checked only when this request sets the frequency or the sync type, so a row that already has a
+ # slower frequency still accepts unrelated edits.
+ if (
+ resulting_sync_type == ExternalDataSchema.SyncType.CDC
+ and (was_sync_frequency_updated or "sync_type" in data)
+ and instance.sync_frequency_interval is not None
+ and instance.sync_frequency_interval > CDC_MAX_SYNC_FREQUENCY_INTERVAL
+ ):
+ raise ValidationError({"sync_frequency": CDC_SYNC_FREQUENCY_TOO_SLOW_ERROR})
+
if source.supports_scheduled_sync and should_sync is True and sync_type is None and instance.sync_type is None:
raise ValidationError("Sync type must be set up first before enabling schema")
@@ -1971,14 +1989,14 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
removes = ["cdc_last_log_position", "cdc_deferred_runs", CDC_RESET_PENDING_KEY]
# Without the marker, the next capture run would empty the buffer, deleting changes a
# capture run already in progress wrote after the snapshot started reading.
- if resnapshot_stays_in_buffer(instance, logger):
+ if resnapshot_stays_in_buffer(instance):
updates[CDC_SNAPSHOT_LANE_KEY] = BUFFER_LANE
# Merge under a row lock so this reset can't clobber a concurrent CDC extract activity's
# sync_type_config writes. Persist BEFORE triggering the workflow so the Postgres source
# sees cdc_mode="snapshot" when it reloads the schema from DB — otherwise a race: the
- # workflow starts, loads stale "streaming" mode, raises CDCHandledExternally, and the
- # full-refresh never runs.
+ # workflow starts, loads stale "streaming" mode, consumes the change buffer instead, and
+ # the full-refresh never runs.
# initial_sync_complete is saved in the same transaction as cdc_mode via extra_model_fields
# so no reader can observe cdc_mode="snapshot" with initial_sync_complete=True.
extra: dict[str, Any] = {"initial_sync_complete": False} if cdc_resync else {}
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/change_data_capture.py b/products/warehouse_sources/backend/presentation/views/external_data_source/change_data_capture.py
index e52447281a2b..0cc40dcf71db 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/change_data_capture.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/change_data_capture.py
@@ -522,8 +522,8 @@ class ExternalDataSourceCDCMixin(base.ExternalDataSourceViewSetBase):
base.logger.exception("Failed engine-side CDC cleanup during disable_cdc", exc_info=e)
base.capture_exception(e, {"source_id": str(instance.id)})
- # Drop each schema's S3 change buffer: the shadow lane's files are raw customer
- # change data with no consumer once CDC is off, and nothing else expires them.
+ # Drop each schema's S3 change buffer: its files are raw customer change data with no
+ # consumer once CDC is off, and only the 14-day lifecycle rule would expire them.
for schema_id in cdc_schema_ids:
base.purge_buffer_prefix(instance.team_id, str(schema_id), base.logger)
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 e0b55fc79bd1..19457179d606 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
@@ -357,13 +357,9 @@ _CDC_EXPOSED_JOB_INPUT_KEYS = {
"cdc_lag_warning_threshold_mb",
"cdc_lag_critical_threshold_mb",
"cdc_consistent_point",
- # Set by migrate_cdc_source_to_buffered, never by the API. Losing it on an unrelated PATCH
- # would resume legacy delivery from an advanced slot and strand the unread buffer.
+ # Set by CDC setup, Repair CDC and capture, never by the API. Losing it on an unrelated PATCH
+ # would make capture convert the source again, which empties its unconsumed 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/stalled_schedules.py b/products/warehouse_sources/backend/stalled_schedules.py
index de00416432ed..f3c7d9d4b063 100644
--- a/products/warehouse_sources/backend/stalled_schedules.py
+++ b/products/warehouse_sources/backend/stalled_schedules.py
@@ -3,9 +3,8 @@
A schema's cadence lives in a Temporal schedule whose paused flag is written once, when the
schedule is created or rewritten (`sync_external_data_job_workflow`). Nothing keeps that flag
in step with `should_sync` afterwards, so a schedule paused out of band stays paused while
-Postgres still reports the schema as syncing. `migrate_cdc_source_to_buffered` pauses every
-per-schema schedule at its step 3 and unpauses at its step 7, so any abort in between leaves
-them down.
+Postgres still reports the schema as syncing. A CDC schema's schedule is the one that consumes
+its change buffer, so a stall there also lets the buffer age toward its expiry.
That failure is silent in a way an ordinary sync failure is not. No run starts, so there is no
job row, no `latest_error`, and nothing for the failure digest to report. Every column a
@@ -78,7 +77,6 @@ class StalledSchema:
# Temporal workflow and belongs to `unstick_external_data_jobs` instead.
kind: str
stalled_for: timedelta
- cdc_ingest_mode: str
# `ad_hoc_sync.py` and the admin action set this on the schema it pauses for an in-flight
# non-scheduled run, and clear it themselves once that run finishes successfully. It surviving
# to a stall check means the run's own cleanup has not (yet, or ever) run, so the pause may
@@ -90,11 +88,6 @@ class StalledSchema:
# raises. Repairing would fail every time with the same error, so this is excluded rather
# than left to fail — rewriting the schema's own cadence is not this tool's job.
has_sync_interval: bool
- # True once a CDC schema has finished its initial snapshot and flipped to streaming
- # (`mark_initial_sync_complete`). `stalled_schema_queryset` already excludes this at the
- # source; this field backs `repairable_here` for the window between discovery and repair,
- # where a schema can flip to streaming after being read as `no_runs`.
- cdc_streaming: bool
# Mirrors `ExternalDataSchema.cdc_halted`: true while the source is marked `cdc_broken`, or
# its extraction schedule was paused after a non-retryable error. This is a configuration
# marker independent of `should_sync` and `status`, so a halted schema can still read
@@ -106,32 +99,16 @@ class StalledSchema:
def repairable_here(self) -> bool:
"""Whether unpausing the schedule is the right fix.
- A buffered CDC source is excluded because its schedule paces buffer consumption: once
- the mode is flipped, restarting the schedule out of sequence merges files against a
- table the buffered lane already writes. Those go back through
- `migrate_cdc_source_to_buffered`.
-
A schema still carrying `admin_unpause_schedule_after_run` is excluded because its pause
may belong to an in-flight admin-triggered run rather than to the outage this repairs.
A schema with no `sync_frequency_interval` is excluded because the schedule builder
cannot turn a null interval into a cadence.
- A streaming CDC schema is excluded because its own workflow paces the schedule; unpausing
- it does not restart a sync, it just races that workflow into re-pausing it. Those go back
- through `repair_cdc`.
-
- A halted CDC schema is excluded for the same reason, one step earlier: the marker exists
- precisely to stop anything else from touching the schema until `repair_cdc` clears it.
+ A halted CDC schema is excluded because the marker exists precisely to stop anything else
+ from touching the schema until `repair_cdc` clears it.
"""
- return (
- self.kind == "no_runs"
- and self.cdc_ingest_mode != "buffered"
- and not self.admin_paused
- and self.has_sync_interval
- and not self.cdc_streaming
- and not self.cdc_halted
- )
+ return self.kind == "no_runs" and not self.admin_paused and self.has_sync_interval and not self.cdc_halted
def stalled_schema_queryset(
@@ -180,7 +157,7 @@ def stalled_schema_queryset(
)
.exclude(source__access_method=ExternalDataSource.AccessMethod.DIRECT)
.exclude(status__in=SELF_REPORTING_STATUSES)
- # Streaming CDC and cdc_halted are excluded in `find_stalled_schemas` in Python, not
+ # cdc_halted is excluded in `find_stalled_schemas` in Python, not
# here: a JSON key lookup against a schema whose `sync_type_config` does not have that
# key evaluates to SQL NULL, and `.exclude()` compiles to `NOT (...)` — NOT NULL is NULL,
# not TRUE, so Postgres drops the row from the result entirely instead of keeping it.
@@ -230,14 +207,11 @@ def find_stalled_schemas(
now = timezone.now()
stalled = []
for schema in schemas:
- # Streaming CDC and cdc_halted are excluded here rather than in the queryset (see the
- # comment there): a paused per-schema schedule is streaming CDC's steady state, and
- # cdc_halted exists precisely to keep everything else off the schedule until repair_cdc
- # clears it. Skipped rather than reported-but-unrepairable, unlike buffered CDC: this
- # population can be the entire fleet during a broken-source incident, and reporting it
- # every sweep would bury the schedule-stall signal this predicate exists to surface.
- if schema.is_cdc and schema.cdc_mode == "streaming":
- continue
+ # cdc_halted is excluded here rather than in the queryset (see the comment there): it exists
+ # precisely to keep everything else off the schedule until repair_cdc clears it. Skipped
+ # rather than reported-but-unrepairable: this population can be the entire fleet during a
+ # broken-source incident, and reporting it every sweep would bury the schedule-stall signal
+ # this predicate exists to surface.
if schema.cdc_halted:
continue
stalled.append(
@@ -249,10 +223,8 @@ def find_stalled_schemas(
source_type=schema.source.source_type,
kind="stuck_job" if schema.id in schemas_with_running_jobs else "no_runs",
stalled_for=now - schema.latest_run_at, # type: ignore[attr-defined]
- cdc_ingest_mode=(schema.source.job_inputs or {}).get("cdc_ingest_mode", "legacy"),
admin_paused=bool((schema.sync_type_config or {}).get("admin_unpause_schedule_after_run")),
has_sync_interval=schema.sync_frequency_interval is not None,
- cdc_streaming=schema.is_cdc and schema.cdc_mode == "streaming",
cdc_halted=schema.cdc_halted,
)
)
@@ -317,18 +289,6 @@ def repair_stalled_schema(stalled: StalledSchema) -> bool:
)
return False
- # A paused schedule is steady state once a CDC schema is streaming — CDCExtractionWorkflow
- # owns it and re-pauses it on its own next tick. Unpausing here does not restart a sync, it
- # just races that workflow for nothing. Re-checked because initial_sync_complete (and so the
- # snapshot-to-streaming flip) can land in the window between discovery and this call.
- if schema.is_cdc and schema.cdc_mode == "streaming":
- logger.info(
- "repair_stalled_schema_schedules_skipped_cdc_streaming",
- schema_id=str(schema.id),
- team_id=schema.team_id,
- )
- return False
-
# The halt marker exists precisely to stop anything else from touching the schedule until
# `repair_cdc` clears it. Re-checked for the same staleness reason as the guards above.
if schema.cdc_halted:
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 66e8c64bcbc8..3642075743bc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -1,10 +1,8 @@
"""CDC Temporal activities.
-cdc_extract_activity: Core extraction — reads WAL, decodes, batches, writes to
-S3 via pipeline, and inserts batch notifications into the warehouse-sources
-Postgres queue for streaming schemas. Snapshot schemas defer their batch
-notifications to `sync_type_config["cdc_deferred_runs"]` until the schema
-transitions to streaming.
+cdc_extract_activity: Core extraction. Reads the WAL, decodes and batches it, and writes each
+table's changes to the S3 change buffer, which the table's own scheduled sync consumes. A
+snapshotting table's changes wait there until its snapshot completes.
validate_cdc_prerequisites_activity: Wraps prerequisite validator for Temporal.
"""
@@ -20,7 +18,6 @@ from collections.abc import Callable
from django.db import InterfaceError, OperationalError, close_old_connections
-import psycopg
import pyarrow as pa
import structlog
import pyarrow.compute as pc
@@ -28,8 +25,6 @@ import posthoganalytics
from temporalio import activity
from temporalio.service import RPCError, RPCStatusCode
-from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
-from posthog.temporal.common.activity_context import current_workflow_id, current_workflow_run_id
from posthog.temporal.common.errors import NonReportableError
from posthog.temporal.common.heartbeat_sync import HeartbeaterSync
from posthog.utils import get_machine_id
@@ -38,8 +33,6 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import (
CDC_SNAPSHOT_LANE_KEY,
ExternalDataSchema,
- complete_schema_run,
- mark_schema_running_unless_halted,
update_sync_type_config_keys,
)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -52,9 +45,6 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.adapters impor
from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (
CDC_SEQ_COLUMN,
ChangeEventBatcher,
- build_scd2_table,
- companion_resource_name,
- deduplicate_table,
enrich_delete_rows,
enrich_toast_omitted_rows,
)
@@ -68,20 +58,16 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.broken import
clear_recovered_self_managed_lag,
mark_cdc_broken,
)
-from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import (
- CDCBufferWriter,
- is_shadow_write_enabled,
- purge_buffer_prefix,
-)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import CDCBufferWriter, purge_buffer_prefix
from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import (
MAX_FRIENDLY_MESSAGE_LENGTH,
CDCErrorCategory,
CDCErrorInfo,
CDCReservedColumnError,
- CDCSchemaMergeError,
CDCSlotNotConfiguredError,
classify_cdc_error,
)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.legacy_conversion import convert_legacy_cdc_state
from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolution import has_engine_seq
from products.warehouse_sources.backend.temporal.data_imports.cdc.naming import (
CDC_EXTRACTION_WORKFLOW_ID_PREFIX,
@@ -91,27 +77,19 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane
BUFFER_LANE,
CDC_RESET_PENDING_KEY,
cancel_running_sync,
- is_buffered_snapshot_enabled,
next_reset_generation,
snapshot_in_buffer,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
captures_to_buffer,
- consolidated_resource_name,
has_queued_batches,
snapshot_can_start_in_buffer,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import SyncTypeLiteral
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer import (
- PostgresProducer,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer import S3BatchWriter
from products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (
_build_schema_snapshot,
)
-from products.warehouse_sources_queue.backend.sdk import BatchQueue
logger = structlog.get_logger(__name__)
@@ -158,27 +136,6 @@ CDC_MAX_EXTRACTION_ATTEMPTS = 3
# identical one says nothing new while burying the runs that do.
CDC_FAILURE_VISIBILITY_COOLDOWN = dt.timedelta(hours=1)
-
-# Shown as latest_error on prior-run jobs reconciled by _reconcile_orphaned_prior_jobs.
-CDC_ORPHANED_JOB_MESSAGE = (
- "CDC run ended without finalizing this job (worker timeout or eviction). It was superseded by a "
- "later run; no data was lost — change capture resumes from the last confirmed replication position."
-)
-# Only reconcile prior RUNNING jobs older than this. A healthy run enqueues its first batch within
-# seconds, so a no-batch job older than this is abandoned; the floor also keeps us clear of any
-# concurrent manual/backfill run of the same source that has only just created its job row.
-CDC_ORPHAN_JOB_MIN_AGE = dt.timedelta(minutes=30)
-# Upper bound: batches are pruned from the queue after PARTITION_PRUNING_INTERVAL (14 days), so a
-# "no batches" verdict is only trustworthy within that window. Never touch older rows — we cannot
-# tell an abandoned run from one whose batches simply aged out.
-CDC_ORPHAN_JOB_MAX_AGE = dt.timedelta(days=14)
-
-# Backpressure guard: past this age a skipped tick is a stuck load, not a slow one — well beyond
-# the loader's recovery-sweep grace (300s) and retry backoffs, so it only trips when a run needs
-# operator attention. Skips past it log at error level; the tick is still skipped (see
-# _previous_load_still_pending for why we never auto-fail the pending run).
-CDC_BACKPRESSURE_STUCK_AGE = dt.timedelta(hours=2)
-
# Per-peek bound on WAL changes. A large backlog is drained over several passes (and, if needed,
# several scheduled runs) instead of one unbounded read that risks the 2h activity timeout and
# re-decodes from the slot start on every retry. The slot advances after each pass, so the next
@@ -219,27 +176,6 @@ class ValidateCDCPrerequisitesInput:
publication_name: str | None
-class _WriteTracker:
- """Per-resource state reused across micro-batch flushes.
-
- Each (table × write_mode) combination produces ONE job with sequential S3
- batch files, matching the multi-batch pattern of pipeline V3.
- """
-
- table_name: str
- write_resource_name: str
- cdc_write_mode: str
- cdc_table_mode: str
- key_columns: list[str]
- job: ExternalDataJob
- s3_writer: S3BatchWriter
- run_uuid: str
- batch_results: list # list[BatchWriteResult]
- batch_index: int = 0
- total_rows: int = 0
-
-
class CDCExtractActivity:
"""Object-oriented body of cdc_extract_activity.
@@ -260,8 +196,6 @@ class CDCExtractActivity:
self.pk_columns_by_table: dict[str, list[str]] = {}
# Missing entry = sync all columns; otherwise the set is the projection (always includes PKs).
self.enabled_columns_by_table: dict[str, set[str]] = {}
- self.write_trackers: dict[str, _WriteTracker] = {}
- self.created_jobs: list[ExternalDataJob] = []
self.adapter: typing.Any = None
self.reader: typing.Any = None
self.batcher: ChangeEventBatcher | None = None
@@ -282,23 +216,13 @@ class CDCExtractActivity:
self.all_table_names: set[str] = set()
# Wall-clock start, set in run(); drives cdc_extraction_duration_seconds.
self._run_started_at: float | None = None
- # Buffer state, shared by the shadow lane and buffered ingress. Writer is lazy so runs that
- # buffer nothing never touch S3 setup; the per-schema file index keeps same-position-range
- # batches (a split transaction) from overwriting each other.
+ # Writer is lazy so runs that buffer nothing never touch S3 setup; the per-schema file index
+ # keeps same-position-range batches (a split transaction) from overwriting each other.
self._buffer_writer: CDCBufferWriter | None = None
self._buffer_file_index: dict[str, int] = {}
self._buffer_cleaned_schemas: set[str] = set()
- # Shadow-only: the lane is validation, so it disables itself rather than failing a run.
- self._shadow_write_failures: int = 0
- self._shadow_disabled_for_run: bool = False
- # Resolved once in _setup (the dwh-cdc-buffer-shadow flag) so neither the
- # flush path nor the batcher re-evaluates a flag per micro-batch.
- self._shadow_enabled: bool = False
- # Table names whose changes this run delivers by buffer alone — no transforms, no
- # sourcebatch dispatch. Resolved once in _setup.
+ # Table names whose changes this run writes to the buffer. Resolved once in _setup.
self._buffered_table_names: set[str] = set()
- self._source_buffered = False
- self._buffered_snapshot_flag: bool | None = None
self._truncated_tables: list[str] = []
# Tables whose reset waits for a sync that can still hand over. The reset re-snapshots them, so
# this run drops their changes.
@@ -321,16 +245,6 @@ class CDCExtractActivity:
time.monotonic() - self._run_started_at
)
- def _emit_deferred_runs_depth(self) -> None:
- """Set the per-source deferred-runs gauge to the current depth across all CDC schemas.
-
- A gauge re-exports its last value, so it must be refreshed whenever deferred runs are
- stored OR drained — otherwise it reads stale-high after a flush. Summed across schemas
- because the gauge is keyed by source, not schema.
- """
- depth = sum(len(s.sync_type_config.get("cdc_deferred_runs") or []) for s in self.cdc_schemas)
- metrics.get_deferred_runs_depth_metric(self.inputs.team_id, str(self.inputs.source_id)).set(depth)
-
def _confirm_position(self, lsn: str) -> None:
"""Advance the replication slot, recording success/failure metrics."""
source_id = str(self.inputs.source_id)
@@ -386,486 +300,89 @@ class CDCExtractActivity:
setattr(schema, field, value)
# ------------------------------------------------------------------
- # Deferred run flushing
+ # Buffer writes
# ------------------------------------------------------------------
- def _flush_deferred_runs(self, schema: ExternalDataSchema) -> None:
- """Insert deferred-run batch notifications into the warehouse-sources Postgres queue.
-
- Called when a schema has just transitioned to cdc_mode="streaming" and has
- entries in sync_type_config["cdc_deferred_runs"].
+ def _write_buffer_file(self, schema: ExternalDataSchema, table_name: str, table: pa.Table) -> None:
+ """Write one micro-batch to the S3 change buffer. Raises on failure: the buffer is the only
+ delivery, and the slot is about to advance past these changes.
"""
- deferred_runs: list[dict] = schema.sync_type_config.get("cdc_deferred_runs", [])
- if not deferred_runs:
- return
-
- assert self.source is not None
- source = self.source
- log = self._schema_log(schema)
-
- log.info(
- "flushing_deferred_cdc_runs",
- schema_id=str(schema.id),
- deferred_count=len(deferred_runs),
- )
-
- for run_meta in deferred_runs:
- job_id = run_meta["job_id"]
- run_uuid = run_meta["run_uuid"]
- batch_results = run_meta.get("batch_results", [])
- total_batches = run_meta.get("total_batches", len(batch_results))
- total_rows = run_meta.get("total_rows", 0)
-
- producer = PostgresProducer(
- database_url=WAREHOUSE_SOURCES_DATABASE_URL,
- team_id=schema.team_id,
- job_id=job_id,
- schema_id=str(schema.id),
- source_id=str(source.id),
- # Fall back to `name` for entries persisted before resource_name was stored.
- resource_name=run_meta.get("resource_name", schema.name),
- sync_type=typing.cast(SyncTypeLiteral, "cdc"),
- run_uuid=run_uuid,
- logger=log,
- primary_keys=run_meta.get("primary_keys"),
- cdc_write_mode=run_meta.get("cdc_write_mode", "incremental_merge"),
- cdc_table_mode=run_meta.get("cdc_table_mode"),
- workflow_id=current_workflow_id(),
- workflow_run_id=current_workflow_run_id(),
- **self._partition_kwargs(schema),
- )
-
- from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3 import (
- BatchWriteResult,
+ file_index = self._buffer_file_index.get(table_name, 0)
+ if self._buffer_writer is None:
+ self._buffer_writer = CDCBufferWriter(self.log)
+
+ schema_id = str(schema.id)
+ if schema_id not in self._buffer_cleaned_schemas:
+ # First write this run: remove files a superseded attempt left at or
+ # past where this run restarted (batch boundaries are not stable
+ # across attempts — see buffer.py). The batch's min seq IS the
+ # restart floor for this schema.
+ restart_seq = pc.min(table.column(CDC_SEQ_COLUMN)).as_py()
+ self._buffer_writer.cleanup_superseded_files(
+ team_id=schema.team_id, schema_id=schema_id, restart_seq=restart_seq
)
+ self._buffer_cleaned_schemas.add(schema_id)
- for i, br in enumerate(batch_results):
- is_final = i == len(batch_results) - 1
- result = BatchWriteResult(
- s3_path=br["s3_path"],
- row_count=br["row_count"],
- byte_size=br["byte_size"],
- batch_index=br["batch_index"],
- timestamp_ns=br.get("timestamp_ns", 0),
- )
- producer.send_batch_notification(
- batch_result=result,
- is_final_batch=is_final,
- total_batches=total_batches if is_final else None,
- total_rows=total_rows if is_final else None,
- data_folder=run_meta.get("data_folder"),
- schema_path=run_meta.get("schema_path"),
- )
-
- try:
- producer.flush()
- finally:
- producer.close()
-
- self._update_schema_sync_type_config(schema, updates={"cdc_deferred_runs": []})
- self._emit_deferred_runs_depth()
-
- log.info("deferred_runs_flushed", schema_id=str(schema.id))
-
- # ------------------------------------------------------------------
- # Tracker creation
- # ------------------------------------------------------------------
- def _get_or_create_tracker(
- self,
- table_name: str,
- write_resource_name: str,
- cdc_write_mode: str,
- cdc_table_mode: str,
- key_columns: list[str],
- schema: ExternalDataSchema,
- ) -> _WriteTracker:
- tracker = self.write_trackers.get(write_resource_name)
- if tracker is not None:
- return tracker
-
- # Stash `cdc_write_mode` alongside the schema snapshot so the Syncs UI can distinguish
- # the two ExternalDataJob rows produced when `cdc_table_mode='both'` — no extra column.
- schema_snapshot = _build_schema_snapshot(schema)
- schema_snapshot["cdc_write_mode"] = cdc_write_mode
-
- job = ExternalDataJob.objects.create(
- team_id=self.inputs.team_id,
- pipeline_id=self.inputs.source_id,
- schema=schema,
- status=ExternalDataJob.Status.RUNNING,
- rows_synced=0,
- workflow_id=activity.info().workflow_id,
- workflow_run_id=activity.info().workflow_run_id,
- pipeline_version=ExternalDataJob.PipelineVersion.V3,
- schema_snapshot=schema_snapshot,
+ result = self._buffer_writer.write_batch(
+ team_id=schema.team_id,
+ schema_id=schema_id,
+ table=table,
+ file_index=file_index,
)
- self.created_jobs.append(job)
+ self._buffer_file_index[table_name] = file_index + 1
- run_uuid = str(uuid.uuid4())
- s3_writer = S3BatchWriter(
- logger=self.log,
- job=job,
- schema_id=str(schema.id),
- run_uuid=run_uuid,
+ metrics.get_buffer_files_written_metric(self.inputs.team_id, str(self.inputs.source_id)).add(1)
+ metrics.get_buffer_write_duration_metric(self.inputs.team_id, str(self.inputs.source_id)).record(
+ result.write_duration_seconds
)
-
- tracker = _WriteTracker(
- table_name=table_name,
- write_resource_name=write_resource_name,
- cdc_write_mode=cdc_write_mode,
- cdc_table_mode=cdc_table_mode,
- key_columns=key_columns,
- job=job,
- s3_writer=s3_writer,
- run_uuid=run_uuid,
- batch_results=[],
+ self._schema_log(schema).debug(
+ "cdc_buffer_written",
+ table=table_name,
+ s3_path=result.s3_path,
+ rows=result.row_count,
+ start_seq=result.start_seq,
+ end_seq=result.end_seq,
)
- self.write_trackers[write_resource_name] = tracker
- return tracker
-
- # ------------------------------------------------------------------
- # Batch notification dispatch & deferred persistence
- # ------------------------------------------------------------------
- def _send_batch_notification(
- self,
- tracker: _WriteTracker,
- batch_result: typing.Any,
- is_final_batch: bool,
- ) -> None:
- """Insert a batch notification into the warehouse-sources Postgres queue for a streaming tracker."""
- assert self.source is not None
- schema = self.schema_by_name[tracker.table_name]
- producer = PostgresProducer(
- database_url=WAREHOUSE_SOURCES_DATABASE_URL,
- team_id=self.inputs.team_id,
- job_id=str(tracker.job.id),
- schema_id=str(schema.id),
- source_id=str(self.source.id),
- resource_name=tracker.write_resource_name,
- sync_type=typing.cast(SyncTypeLiteral, "cdc"),
- run_uuid=tracker.run_uuid,
- logger=self._schema_log(schema),
- primary_keys=tracker.key_columns or None,
- cdc_write_mode=tracker.cdc_write_mode,
- cdc_table_mode=tracker.cdc_table_mode,
- workflow_id=current_workflow_id(),
- workflow_run_id=current_workflow_run_id(),
- **self._partition_kwargs(schema),
- )
- try:
- producer.send_batch_notification(
- batch_result=batch_result,
- is_final_batch=is_final_batch,
- total_batches=tracker.batch_index if is_final_batch else None,
- total_rows=tracker.total_rows if is_final_batch else None,
- data_folder=tracker.s3_writer.get_data_folder() if is_final_batch else None,
- schema_path=tracker.s3_writer.write_schema() if is_final_batch else None,
- )
- producer.flush()
- finally:
- # PostgresProducer holds an open psycopg connection — close per call so we don't leak.
- producer.close()
-
- def _store_deferred_batch(
- self,
- tracker: _WriteTracker,
- batch_result: typing.Any,
- schema: ExternalDataSchema,
- ) -> None:
- """Persist a batch result into the tracker's deferred entry in sync_type_config.
-
- Creates the entry on first call (keyed by run_uuid), appends to it on
- subsequent calls. Persists immediately so progress survives process failures.
-
- The entry lookup + append runs inside the locked merge (see
- update_sync_type_config_keys) so an interleaved API PATCH can't drop the
- deferred runs this activity is accumulating — read-modify-write on a stale
- copy is exactly the lost update the merge prevents.
- """
-
- def _append_batch(config: dict[str, typing.Any]) -> None:
- deferred = config.setdefault("cdc_deferred_runs", [])
- entry: dict | None = next((d for d in deferred if d.get("run_uuid") == tracker.run_uuid), None)
-
- if entry is None:
- entry = {
- "job_id": str(tracker.job.id),
- "run_uuid": tracker.run_uuid,
- # Replayed by the deferred flush so it targets the same Delta table this batch went to.
- "resource_name": tracker.write_resource_name,
- "data_folder": tracker.s3_writer.get_data_folder(),
- "schema_path": None, # written on finalization
- "total_batches": 0,
- "total_rows": 0,
- "primary_keys": tracker.key_columns or None,
- "cdc_write_mode": tracker.cdc_write_mode,
- "cdc_table_mode": tracker.cdc_table_mode,
- "batch_results": [],
- }
- deferred.append(entry)
-
- entry["batch_results"].append(
- {
- "s3_path": batch_result.s3_path,
- "row_count": batch_result.row_count,
- "byte_size": batch_result.byte_size,
- "batch_index": batch_result.batch_index,
- "timestamp_ns": batch_result.timestamp_ns,
- }
- )
- entry["total_batches"] = tracker.batch_index
- entry["total_rows"] = tracker.total_rows
-
- self._update_schema_sync_type_config(schema, mutate=_append_batch)
- self._emit_deferred_runs_depth()
-
- self._schema_log(schema).info(
- "cdc_deferred_run_stored",
- resource=tracker.write_resource_name,
- run_uuid=tracker.run_uuid,
- batch_index=batch_result.batch_index,
- total_batches=tracker.batch_index,
- total_rows=tracker.total_rows,
- )
-
- def _persist_deferred_finalization(
- self, schema: ExternalDataSchema, tracker: _WriteTracker, schema_path: str
- ) -> None:
- """Stamp the final schema_path + totals onto the tracker's deferred entry under the merge lock."""
-
- def _finalize(config: dict[str, typing.Any]) -> None:
- for entry in config.get("cdc_deferred_runs", []):
- if entry.get("run_uuid") == tracker.run_uuid:
- entry["schema_path"] = schema_path
- entry["total_batches"] = tracker.batch_index
- entry["total_rows"] = tracker.total_rows
- break
-
- self._update_schema_sync_type_config(schema, mutate=_finalize)
-
- # ------------------------------------------------------------------
- # Storage naming
- # ------------------------------------------------------------------
- def _partition_kwargs(self, schema: ExternalDataSchema) -> dict[str, typing.Any]:
- """Replay snapshot partitioning so CDC rows match the target Delta.
-
- Without this, partitioned targets silently drop CDC rows. No-op when unpartitioned.
- """
- if not schema.partitioning_enabled:
- return {}
- return {
- "partition_count": schema.partition_count,
- "partition_size": schema.partition_size,
- "partition_keys": schema.partitioning_keys,
- "partition_mode": schema.partition_mode,
- "partition_format": schema.partition_format,
- }
-
- # ------------------------------------------------------------------
- # Shadow buffered ingress
- # ------------------------------------------------------------------
- # Consecutive shadow-write failures before the lane disables for the rest of
- # the run: a persistent S3 failure otherwise pays full retry latency on every
- # micro-batch, stalling the WAL drain loop. The next run retries fresh.
- _SHADOW_MAX_CONSECUTIVE_FAILURES = 3
-
- def _write_buffer_file(self, schema: ExternalDataSchema, table_name: str, table: pa.Table, *, lane: str) -> None:
- """Write one micro-batch to the S3 change buffer. Raises on failure — the caller owns the
- policy, which differs by lane: shadow swallows, buffered ingress must not.
- """
- file_index = self._buffer_file_index.get(table_name, 0)
- try:
- if self._buffer_writer is None:
- self._buffer_writer = CDCBufferWriter(self.log)
-
- schema_id = str(schema.id)
- if schema_id not in self._buffer_cleaned_schemas:
- # First write this run: remove files a superseded attempt left at or
- # past where this run restarted (batch boundaries are not stable
- # across attempts — see buffer.py). The batch's min seq IS the
- # restart floor for this schema.
- restart_seq = pc.min(table.column(CDC_SEQ_COLUMN)).as_py()
- self._buffer_writer.cleanup_superseded_files(
- team_id=schema.team_id, schema_id=schema_id, restart_seq=restart_seq
- )
- self._buffer_cleaned_schemas.add(schema_id)
-
- result = self._buffer_writer.write_batch(
- team_id=schema.team_id,
- schema_id=schema_id,
- table=table,
- file_index=file_index,
- )
-
- metrics.get_buffer_files_written_metric(self.inputs.team_id, str(self.inputs.source_id), lane).add(1)
- metrics.get_buffer_write_duration_metric(self.inputs.team_id, str(self.inputs.source_id), lane).record(
- result.write_duration_seconds
- )
- self._schema_log(schema).debug(
- "cdc_buffer_written",
- table=table_name,
- s3_path=result.s3_path,
- rows=result.row_count,
- start_seq=result.start_seq,
- end_seq=result.end_seq,
- )
- finally:
- # Advance even on failure so ordinals stay aligned with batch position:
- # a lost chunk becomes an honest index gap instead of a later chunk
- # silently claiming its slot.
- self._buffer_file_index[table_name] = file_index + 1
-
- def _maybe_shadow_write_buffer(self, schema: ExternalDataSchema, table_name: str, table: pa.Table) -> None:
- """Shadow-write one micro-batch to the S3 change buffer (dwh-cdc-buffer-shadow flag).
-
- Validation-only while the legacy path stays authoritative: failures are
- swallowed (metric + log) so shadow can never fail an extraction, and the
- slot-advance rules are untouched — gaps in the buffer are expected and
- surfaced by the validate_cdc_buffer command, not guarded against here.
- """
- if not self._shadow_enabled or self._shadow_disabled_for_run:
- return
- if table.num_rows == 0 or not has_engine_seq(table):
- return
-
- try:
- self._write_buffer_file(schema, table_name, table, lane="shadow")
- self._shadow_write_failures = 0
- except Exception:
- self._shadow_write_failures += 1
- metrics.get_shadow_buffer_write_errors_metric(self.inputs.team_id, str(self.inputs.source_id)).add(1)
- self._schema_log(schema).warning("cdc_shadow_buffer_write_failed", table=table_name, exc_info=True)
- if self._shadow_write_failures >= self._SHADOW_MAX_CONSECUTIVE_FAILURES:
- self._shadow_disabled_for_run = True
- self.log.warning("cdc_shadow_buffer_disabled_for_run", consecutive_failures=self._shadow_write_failures)
# ------------------------------------------------------------------
# Per-flush processing
# ------------------------------------------------------------------
- def _process_flush(
- self,
- tables: dict[str, pa.Table],
- is_final: bool = False,
- ) -> set[str]:
- """Enrich, transform, write to S3, and dispatch one micro-batch.
-
- Streaming schemas: batch notification inserted into the Postgres queue immediately after each S3 write.
- Snapshot schemas: batch result persisted to sync_type_config immediately.
-
- Returns the set of write_resource_names that received data.
- """
- flushed: set[str] = set()
+ def _process_flush(self, tables: dict[str, pa.Table]) -> None:
+ """Enrich one micro-batch and write each captured table's changes to the S3 change buffer."""
events_extracted = 0
for table_name, raw_table in tables.items():
schema = self.schema_by_name.get(table_name)
- if schema is None or table_name in self._tables_awaiting_reset:
+ if (
+ schema is None
+ or table_name not in self._buffered_table_names
+ or table_name in self._tables_awaiting_reset
+ ):
continue
self._safe_heartbeat()
- # raw_table has one row per source change event (before SCD2/dedup fan-out).
+ # raw_table has one row per source change event.
events_extracted += raw_table.num_rows
key_columns = self.pk_columns_by_table.get(table_name, [])
- cdc_table_mode = schema.cdc_table_mode
# TOAST fill first so DELETE enrichment copies resolved values, not the
# nulls standing in for omitted columns.
enriched_table = enrich_toast_omitted_rows(raw_table, key_columns)
enriched_table = enrich_delete_rows(enriched_table, key_columns)
-
- if table_name in self._buffered_table_names:
- # The buffer IS the delivery for this schema — the scheduled sync consumes it.
- # A swallowed failure here would lose changes the slot is about to advance past,
- # so this write must fail the run.
- if enriched_table.num_rows:
- # A source column named _ph_cdc_seq means the batcher could not append the
- # engine position; writing anyway would name, order, and clean up files by
- # customer data — cleanup can then delete unconsumed files (see errors.py).
- if not has_engine_seq(enriched_table):
- raise CDCReservedColumnError(f"Table {table_name} has a source column named {CDC_SEQ_COLUMN}")
- self._write_buffer_file(schema, table_name, enriched_table, lane="ingress")
+ if not enriched_table.num_rows:
continue
- # Buffer the raw (pre-dedup/SCD2) stream, then strip the seq column so the legacy write
- # path stays byte-identical. Only ours — a source column of the same name stays.
- self._maybe_shadow_write_buffer(schema, table_name, enriched_table)
- if has_engine_seq(enriched_table):
- enriched_table = enriched_table.remove_column(enriched_table.column_names.index(CDC_SEQ_COLUMN))
-
- # Consolidated shares the snapshot's canonical folder; the `_cdc` companion is
- # CDC-only and stays self-consistent with its `name`-keyed snapshot seed.
- batch_writes: list[tuple[pa.Table, str, str]] = []
- if cdc_table_mode == "consolidated":
- consolidated_name = consolidated_resource_name(schema)
- batch_writes.append(
- (deduplicate_table(enriched_table, key_columns), consolidated_name, "incremental_merge")
- )
- elif cdc_table_mode == "cdc_only":
- batch_writes.append(
- (
- build_scd2_table(enriched_table, key_columns),
- companion_resource_name(schema.name),
- "scd2_append",
- )
- )
- elif cdc_table_mode == "both":
- consolidated_name = consolidated_resource_name(schema)
- batch_writes.append(
- (deduplicate_table(enriched_table, key_columns), consolidated_name, "incremental_merge")
- )
- batch_writes.append(
- (
- build_scd2_table(enriched_table, key_columns),
- companion_resource_name(schema.name),
- "scd2_append",
- )
- )
-
- for write_table, write_resource_name, cdc_write_mode in batch_writes:
- tracker = self._get_or_create_tracker(
- table_name,
- write_resource_name,
- cdc_write_mode,
- cdc_table_mode,
- key_columns,
- schema,
- )
- try:
- batch_result = tracker.s3_writer.write_batch(write_table, batch_index=tracker.batch_index)
- except pa.ArrowTypeError as e:
- # The per-batch table is built consistently (typed columns + safe fallback),
- # so an Arrow type error here is a cross-batch merge conflict — a column whose
- # type genuinely drifted mid-stream. Replaying re-fails identically, so surface
- # it as non-retryable instead of looping the schedule.
- raise CDCSchemaMergeError(
- f"Incompatible column types across CDC batches for {write_resource_name}"
- ) from e
- tracker.batch_results.append(batch_result)
- tracker.batch_index += 1
- tracker.total_rows += write_table.num_rows
- flushed.add(write_resource_name)
-
- self._schema_log(schema).info(
- "cdc_batch_written",
- table=table_name,
- resource=write_resource_name,
- rows=write_table.num_rows,
- batch_index=tracker.batch_index - 1,
- s3_path=batch_result.s3_path,
- )
-
- # Dispatch immediately so progress survives process failures.
- if schema.cdc_mode == "streaming":
- self._send_batch_notification(tracker, batch_result, is_final_batch=is_final)
- elif schema.cdc_mode == "snapshot":
- self._store_deferred_batch(tracker, batch_result, schema)
+ # A source column named _ph_cdc_seq means the batcher could not append the
+ # engine position; writing anyway would name, order, and clean up files by
+ # customer data — cleanup can then delete unconsumed files (see errors.py).
+ if not has_engine_seq(enriched_table):
+ raise CDCReservedColumnError(f"Table {table_name} has a source column named {CDC_SEQ_COLUMN}")
+ self._write_buffer_file(schema, table_name, enriched_table)
if events_extracted:
metrics.get_events_extracted_metric(self.inputs.team_id, str(self.inputs.source_id)).add(events_extracted)
- return flushed
-
# ------------------------------------------------------------------
# Top-level orchestration
# ------------------------------------------------------------------
@@ -874,11 +391,7 @@ class CDCExtractActivity:
1. Connect to source PG, read all pending WAL changes
2. Decode and batch by table
- 3. For each CDC schema:
- - Flush deferred runs if transitioning from snapshot → streaming
- - Write new events to S3
- - Insert batch notification into the warehouse-sources Postgres queue (streaming)
- or persist into sync_type_config (snapshot)
+ 3. Write each captured table's changes to the S3 change buffer
4. Advance slot position
5. Update cdc_last_log_position per schema
"""
@@ -899,19 +412,8 @@ class CDCExtractActivity:
self.log.warning("cdc_setup_transient_app_db_error", exc_info=True)
raise NonReportableError(str(exc)) from exc
- if self._previous_load_still_pending():
- return
-
- self._mark_schemas_running()
- # Best-effort — must never break the extraction run, so guard the call
- # site: the method itself has unguarded lines (activity.info(),
- # conn.close()) and runs before the main try block below.
- try:
- self._reconcile_orphaned_prior_jobs()
- except Exception:
- self.log.warning("cdc_orphan_reconcile_unexpected_failed", exc_info=True)
-
try:
+ self._prepare_buffer()
self._require_configured_slot()
self._finish_pending_resets()
self.reader.connect()
@@ -935,9 +437,7 @@ class CDCExtractActivity:
self._handle_no_changes(truncated_tables)
return
- self._flush_pending_deferred_runs()
- final_flushed = self._final_flush()
- self._finalize_trackers(final_flushed)
+ self._final_flush()
self._advance_slot_after_run()
self._update_log_positions()
@@ -996,33 +496,6 @@ 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)
- # 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 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_batches_in_flight).
- self._source_buffered = True
- for schema in self.cdc_schemas:
- if schema.sync_type_config.get("cdc_deferred_runs"):
- continue
- if captures_to_buffer(schema) or self._start_snapshot_in_buffer(schema):
- self._buffered_table_names.add(schema.name)
- if self._buffered_table_names:
- self.log.info(
- "cdc_buffered_ingress_active",
- buffered=sorted(self._buffered_table_names),
- legacy=sorted(s.name for s in self.cdc_schemas if s.name not in self._buffered_table_names),
- )
# Guarded like the metric meter: CDC activity bodies are also exercised by direct
# instantiation outside an activity context, where activity.info() raises.
@@ -1032,20 +505,37 @@ class CDCExtractActivity:
self.log.info("cdc_extract_retry_attempt", attempt=attempt)
return True
- def _buffered_snapshot_enabled(self) -> bool:
- if self._buffered_snapshot_flag is None:
- self._buffered_snapshot_flag = is_buffered_snapshot_enabled(self.inputs.team_id, self.log)
- return self._buffered_snapshot_flag
-
- def _start_snapshot_in_buffer(self, schema: ExternalDataSchema) -> bool:
- """Route a snapshotting table the buffer does not carry yet to the buffer, if the flag allows.
+ def _prepare_buffer(self) -> None:
+ """Convert leftover legacy state and start pending snapshots in the buffer, before the WAL read."""
+ assert self.source is not None and self.adapter is not None
+ convert_legacy_cdc_state(
+ self.source,
+ self.cdc_schemas,
+ ingest_mode=self.adapter.parse_cdc_config(self.source).ingest_mode,
+ logger=self.log,
+ )
- Only a table with no deferred runs gets here, so none of its changes since the snapshot began
- went to the legacy lane. Its buffer is emptied first: files left from before a gap in capture,
- such as a re-enable, must not be replayed over the snapshot.
+ for schema in self.cdc_schemas:
+ if not captures_to_buffer(schema):
+ # No lane writes this table mode, so the buffer could never deliver its changes.
+ self._schema_log(schema).warning("cdc_table_mode_not_captured", cdc_table_mode=schema.cdc_table_mode)
+ continue
+ # A table with deferred runs gets no buffered snapshot here: its old sync could still hand over
+ # into that buffer without its deferred changes. The reset the conversion staged restarts the
+ # snapshot instead, and holds the table out of capture until the old sync stops. Once that
+ # reset has run, which can be before this read, the table's changes belong in the buffer.
+ if snapshot_can_start_in_buffer(schema) and not (schema.sync_type_config or {}).get("cdc_deferred_runs"):
+ self._start_snapshot_in_buffer(schema)
+ self._buffered_table_names.add(schema.name)
+ self.log.info("cdc_buffered_ingress_active", buffered=sorted(self._buffered_table_names))
+
+ def _start_snapshot_in_buffer(self, schema: ExternalDataSchema) -> None:
+ """Start carrying a snapshotting table's changes in the buffer.
+
+ Runs before this run reads the WAL, so no change for the table has been captured since its
+ snapshot began. Its buffer is emptied first: files left from before a gap in capture, such as
+ a re-enable, must not be replayed over the snapshot.
"""
- if not (snapshot_can_start_in_buffer(schema) and self._buffered_snapshot_enabled()):
- return False
purge_buffer_prefix(schema.team_id, str(schema.id), self._schema_log(schema), strict=True)
def _mark_if_still_snapshotting(config: dict[str, typing.Any]) -> None:
@@ -1059,7 +549,6 @@ class CDCExtractActivity:
self._schema_log(schema).info(
"cdc_snapshot_started_in_buffer", schema_id=str(schema.id), marked=snapshot_in_buffer(schema)
)
- return True
def _delete_own_schedule(self) -> None:
try:
@@ -1069,127 +558,6 @@ class CDCExtractActivity:
except Exception:
self.log.exception("failed_to_delete_own_schedule")
- def _previous_load_still_pending(self) -> bool:
- """Backpressure guard: skip this tick while a previous run's batches are still loading.
-
- CDC ticks don't hold the per-schema pipeline lock the way external-data-job runs do,
- so without this check every tick enqueues a fresh run regardless of whether the
- previous one landed. Coexisting runs of one schema can then be claimed out of order
- by the loader (its head-of-line gate is run-scoped), and an incremental merge applied
- out of order silently overwrites newer rows with older ones. Skipping keeps at most
- one active run per schema; nothing has been peeked and the slot is untouched, so WAL
- accumulates and the next tick catches up.
-
- Per-source, not per-schema: the slot is read once for all tables, so one table's
- pending load must hold back the whole source's tick.
-
- Deliberately no auto-remediation past CDC_BACKPRESSURE_STUCK_AGE: the slot already
- advanced past the pending runs' events, so failing their batches would leave a
- permanent gap in the table. The queue-freshness alert fires well before the
- threshold, and if nobody intervenes the engine eventually invalidates the slot,
- which triggers the existing full re-sync recovery. Fail-open on probe errors — the
- producer writes to the same DB, so a run that can't be probed can't enqueue either.
- """
- # Buffered schemas enqueue nothing and their loads can't reorder — the scheduled sync runs
- # one job per schema at a time and the position guard backstops it. The guard only remains
- # while some schema still dispatches through sourcebatch.
- legacy_schemas = [s for s in self.cdc_schemas if s.name not in self._buffered_table_names]
- if not legacy_schemas:
- return False
-
- schema_ids = [str(s.id) for s in legacy_schemas]
- try:
- conn = psycopg.Connection.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True)
- except Exception:
- self.log.warning("cdc_backpressure_probe_connect_failed", exc_info=True)
- return False
- try:
- age = BatchQueue.get_oldest_non_terminal_batch_age_seconds(
- conn, team_id=self.inputs.team_id, schema_ids=schema_ids
- )
- except Exception:
- self.log.warning("cdc_backpressure_probe_failed", exc_info=True)
- return False
- finally:
- conn.close()
-
- if age is None:
- return False
-
- stuck = age >= CDC_BACKPRESSURE_STUCK_AGE.total_seconds()
- log = self.log.error if stuck else self.log.info
- log("cdc_tick_skipped_pending_load", oldest_pending_age_seconds=round(age, 1), stuck=stuck)
- metrics.get_tick_skipped_metric(self.inputs.team_id, str(self.inputs.source_id), stuck).add(1)
- return True
-
- def _mark_schemas_running(self) -> None:
- """Mark CDC schemas as Running at the start."""
- for schema in self.cdc_schemas:
- mark_schema_running_unless_halted(schema)
-
- def _reconcile_orphaned_prior_jobs(self) -> None:
- """Finalize this source's prior RUNNING jobs that were stranded mid-run.
-
- A CDC run creates an ExternalDataJob at its first WAL event (RUNNING) and only
- finalizes it on clean completion (the loader, for streaming) or in its own failure
- handler. If an activity attempt dies abruptly — a heartbeat/start-to-close timeout
- or worker eviction — that finalizer never runs and the row is stranded RUNNING; every
- later run leaks another. Nothing in-process can close it, so the next run does.
-
- The schedule's SKIP overlap policy means any prior run (a different workflow_run_id)
- has already ended, so its still-RUNNING rows are safe to close. We only fail rows that
- enqueued NO queue batches: with nothing queued the loader has no outstanding work, so
- failing cannot race a late load. Rows that did enqueue batches are left to the loader,
- which owns their completion. Best-effort — must never break the extraction run.
- """
- current_run_id = activity.info().workflow_run_id
- now = dt.datetime.now(tz=dt.UTC)
- try:
- orphans = list(
- ExternalDataJob.objects.filter(
- team_id=self.inputs.team_id,
- schema_id__in=[s.id for s in self.cdc_schemas],
- status=ExternalDataJob.Status.RUNNING,
- pipeline_version=ExternalDataJob.PipelineVersion.V3,
- created_at__gt=now - CDC_ORPHAN_JOB_MAX_AGE,
- created_at__lt=now - CDC_ORPHAN_JOB_MIN_AGE,
- )
- .exclude(workflow_run_id=current_run_id)
- .order_by("created_at")[:200]
- )
- except Exception:
- self.log.warning("cdc_orphan_reconcile_query_failed", exc_info=True)
- return
-
- if not orphans:
- return
-
- try:
- conn = psycopg.Connection.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True)
- except Exception:
- self.log.warning("cdc_orphan_reconcile_queue_connect_failed", exc_info=True)
- return
-
- reconciled = 0
- try:
- for job in orphans:
- try:
- if BatchQueue.count_batches_for_run(conn, job_id=str(job.id)) > 0:
- # The run enqueued batches; the loader owns their completion — leave it.
- continue
- job.status = ExternalDataJob.Status.FAILED
- job.latest_error = CDC_ORPHANED_JOB_MESSAGE
- job.finished_at = dt.datetime.now(tz=dt.UTC)
- job.save(update_fields=["status", "latest_error", "finished_at", "updated_at"])
- reconciled += 1
- except Exception:
- self.log.warning("cdc_orphan_reconcile_job_failed", job_id=str(job.id), exc_info=True)
- finally:
- conn.close()
-
- if reconciled:
- self.log.info("cdc_orphaned_jobs_reconciled", count=reconciled)
-
# ------------------------------------------------------------------
# PK column loading
# ------------------------------------------------------------------
@@ -1340,20 +708,13 @@ class CDCExtractActivity:
advanced past everything it committed and another pass runs, until the backlog drains,
the soft deadline hits, or (defensively) the limit cap is reached.
- Streaming schemas get Kafka messages immediately after each S3 write. The slot is
- advanced after each successful flush so a long extraction never replays committed
- events on the next run.
+ Each flush writes the buffer before the slot advances past it, so a long extraction never
+ replays committed events on the next run.
"""
assert self._run_started_at is not None
assert self.adapter is not None
event_name_to_schema_name = self._build_event_name_map()
- # Converter only when a lane consumes positions: an all-legacy run must not gain the seq
- # column's per-event cost or its parse/overflow crash surface.
- self.batcher = ChangeEventBatcher(
- position_to_seq=self.adapter.position_to_seq
- if (self._shadow_enabled or self._buffered_table_names)
- else None
- )
+ self.batcher = ChangeEventBatcher(position_to_seq=self.adapter.position_to_seq)
on_row = self._make_read_heartbeat()
limit = CDC_MAX_CHANGES_PER_READ
@@ -1386,7 +747,7 @@ class CDCExtractActivity:
if self.batcher.should_flush:
tables = self.batcher.flush()
self.all_table_names.update(tables.keys())
- self._process_flush(tables, is_final=False)
+ self._process_flush(tables)
metrics.get_micro_batches_flushed_metric(self.inputs.team_id, str(self.inputs.source_id)).add(1)
# Advance only to the end of the last FULLY-yielded transaction, never to
# last_end_lsn: a micro-flush can fire mid-transaction (the batcher
@@ -1398,9 +759,8 @@ class CDCExtractActivity:
# (a) a single giant transaction gets no micro-advance until it
# completes (a retry re-decodes it — safe, slow);
# (b) on crash-replay the already-flushed prefix of the in-flight
- # transaction is re-delivered — incremental_merge dedups by PK,
- # scd2_append may create duplicate history rows. Accepted vs. loss.
- # The buffer lane trims that prefix in cleanup_superseded_files.
+ # transaction is re-read; cleanup_superseded_files trims the files
+ # that held it before the retry writes them again.
if (
self.last_complete_txn_end_lsn is not None
and self.last_complete_txn_end_lsn != self.last_confirmed_lsn
@@ -1408,18 +768,14 @@ class CDCExtractActivity:
self._handle_truncates()
self._confirm_position(self.last_complete_txn_end_lsn)
self.last_confirmed_lsn = self.last_complete_txn_end_lsn
- self.log.info(
- "cdc_micro_batch_flushed",
- events_so_far=self.event_count,
- trackers=len(self.write_trackers),
- )
+ self.log.info("cdc_micro_batch_flushed", events_so_far=self.event_count)
# Capture remaining table names before deciding on the next pass / final flush.
self.all_table_names.update(self.batcher.table_names)
rows_consumed = self.reader.last_rows_consumed
# Drained: the peek returned less than a full page, so the backlog is exhausted.
- # Leave any buffered tail for run()'s _final_flush (is_final=True) + advance.
+ # Leave any buffered tail for run()'s _final_flush + advance.
if rows_consumed < limit:
self._backlog_drained = True
return
@@ -1451,14 +807,14 @@ class CDCExtractActivity:
last_complete_txn_end_lsn as the mid-loop micro-flush does): the peek has stopped at a
transaction boundary, so every event yielded this pass belongs to a committed
transaction and is now flushed. Unmatched-table commits carry the slot forward too —
- their WAL is intentionally dropped. Re-reading instead would re-add already-flushed
- events and duplicate SCD2 history rows.
+ their WAL is intentionally dropped. Re-reading instead would write already-flushed
+ events to the buffer again.
"""
assert self.batcher is not None
if self.batcher.event_count > 0:
tables = self.batcher.flush()
self.all_table_names.update(tables.keys())
- self._process_flush(tables, is_final=False)
+ self._process_flush(tables)
metrics.get_micro_batches_flushed_metric(self.inputs.team_id, str(self.inputs.source_id)).add(1)
commit_lsn = self.reader.last_commit_end_lsn
@@ -1556,7 +912,6 @@ class CDCExtractActivity:
# is merged into, under the row lock, so its own fields survive this one.
self._pause_schema_schedule(schema)
stopping = cancel_running_sync(schema)
- # The queue alone, because deferred runs flush only after a hand-over, which the pause prevents.
if stopping is not None or has_queued_batches(schema):
self._defer_reset(
schema,
@@ -1570,11 +925,10 @@ class CDCExtractActivity:
if self.batcher is not None:
self.batcher.discard(schema.name)
# Purged before the marker is set, because the hand-over keeps every file of a marked schema.
- # On a buffered source a stale file can outlive the run and be replayed, so a failed purge
- # fails the run while the slot still holds the TRUNCATE, and the next run repeats the reset.
- purge_buffer_prefix(schema.team_id, str(schema.id), self._schema_log(schema), strict=self._source_buffered)
+ # A failed purge fails the run while the slot still holds the TRUNCATE, so the next run
+ # repeats the reset.
+ purge_buffer_prefix(schema.team_id, str(schema.id), self._schema_log(schema), strict=True)
removes = ["cdc_last_log_position"]
- updates: dict[str, typing.Any] = {"cdc_mode": "snapshot", "reset_pipeline": True}
# Pending until the schedule is unpaused, so a failed unpause repeats on the next run.
def _merge_pending(config: dict[str, typing.Any]) -> None:
@@ -1582,29 +936,18 @@ class CDCExtractActivity:
if merged["clear_deferred_runs"]:
config.pop("cdc_deferred_runs", None)
- # Later runs write the table's changes to the emptied buffer as an unbroken run, so the next
- # snapshot stays in the buffer with them.
- if schema.name in self._buffered_table_names and (
- snapshot_in_buffer(schema) or self._buffered_snapshot_enabled()
- ):
- updates[CDC_SNAPSHOT_LANE_KEY] = BUFFER_LANE
- else:
- removes.append(CDC_SNAPSHOT_LANE_KEY)
- # The unmarked hand-over purges the buffer, so the rest of this run's changes go to
- # deferred runs, as the next run's will.
- self._buffered_table_names.discard(schema.name)
# reset_pipeline forces the batch import to wipe the table first (handle_reset_or_full_refresh),
- # preventing pre-truncate rows from surviving a TRUNCATE or lost-slot re-snapshot.
+ # preventing pre-truncate rows from surviving a TRUNCATE or lost-slot re-snapshot. Later runs
+ # write the table's changes to the emptied buffer as an unbroken run, so the next snapshot
+ # stays in the buffer with them.
self._update_schema_sync_type_config(
schema,
- updates=updates,
+ updates={"cdc_mode": "snapshot", "reset_pipeline": True, CDC_SNAPSHOT_LANE_KEY: BUFFER_LANE},
removes=removes,
mutate=_merge_pending,
extra_model_fields={"initial_sync_complete": False},
)
self._tables_awaiting_reset.discard(schema.name)
- if schema.sync_type_config[CDC_RESET_PENDING_KEY]["clear_deferred_runs"]:
- self._emit_deferred_runs_depth()
return True
def _defer_reset(
@@ -1761,69 +1104,18 @@ class CDCExtractActivity:
now = dt.datetime.now(tz=dt.UTC)
for schema in self.cdc_schemas:
- if not self._repaint_schema_healthy(schema, now):
- continue
- # Per-schema breadcrumb so the Syncs UI shows _why_ the latest run produced no rows.
- self._schema_log(schema).info(
- "cdc_extract_no_changes",
- truncated_tables=truncated_tables,
- )
+ self._record_healthy_run(schema, now)
self.log.info("no_wal_changes")
self._emit_run_duration("no_changes")
# ------------------------------------------------------------------
# Flush + finalization
# ------------------------------------------------------------------
- def _flush_pending_deferred_runs(self) -> None:
- """Flush deferred runs for schemas that transitioned to streaming."""
- assert self.source is not None
- for schema in self.cdc_schemas:
- if schema.cdc_mode == "streaming" and schema.sync_type_config.get("cdc_deferred_runs"):
- self._flush_deferred_runs(schema)
-
- def _final_flush(self) -> set[str]:
- """Flush remaining buffered events with is_final_batch=True."""
+ def _final_flush(self) -> None:
+ """Flush the events the read loop left in the batcher."""
assert self.batcher is not None
if self.batcher.event_count > 0:
- tables = self.batcher.flush()
- return self._process_flush(tables, is_final=True)
- return set()
-
- def _finalize_trackers(self, final_flushed: set[str]) -> None:
- """Finalize trackers after the read loop has drained.
-
- - Streaming trackers that had no data in the final flush need an
- empty finalization batch so the consumer triggers post-load ops.
- - Snapshot trackers: batch results were already persisted to
- sync_type_config by _store_deferred_batch; write schema file
- and update the deferred entry with the final schema_path.
- """
- for resource_name, tracker in self.write_trackers.items():
- schema = self.schema_by_name[tracker.table_name]
-
- if schema.cdc_mode == "streaming":
- if resource_name not in final_flushed:
- # Write a zero-row parquet so the consumer has a valid s3_path to
- # read. It processes 0 rows (DeltaLake no-op) but still runs
- # post-load ops and marks the job completed.
- empty = pa.table({"_empty": pa.array([], type=pa.int8())})
- finalize_result = tracker.s3_writer.write_batch(empty, batch_index=tracker.batch_index)
- tracker.batch_index += 1
- self._send_batch_notification(tracker, finalize_result, is_final_batch=True)
-
- tracker.job.rows_synced = tracker.total_rows
- tracker.job.save(update_fields=["rows_synced", "updated_at"])
-
- elif schema.cdc_mode == "snapshot":
- # Write schema file and update the deferred entry with final metadata.
- schema_path = tracker.s3_writer.write_schema()
- if schema_path is not None:
- self._persist_deferred_finalization(schema, tracker, schema_path)
-
- tracker.job.rows_synced = tracker.total_rows
- tracker.job.status = ExternalDataJob.Status.COMPLETED
- tracker.job.finished_at = dt.datetime.now(tz=dt.UTC)
- tracker.job.save(update_fields=["rows_synced", "status", "finished_at", "updated_at"])
+ self._process_flush(self.batcher.flush())
def _advance_slot_after_run(self) -> None:
"""Advance the slot past everything this run read, once the final flush has landed.
@@ -1864,14 +1156,6 @@ class CDCExtractActivity:
# ------------------------------------------------------------------
# Failure / success finalization
# ------------------------------------------------------------------
- def _fail_created_jobs(self, error: str) -> None:
- for job in self.created_jobs:
- if job.status == ExternalDataJob.Status.RUNNING:
- job.status = ExternalDataJob.Status.FAILED
- job.latest_error = error
- job.finished_at = dt.datetime.now(tz=dt.UTC)
- job.save(update_fields=["status", "latest_error", "finished_at", "updated_at"])
-
def _recover_from_slot_invalidation(self, exc: Exception) -> None:
"""The slot can't be resumed (invalidated or dropped on the source DB): recreate it
and reset every CDC schema to snapshot mode so it re-syncs from current table state.
@@ -1884,13 +1168,9 @@ class CDCExtractActivity:
assert self.adapter is not None
self.log.warning("cdc_slot_unrecoverable_recreating", error=str(exc))
- self._fail_created_jobs(SLOT_INVALIDATION_RECOVERY_MESSAGE)
-
# Reset schemas before touching the slot (schedules stay paused): if recreation
# fails below, the next run hits the invalidation again and recovery reruns
- # idempotently — no schema keeps streaming across the gap unnoticed. Deferred
- # runs are dropped: they reference WAL from the dead slot, the re-snapshot
- # supersedes them, and flushing them later would merge stale rows over fresh ones. A schema
+ # idempotently — no schema keeps streaming across the gap unnoticed. A schema
# whose sync is still stopping keeps its reset pending, and a later run finishes it. Every
# reset here waits on the slot, so a recreation that fails below cannot leave a later run
# free to start a snapshot before capture has a point to resume from.
@@ -1944,7 +1224,6 @@ class CDCExtractActivity:
close_old_connections()
info = classify_cdc_error(exc, self.adapter)
friendly = info.friendly_message[:MAX_FRIENDLY_MESSAGE_LENGTH]
- self._fail_created_jobs(friendly)
# A missing slot/publication won't recover on retry: mark the source broken — that persists
# the per-schema FAILED state + the cdc_broken marker the UI/health check read and pauses the
# schedule, so it stops firing hourly against a resource that is gone (the same zombie the lag
@@ -1963,8 +1242,13 @@ class CDCExtractActivity:
# A non-retryable error re-fails every scheduled run, so pause the schedule instead of
# looping it. No cdc_broken marker: the slot is intact, so it stays Repair-CDC-ineligible.
self._pause_cdc_extraction_schedule()
+ # Outside an activity nothing retries, so every failure there is terminal.
+ retries_left = activity.in_activity() and activity.info().attempt < CDC_MAX_EXTRACTION_ATTEMPTS
+ terminal = not info.retryable or not retries_left
for schema in self.cdc_schemas:
- if not marked_broken:
+ # Only a terminal failure paints the schema. A later successful attempt never repaints it,
+ # because its status belongs to the scheduled sync that consumes the buffer.
+ if terminal and not marked_broken:
schema.status = ExternalDataSchema.Status.FAILED
schema.latest_error = friendly
schema.save(update_fields=["status", "latest_error", "updated_at"])
@@ -1985,11 +1269,10 @@ class CDCExtractActivity:
self._schema_log(schema).error(
"cdc_extract_schema_failed", error=str(exc), category=info.category, retryable=info.retryable
)
- terminal = not info.retryable or activity.info().attempt >= CDC_MAX_EXTRACTION_ATTEMPTS
- # A failure before the first micro-flush creates no ExternalDataJob, so the Syncs tab stays
- # empty while the schema reads FAILED. Backfill a terminal FAILED row per job-less schema so
- # the run is visible — but only once retries are exhausted or the error is non-retryable,
- # otherwise every transient retry would leave a stray failed row.
+ # Capture creates no ExternalDataJob of its own, so the Syncs tab would stay empty while the
+ # schema reads FAILED. Write a terminal FAILED row per schema so the run is visible — but only
+ # once retries are exhausted or the error is non-retryable, otherwise every transient retry
+ # would leave a stray failed row.
if terminal:
try:
self._create_failure_visibility_jobs(friendly)
@@ -2066,21 +1349,18 @@ class CDCExtractActivity:
self.log.warning("cdc_unclassified_capture_failed", exc_info=True)
def _create_failure_visibility_jobs(self, friendly_error: str) -> None:
- """Create one terminal FAILED ExternalDataJob per job-less CDC schema for this run.
+ """Create one terminal FAILED ExternalDataJob per CDC schema for this run.
- Mirrors the running-job creation in _get_or_create_tracker (workflow ids, V3, snapshot) so
- the Syncs tab renders these the same way as a job that failed after it started writing.
- Schemas whose job already exists this run (failed by _fail_created_jobs) are skipped, as are
- schemas still inside the cooldown for this same failure (see _schemas_in_failure_cooldown).
+ Schemas still inside the cooldown for this same failure are skipped (see
+ _schemas_in_failure_cooldown).
"""
now = dt.datetime.now(tz=dt.UTC)
activity_info = activity.info()
- schema_ids_with_jobs = {job.schema_id for job in self.created_jobs}
in_cooldown = self._schemas_in_failure_cooldown(friendly_error, now)
if in_cooldown:
self.log.info("cdc_failure_visibility_jobs_suppressed", schemas=len(in_cooldown))
for schema in self.cdc_schemas:
- if schema.id in schema_ids_with_jobs or schema.id in in_cooldown:
+ if schema.id in in_cooldown:
continue
ExternalDataJob.objects.create(
team_id=self.inputs.team_id,
@@ -2097,15 +1377,14 @@ class CDCExtractActivity:
)
def _schemas_in_failure_cooldown(self, friendly_error: str, now: dt.datetime) -> set[uuid.UUID]:
- """Schemas whose most recent extraction job already reports this exact failure, within the
- cooldown.
-
- Only the newest extraction job in the window counts: anything that happened since — a
- successful run, a different error, a run that synced rows before failing — is news, so the
- schema falls out of the cooldown and gets its row. Rows from other workflows are ignored: a
- schema still snapshotting runs the regular per-schema pipeline alongside change capture, and
- those runs say nothing about whether this failure has already been reported. One query for
- the whole source; the window keeps it small.
+ """Schemas whose most recent capture failure row already reports this exact failure, within
+ the cooldown.
+
+ Only the newest capture row in the window counts, so a different error gets its own row.
+ Capture writes no row for a successful run, so the same failure recurring after one stays
+ suppressed until the window ends. Rows from other workflows are ignored: they come from each
+ table's scheduled sync, which says nothing about whether this failure has already been
+ reported. One query for the whole source; the window keeps it small.
"""
recent_jobs = (
ExternalDataJob.objects.filter(
@@ -2115,7 +1394,7 @@ class CDCExtractActivity:
workflow_id__startswith=CDC_EXTRACTION_WORKFLOW_ID_PREFIX,
)
.order_by("schema_id", "-created_at")
- .values("schema_id", "status", "latest_error", "rows_synced")
+ .values("schema_id", "status", "latest_error")
)
in_cooldown: set[uuid.UUID] = set()
@@ -2125,11 +1404,7 @@ class CDCExtractActivity:
if schema_id in seen:
continue
seen.add(schema_id)
- if (
- job["status"] == ExternalDataJob.Status.FAILED
- and job["latest_error"] == friendly_error
- and not job["rows_synced"]
- ):
+ if job["status"] == ExternalDataJob.Status.FAILED and job["latest_error"] == friendly_error:
in_cooldown.add(schema_id)
return in_cooldown
@@ -2144,41 +1419,26 @@ class CDCExtractActivity:
updates={"cdc_last_run_at": run_at.isoformat(), "cdc_last_run_event_count": self.event_count},
)
- def _repaint_schema_healthy(self, schema: ExternalDataSchema, now: dt.datetime) -> bool:
- """Mark a schema COMPLETED after a successful run, respecting the absorbing broken state.
+ def _record_healthy_run(self, schema: ExternalDataSchema, now: dt.datetime) -> None:
+ """Record that extraction ran for this schema, without touching its status.
- The marker check and the repaint run in one locked transaction (complete_schema_run) —
- checking here on the in-memory copy would race the sweeper marking the source broken and
- overwrite its FAILED with a stale COMPLETED. Returns whether the repaint happened.
+ The schema's status belongs to the scheduled sync that consumes its buffer. Repainting it
+ here would erase a failing consumer run within one capture tick, hiding a buffer backlog
+ until its files hit the S3 TTL, which is unrecoverable.
"""
try:
- # The heartbeat records liveness (this run happened), independent of health.
self._record_run_heartbeat(schema, now)
- # A buffered schema's status belongs to the scheduled sync that consumes its files.
- # Repainting COMPLETED here would erase a failing consumer run within one capture tick,
- # hiding a buffer backlog until its files hit the S3 TTL — which is unrecoverable.
- if schema.name in self._buffered_table_names:
- # A completed tick proves extraction runs again. The consumer cannot clear this
- # marker: its job completions are absorbed while the marker holds.
- if (schema.sync_type_config or {}).get("cdc_extraction_paused"):
- self._update_schema_sync_type_config(schema, removes=["cdc_extraction_paused"])
- return False
- if not complete_schema_run(schema, last_synced_at=now):
- self._schema_log(schema).info("cdc_success_repaint_skipped_broken")
- return False
+ # A completed tick proves extraction runs again. The consumer cannot clear this marker:
+ # its job completions are absorbed while the marker holds.
+ if (schema.sync_type_config or {}).get("cdc_extraction_paused"):
+ self._update_schema_sync_type_config(schema, removes=["cdc_extraction_paused"])
except ExternalDataSchema.DoesNotExist:
- return False
- return True
+ pass
def _finalize_success(self) -> None:
now = dt.datetime.now(tz=dt.UTC)
- synced_tables = {tracker.table_name for tracker in self.write_trackers.values()}
for schema in self.cdc_schemas:
- if not self._repaint_schema_healthy(schema, now):
- continue
- # Breadcrumb for idle tables; _handle_no_changes only covers the whole-source-quiet case.
- if schema.name not in synced_tables:
- self._schema_log(schema).info("cdc_extract_no_changes")
+ self._record_healthy_run(schema, now)
self._emit_run_duration("completed")
@@ -2292,9 +1552,9 @@ def cleanup_orphan_slots_activity() -> None:
metrics.get_sweeper_source_errors_metric().add(1)
sources_errored += 1
- # Shadow-buffer prefixes: destroy() defers all external reaping to this
- # sweep, so without this the raw change files outlive the source until
- # a lifecycle rule exists. Idempotent — a purged prefix is a no-op.
+ # Buffer prefixes: destroy() defers all external reaping to this sweep, so
+ # without this the change files outlive the source until the lifecycle rule
+ # expires them. Idempotent — a purged prefix is a no-op.
for schema_id in ExternalDataSchema.objects.filter(
source=source, sync_type=ExternalDataSchema.SyncType.CDC
).values_list("id", flat=True):
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 a3a1b1ca51c5..ce0c881c2486 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/batcher.py
@@ -23,8 +23,7 @@ CDC_SEQ_COLUMN = "_ph_cdc_seq"
# name (see the collision skip in _events_to_table).
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.
+# Suffix of the SCD2 companion table's resource name ({schema.name}_cdc).
CDC_COMPANION_SUFFIX = "_cdc"
@@ -412,33 +411,6 @@ def enrich_toast_omitted_rows(
return pa.table(new_columns, schema=pa.schema(new_fields))
-def deduplicate_table(pa_table: pa.Table, pk_columns: list[str]) -> pa.Table:
- """Keep only the last row per primary key in a CDC batch.
-
- Rows are assumed to be in WAL order (oldest first). For each unique PK tuple
- the last (most recent) row survives. If pk_columns is empty or none of the PK
- columns are present in the table, the original table is returned unchanged.
- """
- if not pk_columns or pa_table.num_rows == 0:
- return pa_table
-
- present_pks = [col for col in pk_columns if col in pa_table.column_names]
- if not present_pks:
- return pa_table
-
- pk_arrays = [pa_table.column(col).to_pylist() for col in present_pks]
-
- # Track the last row index seen for each PK tuple
- pk_to_last_idx: dict[tuple, int] = {}
- for i in range(pa_table.num_rows):
- key = tuple(arr[i] for arr in pk_arrays)
- pk_to_last_idx[key] = i
-
- # Preserve original row ordering
- indices = sorted(pk_to_last_idx.values())
- return pa_table.take(indices)
-
-
def build_scd2_table(pa_table: pa.Table, pk_columns: list[str]) -> pa.Table:
"""Add SCD Type 2 columns (valid_from, valid_to) to a raw CDC event table.
@@ -461,8 +433,7 @@ def build_scd2_table(pa_table: pa.Table, pk_columns: list[str]) -> pa.Table:
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.
+ # and declaring a type it does not have makes pyarrow reject the append outright.
ts_type = (
pa_table.schema.field(CDC_TIMESTAMP_COLUMN).type
if CDC_TIMESTAMP_COLUMN in pa_table.column_names
@@ -584,9 +555,8 @@ def _events_to_table(events: list[ChangeEvent], position_to_seq: Callable[[str],
arrays.append(pa.array(omitted_lists, type=pa.list_(pa.string())))
fields.append(pa.field(TOAST_OMITTED_COLUMN, pa.list_(pa.string())))
- # Skip on collision: a source column literally named _ph_cdc_seq must pass
- # through to the legacy lane untouched. The batch then carries no engine seq
- # and the shadow writer skips it.
+ # Skip on collision: a source column literally named _ph_cdc_seq is never overwritten. The batch
+ # then carries no engine seq, and capture refuses to write it to the buffer.
if position_to_seq is not None and CDC_SEQ_COLUMN not in column_names:
seq_values = [position_to_seq(event.position_serialized) for event in events]
arrays.append(pa.array(seq_values, type=pa.int64()))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py
index ab4c3604286c..17e7141e4a8c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py
@@ -24,10 +24,7 @@ that straddles that position first has its settled rows rewritten under a narrow
range. A schema reset (TRUNCATE / lost slot) invalidates the whole prefix —
`purge_buffer_prefix`.
-Two lanes write here. Shadow (the `dwh-cdc-buffer-shadow` feature flag, per team,
-evaluated once per extraction run and fail-closed) writes a validation copy while
-legacy delivery stays authoritative. Buffered ingress (`cdc_ingest_mode="buffered"`
-in the source's `job_inputs`) writes the same files as the ONLY delivery — the
+Capture writes these files as the only delivery of a table's changes: the table's
scheduled sync consumes them, and a write failure fails the run rather than being
swallowed, because the slot is about to advance past those changes.
@@ -56,7 +53,6 @@ from posthog.dataclasses import frozen
from products.data_warehouse.backend.facade.api import get_s3_client
from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN
-from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import team_flag_enabled
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common import (
ensure_bucket,
strip_s3_protocol,
@@ -66,10 +62,6 @@ BUFFER_ROOT_FOLDER = "cdc_producer"
# How long the lifecycle rule in the module docstring keeps a buffer file after it is written.
BUFFER_FILE_RETENTION = dt.timedelta(days=14)
-# Per-team gate for the shadow lane — the single on/off control. Fail-closed on
-# evaluation errors, so the soak can only ever shrink, never grow, by accident.
-SHADOW_WRITE_FLAG = "dwh-cdc-buffer-shadow"
-
_SEQ_WIDTH = 20 # zero-pad width covering the full u64 range
_INDEX_WIDTH = 6
@@ -81,15 +73,6 @@ _FILE_NAME_RE = re.compile(rf"([0-9]{{{_SEQ_WIDTH}}})-([0-9]{{{_SEQ_WIDTH}}})-([
_STAGING_SUFFIX = ".staging"
-def is_shadow_write_enabled(team_id: int, logger: FilteringBoundLogger) -> bool:
- """Whether the shadow lane may write for this team, evaluated once per run.
-
- Never raises: a flag-service failure leaves the lane off, which costs a gap in
- validation data — the legacy path is unaffected either way.
- """
- return team_flag_enabled(SHADOW_WRITE_FLAG, team_id, logger)
-
-
def get_buffer_prefix(team_id: int, schema_id: str) -> str:
return f"s3://{settings.DATAWAREHOUSE_BUCKET}/{BUFFER_ROOT_FOLDER}/{team_id}/{schema_id}"
@@ -311,11 +294,11 @@ class CDCBufferWriter:
def purge_buffer_prefix(team_id: int, schema_id: str, logger: FilteringBoundLogger, *, strict: bool = False) -> None:
"""Remove a schema's entire buffer prefix.
- Called when a table is emptied for a new snapshot (TRUNCATE, lost slot, repair), and at the
- snapshot→streaming flip when the snapshot's changes went to legacy deferred runs: there every
- buffer file predates a gap no consumer could order across. Best-effort by default; `strict`
- propagates failures (except a missing prefix) for callers where a survived stale file would
- corrupt the table.
+ Called when a table is emptied for a new snapshot (TRUNCATE, lost slot, repair), when capture
+ starts a snapshot in the buffer, and at the snapshot→streaming flip of a snapshot capture never
+ started there: every buffer file then predates a gap no consumer could order across.
+ Best-effort by default; `strict` propagates failures (except a missing prefix) for callers where
+ a survived stale file would corrupt the table.
"""
prefix = strip_s3_protocol(get_buffer_prefix(team_id, schema_id))
try:
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 089c1fc436d0..7f620a8dac46 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py
@@ -36,7 +36,6 @@ class CDCErrorCategory(enum.StrEnum):
PERMISSION_DENIED = "permission_denied"
WAL_DECODE_ERROR = "wal_decode_error"
TRANSACTION_TOO_LARGE = "transaction_too_large"
- SCHEMA_MERGE_INCOMPATIBLE = "schema_merge_incompatible"
RESERVED_COLUMN_CONFLICT = "reserved_column_conflict"
UNKNOWN = "unknown"
@@ -73,11 +72,10 @@ class CDCReservedColumnError(Exception):
Non-retryable: the collision is a property of the customer's table, so replaying re-fails.
- 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 engine position column it is raised when capture writes the buffer — 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.
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
@@ -85,16 +83,6 @@ class CDCReservedColumnError(Exception):
"""
-class CDCSchemaMergeError(Exception):
- """A column's values can't be reconciled into one Parquet type across micro-batches.
-
- Non-retryable: the conflicting batches replay identically, so re-running re-fails. The
- activity raises this when an Arrow schema merge rejects the data (e.g. a source column
- that genuinely changed type mid-stream — int in one batch, text in another). Defined
- here so the shared classifier owns the mapping to ``SCHEMA_MERGE_INCOMPATIBLE``.
- """
-
-
# (friendly_message, retryable) per category. Messages are STATIC templates — they never
# interpolate host/user/password or raw exception text, so stored copy can't leak credentials.
_CATEGORY_DEFAULTS: dict[CDCErrorCategory, tuple[str, bool]] = {
@@ -171,12 +159,6 @@ _CATEGORY_DEFAULTS: dict[CDCErrorCategory, tuple[str, bool]] = {
"once. Reduce the size of bulk operations on the source, then re-sync.",
False,
),
- CDCErrorCategory.SCHEMA_MERGE_INCOMPATIBLE: (
- "A source column changed type partway through the change stream (for example, numbers and text "
- "in the same column), so the changes can no longer be combined into one table. Disable and "
- "re-enable change data capture to re-sync from a fresh snapshot.",
- False,
- ),
CDCErrorCategory.RESERVED_COLUMN_CONFLICT: (
"A source table has a column named _ph_cdc_seq, which PostHog uses for change data capture. "
"Rename the column on your database, or choose another sync method for that table.",
@@ -218,8 +200,6 @@ def classify_cdc_error(exc: BaseException, adapter: CDCSourceAdapter | None) ->
return cdc_error_info(CDCErrorCategory.SLOT_NOT_CONFIGURED)
if isinstance(err, CDCTransactionTooLargeError):
return cdc_error_info(CDCErrorCategory.TRANSACTION_TOO_LARGE)
- if isinstance(err, CDCSchemaMergeError):
- return cdc_error_info(CDCErrorCategory.SCHEMA_MERGE_INCOMPATIBLE)
if isinstance(err, CDCReservedColumnError):
return cdc_error_info(CDCErrorCategory.RESERVED_COLUMN_CONFLICT)
if adapter is not None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/legacy_conversion.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/legacy_conversion.py
new file mode 100644
index 000000000000..09cdb89db066
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/legacy_conversion.py
@@ -0,0 +1,229 @@
+"""One-time conversion of the state the retired legacy CDC lane left behind.
+
+The legacy lane delivered some tables' changes from capture itself. It paused each such table's
+schedule while it streamed, held a snapshotting table's changes as deferred runs in
+`sync_type_config`, marked its source `cdc_ingest_mode: legacy`, and created job rows of its own.
+Capture now only writes the S3 buffer, so it runs this before every read. Each step finds nothing
+once the state it converts is gone, so this module can go once no source logs a conversion.
+
+Every step that can fail raises before capture reads the WAL, so a failed conversion retries on the
+next run with nothing written to the buffer in between.
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+from collections.abc import Sequence
+from typing import Any
+
+from django.db import transaction
+
+import psycopg
+from structlog.types import FilteringBoundLogger
+
+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,
+ 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.buffer import purge_buffer_prefix
+from products.warehouse_sources.backend.temporal.data_imports.cdc.naming import CDC_EXTRACTION_WORKFLOW_ID_PREFIX
+from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import (
+ CDC_RESET_PENDING_KEY,
+ stage_handed_over_reset,
+)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import LEGACY_CONVERTED_AT_KEY
+from products.warehouse_sources.backend.temporal.data_imports.cdc.types import IngestMode, decode_job_inputs
+from products.warehouse_sources_queue.backend.sdk import BatchQueue
+
+# Shown as latest_error on the capture job rows `_close_stranded_capture_jobs` fails.
+STRANDED_CAPTURE_JOB_MESSAGE = (
+ "CDC run ended without finalizing this job (worker timeout or eviction). It was superseded by a "
+ "later run; no data was lost — change capture resumes from the last confirmed replication position."
+)
+# A healthy capture run queued its first batch within seconds, so a batch-less row older than this is
+# abandoned, and one younger may still belong to a run that is finishing.
+_STRANDED_JOB_MIN_AGE = dt.timedelta(minutes=30)
+# Batches are pruned from the queue after 14 days, so "no batches" is only trustworthy inside that
+# window. Older rows stay as they are, because an abandoned run looks the same as one whose batches aged out.
+_STRANDED_JOB_MAX_AGE = dt.timedelta(days=14)
+
+
+def convert_legacy_cdc_state(
+ source: ExternalDataSource,
+ schemas: Sequence[ExternalDataSchema],
+ *,
+ ingest_mode: IngestMode,
+ logger: FilteringBoundLogger,
+) -> None:
+ """Convert whatever legacy state this source still carries. Raises on a failure that must retry."""
+ # Staged first, so a legacy source's schedule rebuild below leaves these tables to their reset.
+ for schema in schemas:
+ if (schema.sync_type_config or {}).get("cdc_deferred_runs"):
+ _hand_deferred_runs_to_reset(schema, logger)
+ if ingest_mode != "buffered":
+ _convert_legacy_source(source, schemas, logger)
+ try:
+ _close_stranded_capture_jobs(source, schemas, logger)
+ except Exception:
+ # Cosmetic: a stranded row only misreports a run that already ended.
+ logger.warning("cdc_stranded_capture_jobs_close_failed", exc_info=True)
+
+
+def _hand_deferred_runs_to_reset(schema: ExternalDataSchema, logger: FilteringBoundLogger) -> None:
+ """Stage a reset for a table the legacy lane still held deferred runs for, which capture then finishes.
+
+ Nothing merges deferred runs anymore, so the table snapshots again in the buffer. The reset waits
+ until the old sync can no longer hand over, because one that hands over after it would flip the
+ table to streaming without those changes. It drops the deferred runs and starts the new snapshot.
+ Staging again while it waits is harmless: the reset merges into the one already pending.
+ """
+ deferred_runs = len(schema.sync_type_config.get("cdc_deferred_runs") or [])
+ schema.sync_type_config = update_sync_type_config_keys(schema.id, schema.team_id, mutate=stage_handed_over_reset)
+ logger.info("cdc_legacy_deferred_runs_handed_to_reset", schema_id=str(schema.id), deferred_runs=deferred_runs)
+
+
+def _convert_legacy_source(
+ source: ExternalDataSource, schemas: Sequence[ExternalDataSchema], logger: FilteringBoundLogger
+) -> None:
+ """Move a source whose changes the legacy lane still delivered onto the buffer.
+
+ Its buffer holds only copies of changes the legacy lane already delivered, so it is emptied
+ before capture writes the first file. What capture reads next continues from the slot's
+ position, which legacy delivery already reached, so each table is current as of now, and is
+ stamped so that its first sync reads the buffer instead of taking it for expired. The legacy lane
+ paused the schedule of every streaming table because capture delivered its changes. That schedule
+ is now the table's consumer, so it is rebuilt. Legacy batches still in the load queue land first,
+ because the consumer stands down while any are in flight.
+ """
+ # See `_resume_schedule` for why this import is deferred.
+ from products.data_warehouse.backend.facade.api import cdc_min_interval # noqa: PLC0415
+
+ all_cdc_schema_ids = list(
+ ExternalDataSchema.objects.filter(
+ team_id=source.team_id, source_id=source.id, sync_type=ExternalDataSchema.SyncType.CDC
+ )
+ .exclude(deleted=True)
+ .values_list("id", flat=True)
+ )
+ for schema_id in all_cdc_schema_ids:
+ purge_buffer_prefix(source.team_id, str(schema_id), logger, strict=True)
+ converted_at = dt.datetime.now(dt.UTC).isoformat()
+ for schema_id in all_cdc_schema_ids:
+ update_sync_type_config_keys(schema_id, source.team_id, updates={LEGACY_CONVERTED_AT_KEY: converted_at})
+
+ capture_interval = cdc_min_interval(schema.sync_frequency_interval for schema in schemas)
+ for schema in schemas:
+ _keep_capture_cadence(schema, capture_interval, logger)
+ _resume_schedule(schema)
+
+ # Written last, so a failure above repeats the whole conversion. A repeat is safe because the run
+ # fails before it reads the WAL, so the buffer has gained nothing a second purge would drop.
+ source.job_inputs = _mark_source_buffered(source)
+ logger.info("cdc_legacy_source_converted", schemas=len(all_cdc_schema_ids))
+
+
+def _keep_capture_cadence(
+ schema: ExternalDataSchema, capture_interval: dt.timedelta, logger: FilteringBoundLogger
+) -> None:
+ """Speed a table up to capture's cadence, which is how often the legacy lane delivered its changes.
+
+ Its own schedule loads it from now on, so a table set slower than its source's fastest table would
+ otherwise fall behind by the difference.
+ """
+ if schema.sync_frequency_interval is None or schema.sync_frequency_interval <= capture_interval:
+ return
+ logger.info(
+ "cdc_legacy_table_frequency_raised",
+ schema_id=str(schema.id),
+ from_seconds=schema.sync_frequency_interval.total_seconds(),
+ to_seconds=capture_interval.total_seconds(),
+ )
+ ExternalDataSchema.objects.filter(id=schema.id, team_id=schema.team_id).update(
+ sync_frequency_interval=capture_interval, updated_at=dt.datetime.now(dt.UTC)
+ )
+ schema.sync_frequency_interval = capture_interval
+
+
+def _mark_source_buffered(source: ExternalDataSource) -> dict[str, Any]:
+ """Mark the source buffered on its current row, so a concurrent edit to its settings survives.
+
+ A queryset update, not `source.save()`, whose activity-log diff walks the source's whole job history.
+ """
+ with transaction.atomic():
+ locked = ExternalDataSource.objects.select_for_update(of=("self",)).get(id=source.id, team_id=source.team_id)
+ job_inputs = {**decode_job_inputs(locked.job_inputs), "cdc_ingest_mode": "buffered"}
+ ExternalDataSource.objects.filter(id=source.id, team_id=source.team_id).update(
+ job_inputs=job_inputs, updated_at=dt.datetime.now(dt.UTC)
+ )
+ return job_inputs
+
+
+def _resume_schedule(schema: ExternalDataSchema) -> None:
+ """Rebuild the table's schedule unpaused, and create it if it is missing.
+
+ A plain unpause does nothing to a missing schedule. Skipped where the pause is deliberate: a
+ schema whose status is Paused, an admin-triggered run that holds the schedule until it finishes,
+ a broken source that waits for Repair CDC, which unpauses it, and a pending reset, which unpauses
+ it once it has reset the table. A capture pause is not checked, because capture is running, so
+ that pause is over. A schema with no sync frequency is skipped because the schedule builder cannot
+ turn a null interval into a cadence.
+ """
+ # data_load.service imports temporalio at module scope; deferred to keep the Temporal client off
+ # this module's import path, as capture's other schedule calls do.
+ from products.data_warehouse.backend.facade.api import sync_external_data_job_workflow # noqa: PLC0415
+
+ config = schema.sync_type_config or {}
+ if (
+ schema.status == ExternalDataSchema.Status.PAUSED
+ or config.get("cdc_broken")
+ or config.get("admin_unpause_schedule_after_run")
+ or config.get(CDC_RESET_PENDING_KEY)
+ or schema.sync_frequency_interval is None
+ ):
+ return
+ sync_external_data_job_workflow(schema, create=True, should_sync=True, trigger_immediately=False)
+
+
+def _close_stranded_capture_jobs(
+ source: ExternalDataSource, schemas: Sequence[ExternalDataSchema], logger: FilteringBoundLogger
+) -> None:
+ """Fail RUNNING job rows the legacy lane's capture runs left behind.
+
+ Legacy capture created one per written table and closed it when the run finished. A run that died
+ mid-way left its row RUNNING. A row with batches in the queue belongs to the loader, which closes
+ it. A row without any has no outstanding work, so failing it cannot race a late load. Scoped to
+ capture's own workflow ids, so a table's scheduled sync is never touched.
+ """
+ now = dt.datetime.now(tz=dt.UTC)
+ stranded = list(
+ ExternalDataJob.objects.filter(
+ team_id=source.team_id,
+ schema_id__in=[s.id for s in schemas],
+ status=ExternalDataJob.Status.RUNNING,
+ workflow_id__startswith=CDC_EXTRACTION_WORKFLOW_ID_PREFIX,
+ created_at__gt=now - _STRANDED_JOB_MAX_AGE,
+ created_at__lt=now - _STRANDED_JOB_MIN_AGE,
+ ).order_by("created_at")[:200]
+ )
+ if not stranded:
+ return
+
+ closed = 0
+ conn = psycopg.Connection.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True)
+ try:
+ for job in stranded:
+ if BatchQueue.count_batches_for_run(conn, job_id=str(job.id)) > 0:
+ continue
+ job.status = ExternalDataJob.Status.FAILED
+ job.latest_error = STRANDED_CAPTURE_JOB_MESSAGE
+ job.finished_at = now
+ job.save(update_fields=["status", "latest_error", "finished_at", "updated_at"])
+ closed += 1
+ finally:
+ conn.close()
+ if closed:
+ logger.info("cdc_stranded_capture_jobs_closed", count=closed)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.py
index 3c40bd3a36ce..6935256a7124 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/metrics.py
@@ -43,11 +43,14 @@ def get_micro_batches_flushed_metric(team_id: int, source_id: str) -> MetricCoun
)
-def get_buffer_files_written_metric(team_id: int, source_id: str, lane: str) -> MetricCounter:
- """`lane` is "shadow" (validation copy) or "ingress" (authoritative delivery)."""
+# Every buffer write is authoritative delivery. The label keeps the value dashboards already filter on.
+_BUFFER_LANE_LABEL = {"lane": "ingress"}
+
+
+def get_buffer_files_written_metric(team_id: int, source_id: str) -> MetricCounter:
return (
_source_meter(team_id, source_id)
- .with_additional_attributes({"lane": lane})
+ .with_additional_attributes(_BUFFER_LANE_LABEL)
.create_counter("cdc_buffer_files_written_total", "Total buffer files written, by lane")
)
@@ -64,16 +67,10 @@ def get_extract_retry_metric(team_id: int, source_id: str) -> MetricCounter:
)
-def get_shadow_buffer_write_errors_metric(team_id: int, source_id: str) -> MetricCounter:
- return _source_meter(team_id, source_id).create_counter(
- "cdc_shadow_buffer_write_errors_total", "Total swallowed shadow buffer write failures"
- )
-
-
-def get_buffer_write_duration_metric(team_id: int, source_id: str, lane: str) -> MetricHistogramFloat:
+def get_buffer_write_duration_metric(team_id: int, source_id: str) -> MetricHistogramFloat:
return (
_source_meter(team_id, source_id)
- .with_additional_attributes({"lane": lane})
+ .with_additional_attributes(_BUFFER_LANE_LABEL)
.create_histogram_float("cdc_buffer_write_duration_seconds", "Duration of buffer S3 writes, by lane", "s")
)
@@ -86,17 +83,6 @@ def get_extraction_duration_metric(team_id: int, source_id: str, status: str) ->
)
-def get_tick_skipped_metric(team_id: int, source_id: str, stuck: bool) -> MetricCounter:
- return (
- _meter()
- .with_additional_attributes({"team_id": str(team_id), "source_id": source_id, "stuck": str(stuck).lower()})
- .create_counter(
- "cdc_ticks_skipped_pending_load_total",
- "Total extraction ticks skipped because a previous run's batches are still loading",
- )
- )
-
-
def get_slot_advance_metric(team_id: int, source_id: str) -> MetricCounter:
return _source_meter(team_id, source_id).create_counter("cdc_slot_advance_total", "Total replication slot advances")
@@ -107,17 +93,6 @@ def get_slot_advance_failures_metric(team_id: int, source_id: str) -> MetricCoun
)
-def get_deferred_runs_depth_metric(team_id: int, source_id: str) -> MetricGauge:
- return _source_meter(team_id, source_id).create_gauge(
- "cdc_deferred_runs_depth", "Deferred CDC runs awaiting the snapshot→streaming flush"
- )
-
-
-# ---------------------------------------------------------------------------
-# Orphan-slot sweeper
-# ---------------------------------------------------------------------------
-
-
def get_wal_lag_metric(team_id: int, source_id: str) -> MetricGauge:
return _source_meter(team_id, source_id).create_gauge("cdc_wal_lag_bytes", "Replication slot WAL lag", "By")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
index 7948db39e52d..c80642f8f462 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
@@ -130,9 +130,9 @@ def _repair_locked(source: ExternalDataSource) -> int:
# Reset schemas before touching the slot (same ordering as the extraction activity's
# slot-invalidation recovery): if recreation fails below, a re-run repeats idempotently
- # and no schema keeps streaming across the gap unnoticed. Deferred runs are dropped —
- # they reference WAL from the dead slot and the re-snapshot supersedes them. The
- # `cdc_broken` markers deliberately survive this step: they are the retry gate.
+ # and no schema keeps streaming across the gap unnoticed. Deferred runs left by the retired
+ # legacy lane are dropped: the re-snapshot supersedes them. The `cdc_broken` markers
+ # deliberately survive this step: they are the retry gate.
for schema_id in all_cdc_schema_ids:
if schema_id in handed_over:
continue
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/snapshot_lane.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/snapshot_lane.py
index 8aed20414461..9d2a7b6294d2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/snapshot_lane.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/snapshot_lane.py
@@ -1,14 +1,12 @@
-"""Which lane carries a CDC table's changes while it takes a snapshot on a buffered source.
+"""Whether the S3 change buffer carries a CDC table's snapshot.
-The buffer can carry them only when it holds every change since the table's buffer was last
+The buffer carries a snapshot when it holds every change since the table's buffer was last
emptied. Replaying an unbroken run of changes over the snapshot, in order, converges on the
source's state even when some of them predate the snapshot, so the hand-over deletes nothing. A
gap breaks that: an older change replayed without the ones after it leaves a stale row.
-A marker on the schema records that the buffer carries the current snapshot. Routing and the
-hand-over read the marker, never the flag, so one snapshot never splits between the buffer and
-legacy deferred runs when the flag flips or its evaluation fails. Kept free of the pipeline
-imports, so the schema API can call it.
+A marker on the schema records that the buffer carries the current snapshot, and the hand-over
+reads it. Kept free of the pipeline imports, so the schema API can call it.
"""
from __future__ import annotations
@@ -16,8 +14,6 @@ from __future__ import annotations
from functools import partial
from typing import TYPE_CHECKING, Any
-import posthoganalytics
-from structlog.types import FilteringBoundLogger
from temporalio.service import RPCError, RPCStatusCode
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
@@ -29,71 +25,37 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.naming import
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import parse_ingest_mode
if TYPE_CHECKING:
+ from structlog.types import FilteringBoundLogger
+
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
-# Gates starting a snapshot in the buffer. Turned on once no worker runs the previous release: an
-# older worker ignores the marker, so it would defer that table's changes or purge its buffer.
-BUFFERED_SNAPSHOT_FLAG = "dwh-cdc-buffered-snapshot"
BUFFER_LANE = "buffer"
# Marks a table whose reset waits for a sync that can still hand over. The slot or the request moves
# on meanwhile, so this key is what makes a later capture run finish the reset.
CDC_RESET_PENDING_KEY = "cdc_reset_pending"
-def team_flag_enabled(flag: str, team_id: int, logger: FilteringBoundLogger) -> bool:
- """Evaluate a per-team warehouse flag. Never raises: a flag-service failure reads as off."""
- from posthog.models.team import Team
-
- try:
- team = Team.objects.get(pk=team_id)
- return bool(
- posthoganalytics.feature_enabled(
- flag,
- str(team.uuid),
- groups={"organization": str(team.organization_id), "project": str(team.id)},
- # team_id drives the release conditions (the warehouse convention for
- # per-team rollouts); the group context is passed for consistency with
- # the other warehouse flags and for org-wide kill switches.
- person_properties={"team_id": str(team.id)},
- group_properties={
- "organization": {"id": str(team.organization_id)},
- "project": {"id": str(team.id)},
- },
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
- )
- except Exception:
- logger.warning("cdc_flag_check_failed", flag=flag, team_id=team_id, exc_info=True)
- return False
-
-
-def is_buffered_snapshot_enabled(team_id: int, logger: FilteringBoundLogger) -> bool:
- return team_flag_enabled(BUFFERED_SNAPSHOT_FLAG, team_id, logger)
-
-
def snapshot_in_buffer(schema: ExternalDataSchema) -> bool:
"""Whether the buffer carries this schema's current snapshot."""
return (schema.sync_type_config or {}).get(CDC_SNAPSHOT_LANE_KEY) == BUFFER_LANE
-def resnapshot_stays_in_buffer(schema: ExternalDataSchema, logger: FilteringBoundLogger) -> bool:
+def resnapshot_stays_in_buffer(schema: ExternalDataSchema) -> bool:
"""Whether a reset of this schema to snapshot keeps its changes in the buffer.
- True for a table whose changes already go to the buffer: a streaming table on a buffered source
- with no deferred runs left, or one already snapshotting there. Its buffer holds an unbroken run
- of changes up to the reset, and a capture run in progress keeps adding to it. Any other table is
- decided by capture, which first empties the buffer, because files from before a gap in capture
- must not be replayed.
+ True for a table whose buffer already holds an unbroken run of its changes: a streaming table on
+ a buffered source with no deferred runs left, or one already snapshotting there. A capture run in
+ progress keeps adding to that buffer. Any other table is started by capture, which first empties
+ the buffer, because files from before a gap in capture must not be replayed. A source capture
+ has not converted yet is one such case: its buffer holds copies of changes the legacy lane
+ already delivered.
"""
if snapshot_in_buffer(schema):
return True
return (
parse_ingest_mode(schema.source.job_inputs) == "buffered"
and schema.cdc_mode == "streaming"
- and schema.initial_sync_complete
and not (schema.sync_type_config or {}).get("cdc_deferred_runs")
- and is_buffered_snapshot_enabled(schema.team_id, logger)
)
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 0f05134e8f9d..4dc666c8ed9b 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
@@ -58,7 +58,6 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolutio
has_engine_seq,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import snapshot_in_buffer
-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,
safe_parse_datetime,
@@ -91,8 +90,8 @@ 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.
+# The tables each mode's change stream feeds, as the write mode the loader uses for each, in the order
+# a run 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,),
@@ -108,17 +107,8 @@ class CDCLane:
write_mode: CDCWriteMode
-# In `sync_type_config`. Set by the flip command on each schema it moves to the buffer and never
-# cleared, so a later flip can tell the `_ph_cdc_seq` the buffered lane wrote from a column the
-# source owns.
-BUFFERED_BEFORE_KEY = "cdc_buffered_before"
-
-
def serves_buffered_lane(schema: ExternalDataSchema) -> bool:
- """Schema-side conditions for buffered ingress: streaming, seeded, and in a table mode with lanes.
-
- The source's `ingest_mode` is the other half.
- """
+ """Whether this schema's scheduled sync consumes the buffer: streaming, seeded, and in a table mode with lanes."""
return bool(
schema.is_cdc
and schema.cdc_mode == "streaming"
@@ -128,16 +118,12 @@ def serves_buffered_lane(schema: ExternalDataSchema) -> bool:
def captures_to_buffer(schema: ExternalDataSchema) -> bool:
- """Schema-side condition for capture to write this schema's changes into the buffer.
+ """Whether capture writes this schema's changes to the buffer.
- Wider than `serves_buffered_lane`: a table whose snapshot the buffer carries is captured too,
- and the consumer reads those changes once the snapshot completes.
+ Wider than `serves_buffered_lane`: a table in a mode the buffer serves is captured whatever its
+ state, and a snapshotting table's changes wait there until its snapshot completes.
"""
- return bool(
- schema.is_cdc
- and schema.cdc_table_mode in _LANE_WRITE_MODES
- and (serves_buffered_lane(schema) or snapshot_in_buffer(schema))
- )
+ return bool(schema.is_cdc and schema.cdc_table_mode in _LANE_WRITE_MODES)
def snapshot_can_start_in_buffer(schema: ExternalDataSchema) -> bool:
@@ -154,24 +140,19 @@ def purge_buffer_before_handover(schema: ExternalDataSchema, logger: FilteringBo
"""Before a snapshot hands over to streaming, drop the buffer files it must not replay.
When the buffer carried the snapshot, it holds an unbroken run of changes, and replaying all of
- them over the snapshot converges, so nothing goes. Otherwise the snapshot's changes went to
- legacy deferred runs, and every file predates a gap: an old file replayed after them would bring
- back rows. Strict, because a surviving stale file corrupts the table.
+ them over the snapshot converges, so nothing goes. Otherwise capture never started the snapshot
+ in the buffer, so every file in it predates a gap: an old file replayed there would bring back
+ rows. Strict, because a surviving stale file corrupts the table.
"""
if snapshot_in_buffer(schema):
return
purge_buffer_prefix(schema.team_id, str(schema.id), logger, strict=True)
-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.
+ One entry per Delta table the mode writes, in the order a run writes them.
An unrecognized mode returns nothing, which reads as "not a lane the buffer serves".
"""
return [
@@ -193,6 +174,8 @@ _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"
+# When capture moved the table's legacy source onto the buffer, kept in the table's sync_type_config.
+LEGACY_CONVERTED_AT_KEY = "cdc_legacy_converted_at"
def read_completed_listing_proof(schema: ExternalDataSchema) -> dt.datetime | None:
@@ -262,6 +245,11 @@ def buffer_may_have_expired_unread(schema: ExternalDataSchema, now: dt.datetime)
if schema.last_synced_at is None:
return False
cutoff = now - BUFFER_FILE_RETENTION
+ # The conversion empties the buffer at a position the legacy lane had already delivered, so the
+ # table is current from then on, though no run has listed the buffer yet.
+ converted_at = (schema.sync_type_config or {}).get(LEGACY_CONVERTED_AT_KEY)
+ if converted_at is not None and dt.datetime.fromisoformat(converted_at) >= cutoff:
+ return False
# Every completion moves it, so nothing has drained since the cutoff either.
if schema.last_synced_at < cutoff:
return True
@@ -341,7 +329,6 @@ def _history_transform(replay: ReplayFilter, key_columns: list[str]) -> Callable
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
@@ -412,25 +399,19 @@ def scheduled_sync_consumes_buffer(schema: ExternalDataSchema) -> bool:
Doubles as the pipeline-version override: buffered consumption must run the v3 pipeline,
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.
+ rollout flag cannot see individual schemas, so the version check consults this predicate
+ before the flag.
"""
- return consumes_buffer(schema, ingest_mode=parse_ingest_mode(schema.source.job_inputs))
+ return serves_buffered_lane(schema)
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.
+ A previous attempt of THIS job is what the consumer stands down for. The check 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; fencing batches by attempt in the producer is the follow-up.
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
@@ -446,8 +427,6 @@ def has_batches_in_flight(schema: ExternalDataSchema) -> bool:
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
return has_queued_batches(schema)
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 832e66069f33..4d05f38c9086 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
@@ -20,7 +20,6 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import
TOAST_OMITTED_COLUMN,
ChangeEventBatcher,
build_scd2_table,
- deduplicate_table,
enrich_delete_rows,
enrich_toast_omitted_rows,
)
@@ -300,80 +299,6 @@ class TestEventsToTableEdgeCases:
assert table.column("seats").type == pa.string()
-class TestDeduplicateTable:
- def _make_raw_table(self, events):
- batcher = ChangeEventBatcher()
- for ev in events:
- batcher.add(ev)
- return batcher.flush()["users"]
-
- @parameterized.expand(
- [
- (
- "single_event_unchanged",
- [("I", {"id": 1})],
- ["id"],
- 1,
- None,
- ),
- (
- "two_updates_same_pk_keeps_last",
- [("U", {"id": 1, "name": "Alice"}), ("U", {"id": 1, "name": "Bob"})],
- ["id"],
- 1,
- {"name": "Bob"},
- ),
- (
- "different_pks_both_kept",
- [("I", {"id": 1, "name": "Alice"}), ("I", {"id": 2, "name": "Bob"})],
- ["id"],
- 2,
- None,
- ),
- (
- "insert_then_delete_keeps_delete",
- [("I", {"id": 1, "name": "Alice"}), ("D", {"id": 1})],
- ["id"],
- 1,
- {"_ph_cdc_op": "D"},
- ),
- (
- "empty_pk_returns_unchanged",
- [("I", {"id": 1}), ("I", {"id": 2})],
- [],
- 2,
- None,
- ),
- (
- "missing_pk_col_returns_unchanged",
- [("I", {"id": 1}), ("I", {"id": 2})],
- ["nonexistent_col"],
- 2,
- None,
- ),
- ],
- )
- def test_deduplicate(self, _name, ops_and_cols, pk_columns, expected_rows, expected_values):
- events = [
- _make_event(op=op, columns=cols, position=f"0/{i}00") for i, (op, cols) in enumerate(ops_and_cols, start=1)
- ]
- table = self._make_raw_table(events)
- result = deduplicate_table(table, pk_columns)
- assert result.num_rows == expected_rows
- if expected_values:
- for col, val in expected_values.items():
- assert result.column(col)[0].as_py() == val
-
- def test_preserves_row_order(self):
- events = [
- _make_event(op="I", columns={"id": 2, "name": "Bob"}, position="0/100"),
- _make_event(op="I", columns={"id": 1, "name": "Alice"}, position="0/200"),
- ]
- table = self._make_raw_table(events)
- result = deduplicate_table(table, ["id"])
- assert result.column("id").to_pylist() == [2, 1]
-
-
class TestBuildScd2Table:
def _make_raw_table(self, events):
batcher = ChangeEventBatcher()
@@ -722,7 +647,6 @@ class TestSeqColumn:
assert has_engine_seq(table)
assert has_engine_seq(toasted)
assert has_engine_seq(enriched)
- assert has_engine_seq(deduplicate_table(enriched, ["id"]))
assert has_engine_seq(build_scd2_table(enriched, ["id"]))
def test_engine_seq_is_stamped_and_survives_a_parquet_round_trip(self):
@@ -769,16 +693,10 @@ class TestSeqColumn:
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)
+ def test_scd2_columns_match_the_timestamp_column(self):
+ # `valid_from` carries the timestamp column's own values, so it must carry its type too:
+ # declaring a fixed UTC type made pyarrow reject every naive batch.
+ ts = pa.timestamp("us")
table = pa.table(
{
"id": pa.array([1, 1], pa.int64()),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.py
index 09d12de615bc..0bb3464e0eb6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.py
@@ -60,52 +60,6 @@ class TestBufferFileName:
assert sorted(shuffled) == [build_buffer_file_name(*r) for r in sorted(ranges)]
-class TestIsShadowWriteEnabled:
- """The per-team flag is the single gate, and it fails closed."""
-
- def _call(self, *, flag, team_lookup_ok: bool = True) -> bool:
- from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import is_shadow_write_enabled
-
- team = MagicMock(uuid="team-uuid", id=2, organization_id="org-uuid")
- team_manager = MagicMock()
- team_manager.objects.get.return_value = team
- if not team_lookup_ok:
- team_manager.objects.get.side_effect = Exception("db down")
-
- flag_fn = MagicMock(side_effect=flag) if callable(flag) else MagicMock(return_value=flag)
- with (
- patch.dict("sys.modules", {"posthog.models.team": MagicMock(Team=team_manager)}),
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane.posthoganalytics.feature_enabled",
- flag_fn,
- ),
- ):
- result = is_shadow_write_enabled(2, MagicMock())
- self._last_flag_call = flag_fn
- return result
-
- def test_follows_the_flag(self):
- assert self._call(flag=True) is True
- assert self._call(flag=False) is False
-
- def test_passes_team_scoped_targeting_context(self):
- # team_id drives the release conditions (warehouse per-team rollout convention),
- # so a soak covers single teams rather than whole orgs.
- self._call(flag=True)
- kwargs = self._last_flag_call.call_args.kwargs
- assert kwargs["person_properties"]["team_id"] == "2"
- assert kwargs["groups"]["project"] == "2"
-
- def test_flag_service_failure_disables_rather_than_raises(self):
- def boom(*_a, **_k):
- raise RuntimeError("flag service down")
-
- assert self._call(flag=boom) is False
-
- def test_team_lookup_failure_disables_rather_than_raises(self):
- assert self._call(flag=True, team_lookup_ok=False) is False
-
-
class TestCDCBufferWriter:
def _writer_with_captured_files(self) -> tuple[CDCBufferWriter, dict[str, io.BytesIO]]:
files: dict[str, io.BytesIO] = {}
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 f662a5c014e2..0bb01a121dcb 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
@@ -6,13 +6,13 @@ from unittest.mock import ANY, AsyncMock, MagicMock, call, 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
_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"
+_SOURCE = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source"
_SNAPSHOT_LANE = "products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane"
@@ -91,23 +91,24 @@ def _dispatch(
class TestBufferedDispatch:
- def test_a_flipped_schema_is_consumed_here_instead_of_by_the_extraction_workflow(self):
+ def test_a_streaming_schema_is_consumed_from_the_buffer(self):
response = _dispatch(_schema(), _inputs())
assert response.name == "users"
assert response.cdc_write_mode == "incremental_merge"
- @pytest.mark.parametrize(
- "overrides,ingest_mode",
- [
- ({}, "legacy"),
- ({"cdc_table_mode": "something_new"}, "buffered"),
- ({"initial_sync_complete": False}, "buffered"),
- ],
- )
- def test_a_schema_the_buffer_does_not_serve_stays_with_the_extraction_workflow(self, overrides, ingest_mode):
- with pytest.raises(CDCHandledExternally):
- _dispatch(_schema(ingest_mode, **overrides), _inputs())
+ def test_an_unrecognized_table_mode_fails_the_run(self):
+ with pytest.raises(ValueError, match="cdc_table_mode"):
+ _dispatch(_schema(cdc_table_mode="something_new"), _inputs())
+
+ def test_a_streaming_schema_whose_data_was_deleted_runs_a_snapshot(self):
+ with (
+ patch(f"{_SOURCE}.source_requires_ssl", return_value=False),
+ patch(f"{_SOURCE}.postgres_source") as snapshot,
+ ):
+ _dispatch(_schema(initial_sync_complete=False), _inputs())
+
+ snapshot.assert_called_once()
def test_a_cdc_only_schema_is_consumed_into_its_companion_table(self):
response = _dispatch(_schema(cdc_table_mode="cdc_only"), _inputs())
@@ -137,10 +138,9 @@ class TestBufferedDispatch:
with pytest.raises(ValueError, match="no job row"):
_dispatch(_schema(), _inputs(), job_version=None)
- 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)
+ @pytest.mark.parametrize("ingest_mode, in_flight", [("buffered", True), ("legacy", False)])
+ def test_a_delivery_still_in_flight_or_an_unconverted_source_no_ops_the_tick(self, ingest_mode, in_flight):
+ response = _dispatch(_schema(ingest_mode, cdc_table_mode="both"), _inputs(), in_flight=in_flight)
assert list(response.items()) == []
assert response.lanes is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_errors.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_errors.py
index a25261ee8c2f..1eb3b244e9aa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_errors.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_errors.py
@@ -5,7 +5,6 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import
MAX_FRIENDLY_MESSAGE_LENGTH,
CDCErrorCategory,
CDCErrorInfo,
- CDCSchemaMergeError,
CDCSlotNotConfiguredError,
CDCTransactionTooLargeError,
cdc_error_info,
@@ -41,7 +40,6 @@ class TestCDCErrorInfo:
(CDCErrorCategory.SLOT_IN_USE, True),
(CDCErrorCategory.WAL_DECODE_ERROR, False),
(CDCErrorCategory.TRANSACTION_TOO_LARGE, False),
- (CDCErrorCategory.SCHEMA_MERGE_INCOMPATIBLE, False),
(CDCErrorCategory.UNKNOWN, True),
]
)
@@ -94,16 +92,6 @@ class TestClassifyCDCError:
assert info.category is CDCErrorCategory.SLOT_NOT_CONFIGURED
assert info.retryable is False
- def test_schema_merge_error_is_non_retryable_via_cause_chain(self):
- # The activity wraps the Arrow type error as CDCSchemaMergeError; classification must
- # find it through the cause chain and mark the run non-retryable so it stops looping.
- cause = CDCSchemaMergeError("Incompatible column types across CDC batches for orders")
- wrapper = RuntimeError("flush failed")
- wrapper.__cause__ = cause
- info = classify_cdc_error(wrapper, None)
- assert info.category is CDCErrorCategory.SCHEMA_MERGE_INCOMPATIBLE
- assert info.retryable is False
-
def test_non_psycopg_exception_with_slot_message_is_not_classified(self):
# A non-psycopg exception whose message happens to contain slot/auth patterns must not be
# misclassified as non-retryable — only psycopg exceptions carry these patterns meaningfully.
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 ad2cf1160043..97e4ea579f60 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
@@ -1,10 +1,12 @@
import uuid
-from contextlib import nullcontext
+from collections.abc import Iterator
+from contextlib import contextmanager
from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
from typing import Literal
import pytest
-from unittest.mock import MagicMock, patch
+from unittest.mock import ANY, DEFAULT, MagicMock, patch
from django.db.utils import InterfaceError, OperationalError
@@ -19,18 +21,19 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import CDC_SNAPSHOT_LANE_KEY, ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.cdc.activities import (
- CDC_BACKPRESSURE_STUCK_AGE,
CDC_MAX_CHANGES_PER_READ,
CDC_MAX_EXTRACTION_ATTEMPTS,
- CDC_ORPHAN_JOB_MIN_AGE,
- CDC_ORPHANED_JOB_MESSAGE,
SLOT_INVALIDATION_RECOVERY_MESSAGE,
CDCExtractActivity,
CDCExtractInput,
cdc_extract_activity,
cleanup_orphan_slots_activity,
)
-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_SEQ_COLUMN,
+ CDC_SEQ_PROVENANCE,
+ ChangeEventBatcher,
+)
from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCErrorCategory, cdc_error_info
from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import (
cancel_running_sync,
@@ -41,7 +44,8 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.types import C
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter import PostgresCDCAdapter
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.position import PgLSN
from products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException
-from products.warehouse_sources_queue.backend.core.jobs_db import BatchQueue
+
+_ACTIVITIES = "products.warehouse_sources.backend.temporal.data_imports.cdc.activities"
def _make_event(
@@ -82,20 +86,7 @@ def _make_source(source_id=None, job_inputs=None):
return source
-def _make_schema(
- name,
- cdc_mode="streaming",
- cdc_table_mode="consolidated",
- source=None,
- schema_id=None,
- s3_folder_name=None,
- partitioning_enabled=False,
- partitioning_keys=None,
- partition_mode=None,
- partition_format=None,
- partition_count=None,
- partition_size=None,
-):
+def _make_schema(name, cdc_mode="streaming", cdc_table_mode="consolidated", source=None, schema_id=None):
schema = MagicMock()
schema.id = schema_id or uuid.uuid4()
schema.name = name
@@ -108,16 +99,7 @@ def _make_schema(
schema.cdc_table_mode = cdc_table_mode
schema.should_sync = True
schema.deleted = False
- # Real values (not MagicMocks) so storage-name and partition helpers evaluate deterministically.
- schema.resolved_s3_folder_name = s3_folder_name
- schema.partitioning_enabled = partitioning_enabled
- schema.partitioning_keys = partitioning_keys
- schema.partition_mode = partition_mode
- schema.partition_format = partition_format
- schema.partition_count = partition_count
- schema.partition_size = partition_size
schema.save = MagicMock()
- type(schema).cdc_halted = ExternalDataSchema.cdc_halted
return schema
@@ -140,34 +122,10 @@ def _fake_update_schema_sync_type_config(schema, *, updates=None, removes=None,
setattr(schema, field, value)
-def _fake_complete_schema_run(schema, *, last_synced_at):
- """Stand-in for complete_schema_run mirroring its contract on the in-memory mock schema:
- a broken marker blocks the repaint, otherwise the paused marker clears and the schema
- repaints COMPLETED. The real locked-transaction semantics are covered by
- tests/test_models.py::TestCompleteSchemaRun."""
- config = schema.sync_type_config or {}
- if config.get("cdc_broken"):
- return False
- config.pop("cdc_extraction_paused", None)
- schema.sync_type_config = config
- schema.status = ExternalDataSchema.Status.COMPLETED
- schema.latest_error = None
- schema.last_synced_at = last_synced_at
- return True
-
-
-def _fake_mark_schema_running_unless_halted(schema):
- """Stand-in for mark_schema_running_unless_halted on the in-memory mock schema. The real
- conditional update is covered by tests/test_models.py::TestMarkSchemaRunningUnlessHalted."""
- if schema.cdc_halted:
- return False
- schema.status = ExternalDataSchema.Status.RUNNING
- return True
-
-
@pytest.fixture(autouse=True)
-def _stub_sync_type_config_merge():
- """Route every activity sync_type_config write onto the in-memory mock schema (no DB)."""
+def _stub_app_db_writes():
+ # The real sync_type_config merge and the legacy-state conversion both go to the app DB, which
+ # these mock-only tests don't have. The conversion has its own tests.
with (
patch(
"products.warehouse_sources.backend.temporal.data_imports.cdc.activities.cancel_running_sync",
@@ -178,95 +136,58 @@ def _stub_sync_type_config_merge():
return_value=False,
),
patch("products.data_warehouse.backend.facade.api.pause_external_data_schedule"),
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.mark_schema_running_unless_halted",
- side_effect=_fake_mark_schema_running_unless_halted,
- ),
patch.object(
CDCExtractActivity,
"_update_schema_sync_type_config",
side_effect=_fake_update_schema_sync_type_config,
),
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.complete_schema_run",
- side_effect=_fake_complete_schema_run,
- ),
+ patch(f"{_ACTIVITIES}.convert_legacy_cdc_state"),
+ patch(f"{_ACTIVITIES}.cancel_running_sync", return_value=None),
):
yield
-# Shared patch decorator for CDC activity tests
-_CDC_ACTIVITY_PATCHES = [
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections",
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob",
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource",
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCExtractActivity._get_cdc_schemas",
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter",
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter",
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer",
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity",
-]
-
-
-def _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- schemas,
- events,
-):
- """Wire up the standard mocks for CDC activity tests."""
- MockSourceModel.objects.get.return_value = source
- mock_get_schemas.return_value = schemas
-
- mock_reader = MagicMock(last_commit_end_lsn=None)
- mock_reader.read_changes.return_value = iter(events)
- mock_reader.truncated_tables = []
+@contextmanager
+def _capture_harness(source, schemas, events=()) -> Iterator[SimpleNamespace]:
+ reader = MagicMock(last_commit_end_lsn=None)
+ reader.read_changes.return_value = iter(events)
+ reader.truncated_tables = []
# Below CDC_MAX_CHANGES_PER_READ so the bounded read loop treats this as a single drained pass.
- mock_reader.last_rows_consumed = len(events)
- mock_reader.get_decoder_key_columns.return_value = []
- mock_adapter = MagicMock()
- mock_adapter.create_reader.return_value = mock_reader
- mock_adapter.is_slot_invalidation_error.return_value = False
- mock_adapter.classify_error.return_value = None # default: unrecognized -> unknown/retryable
- # Real converter, not a MagicMock return: the batcher feeds its output into a
- # typed pa.array, which would reject a MagicMock in every streaming test.
- mock_adapter.position_to_seq.side_effect = lambda position: PgLSN.deserialize(position).value
- mock_get_adapter.return_value = mock_adapter
-
- mock_s3 = MagicMock()
- mock_batch_result = MagicMock()
- mock_batch_result.s3_path = "s3://bucket/data/part-0000.parquet"
- mock_batch_result.row_count = len(events)
- mock_batch_result.byte_size = 512
- mock_batch_result.batch_index = 0
- mock_batch_result.timestamp_ns = 123456
- mock_s3.write_batch.return_value = mock_batch_result
- mock_s3.write_schema.return_value = "s3://bucket/schema.json"
- mock_s3.get_data_folder.return_value = "s3://bucket/data/"
- MockS3Writer.return_value = mock_s3
-
- mock_producer = MagicMock()
- MockProducer.return_value = mock_producer
-
- mock_job = MagicMock()
- mock_job.id = uuid.uuid4()
- MockJob.objects.create.return_value = mock_job
- MockJob.PipelineVersion.V2 = "v2-non-dlt"
- MockJob.Status.RUNNING = "Running"
- MockJob.Status.COMPLETED = "Completed"
- MockJob.Status.FAILED = "Failed"
-
- mock_activity.heartbeat = MagicMock()
- mock_activity.info.return_value = MagicMock(workflow_id="wf-1", workflow_run_id="run-1", attempt=1)
-
- return mock_reader, mock_s3, mock_producer, mock_job
+ reader.last_rows_consumed = len(events)
+ reader.get_decoder_key_columns.return_value = []
+
+ with (
+ patch(f"{_ACTIVITIES}.close_old_connections") as close_old_connections,
+ patch(f"{_ACTIVITIES}.ExternalDataSource") as MockSourceModel,
+ patch(f"{_ACTIVITIES}.ExternalDataJob"),
+ patch.object(CDCExtractActivity, "_get_cdc_schemas", return_value=list(schemas)),
+ patch(f"{_ACTIVITIES}.get_cdc_adapter") as mock_get_adapter,
+ patch(f"{_ACTIVITIES}.CDCBufferWriter") as MockBufferWriter,
+ patch(f"{_ACTIVITIES}.purge_buffer_prefix") as purge,
+ patch(f"{_ACTIVITIES}.activity") as mock_activity,
+ # The reset and failure paths call Temporal and Celery, which these tests must not reach.
+ patch("products.data_warehouse.backend.facade.api.unpause_external_data_schedule"),
+ patch("products.data_warehouse.backend.facade.api.pause_cdc_extraction_schedule"),
+ patch("products.data_warehouse.backend.facade.tasks.schedule_external_data_failure_digest"),
+ ):
+ MockSourceModel.objects.get.return_value = source
+ adapter = mock_get_adapter.return_value
+ adapter.create_reader.return_value = reader
+ adapter.is_slot_invalidation_error.return_value = False
+ adapter.classify_error.return_value = None # default: unrecognized -> unknown/retryable
+ # Real converter, not a MagicMock return: the batcher feeds its output into a typed pa.array.
+ adapter.position_to_seq.side_effect = lambda position: PgLSN.deserialize(position).value
+ MockBufferWriter.return_value.write_batch.return_value.write_duration_seconds = 0.01
+ mock_activity.info.return_value = MagicMock(workflow_id="wf-1", workflow_run_id="run-1", attempt=1)
+ yield SimpleNamespace(
+ reader=reader,
+ adapter=adapter,
+ buffer=MockBufferWriter.return_value,
+ purge=purge,
+ activity=mock_activity,
+ close_old_connections=close_old_connections,
+ extract=lambda: cdc_extract_activity(CDCExtractInput(team_id=1, source_id=source.id)),
+ )
class TestGetCDCAdapter:
@@ -410,188 +331,6 @@ class TestSetupSelfCleansUnrunnableSchedules:
mock_get_adapter.assert_not_called()
-class TestBackpressureGuard:
- def _activity(self) -> CDCExtractActivity:
- source = _make_source()
- act = _make_extract_activity(source)
- act.cdc_schemas = [_make_schema("users", source=source)]
- return act
-
- @pytest.mark.parametrize(
- "age_seconds,expect_skip,expect_stuck",
- [
- (None, False, None),
- (30.0, True, False),
- (CDC_BACKPRESSURE_STUCK_AGE.total_seconds() + 1, True, True),
- ],
- )
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.metrics.get_tick_skipped_metric")
- @patch("psycopg.Connection.connect")
- def test_skips_only_while_previous_batches_pend(
- self, mock_connect, mock_metric, age_seconds, expect_skip, expect_stuck
- ):
- act = self._activity()
-
- with patch.object(BatchQueue, "get_oldest_non_terminal_batch_age_seconds", return_value=age_seconds):
- assert act._previous_load_still_pending() is expect_skip
-
- if expect_skip:
- mock_metric.assert_called_once_with(act.inputs.team_id, str(act.inputs.source_id), expect_stuck)
- else:
- mock_metric.assert_not_called()
-
- def test_fails_open_when_queue_db_unreachable(self):
- act = self._activity()
-
- with patch("psycopg.Connection.connect", side_effect=Exception("queue db down")):
- assert act._previous_load_still_pending() is False
-
- # close_old_connections is real Django connection housekeeping: without the patch this
- # non-django_db test blows up whenever a django_db test ran earlier in the same process.
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- @patch("psycopg.Connection.connect")
- def test_run_skips_tick_without_touching_schemas_or_reader(self, mock_connect, _mock_close_conns):
- act = self._activity()
-
- with (
- patch.object(act, "_setup", return_value=True),
- patch.object(act, "_mark_schemas_running") as mark_running,
- patch.object(BatchQueue, "get_oldest_non_terminal_batch_age_seconds", return_value=42.0),
- ):
- act.run()
-
- mark_running.assert_not_called()
- assert act.reader is None
-
-
-class TestFlushDeferredRuns:
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- def test_sends_kafka_messages_for_deferred_runs(self, MockProducer):
- mock_producer = MagicMock()
- MockProducer.return_value = mock_producer
-
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- schema.sync_type_config["cdc_deferred_runs"] = [
- {
- "job_id": "job-1",
- "run_uuid": "run-1",
- "data_folder": "s3://bucket/data/",
- "schema_path": "s3://bucket/schema.json",
- "total_batches": 1,
- "total_rows": 10,
- "batch_results": [
- {
- "s3_path": "s3://bucket/data/part-0000.parquet",
- "row_count": 10,
- "byte_size": 1024,
- "batch_index": 0,
- "timestamp_ns": 123456789,
- }
- ],
- }
- ]
-
- _make_extract_activity(source)._flush_deferred_runs(schema)
-
- mock_producer.send_batch_notification.assert_called_once()
- mock_producer.flush.assert_called_once()
-
- assert schema.sync_type_config["cdc_deferred_runs"] == []
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- def test_no_op_when_no_deferred_runs(self, MockProducer):
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- schema.sync_type_config = {"cdc_mode": "streaming"}
-
- _make_extract_activity(source)._flush_deferred_runs(schema)
-
- MockProducer.assert_not_called()
- schema.save.assert_not_called()
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- def test_multiple_deferred_runs(self, MockProducer):
- mock_producer = MagicMock()
- MockProducer.return_value = mock_producer
-
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- schema.sync_type_config["cdc_deferred_runs"] = [
- {
- "job_id": f"job-{i}",
- "run_uuid": f"run-{i}",
- "data_folder": f"s3://bucket/data-{i}/",
- "schema_path": f"s3://bucket/schema-{i}.json",
- "total_batches": 1,
- "total_rows": 5,
- "batch_results": [
- {
- "s3_path": f"s3://bucket/data-{i}/part-0000.parquet",
- "row_count": 5,
- "byte_size": 512,
- "batch_index": 0,
- }
- ],
- }
- for i in range(3)
- ]
-
- _make_extract_activity(source)._flush_deferred_runs(schema)
-
- # 3 deferred runs, each with 1 batch → 3 send calls, 3 flush calls (one per producer)
- assert mock_producer.send_batch_notification.call_count == 3
- assert mock_producer.flush.call_count == 3
- assert schema.sync_type_config["cdc_deferred_runs"] == []
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- def test_deferred_flush_uses_stored_resource_name_and_replays_partition_config(self, MockProducer):
- """Deferred flush targets the stored Delta resource and replays partition config."""
- mock_producer = MagicMock()
- MockProducer.return_value = mock_producer
-
- source = _make_source()
- # Folder pinned bare while `name` is qualified, plus partitioning — exercises both fixes.
- schema = _make_schema(
- "public.users",
- cdc_mode="streaming",
- source=source,
- s3_folder_name="users",
- partitioning_enabled=True,
- partitioning_keys=["id"],
- partition_mode="numerical",
- partition_size=1_000_000,
- )
- schema.sync_type_config["cdc_deferred_runs"] = [
- {
- "job_id": "job-1",
- "run_uuid": "run-1",
- "resource_name": "users",
- "data_folder": "s3://bucket/data/",
- "schema_path": "s3://bucket/schema.json",
- "total_batches": 1,
- "total_rows": 10,
- "batch_results": [
- {
- "s3_path": "s3://bucket/data/part-0000.parquet",
- "row_count": 10,
- "byte_size": 1024,
- "batch_index": 0,
- "timestamp_ns": 123456789,
- }
- ],
- }
- ]
-
- _make_extract_activity(source)._flush_deferred_runs(schema)
-
- kwargs = MockProducer.call_args.kwargs
- assert kwargs["resource_name"] == "users"
- assert kwargs["partition_keys"] == ["id"]
- assert kwargs["partition_mode"] == "numerical"
- assert kwargs["partition_size"] == 1_000_000
-
-
class TestBuildEventNameMap:
@pytest.mark.parametrize(
"schema_name,schema_metadata,source_schema_config,wal_event_name,expected_canonical",
@@ -621,453 +360,57 @@ class TestBuildEventNameMap:
assert activity_obj._build_event_name_map().get(wal_event_name) == expected_canonical
-class TestShadowBufferWrite:
- """Shadow buffered-ingress writes around _process_flush.
-
- Enablement is the per-team dwh-cdc-buffer-shadow flag, resolved once in _setup;
- these drive it end-to-end through the real gate (`is_shadow_write_enabled`).
- """
-
- def _run(self, MockBufferWriter, events, shadow_on: bool):
- with (
- patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections"),
- patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob") as MockJob,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource"
- ) as MockSourceModel,
- patch.object(CDCExtractActivity, "_get_cdc_schemas") as mock_get_schemas,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter"
- ) as mock_get_adapter,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter"
- ) as MockS3Writer,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer"
- ) as MockProducer,
- patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity") as mock_activity,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.is_shadow_write_enabled",
- return_value=shadow_on,
- ),
- ):
- MockBufferWriter.return_value.write_batch.return_value.write_duration_seconds = 0.01
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- mock_reader, mock_s3, mock_producer, _mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- MagicMock(),
- source,
- [schema],
- events,
- )
- cdc_extract_activity(CDCExtractInput(team_id=1, source_id=source.id))
- return schema, mock_reader, mock_s3, mock_producer
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_shadow_off_by_default_writes_nothing(self, MockBufferWriter):
- events = [_make_event(op="I", position="0/100")]
- _schema, _reader, mock_s3, _producer = self._run(MockBufferWriter, events, shadow_on=False)
-
- MockBufferWriter.assert_not_called()
- # Legacy lane stays byte-identical: no seq column reaches the S3 writer.
- legacy_table = mock_s3.write_batch.call_args[0][0]
- assert CDC_SEQ_COLUMN not in legacy_table.column_names
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_shadow_on_writes_raw_stream_with_seq(self, MockBufferWriter):
- events = [
- _make_event(op="I", position="0/100", columns={"id": 1, "name": "Alice"}),
- _make_event(op="U", position="0/200", columns={"id": 1, "name": "Bob"}),
- ]
- schema, _reader, mock_s3, mock_producer = self._run(MockBufferWriter, events, shadow_on=True)
-
- buffer_call = MockBufferWriter.return_value.write_batch.call_args
- assert buffer_call.kwargs["team_id"] == 1
- assert buffer_call.kwargs["schema_id"] == str(schema.id)
- assert buffer_call.kwargs["file_index"] == 0
- shadow_table = buffer_call.kwargs["table"]
- assert shadow_table.column(CDC_SEQ_COLUMN).to_pylist() == [0x100, 0x200]
- # Raw stream: one row per change event, before dedup collapses the PK.
- assert shadow_table.num_rows == 2
-
- legacy_table = mock_s3.write_batch.call_args[0][0]
- assert CDC_SEQ_COLUMN not in legacy_table.column_names
- mock_producer.send_batch_notification.assert_called_once()
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_shadow_failure_never_fails_extraction(self, MockBufferWriter):
- MockBufferWriter.return_value.write_batch.side_effect = Exception("s3 down")
- events = [_make_event(op="I", position="0/100")]
- _schema, mock_reader, mock_s3, mock_producer = self._run(MockBufferWriter, events, shadow_on=True)
-
- # Legacy lane completed despite the shadow failure — including slot advance.
- mock_s3.write_batch.assert_called_once()
- mock_producer.send_batch_notification.assert_called_once()
- mock_reader.confirm_position.assert_called_once_with("0/100")
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_source_column_named_like_seq_passes_through_legacy_untouched(self, MockBufferWriter):
- # Collision: batcher skips the engine seq append, the strip must not touch
- # the user's column, and the shadow lane must not treat it as positions.
- events = [_make_event(op="I", position="0/100", columns={"id": 1, CDC_SEQ_COLUMN: 42})]
- _schema, _reader, mock_s3, _producer = self._run(MockBufferWriter, events, shadow_on=True)
-
- MockBufferWriter.return_value.write_batch.assert_not_called()
- legacy_table = mock_s3.write_batch.call_args[0][0]
- assert legacy_table.column(CDC_SEQ_COLUMN).to_pylist() == [42]
-
- def _hook_activity(self, trailing_column: bool = False):
- source = _make_source()
- act = _make_extract_activity(source)
- schema = _make_schema("users", cdc_mode="streaming", source=source)
+class TestWriteBufferFile:
+ def _table(self, seq, *, trailing_column=False):
table = pa.table({"id": pa.array([1], type=pa.int64())}).append_column(
pa.field(CDC_SEQ_COLUMN, pa.int64(), metadata=CDC_SEQ_PROVENANCE),
- pa.array([256], type=pa.int64()),
+ pa.array([seq], type=pa.int64()),
)
if trailing_column:
table = table.append_column(pa.field("added_later", pa.string()), pa.array(["x"], type=pa.string()))
- return act, schema, table
+ return table
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_shadow_writes_when_a_column_sits_after_the_seq_column(self, MockBufferWriter):
- # The hook used to locate the position by index, assuming the batcher appended it last. A
- # column added after it would silently stop buffering, or feed cleanup a restart floor read
- # off the wrong column.
- act, schema, table = self._hook_activity(trailing_column=True)
- MockBufferWriter.return_value.write_batch.return_value = MagicMock(write_duration_seconds=0.01)
- act._shadow_enabled = True
+ @patch(f"{_ACTIVITIES}.CDCBufferWriter")
+ def test_the_restart_floor_is_read_from_the_seq_column_by_name(self, MockBufferWriter):
+ # A lookup by index, which assumes the batcher appends the position last, would feed cleanup a
+ # restart floor read off whichever column follows it.
+ source = _make_source()
+ schema = _make_schema("users", source=source)
+ MockBufferWriter.return_value.write_batch.return_value.write_duration_seconds = 0.01
- act._maybe_shadow_write_buffer(schema, "users", table)
+ _make_extract_activity(source)._write_buffer_file(schema, "users", self._table(256, trailing_column=True))
MockBufferWriter.return_value.write_batch.assert_called_once()
assert MockBufferWriter.return_value.cleanup_superseded_files.call_args.kwargs["restart_seq"] == 256
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_shadow_skips_a_source_owned_seq_column(self, MockBufferWriter):
- act, schema, _ = self._hook_activity()
- unstamped = pa.table({"id": pa.array([1], type=pa.int64()), CDC_SEQ_COLUMN: pa.array([999], type=pa.int64())})
- act._shadow_enabled = True
-
- act._maybe_shadow_write_buffer(schema, "users", unstamped)
+ @patch(f"{_ACTIVITIES}.CDCBufferWriter")
+ def test_each_schema_cleans_superseded_files_once_before_its_first_write(self, MockBufferWriter):
+ # A later batch can start at a position an earlier file of this run already holds, so cleaning
+ # again before it would delete that file.
+ source = _make_source()
+ users = _make_schema("users", source=source)
+ orders = _make_schema("orders", source=source)
+ buffer = MockBufferWriter.return_value
+ buffer.write_batch.return_value.write_duration_seconds = 0.01
+ act = _make_extract_activity(source)
- MockBufferWriter.return_value.write_batch.assert_not_called()
+ act._write_buffer_file(users, "users", self._table(256))
+ act._write_buffer_file(users, "users", self._table(512))
+ act._write_buffer_file(orders, "orders", self._table(768))
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_shadow_file_index_increments_per_table_including_failures(self, MockBufferWriter):
- act, schema, table = self._hook_activity()
- MockBufferWriter.return_value.write_batch.side_effect = [
- MagicMock(write_duration_seconds=0.01),
- Exception("s3 down"),
- MagicMock(write_duration_seconds=0.01),
+ assert [(name, kwargs["schema_id"]) for name, _args, kwargs in buffer.mock_calls] == [
+ ("cleanup_superseded_files", str(users.id)),
+ ("write_batch", str(users.id)),
+ ("write_batch", str(users.id)),
+ ("cleanup_superseded_files", str(orders.id)),
+ ("write_batch", str(orders.id)),
]
- act._shadow_enabled = True
- with nullcontext():
- act._maybe_shadow_write_buffer(schema, "users", table)
- act._maybe_shadow_write_buffer(schema, "users", table)
- act._maybe_shadow_write_buffer(schema, "users", table)
- act._maybe_shadow_write_buffer(schema, "other", table)
-
- calls = MockBufferWriter.return_value.write_batch.call_args_list
- # Failure still advances the ordinal: a lost chunk is an index gap, not a
- # later chunk silently claiming its slot.
- assert [c.kwargs["file_index"] for c in calls] == [0, 1, 2, 0]
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_shadow_disables_for_run_after_consecutive_failures(self, MockBufferWriter):
- act, schema, table = self._hook_activity()
- MockBufferWriter.return_value.write_batch.side_effect = Exception("s3 down")
- act._shadow_enabled = True
- with nullcontext():
- for _ in range(5):
- act._maybe_shadow_write_buffer(schema, "users", table)
-
- # Breaker trips at 3 consecutive failures; later flushes skip entirely.
- assert MockBufferWriter.return_value.write_batch.call_count == 3
- assert act._shadow_disabled_for_run is True
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_first_write_per_schema_cleans_superseded_files(self, MockBufferWriter):
- act, schema, table = self._hook_activity()
- MockBufferWriter.return_value.write_batch.return_value.write_duration_seconds = 0.01
- act._shadow_enabled = True
- with nullcontext():
- act._maybe_shadow_write_buffer(schema, "users", table)
- act._maybe_shadow_write_buffer(schema, "users", table)
-
- cleanup = MockBufferWriter.return_value.cleanup_superseded_files
- cleanup.assert_called_once_with(team_id=schema.team_id, schema_id=str(schema.id), restart_seq=256)
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")
- def test_reset_to_snapshot_purges_buffer_prefix(self, mock_purge):
- act, schema, _table = self._hook_activity()
- act._reset_schema_to_snapshot(schema)
- mock_purge.assert_called_once()
- assert mock_purge.call_args.args[1] == str(schema.id)
+ assert [c.kwargs["restart_seq"] for c in buffer.cleanup_superseded_files.call_args_list] == [256, 768]
class TestCDCExtractActivity:
"""Integration tests for cdc_extract_activity with mocked external deps."""
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_streaming_schema_writes_s3_and_sends_kafka(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- events = [
- _make_event(op="I", table="users", position="0/100", columns={"id": 1, "name": "Alice"}),
- _make_event(op="U", table="users", position="0/200", columns={"id": 1, "name": "Bob"}),
- ]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- mock_reader.connect.assert_called_once()
- mock_s3.write_batch.assert_called_once()
- mock_producer.send_batch_notification.assert_called_once()
- mock_producer.flush.assert_called_once()
- mock_reader.confirm_position.assert_called_once_with("0/200")
- mock_reader.close.assert_called_once()
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_bare_named_schema_matches_schema_qualified_wal_events(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- """A schema whose `name` is stored bare (no `public.` prefix) must still match the
- schema-qualified table name the WAL stream emits. Otherwise every change is silently
- dropped and the table goes stale despite a healthy slot."""
- source = _make_source()
- # `name` is bare, but schema_metadata resolves the real source location.
- schema = _make_schema("product_productintegrationevent", cdc_mode="streaming", source=source)
- schema.sync_type_config["schema_metadata"] = {
- "source_schema": "public",
- "source_table_name": "product_productintegrationevent",
- }
- schema.sync_type_config["primary_key_columns"] = ["id"]
- # WAL events arrive schema-qualified, as Postgres logical decoding always emits them.
- events = [
- _make_event(op="I", table="public.product_productintegrationevent", position="0/100"),
- ]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- # The change was captured, not dropped by the table-name filter.
- mock_s3.write_batch.assert_called()
- mock_producer.send_batch_notification.assert_called()
- mock_reader.confirm_position.assert_called_once_with("0/100")
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_streaming_job_not_marked_completed_by_activity(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- """For streaming schemas, the activity should NOT mark the job as COMPLETED.
- The Kafka consumer marks it after loading to DeltaLake."""
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- events = [_make_event(op="I", table="users", position="0/100")]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- # No save call for the job should include "status" in update_fields
- mock_job.save.assert_called()
- for call in mock_job.save.call_args_list:
- assert "status" not in call.kwargs.get("update_fields", [])
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_snapshot_schema_writes_s3_defers_kafka_and_marks_job_completed(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- """Snapshot schemas write to S3 and defer the Kafka notification (stored in
- sync_type_config) until the schema transitions to streaming. The job is marked
- COMPLETED immediately since no Kafka consumer will process it."""
- source = _make_source()
- schema = _make_schema("users", cdc_mode="snapshot", source=source)
- events = [_make_event(op="I", table="users", position="0/100")]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- mock_s3.write_batch.assert_called_once()
- MockProducer.assert_not_called()
-
- deferred = schema.sync_type_config.get("cdc_deferred_runs", [])
- assert len(deferred) == 1
- assert deferred[0]["run_uuid"] is not None
- assert deferred[0]["total_rows"] == 1
-
- mock_reader.confirm_position.assert_called_once_with("0/100")
-
- # Job is completed by the activity (no Kafka consumer to do it)
- assert any("status" in call.kwargs.get("update_fields", []) for call in mock_job.save.call_args_list)
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_no_changes_returns_early_with_completed_status(
- self,
- mock_close_conns,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- mock_activity,
- ):
- source = _make_source()
- MockSourceModel.objects.get.return_value = source
- mock_activity.info.return_value = MagicMock(workflow_id="wf-1", workflow_run_id="run-1", attempt=1)
-
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- mock_get_schemas.return_value = [schema]
-
- mock_reader = MagicMock(last_commit_end_lsn=None)
- mock_reader.read_changes.return_value = iter([])
- mock_reader.truncated_tables = []
- mock_reader.last_rows_consumed = 0
- mock_reader.current_position.return_value = "0/900"
- mock_adapter = MagicMock()
- mock_adapter.create_reader.return_value = mock_reader
- mock_get_adapter.return_value = mock_adapter
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- # The peek examined everything up to the pre-read position and found nothing to sync, so the
- # slot must still move. Leaving it pinned makes a busy source retain WAL on every quiet run
- # until the lag safety net drops the slot.
- mock_reader.confirm_position.assert_called_once_with("0/900")
- mock_reader.close.assert_called_once()
-
- # Schema marked completed even with no changes
- assert schema.status == "Completed"
- assert schema.latest_error is None
- assert schema.last_synced_at is not None
-
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -1096,993 +439,68 @@ class TestCDCExtractActivity:
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_setup_app_db_connection_blip_is_not_reported(
- self,
- _name,
- exception_cls,
- mock_close_conns,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- mock_activity,
- ):
- # `_setup` only reads our own app DB (never a customer's), so a dropped connection here
- # (e.g. PgBouncer closing an idle connection) is a transient blip, not a broken sync. It
- # must still be retried by Temporal, but shouldn't page as a fresh, reportable bug on
- # every attempt.
- MockSourceModel.DoesNotExist = ExternalDataSource.DoesNotExist
- MockSourceModel.objects.get.side_effect = exception_cls("server closed the connection unexpectedly")
-
- inputs = CDCExtractInput(team_id=1, source_id=uuid.uuid4())
-
- with pytest.raises(NonReportableError, match="server closed the connection unexpectedly"):
- cdc_extract_activity(inputs)
-
- mock_get_schemas.assert_not_called()
- mock_get_adapter.assert_not_called()
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_events_for_unknown_tables_are_filtered(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- events = [
- _make_event(op="I", table="users", position="0/100"),
- _make_event(op="I", table="other_table", position="0/200"),
- ]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- # Only 1 S3 write (for "users"), not for "other_table"
- mock_s3.write_batch.assert_called_once()
- call_args = mock_s3.write_batch.call_args
- pa_table = call_args[0][0]
- assert pa_table.num_rows == 1
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_reader_closed_on_error(
- self,
- mock_close_conns,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- mock_activity,
- ):
- source = _make_source()
- MockSourceModel.objects.get.return_value = source
-
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- mock_get_schemas.return_value = [schema]
-
- mock_reader = MagicMock(last_commit_end_lsn=None)
- mock_reader.read_changes.side_effect = RuntimeError("connection lost")
- mock_reader.truncated_tables = []
- mock_adapter = MagicMock()
- mock_adapter.create_reader.return_value = mock_reader
- mock_adapter.is_slot_invalidation_error.return_value = False
- mock_adapter.classify_error.return_value = None
- mock_get_adapter.return_value = mock_adapter
-
- # Retryable on a non-final attempt: no failure-visibility row, so ExternalDataJob is untouched.
- mock_activity.info.return_value = MagicMock(workflow_id="wf-1", workflow_run_id="run-1", attempt=1)
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
-
- with pytest.raises(RuntimeError, match="connection lost"):
- cdc_extract_activity(inputs)
-
- mock_reader.close.assert_called_once()
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_schema_status_set_to_failed_on_error(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- events = [_make_event(op="I", table="users", position="0/100")]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- # Make S3 write fail
- mock_s3.write_batch.side_effect = RuntimeError("S3 write failed")
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
-
- with pytest.raises(RuntimeError, match="S3 write failed"):
- cdc_extract_activity(inputs)
-
- # Schema is marked FAILED with the friendly message — the raw error never reaches the user.
- assert schema.status == "Failed"
- assert schema.latest_error == cdc_error_info(CDCErrorCategory.UNKNOWN).friendly_message
- assert "S3 write failed" not in schema.latest_error
-
- # A RUNNING job already exists (created before the flush failed), so the failure path must
- # NOT add a second failure-visibility row — only the original job is created and then failed.
- MockJob.objects.create.assert_called_once()
-
- # Slot should NOT have been advanced
- mock_reader.confirm_position.assert_not_called()
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_dropped_connection_during_flush_still_records_failure(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- events = [_make_event(op="I", table="users", position="0/100")]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- # The source DB (or the warehouse-sources DB) drops the connection mid-flush — the same
- # OperationalError seen when Postgres kills a connection out from under a long-running
- # activity thread.
- mock_s3.write_batch.side_effect = OperationalError("the connection is closed")
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
-
- with pytest.raises(OperationalError, match="the connection is closed"):
- cdc_extract_activity(inputs)
-
- # The stale connection left by the drop must be evicted again before the failure handler
- # writes the job/schema failure state, otherwise that write immediately re-raises the same
- # "connection is closed" error and the friendly message never gets recorded. One call from
- # run()'s own startup eviction, one from the failure handler.
- assert mock_close_conns.call_count == 2
-
- assert schema.status == "Failed"
- assert schema.latest_error == cdc_error_info(CDCErrorCategory.UNKNOWN).friendly_message
- mock_reader.confirm_position.assert_not_called()
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- @patch.object(CDCExtractActivity, "_pause_cdc_extraction_schedule")
- def test_unmergeable_schema_fails_non_retryably(
- self,
- _mock_pause_schedule,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- events = [_make_event(op="I", table="users", position="0/100")]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- # A cross-batch Arrow merge conflict (a column that drifted type mid-stream) surfaces
- # from write_batch as ArrowTypeError. Replaying re-fails identically, so the run must
- # stop rather than loop the schedule.
- mock_s3.write_batch.side_effect = pa.ArrowTypeError(
- "Unable to merge: Field seats has incompatible types: int64 vs string"
- )
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
-
- with pytest.raises(NonRetryableException):
- cdc_extract_activity(inputs)
-
- assert schema.status == "Failed"
- assert schema.latest_error == cdc_error_info(CDCErrorCategory.SCHEMA_MERGE_INCOMPATIBLE).friendly_message
- # The raw column/type detail never reaches the user-facing message.
- assert "int64" not in schema.latest_error
- mock_reader.confirm_position.assert_not_called()
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_cdc_last_log_position_updated_per_schema(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- events = [
- _make_event(op="I", table="users", position="0/100"),
- _make_event(op="U", table="users", position="0/200"),
- ]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- # cdc_last_log_position should be updated to the last event's position
- assert schema.sync_type_config["cdc_last_log_position"] == "0/200"
-
- @patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.unpause_external_data_schedule",
- create=True,
- )
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_truncate_only_batch_sets_snapshot_and_advances_slot(
- self,
- mock_close_conns,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- mock_activity,
- mock_unpause,
- ):
- source = _make_source()
- MockSourceModel.objects.get.return_value = source
-
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- mock_get_schemas.return_value = [schema]
-
- mock_reader = MagicMock(last_commit_end_lsn=None)
- mock_reader.read_changes.return_value = iter([]) # no DML events
- mock_reader.truncated_tables = ["users"]
- mock_reader.last_rows_consumed = 0
- mock_reader.last_commit_end_lsn = "0/500"
- mock_reader.get_decoder_key_columns.return_value = []
- mock_adapter = MagicMock()
- mock_adapter.create_reader.return_value = mock_reader
- mock_get_adapter.return_value = mock_adapter
-
- mock_activity.heartbeat = MagicMock()
- mock_activity.info.return_value = MagicMock(workflow_id="wf-1", workflow_run_id="run-1", attempt=1)
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- assert schema.sync_type_config["cdc_mode"] == "snapshot"
- assert schema.sync_type_config["reset_pipeline"] is True
- assert schema.initial_sync_complete is False
- mock_reader.confirm_position.assert_called_once_with("0/500")
-
- # The decoder reports a truncated table qualified, even when the schema is stored bare.
- @parameterized.expand([("bare", "users"), ("qualified_as_the_decoder_reports_it", "public.users")])
- @patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.unpause_external_data_schedule",
- create=True,
- )
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_truncate_sets_snapshot_mode(
- self,
- _name,
- truncated_name,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- mock_unpause,
- ):
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- events = [_make_event(op="I", table="users", position="0/100")]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- mock_reader.truncated_tables = [truncated_name]
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- # Schema should be set back to snapshot mode and forced to re-snapshot from scratch
- assert schema.sync_type_config["cdc_mode"] == "snapshot"
- assert schema.sync_type_config["reset_pipeline"] is True
- assert schema.initial_sync_complete is False
- assert "cdc_last_log_position" not in schema.sync_type_config
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_multi_table_events_grouped_correctly(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- source = _make_source()
- users_schema = _make_schema("users", cdc_mode="streaming", source=source)
- orders_schema = _make_schema("orders", cdc_mode="streaming", source=source)
- events = [
- _make_event(op="I", table="users", position="0/100", columns={"id": 1, "name": "Alice"}),
- _make_event(op="I", table="orders", position="0/200", columns={"id": 10, "total": 99}),
- _make_event(op="U", table="users", position="0/300", columns={"id": 1, "name": "Bob"}),
- ]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [users_schema, orders_schema],
- events,
- )
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- # Should have 2 S3 writes (one for users, one for orders)
- assert mock_s3.write_batch.call_count == 2
-
- # Should have 2 Kafka producers (one for each table)
- assert MockProducer.call_count == 2
-
- # Slot should advance to the last event's position
- mock_reader.confirm_position.assert_called_once_with("0/300")
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_unchanged_sibling_table_logs_no_changes_breadcrumb(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- source = _make_source()
- users_schema = _make_schema("users", cdc_mode="streaming", source=source)
- orders_schema = _make_schema("orders", cdc_mode="streaming", source=source)
- # Only `users` changes this run; `orders` is idle.
- events = [_make_event(op="I", table="users", position="0/100", columns={"id": 1, "name": "Alice"})]
-
- _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [users_schema, orders_schema],
- events,
- )
-
- schema_loggers: dict[str, MagicMock] = {}
-
- def fake_schema_log(schema):
- return schema_loggers.setdefault(schema.name, MagicMock())
-
- with patch.object(CDCExtractActivity, "_schema_log", side_effect=fake_schema_log):
- cdc_extract_activity(CDCExtractInput(team_id=1, source_id=source.id))
-
- def logged_events(name: str) -> list[str]:
- return [call.args[0] for call in schema_loggers[name].info.call_args_list]
-
- assert "cdc_extract_no_changes" in logged_events("orders")
- assert "cdc_extract_no_changes" not in logged_events("users")
-
- @patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.unpause_external_data_schedule",
- create=True,
- )
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_truncated_schema_log_position_not_updated(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- mock_unpause,
- ):
- """A schema reset to snapshot mode by a TRUNCATE should not have
- cdc_last_log_position updated — it will re-snapshot from scratch."""
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- schema.sync_type_config["cdc_last_log_position"] = "0/OLD"
- events = [_make_event(op="I", table="users", position="0/100")]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
- mock_reader.truncated_tables = ["users"]
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- assert schema.sync_type_config.get("cdc_mode") == "snapshot"
- assert schema.sync_type_config.get("reset_pipeline") is True
- assert schema.sync_type_config.get("cdc_last_log_position") is None
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_both_mode_creates_two_trackers(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- schema.sync_type_config["cdc_table_mode"] = "both"
- schema.cdc_table_mode = "both"
- events = [_make_event(op="I", table="users", position="0/100", columns={"id": 1, "name": "Alice"})]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- # Two S3 writes: one for the consolidated table, one for the _cdc table
- assert mock_s3.write_batch.call_count == 2
-
- written_tables = [call[0][0] for call in mock_s3.write_batch.call_args_list]
- consolidated_table = written_tables[0]
- cdc_table = written_tables[1]
-
- # Consolidated table: 1 row (deduplicated INSERT), no valid_from/valid_to
- assert consolidated_table.num_rows == 1
- assert "valid_from" not in consolidated_table.column_names
- assert "valid_to" not in consolidated_table.column_names
-
- # _cdc table: 1 row with SCD2 columns
- assert cdc_table.num_rows == 1
- assert "valid_from" in cdc_table.column_names
- assert "valid_to" in cdc_table.column_names
-
- # Two Kafka producers: one with incremental_merge, one with scd2_append
- assert MockProducer.call_count == 2
- write_modes = {call.kwargs["cdc_write_mode"] for call in MockProducer.call_args_list}
- assert write_modes == {"incremental_merge", "scd2_append"}
-
- resource_names = {call.kwargs["resource_name"] for call in MockProducer.call_args_list}
- assert resource_names == {"users", "users_cdc"}
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_consolidated_table_uses_pinned_folder_name_not_schema_name(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- """Consolidated CDC writes use the pinned folder for bare→qualified schemas."""
- source = _make_source()
- # `name` is qualified, but the folder was pinned to the original bare path during migration.
- schema = _make_schema("public.users", cdc_mode="streaming", source=source, s3_folder_name="users")
- events = [_make_event(op="I", table="public.users", position="0/100", columns={"id": 1, "name": "Alice"})]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- mock_s3.write_batch.assert_called_once()
- assert MockProducer.call_count == 1
- # The fix: storage resource name is the pinned folder ("users"), not "public.users".
- assert MockProducer.call_args.kwargs["resource_name"] == "users"
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_partition_config_replayed_to_loader_when_snapshot_partitioned(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- """Partitioned snapshots replay their partition config to CDC batch notifications."""
- source = _make_source()
- schema = _make_schema(
- "users",
- cdc_mode="streaming",
- source=source,
- partitioning_enabled=True,
- partitioning_keys=["id"],
- partition_mode="numerical",
- partition_size=1_000_000,
- )
- events = [_make_event(op="I", table="users", position="0/100", columns={"id": 1, "name": "Alice"})]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- assert MockProducer.call_count == 1
- kwargs = MockProducer.call_args.kwargs
- assert kwargs["partition_keys"] == ["id"]
- assert kwargs["partition_mode"] == "numerical"
- assert kwargs["partition_size"] == 1_000_000
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_partition_config_omitted_when_snapshot_unpartitioned(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- """Unpartitioned snapshots do not send partition config to CDC batch notifications."""
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source, partitioning_enabled=False)
- events = [_make_event(op="I", table="users", position="0/100", columns={"id": 1, "name": "Alice"})]
-
- _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- assert MockProducer.call_count == 1
- kwargs = MockProducer.call_args.kwargs
- assert kwargs.get("partition_keys") is None
- assert kwargs.get("partition_mode") is None
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_cdc_only_mode_creates_single_cdc_tracker(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- schema.sync_type_config["cdc_table_mode"] = "cdc_only"
- schema.cdc_table_mode = "cdc_only"
- events = [_make_event(op="I", table="users", position="0/100", columns={"id": 1, "name": "Alice"})]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
-
- # Only one S3 write for the _cdc resource
- mock_s3.write_batch.assert_called_once()
- written_table = mock_s3.write_batch.call_args[0][0]
- assert written_table.num_rows == 1
- assert "valid_from" in written_table.column_names
- assert "valid_to" in written_table.column_names
-
- # Only one Kafka producer with scd2_append and _cdc resource name
- assert MockProducer.call_count == 1
- producer_kwargs = MockProducer.call_args.kwargs
- assert producer_kwargs["resource_name"] == "users_cdc"
- assert producer_kwargs["cdc_write_mode"] == "scd2_append"
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ChangeEventBatcher")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_micro_batch_flush_sends_kafka_immediately(
+ def test_setup_app_db_connection_blip_is_not_reported(
self,
+ _name,
+ exception_cls,
mock_close_conns,
- MockJob,
MockSourceModel,
mock_get_schemas,
mock_get_adapter,
- MockS3Writer,
- MockProducer,
mock_activity,
- MockBatcher,
):
- from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (
- ChangeEventBatcher as RealBatcher,
- )
-
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- schema.sync_type_config["cdc_table_mode"] = "consolidated"
- schema.cdc_table_mode = "consolidated"
- events = [
- _make_event(op="I", table="users", position="0/100", columns={"id": 1, "name": "Alice"}),
- _make_event(op="I", table="users", position="0/200", columns={"id": 2, "name": "Bob"}),
- _make_event(op="I", table="users", position="0/300", columns={"id": 3, "name": "Charlie"}),
- ]
-
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- # Use a real batcher with max_events=2 so after the 2nd event should_flush is True
- MockBatcher.return_value = RealBatcher(max_events=2)
+ # `_setup` only reads our own app DB (never a customer's), so a dropped connection here
+ # (e.g. PgBouncer closing an idle connection) is a transient blip, not a broken sync. It
+ # must still be retried by Temporal, but shouldn't page as a fresh, reportable bug on
+ # every attempt.
+ MockSourceModel.DoesNotExist = ExternalDataSource.DoesNotExist
+ MockSourceModel.objects.get.side_effect = exception_cls("server closed the connection unexpectedly")
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
+ inputs = CDCExtractInput(team_id=1, source_id=uuid.uuid4())
- # 2 events trigger a micro-batch flush (non-final), then 1 event triggers the final flush
- # Each flush produces one S3 write and one Kafka send
- assert mock_s3.write_batch.call_count == 2
- assert mock_producer.send_batch_notification.call_count == 2
+ with pytest.raises(NonReportableError, match="server closed the connection unexpectedly"):
+ cdc_extract_activity(inputs)
- # Micro-batch (first call) is NOT the final batch; final flush IS
- send_calls = mock_producer.send_batch_notification.call_args_list
- assert send_calls[0].kwargs["is_final_batch"] is False
- assert send_calls[1].kwargs["is_final_batch"] is True
+ mock_get_schemas.assert_not_called()
+ mock_get_adapter.assert_not_called()
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_deferred_run_stored_per_batch_for_snapshot_schema(
+ def test_reader_closed_on_error(
self,
mock_close_conns,
- MockJob,
MockSourceModel,
mock_get_schemas,
mock_get_adapter,
- MockS3Writer,
- MockProducer,
mock_activity,
):
source = _make_source()
- schema = _make_schema("users", cdc_mode="snapshot", source=source)
- schema.sync_type_config["cdc_table_mode"] = "consolidated"
- schema.cdc_table_mode = "consolidated"
- events = [
- _make_event(op="I", table="users", position="0/100", columns={"id": 1, "name": "Alice"}),
- _make_event(op="I", table="users", position="0/200", columns={"id": 2, "name": "Bob"}),
- ]
+ MockSourceModel.objects.get.return_value = source
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ mock_get_schemas.return_value = [schema]
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
+ mock_reader = MagicMock(last_commit_end_lsn=None)
+ mock_reader.read_changes.side_effect = RuntimeError("connection lost")
+ mock_reader.truncated_tables = []
+ mock_adapter = MagicMock()
+ mock_adapter.create_reader.return_value = mock_reader
+ mock_adapter.is_slot_invalidation_error.return_value = False
+ mock_adapter.classify_error.return_value = None
+ mock_get_adapter.return_value = mock_adapter
- # Snapshot mode defers Kafka — no producer should be created during extraction
- MockProducer.assert_not_called()
+ # Retryable on a non-final attempt: no failure-visibility row, so ExternalDataJob is untouched.
+ mock_activity.info.return_value = MagicMock(workflow_id="wf-1", workflow_run_id="run-1", attempt=1)
- # Exactly one deferred run entry (one tracker for the consolidated table)
- deferred = schema.sync_type_config.get("cdc_deferred_runs", [])
- assert len(deferred) == 1
+ inputs = CDCExtractInput(team_id=1, source_id=source.id)
- entry = deferred[0]
- assert entry["run_uuid"] is not None
- assert len(entry["batch_results"]) == 1
- batch = entry["batch_results"][0]
- assert batch["s3_path"] == "s3://bucket/data/part-0000.parquet"
- assert batch["row_count"] == len(events)
+ with pytest.raises(RuntimeError, match="connection lost"):
+ cdc_extract_activity(inputs)
- # Job should be marked COMPLETED by the activity (no Kafka consumer will do it)
- assert any("status" in call.kwargs.get("update_fields", []) for call in mock_job.save.call_args_list)
+ mock_reader.close.assert_called_once()
class TestSlotAdvanceTransactionSafety:
@@ -2093,87 +511,54 @@ class TestSlotAdvanceTransactionSafety:
LSN while the transaction's tail is still un-yielded would lose the tail on crash.
"""
- @pytest.mark.parametrize(
- "event_positions,max_events,crashes,expected_advances",
+ @parameterized.expand(
[
# Mid-transaction flush: txn-1 (0/100) ×2 then txn-2 (0/200) ×3, flush after
# 4 events lands mid txn-2. The micro-flush advances only to txn-1's end LSN;
# the final flush advances to txn-2's.
- (["0/100", "0/100", "0/200", "0/200", "0/200"], 4, False, ["0/100", "0/200"]),
+ (
+ "flush_mid_second_transaction",
+ ["0/100", "0/100", "0/200", "0/200", "0/200"],
+ 4,
+ [("write", 0), ("advance", "0/100"), ("write", 1), ("advance", "0/200")],
+ ),
# Single transaction (one commit LSN): a threshold of 2 forces a mid-transaction
# micro-flush, but the transaction never completes during the loop, so no
- # micro-advance may happen — only the final flush advances, once.
- (["0/100", "0/100", "0/100"], 2, False, ["0/100"]),
- # Crash mid txn-2 (after the micro-flush at 4 events, before txn-2 finishes):
- # the slot stays at txn-1's end and must never reach txn-2's LSN.
- (["0/100", "0/100", "0/200", "0/200"], 4, True, ["0/100"]),
- ],
+ # micro-advance may happen. Only the final flush advances, once. Both files cover the
+ # same positions, so only the file index stops the second from replacing the first.
+ (
+ "flush_inside_one_transaction",
+ ["0/100", "0/100", "0/100"],
+ 2,
+ [("write", 0), ("write", 1), ("advance", "0/100")],
+ ),
+ ]
)
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ChangeEventBatcher")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_slot_advances_only_past_completed_transactions(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- MockBatcher,
- event_positions,
- max_events,
- crashes,
- expected_advances,
- ):
- from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (
- ChangeEventBatcher as RealBatcher,
- )
-
+ def test_slot_advances_only_past_completed_transactions(self, _name, event_positions, max_events, expected_order):
source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
+ schema = _make_schema("users", source=source)
events = [
_make_event(op="I", table="users", position=pos, columns={"id": i}) for i, pos in enumerate(event_positions)
]
+ order: list[tuple[str, int | str]] = []
- mock_reader, mock_s3, mock_producer, mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- if crashes:
- # The source dies after yielding the listed events but before txn-2 finishes.
- def _dying_changes():
- yield from events
- raise RuntimeError("pod killed mid-transaction")
-
- mock_reader.read_changes.return_value = _dying_changes()
-
- MockBatcher.return_value = RealBatcher(max_events=max_events)
+ def _write(**kwargs):
+ order.append(("write", kwargs["file_index"]))
+ return DEFAULT
- run_ctx = pytest.raises(RuntimeError, match="pod killed mid-transaction") if crashes else nullcontext()
- with run_ctx:
- cdc_extract_activity(CDCExtractInput(team_id=1, source_id=source.id))
+ with (
+ _capture_harness(source, [schema], events) as capture,
+ patch(
+ f"{_ACTIVITIES}.ChangeEventBatcher",
+ side_effect=lambda **kwargs: ChangeEventBatcher(max_events=max_events, **kwargs),
+ ),
+ ):
+ capture.buffer.write_batch.side_effect = _write
+ capture.reader.confirm_position.side_effect = lambda lsn: order.append(("advance", lsn))
+ capture.extract()
- advanced_positions = [c.args[0] for c in mock_reader.confirm_position.call_args_list]
- assert advanced_positions == expected_advances
+ # Every advance comes after the write of the changes it releases.
+ assert order == expected_order
class TestErrorClassification:
@@ -2483,7 +868,6 @@ class TestErrorClassification:
with pytest.raises(psycopg.OperationalError, match="Connection refused"):
cdc_extract_activity(inputs)
- assert schema.latest_error == cdc_error_info(CDCErrorCategory.CONNECTION_FAILED).friendly_message
mock_posthoganalytics.capture.assert_not_called()
@patch(
@@ -2608,166 +992,90 @@ class TestSlotInvalidationRecovery:
"""When the replication slot is invalidated/dropped on the source DB, the activity
must recreate it and reset all CDC schemas to snapshot mode instead of failing forever."""
- def _setup(self, mock_get_schemas, mock_get_adapter, MockSourceModel, mock_activity):
- source = _make_source()
- MockSourceModel.objects.get.return_value = source
+ @contextmanager
+ def _invalidated_slot(self, source, schema) -> Iterator[SimpleNamespace]:
+ with _capture_harness(source, [schema]) as capture:
+ capture.reader.read_changes.side_effect = psycopg.errors.ObjectNotInPrerequisiteState(
+ 'can no longer get changes from replication slot "posthog_slot"\n'
+ "DETAIL: This slot has been invalidated because it exceeded the maximum reserved size."
+ )
+ capture.adapter.is_slot_invalidation_error.return_value = True
+ capture.adapter.recreate_slot.return_value = {"cdc_consistent_point": "0/AA"}
+ yield capture
+ def test_invalidated_slot_is_recreated_and_schemas_reset_to_snapshot(self):
+ source = _make_source()
schema = _make_schema("users", cdc_mode="streaming", source=source)
schema.sync_type_config["cdc_last_log_position"] = "0/OLD"
- schema.sync_type_config["cdc_deferred_runs"] = [{"run_uuid": "stale"}]
- mock_get_schemas.return_value = [schema]
-
- invalidation_error = psycopg.errors.ObjectNotInPrerequisiteState(
- 'can no longer get changes from replication slot "posthog_slot"\n'
- "DETAIL: This slot has been invalidated because it exceeded the maximum reserved size."
- )
- mock_reader = MagicMock(last_commit_end_lsn=None)
- mock_reader.read_changes.side_effect = invalidation_error
- mock_reader.truncated_tables = []
-
- mock_adapter = MagicMock()
- mock_adapter.create_reader.return_value = mock_reader
- mock_adapter.is_slot_invalidation_error.return_value = True
- mock_adapter.classify_error.return_value = None
- mock_get_adapter.return_value = mock_adapter
-
- mock_activity.heartbeat = MagicMock()
- # attempt=1 so the retryable recovery-failure paths don't create failure-visibility rows
- # (which would need ExternalDataJob mocked); job creation is covered in TestFailureVisibilityJobs.
- mock_activity.info.return_value = MagicMock(workflow_id="wf-1", workflow_run_id="run-1", attempt=1)
-
- return source, schema, mock_reader, mock_adapter
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_invalidated_slot_is_recreated_and_schemas_reset_to_snapshot(
- self,
- mock_close_conns,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- mock_activity,
- ):
- source, schema, mock_reader, mock_adapter = self._setup(
- mock_get_schemas, mock_get_adapter, MockSourceModel, mock_activity
- )
- def _recreate_slot(source_arg, tables):
- # Schemas must already be reset when the slot is recreated — if recreation
- # fails, no schema may keep streaming across the gap on the next run.
- assert schema.sync_type_config["cdc_mode"] == "snapshot"
- return {"cdc_consistent_point": "0/AA"}
+ with self._invalidated_slot(source, schema) as capture:
- mock_adapter.recreate_slot.side_effect = _recreate_slot
+ def _recreate_slot(source_arg, tables):
+ # The reset, its buffer purge included, must be complete before the slot is recreated.
+ # Once the new slot exists, no run hits the invalidation error again, so a reset that
+ # failed after that point would never repeat and the schema would stream across the gap.
+ assert schema.sync_type_config["cdc_mode"] == "snapshot"
+ capture.purge.assert_called_once_with(schema.team_id, str(schema.id), ANY, strict=True)
+ return {"cdc_consistent_point": "0/AA"}
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- # Recovery handles the error — the activity must not raise (no pointless Temporal retries).
- cdc_extract_activity(inputs)
+ capture.adapter.recreate_slot.side_effect = _recreate_slot
+ # Recovery handles the error — the activity must not raise (no pointless Temporal retries).
+ capture.extract()
- mock_adapter.recreate_slot.assert_called_once_with(source, tables=["public.users"])
+ capture.adapter.recreate_slot.assert_called_once_with(source, tables=["public.users"])
assert source.job_inputs["cdc_consistent_point"] == "0/AA"
source.save.assert_called()
assert schema.sync_type_config["cdc_mode"] == "snapshot"
assert schema.sync_type_config["reset_pipeline"] is True
assert "cdc_last_log_position" not in schema.sync_type_config
- assert "cdc_deferred_runs" not in schema.sync_type_config
assert schema.initial_sync_complete is False
assert schema.status == "Failed"
assert schema.latest_error == SLOT_INVALIDATION_RECOVERY_MESSAGE
- mock_reader.close.assert_called_once()
+ capture.reader.close.assert_called_once()
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_recreate_passes_source_qualified_table_names(
- self,
- mock_close_conns,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- mock_activity,
- ):
+ def test_recreate_passes_source_qualified_table_names(self):
# Recovery must resolve each schema's real source location from its metadata,
# not assume every table lives in the source's default schema. Otherwise a table
# in a non-default schema gets jammed under `public` and the publication rebuild
# fails with `relation "public.tll.students" does not exist`.
- source, schema, mock_reader, mock_adapter = self._setup(
- mock_get_schemas, mock_get_adapter, MockSourceModel, mock_activity
- )
- schema.name = "students"
+ source = _make_source()
+ schema = _make_schema("students", cdc_mode="streaming", source=source)
schema.sync_type_config["schema_metadata"] = {"source_schema": "tll", "source_table_name": "students"}
- mock_adapter.recreate_slot.return_value = {"cdc_consistent_point": "0/AA"}
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- cdc_extract_activity(inputs)
+ with self._invalidated_slot(source, schema) as capture:
+ capture.extract()
- mock_adapter.recreate_slot.assert_called_once_with(source, tables=["tll.students"])
+ capture.adapter.recreate_slot.assert_called_once_with(source, tables=["tll.students"])
assert source.job_inputs["cdc_consistent_point"] == "0/AA"
source.save.assert_called()
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_recovery_failure_marks_schemas_failed_and_raises(
- self,
- mock_close_conns,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- mock_activity,
- ):
- source, schema, mock_reader, mock_adapter = self._setup(
- mock_get_schemas, mock_get_adapter, MockSourceModel, mock_activity
- )
- mock_adapter.recreate_slot.side_effect = RuntimeError("cannot recreate slot")
+ def test_recovery_failure_marks_schemas_failed_and_raises(self):
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- with pytest.raises(RuntimeError, match="cannot recreate slot"):
- cdc_extract_activity(inputs)
+ with self._invalidated_slot(source, schema) as capture:
+ capture.adapter.recreate_slot.side_effect = RuntimeError("cannot recreate slot")
+ capture.activity.info.return_value.attempt = CDC_MAX_EXTRACTION_ATTEMPTS
+ with pytest.raises(RuntimeError, match="cannot recreate slot"):
+ capture.extract()
assert schema.status == "Failed"
# The raw recovery error stays in the logs; the user-facing column gets friendly copy.
assert schema.latest_error == cdc_error_info(CDCErrorCategory.UNKNOWN).friendly_message
assert "cannot recreate slot" not in schema.latest_error
- mock_reader.close.assert_called_once()
+ capture.reader.close.assert_called_once()
@parameterized.expand([("recreation_failed", True), ("recreation_succeeded", False)])
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_a_reset_waits_for_the_new_slot_before_a_later_run_can_finish_it(
- self,
- _name,
- awaits_slot,
- mock_close_conns,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- mock_activity,
- ):
+ def test_a_reset_waits_for_the_new_slot_before_a_later_run_can_finish_it(self, _name, awaits_slot):
# A reset left pending by recovery must stay paused while the slot is missing: its snapshot
# would start with no consistent point for capture to resume from.
- source, schema, mock_reader, mock_adapter = self._setup(
- mock_get_schemas, mock_get_adapter, MockSourceModel, mock_activity
- )
- if awaits_slot:
- mock_adapter.recreate_slot.side_effect = RuntimeError("cannot recreate slot")
- else:
- mock_adapter.recreate_slot.return_value = {"cdc_consistent_point": "0/AA"}
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
with (
+ self._invalidated_slot(source, schema) as capture,
patch(
"products.warehouse_sources.backend.temporal.data_imports.cdc.activities.cancel_running_sync",
return_value="users-snapshot",
@@ -2775,38 +1083,26 @@ class TestSlotInvalidationRecovery:
patch("products.data_warehouse.backend.facade.api.unpause_external_data_schedule") as unpause,
):
if awaits_slot:
+ capture.adapter.recreate_slot.side_effect = RuntimeError("cannot recreate slot")
with pytest.raises(RuntimeError, match="cannot recreate slot"):
- cdc_extract_activity(inputs)
+ capture.extract()
else:
- cdc_extract_activity(inputs)
+ capture.extract()
unpause.assert_not_called()
assert schema.sync_type_config["cdc_reset_pending"]["awaiting_slot"] is awaits_slot
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_non_invalidation_errors_do_not_trigger_recovery(
- self,
- mock_close_conns,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- mock_activity,
- ):
- source, schema, mock_reader, mock_adapter = self._setup(
- mock_get_schemas, mock_get_adapter, MockSourceModel, mock_activity
- )
- mock_reader.read_changes.side_effect = RuntimeError("connection lost")
- mock_adapter.is_slot_invalidation_error.return_value = False
+ def test_non_invalidation_errors_do_not_trigger_recovery(self):
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
- inputs = CDCExtractInput(team_id=1, source_id=source.id)
- with pytest.raises(RuntimeError, match="connection lost"):
- cdc_extract_activity(inputs)
+ with self._invalidated_slot(source, schema) as capture:
+ capture.reader.read_changes.side_effect = RuntimeError("connection lost")
+ capture.adapter.is_slot_invalidation_error.return_value = False
+ with pytest.raises(RuntimeError, match="connection lost"):
+ capture.extract()
- mock_adapter.recreate_slot.assert_not_called()
+ capture.adapter.recreate_slot.assert_not_called()
assert schema.sync_type_config["cdc_mode"] == "streaming"
@@ -2893,74 +1189,10 @@ class TestCleanupOrphanSlotsRetentionCap:
mock_mark_broken.assert_not_called()
-class TestExtractionHeartbeat:
- """Every run records a per-schema last-run heartbeat in sync_type_config so a quiet (zero-event)
- source still proves extraction is alive — without an ExternalDataJob row per idle hourly run."""
-
- @parameterized.expand(
- [
- ("no_changes_records_zero", [], 0),
- (
- "with_events_records_count",
- [
- _make_event(op="I", table="users", position="0/100"),
- _make_event(op="U", table="users", position="0/200"),
- ],
- 2,
- ),
- ]
- )
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_records_last_run_heartbeat(
- self,
- _name,
- events,
- expected_count,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
-
- cdc_extract_activity(CDCExtractInput(team_id=1, source_id=source.id))
-
- config = schema.sync_type_config
- assert config["cdc_last_run_event_count"] == expected_count
- # Stored as an ISO-8601 string so the health check and cdc_status can parse it back.
- assert isinstance(config["cdc_last_run_at"], str)
- datetime.fromisoformat(config["cdc_last_run_at"])
-
-
class TestFailureVisibilityJobs:
- """A run that fails before the first micro-flush creates no job in the normal path, leaving the
- Syncs tab blank while the schema reads FAILED. The activity backfills a terminal FAILED row —
- but only once retries are exhausted or the error is non-retryable, never per transient retry."""
+ """Capture creates no job of its own, so a failed run would leave the Syncs tab blank while the
+ schema reads FAILED. The activity writes a terminal FAILED row — but only once retries are
+ exhausted or the error is non-retryable, never per transient retry."""
def _drive_failure(
self,
@@ -2992,7 +1224,11 @@ class TestFailureVisibilityJobs:
MockJob.objects.create.return_value = MagicMock(id=uuid.uuid4())
mock_activity.heartbeat = MagicMock()
- mock_activity.info.return_value = MagicMock(workflow_id="wf-1", workflow_run_id="run-1", attempt=attempt)
+ mock_activity.in_activity.return_value = attempt is not None
+ if attempt is None:
+ mock_activity.info.side_effect = RuntimeError("Not in activity context")
+ else:
+ mock_activity.info.return_value = MagicMock(workflow_id="wf-1", workflow_run_id="run-1", attempt=attempt)
# The non-retryable pause hits Temporal (sync_connect); stub it so these stay off the network.
with (
@@ -3052,6 +1288,7 @@ class TestFailureVisibilityJobs:
mock_activity=mock_activity,
)
+ assert (schema.status == ExternalDataSchema.Status.FAILED) is expect_created
if not expect_created:
MockJob.objects.create.assert_not_called()
return
@@ -3066,6 +1303,36 @@ class TestFailureVisibilityJobs:
# User-facing column carries the friendly, credential-safe copy — never the raw exception.
assert kwargs["latest_error"] == cdc_error_info(expected_category).friendly_message
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
+ @patch.object(CDCExtractActivity, "_get_cdc_schemas")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
+ def test_a_retryable_failure_outside_an_activity_marks_the_schema_failed(
+ self,
+ mock_close_conns,
+ MockJob,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ mock_activity,
+ ):
+ schema = _make_schema("users", cdc_mode="streaming")
+ self._drive_failure(
+ error=psycopg.OperationalError("connection refused"),
+ attempt=None,
+ schemas=[schema],
+ MockJob=MockJob,
+ MockSourceModel=MockSourceModel,
+ mock_get_schemas=mock_get_schemas,
+ mock_get_adapter=mock_get_adapter,
+ mock_activity=mock_activity,
+ )
+
+ assert schema.status == ExternalDataSchema.Status.FAILED
+ assert schema.latest_error == cdc_error_info(CDCErrorCategory.CONNECTION_FAILED).friendly_message
+
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -3300,113 +1567,39 @@ class TestQuietRunSlotAdvance:
act._handle_no_changes([])
- assert act.cdc_schemas[0].status == ExternalDataSchema.Status.COMPLETED
-
-
-class TestSuccessRepaintGuards:
- """A run finishing after the sweeper marked the source broken must not repaint the schema
- healthy — that hides the breakage from the UI and from the failure digest email."""
-
- def _activity_with(self, *schemas):
- source = schemas[0].source
- act = _make_extract_activity(source)
- act.cdc_schemas = list(schemas)
- return act
-
- @pytest.mark.parametrize("finalize", ["success", "no_changes"])
- def test_broken_schema_keeps_failed_state_and_paused_marker_clears(self, finalize):
- source = _make_source()
- broken = _make_schema("broken_table", source=source)
- broken.status = "Failed"
- broken.sync_type_config["cdc_broken"] = {"reason": "auto_dropped_critical_lag"}
- recovered = _make_schema("recovered_table", source=source)
- recovered.sync_type_config["cdc_extraction_paused"] = {"reason": "auth_failed"}
- act = self._activity_with(broken, recovered)
-
- if finalize == "success":
- act._finalize_success()
- else:
- act.reader = MagicMock(last_commit_end_lsn=None)
- act._handle_no_changes([])
-
- assert broken.status == "Failed"
- assert "cdc_broken" in broken.sync_type_config
- assert recovered.status == ExternalDataSchema.Status.COMPLETED
- # A successful run proves extraction resumed; the stale pause marker must not keep the
- # digest email reporting "paused, action required".
- assert "cdc_extraction_paused" not in recovered.sync_type_config
+ assert "cdc_last_run_at" in act.cdc_schemas[0].sync_type_config
- def test_a_buffered_schema_clears_its_pause_marker_but_keeps_the_consumers_status(self):
+ def test_a_quiet_run_releases_the_wal_up_to_where_its_peek_began(self):
+ # WAL committed after the peek began was never examined, so the release must stop at the
+ # position taken before the peek.
source = _make_source()
- buffered = _make_schema("buffered_table", source=source)
- buffered.status = ExternalDataSchema.Status.FAILED
- buffered.sync_type_config["cdc_extraction_paused"] = {"reason": "transaction_too_large"}
- act = self._activity_with(buffered)
- act._buffered_table_names = {"buffered_table"}
+ schema = _make_schema("users", source=source)
- act._finalize_success()
+ with _capture_harness(source, [schema]) as capture:
+ capture.reader.current_position.side_effect = lambda: (
+ "0/A00" if capture.reader.read_changes.called else "0/900"
+ )
+ capture.extract()
- assert "cdc_extraction_paused" not in buffered.sync_type_config
- assert buffered.status == ExternalDataSchema.Status.FAILED
+ capture.reader.confirm_position.assert_called_once_with("0/900")
+ capture.reader.close.assert_called_once()
class TestCDCBoundedReadLoop:
"""The read loop peeks at most CDC_MAX_CHANGES_PER_READ changes per pass, advancing the slot
between passes so a large backlog drains over several passes (and, if needed, runs)."""
- def _run_with_reader(
- self,
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- reader,
- ):
+ def _run_with_reader(self, reader) -> SimpleNamespace:
source = _make_source()
schema = _make_schema("users", cdc_mode="streaming", source=source)
schema.sync_type_config["primary_key_columns"] = ["id"]
- _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- [],
- )
- # Replace the default MagicMock reader with the scripted multi-pass reader.
- mock_get_adapter.return_value.create_reader.return_value = reader
+ with _capture_harness(source, [schema]) as capture:
+ # Replace the default MagicMock reader with the scripted multi-pass reader.
+ capture.adapter.create_reader.return_value = reader
+ capture.extract()
+ return capture
- cdc_extract_activity(CDCExtractInput(team_id=1, source_id=source.id))
- return schema
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_full_page_then_drained_advances_slot_between_passes(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
+ def test_full_page_then_drained_advances_slot_between_passes(self):
reader = _ScriptedReader(
[
([_make_event(op="I", table="users", position="0/100")], CDC_MAX_CHANGES_PER_READ, "0/100"),
@@ -3414,87 +1607,36 @@ class TestCDCBoundedReadLoop:
]
)
- self._run_with_reader(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- reader,
- )
+ capture = self._run_with_reader(reader)
# Two peeks: a full page, then a drained one. The first pass advances the slot to its last
# commit before re-peeking; the final flush advances to the second pass's last event.
assert len(reader.upto_nchanges_calls) == 2
assert reader.confirmed_positions == ["0/100", "0/200"]
+ # The first pass is written before the second peek, so the advance between them releases
+ # nothing that exists only in memory.
+ written = [
+ c.kwargs["table"].column(CDC_SEQ_COLUMN).to_pylist() for c in capture.buffer.write_batch.call_args_list
+ ]
+ assert written == [[0x100], [0x200]]
# The per-row heartbeat callback was wired through read_changes and fired during the reads.
assert reader.on_row_calls == 2
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_soft_deadline_stops_starting_new_passes(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- monkeypatch,
- ):
+ def test_soft_deadline_stops_starting_new_passes(self, monkeypatch):
# Deadline already elapsed: a full first page must not start a second pass.
- monkeypatch.setattr(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDC_READ_SOFT_DEADLINE_SECONDS", 0
- )
+ monkeypatch.setattr(f"{_ACTIVITIES}.CDC_READ_SOFT_DEADLINE_SECONDS", 0)
reader = _ScriptedReader(
[([_make_event(op="I", table="users", position="0/100")], CDC_MAX_CHANGES_PER_READ, "0/100")]
)
- schema = self._run_with_reader(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- reader,
- )
+ capture = self._run_with_reader(reader)
assert len(reader.upto_nchanges_calls) == 1 # no second peek despite a full page
- assert schema.status == "Completed" # the run still finalizes what it read
+ # The run still delivers what it read.
+ capture.buffer.write_batch.assert_called_once()
+ assert reader.confirmed_positions == ["0/100"]
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_full_page_with_no_committed_progress_doubles_the_limit(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
+ def test_full_page_with_no_committed_progress_doubles_the_limit(self):
# Defensive backstop: a full page that commits nothing (so the slot can't advance) grows
# the window instead of re-peeking the identical page forever.
reader = _ScriptedReader(
@@ -3504,40 +1646,12 @@ class TestCDCBoundedReadLoop:
]
)
- self._run_with_reader(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- reader,
- )
+ self._run_with_reader(reader)
assert reader.upto_nchanges_calls == [CDC_MAX_CHANGES_PER_READ, CDC_MAX_CHANGES_PER_READ * 2]
assert reader.confirmed_positions == ["0/300"] # nothing to advance on pass 1; pass 2 drains
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
- @patch.object(CDCExtractActivity, "_get_cdc_schemas")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
- def test_heartbeat_timeout_does_not_abort_the_read_loop(
- self,
- mock_close_conns,
- MockJob,
- MockSourceModel,
- mock_get_schemas,
- mock_get_adapter,
- MockS3Writer,
- MockProducer,
- mock_activity,
- ):
+ def test_heartbeat_timeout_does_not_abort_the_read_loop(self):
# The Temporal SDK relays a sync activity's heartbeat through the worker's event loop
# with its own short internal timeout, which can trip transiently under load. That must
# never fail an otherwise-healthy extraction.
@@ -3545,88 +1659,14 @@ class TestCDCBoundedReadLoop:
schema = _make_schema("users", cdc_mode="streaming", source=source)
schema.sync_type_config["primary_key_columns"] = ["id"]
events = [_make_event(op="I", table="users", position="0/100")]
- _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- mock_close_conns,
- source,
- [schema],
- events,
- )
- mock_activity.heartbeat.side_effect = TimeoutError()
-
- cdc_extract_activity(CDCExtractInput(team_id=1, source_id=source.id))
-
- assert mock_activity.heartbeat.called
- assert schema.status == "Completed"
-
-
-class TestReconcileOrphanedPriorJobs:
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.psycopg.Connection.connect")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.BatchQueue.count_batches_for_run")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
- def test_only_fails_stale_prior_runs_with_no_queued_batches(self, mock_activity, mock_count, mock_connect, team):
- mock_activity.info.return_value = MagicMock(workflow_run_id="current-run")
-
- source = ExternalDataSource.objects.create(
- team_id=team.pk,
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- status="Completed",
- source_type="Postgres",
- )
- schema = ExternalDataSchema.objects.create(
- team_id=team.pk,
- source=source,
- name="users",
- sync_type=ExternalDataSchema.SyncType.CDC,
- sync_type_config={"cdc_mode": "streaming"},
- )
-
- def _job(workflow_run_id: str, age: timedelta) -> ExternalDataJob:
- job = ExternalDataJob.objects.create(
- team_id=team.pk,
- pipeline_id=source.pk,
- schema=schema,
- status=ExternalDataJob.Status.RUNNING,
- rows_synced=0,
- workflow_id="wf",
- workflow_run_id=workflow_run_id,
- pipeline_version=ExternalDataJob.PipelineVersion.V3,
- )
- # created_at is auto_now_add; backdate via update to control the reconcile window.
- ExternalDataJob.objects.filter(id=job.id).update(created_at=datetime.now(UTC) - age)
- return job
-
- old_no_batch = _job("old-1", timedelta(hours=2)) # stale, ended, empty -> FAILED
- old_with_batch = _job("old-2", timedelta(hours=2)) # stale but queued -> left alone
- current_run = _job("current-run", timedelta(hours=2)) # this run's own -> left alone
- too_recent = _job("recent-1", CDC_ORPHAN_JOB_MIN_AGE / 2) # inside floor -> left alone
- ancient = _job("ancient-1", timedelta(days=20)) # past batch retention -> left alone
-
- # Only old_with_batch reports queued batches; the rest have none.
- mock_count.side_effect = lambda conn, job_id: 3 if job_id == str(old_with_batch.id) else 0
- activity_obj = CDCExtractActivity(CDCExtractInput(team_id=team.pk, source_id=source.pk))
- activity_obj.log = MagicMock()
- activity_obj.cdc_schemas = [schema]
-
- activity_obj._reconcile_orphaned_prior_jobs()
+ with _capture_harness(source, [schema], events) as capture:
+ capture.activity.heartbeat.side_effect = TimeoutError()
+ capture.extract()
- old_no_batch.refresh_from_db()
- assert old_no_batch.status == ExternalDataJob.Status.FAILED
- assert old_no_batch.latest_error == CDC_ORPHANED_JOB_MESSAGE
- assert old_no_batch.finished_at is not None
-
- for untouched in (old_with_batch, current_run, too_recent, ancient):
- untouched.refresh_from_db()
- assert untouched.status == ExternalDataJob.Status.RUNNING
+ assert capture.activity.heartbeat.called
+ capture.buffer.write_batch.assert_called_once()
+ capture.reader.confirm_position.assert_called_once_with("0/100")
@pytest.mark.django_db
@@ -3639,59 +1679,23 @@ class TestFailureVisibilityCooldown:
AUTH_FAILED = cdc_error_info(CDCErrorCategory.AUTH_FAILED).friendly_message
@pytest.mark.parametrize(
- "previous_status,previous_error,previous_rows_synced,previous_age_minutes,snapshot_run_since,expect_new_row",
+ "previous_error,previous_age_minutes,scheduled_sync_since,expect_new_row",
[
# Nothing has changed since the last extraction row said exactly this — no new row.
- pytest.param(
- ExternalDataJob.Status.FAILED,
- CONNECTION_FAILED,
- 0,
- 0,
- False,
- False,
- id="identical_failure_within_cooldown",
- ),
- # A schema still snapshotting keeps running the regular per-schema pipeline; those rows
- # say nothing about whether this failure has been reported, so they don't reopen it.
- pytest.param(
- ExternalDataJob.Status.FAILED,
- CONNECTION_FAILED,
- 0,
- 0,
- True,
- False,
- id="unrelated_snapshot_run_since",
- ),
+ pytest.param(CONNECTION_FAILED, 0, False, False, id="identical_failure_within_cooldown"),
+ # The table's own scheduled sync runs alongside capture; its rows say nothing about
+ # whether this failure has been reported, so they don't reopen it.
+ pytest.param(CONNECTION_FAILED, 0, True, False, id="unrelated_scheduled_sync_since"),
# Everything below is news, so the outage gets a fresh row.
- pytest.param(
- ExternalDataJob.Status.FAILED,
- CONNECTION_FAILED,
- 0,
- 90,
- False,
- True,
- id="identical_failure_past_cooldown",
- ),
- pytest.param(ExternalDataJob.Status.COMPLETED, None, 10, 0, False, True, id="extraction_succeeded_since"),
- pytest.param(ExternalDataJob.Status.FAILED, AUTH_FAILED, 0, 0, False, True, id="different_error_since"),
- pytest.param(
- ExternalDataJob.Status.FAILED,
- CONNECTION_FAILED,
- 10,
- 0,
- False,
- True,
- id="previous_run_synced_rows_first",
- ),
+ pytest.param(CONNECTION_FAILED, 90, False, True, id="identical_failure_past_cooldown"),
+ pytest.param(AUTH_FAILED, 0, False, True, id="different_error_since"),
],
)
def test_repeat_failure_rows_collapse_until_something_changes(
self,
- previous_status,
previous_error,
- previous_rows_synced,
previous_age_minutes,
- snapshot_run_since,
+ scheduled_sync_since,
expect_new_row,
team,
):
@@ -3714,8 +1718,8 @@ class TestFailureVisibilityCooldown:
team_id=team.pk,
pipeline_id=source.pk,
schema=schema,
- status=previous_status,
- rows_synced=previous_rows_synced,
+ status=ExternalDataJob.Status.FAILED,
+ rows_synced=0,
latest_error=previous_error,
workflow_id=f"cdc-extraction-{source.pk}-2026-08-04T18:15:00Z",
workflow_run_id="run-1",
@@ -3726,7 +1730,7 @@ class TestFailureVisibilityCooldown:
created_at=datetime.now(UTC) - timedelta(minutes=previous_age_minutes)
)
- if snapshot_run_since:
+ if scheduled_sync_since:
ExternalDataJob.objects.create(
team_id=team.pk,
pipeline_id=source.pk,
@@ -3734,7 +1738,7 @@ class TestFailureVisibilityCooldown:
status=ExternalDataJob.Status.COMPLETED,
rows_synced=0,
workflow_id=f"{schema.pk}-2026-08-04T18:20:00Z",
- workflow_run_id="run-snapshot",
+ workflow_run_id="run-scheduled-sync",
pipeline_version=ExternalDataJob.PipelineVersion.V3,
)
@@ -3753,75 +1757,10 @@ class TestFailureVisibilityCooldown:
class TestBufferedIngressCapture:
- # Capture for a flipped source: eligible schemas are delivered by buffer alone, ineligible ones
- # keep today's transforms and sourcebatch dispatch, and a buffer failure must fail the run —
- # the slot is about to advance past those changes.
-
- def _run(
- self,
- MockBufferWriter,
- events,
- schemas,
- source,
- capture: dict | None = None,
- truncated=(),
- snapshot_flag=True,
- commit_end_lsn=None,
- ):
- with (
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.is_buffered_snapshot_enabled",
- return_value=snapshot_flag,
- ),
- patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections"),
- patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataJob") as MockJob,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource"
- ) as MockSourceModel,
- patch.object(CDCExtractActivity, "_get_cdc_schemas") as mock_get_schemas,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter"
- ) as mock_get_adapter,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.S3BatchWriter"
- ) as MockS3Writer,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer"
- ) as MockProducer,
- patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity") as mock_activity,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.is_shadow_write_enabled",
- return_value=False,
- ),
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.complete_schema_run"
- ) as mock_complete,
- ):
- MockBufferWriter.return_value.write_batch.return_value.write_duration_seconds = 0.01
- mock_reader, mock_s3, mock_producer, _mock_job = _setup_mocks(
- mock_activity,
- MockProducer,
- MockS3Writer,
- mock_get_adapter,
- mock_get_schemas,
- MockSourceModel,
- MockJob,
- MagicMock(),
- source,
- schemas,
- events,
- )
- mock_get_adapter.return_value.parse_cdc_config.return_value.ingest_mode = "buffered"
- mock_reader.truncated_tables = list(truncated)
- mock_reader.last_commit_end_lsn = commit_end_lsn
- if capture is not None:
- capture["reader_ref"] = mock_reader
- capture["complete_schema_run"] = mock_complete
- cdc_extract_activity(CDCExtractInput(team_id=1, source_id=source.id))
- return mock_reader, mock_s3, mock_producer
+ # The buffer is the only delivery of a table's changes, and the table's scheduled sync consumes
+ # it. A buffer failure must fail the run, because the slot is about to advance past those changes.
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_a_buffered_schema_is_delivered_by_buffer_alone(self, MockBufferWriter):
+ def test_a_run_buffers_the_raw_change_stream_and_records_its_position(self):
source = _make_source()
schema = _make_schema("users", cdc_mode="streaming", source=source)
events = [
@@ -3829,50 +1768,109 @@ class TestBufferedIngressCapture:
_make_event(op="U", position="0/200", columns={"id": 1, "name": "Bob"}),
]
- mock_reader, mock_s3, mock_producer = self._run(MockBufferWriter, events, [schema], source)
+ with _capture_harness(source, [schema], events) as capture:
+ capture.extract()
- buffered = MockBufferWriter.return_value.write_batch.call_args.kwargs["table"]
- assert buffered.column(CDC_SEQ_COLUMN).to_pylist() == [0x100, 0x200]
+ buffered = capture.buffer.write_batch.call_args.kwargs["table"]
# Raw stream, seq intact — the loader dedupes and resolves positions.
- assert buffered.num_rows == 2
- # No legacy delivery: no S3 batch, no sourcebatch row, so no ExternalDataJob to bill.
- mock_s3.write_batch.assert_not_called()
- mock_producer.send_batch_notification.assert_not_called()
+ assert buffered.column(CDC_SEQ_COLUMN).to_pylist() == [0x100, 0x200]
# The point of the whole design: durable buffer releases the customer's WAL immediately.
- mock_reader.confirm_position.assert_called_once_with("0/200")
+ capture.reader.confirm_position.assert_called_once_with("0/200")
+ assert schema.sync_type_config["cdc_last_log_position"] == "0/200"
+
+ def test_wal_events_reach_the_schema_they_belong_to(self):
+ # WAL events are always schema-qualified, but a schema's `name` may be stored bare. An exact
+ # name match would drop every change for that schema, and the table would go stale despite a
+ # healthy slot. Events for a table no schema covers are dropped.
+ source = _make_source()
+ schema = _make_schema("orders", cdc_mode="streaming", source=source)
+ events = [
+ _make_event(op="I", table="public.orders", position="0/100", columns={"id": 1}),
+ _make_event(op="I", table="public.not_synced", position="0/200", columns={"id": 2}),
+ ]
+
+ with _capture_harness(source, [schema], events) as capture:
+ capture.extract()
+
+ written = [
+ (c.kwargs["schema_id"], c.kwargs["table"].num_rows) for c in capture.buffer.write_batch.call_args_list
+ ]
+ assert written == [(str(schema.id), 1)]
@parameterized.expand(
[
- ("flag_on_starts_it_in_the_buffer", True, {}, True),
- ("flag_off_keeps_it_on_deferred_runs", False, {}, False),
- (
- "a_snapshot_already_in_the_buffer_stays_there_when_the_flag_is_off",
- False,
- {CDC_SNAPSHOT_LANE_KEY: "buffer"},
- True,
- ),
+ ("known_mode_captured", "consolidated", {}, True),
+ # No lane consumes an unrecognized mode, so the buffer could never deliver its changes.
+ ("unrecognized_mode_skipped", "not_a_table_mode", {}, False),
]
)
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_a_snapshotting_tables_changes_follow_its_snapshot_lane(
- self, _name, snapshot_flag, config, buffered, MockBufferWriter, mock_purge
- ):
+ def test_each_captured_table_gets_its_own_file(self, _name, orders_table_mode, orders_config, orders_captured):
+ source = _make_source()
+ users = _make_schema("users", cdc_mode="streaming", source=source)
+ orders = _make_schema("orders", cdc_mode="streaming", cdc_table_mode=orders_table_mode, source=source)
+ orders.sync_type_config.update(orders_config)
+ events = [
+ _make_event(op="I", table="users", position="0/100", columns={"id": 1}),
+ _make_event(op="I", table="orders", position="0/200", columns={"id": 10}),
+ _make_event(op="U", table="users", position="0/300", columns={"id": 1}),
+ ]
+
+ with _capture_harness(source, [users, orders], events) as capture:
+ capture.extract()
+
+ written = sorted(
+ (c.kwargs["schema_id"], c.kwargs["table"].num_rows) for c in capture.buffer.write_batch.call_args_list
+ )
+ expected = [(str(users.id), 2), *([(str(orders.id), 1)] if orders_captured else [])]
+ assert written == sorted(expected)
+ capture.reader.confirm_position.assert_called_once_with("0/300")
+
+ @parameterized.expand(
+ [
+ ("unmarked_snapshot_starts_in_an_emptied_buffer", {}, True),
+ ("marked_snapshot_keeps_its_buffer", {CDC_SNAPSHOT_LANE_KEY: "buffer"}, False),
+ ]
+ )
+ def test_a_snapshotting_tables_changes_wait_in_the_buffer(self, _name, config, purged):
source = _make_source()
seeding = _make_schema("events", cdc_mode="snapshot", source=source)
seeding.initial_sync_complete = False
seeding.sync_type_config.update(config)
events = [_make_event(op="I", position="0/100", table="events", columns={"id": 1})]
+ at_read: dict = {}
- _reader, mock_s3, _producer = self._run(
- MockBufferWriter, events, [seeding], source, snapshot_flag=snapshot_flag
- )
+ with _capture_harness(source, [seeding], events) as capture:
+
+ def _read_changes(**_kwargs):
+ at_read["purges"] = [(c.args[1], c.kwargs["strict"]) for c in capture.purge.call_args_list]
+ at_read["lane"] = seeding.sync_type_config.get(CDC_SNAPSHOT_LANE_KEY)
+ return iter(events)
+
+ capture.reader.read_changes.side_effect = _read_changes
+ capture.extract()
+
+ # Emptied before the read, and strictly: files from before a gap in capture must not replay
+ # over the snapshot. Marked before the read too. Otherwise a crash after the first write would
+ # have the next run empty the buffer again and drop changes the slot already released.
+ expected_purges = [(str(seeding.id), True)] if purged else []
+ assert at_read == {"purges": expected_purges, "lane": "buffer"}
+ assert capture.purge.call_count == len(expected_purges)
+ capture.buffer.write_batch.assert_called_once()
- assert MockBufferWriter.return_value.write_batch.called is buffered
- assert mock_s3.write_batch.called is not buffered
- assert (seeding.sync_type_config.get(CDC_SNAPSHOT_LANE_KEY) == "buffer") is buffered
- # Only a snapshot starting in the buffer empties it: files from before a gap must not replay.
- assert [c.kwargs["strict"] for c in mock_purge.call_args_list] == ([True] if buffered and not config else [])
+ def test_a_snapshot_that_hands_over_first_is_left_unmarked(self):
+ # The hand-over clears the marker when it flips the table. A marker set after the flip would
+ # outlive the snapshot it described.
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="snapshot", source=source)
+ act = _make_extract_activity(source)
+
+ with patch(
+ f"{_ACTIVITIES}.purge_buffer_prefix",
+ side_effect=lambda *_a, **_k: schema.sync_type_config.update(cdc_mode="streaming"),
+ ):
+ act._start_snapshot_in_buffer(schema)
+
+ assert CDC_SNAPSHOT_LANE_KEY not in schema.sync_type_config
def test_a_truncate_is_handled_before_the_slot_advances_past_it(self):
source = _make_source()
@@ -3897,59 +1895,34 @@ class TestBufferedIngressCapture:
assert [call[0] for call in order.mock_calls] == ["purge", "confirm"]
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_a_truncate_drops_the_tables_pending_changes_and_purges_strictly(self, MockBufferWriter, mock_purge):
+ @parameterized.expand(
+ [
+ # The re-snapshot covers the changes read before the TRUNCATE, and buffering them would
+ # bring the truncated rows back.
+ ("after_changes_in_the_same_run", [_make_event(op="I", position="0/100", columns={"id": 1})], "users"),
+ ("with_no_other_changes", [], "users"),
+ ("reported_qualified_for_a_bare_schema", [], "public.users"),
+ ]
+ )
+ def test_a_truncate_resets_the_table_to_a_snapshot_in_an_emptied_buffer(self, _name, events, truncated_name):
source = _make_source()
schema = _make_schema("users", cdc_mode="streaming", source=source)
- events = [_make_event(op="I", position="0/100", columns={"id": 1})]
+ schema.sync_type_config["cdc_last_log_position"] = "0/OLD"
- # The TRUNCATE commits after the last row event, in a transaction of its own.
- reader, _s3, _producer = self._run(
- MockBufferWriter, events, [schema], source, truncated=["users"], commit_end_lsn="0/300"
- )
+ with _capture_harness(source, [schema], events) as capture:
+ capture.reader.truncated_tables = [truncated_name]
+ capture.reader.last_commit_end_lsn = "0/500"
+ capture.extract()
- # Confirming only the last event's position would read the TRUNCATE again and reset the table
- # a second time, dropping changes a snapshot started in between never saw.
- assert reader.confirm_position.call_args_list[-1].args == ("0/300",)
- MockBufferWriter.return_value.write_batch.assert_not_called()
- assert mock_purge.call_args.kwargs["strict"] is True
+ capture.buffer.write_batch.assert_not_called()
+ # Strict, because a stale file that survives the run would be replayed over the re-snapshot.
+ assert [(c.args[1], c.kwargs["strict"]) for c in capture.purge.call_args_list] == [(str(schema.id), True)]
assert schema.sync_type_config["cdc_mode"] == "snapshot"
+ assert schema.sync_type_config["reset_pipeline"] is True
assert schema.sync_type_config[CDC_SNAPSHOT_LANE_KEY] == "buffer"
-
- @patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix",
- side_effect=Exception("s3 down"),
- )
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_a_failed_purge_after_a_truncate_leaves_the_table_unmarked(self, MockBufferWriter, _mock_purge):
- # The hand-over keeps every file of a marked schema, so a marker left by a failed purge would
- # replay the pre-TRUNCATE files over the re-snapshot.
- source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
- events = [_make_event(op="I", position="0/100", columns={"id": 1})]
- captured: dict = {}
-
- with pytest.raises(Exception, match="s3 down"):
- self._run(MockBufferWriter, events, [schema], source, capture=captured, truncated=["users"])
-
- captured["reader_ref"].confirm_position.assert_not_called()
- assert schema.sync_type_config["cdc_mode"] == "streaming"
- assert CDC_SNAPSHOT_LANE_KEY not in schema.sync_type_config
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")
- def test_a_snapshot_that_hands_over_first_is_left_unmarked(self, mock_purge):
- # The hand-over clears the marker when it flips the table. A marker set after the flip would
- # outlive the snapshot, and the rollback command would refuse the source for good.
- source = _make_source()
- schema = _make_schema("users", cdc_mode="snapshot", source=source)
- act = _make_extract_activity(source)
- mock_purge.side_effect = lambda *_a, **_k: schema.sync_type_config.update(cdc_mode="streaming")
-
- with patch.object(act, "_buffered_snapshot_enabled", return_value=True):
- assert act._start_snapshot_in_buffer(schema) is True
-
- assert CDC_SNAPSHOT_LANE_KEY not in schema.sync_type_config
+ assert "cdc_last_log_position" not in schema.sync_type_config
+ assert schema.initial_sync_complete is False
+ capture.reader.confirm_position.assert_called_once_with("0/500")
@parameterized.expand(
[
@@ -3978,7 +1951,7 @@ class TestBufferedIngressCapture:
("temporal_unavailable", RPCError("unavailable", RPCStatusCode.UNAVAILABLE, b""), None, {}, "raises"),
]
)
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")
+ @patch(f"{_ACTIVITIES}.purge_buffer_prefix")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane.ExternalDataJob")
def test_a_reset_stops_the_tables_running_sync_first(
self, _name, cancel_error, oldest_queued_batch_age, config, outcome, MockJob, mock_purge
@@ -3993,10 +1966,7 @@ class TestBufferedIngressCapture:
running.order_by.return_value.first.return_value = MagicMock(workflow_id="users-snapshot")
with (
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.cancel_running_sync",
- cancel_running_sync,
- ),
+ patch(f"{_ACTIVITIES}.cancel_running_sync", cancel_running_sync),
patch(
"products.data_warehouse.backend.facade.api.cancel_external_data_workflow",
side_effect=cancel_error,
@@ -4027,22 +1997,37 @@ class TestBufferedIngressCapture:
@parameterized.expand(
[
- ("sync_still_stopping", "users-snapshot", {"clear_deferred_runs": False}, True),
- ("sync_stopped", None, {"clear_deferred_runs": False}, False),
- ("sync_stopped_after_a_request_reset", None, {"clear_deferred_runs": True, "trigger": True}, False),
+ ("sync_still_stopping", "users-snapshot", {"clear_deferred_runs": False}, False, True),
+ ("sync_stopped", None, {"clear_deferred_runs": False}, False, False),
+ ("sync_stopped_after_a_request_reset", None, {"clear_deferred_runs": True, "trigger": True}, False, False),
+ (
+ "legacy_deferred_runs_old_sync_stopping",
+ "users-snapshot",
+ {"clear_deferred_runs": True, "trigger": True},
+ True,
+ True,
+ ),
+ (
+ "legacy_deferred_runs_old_sync_stopped",
+ None,
+ {"clear_deferred_runs": True, "trigger": True},
+ True,
+ False,
+ ),
]
)
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
def test_a_pending_reset_finishes_before_the_read_once_the_sync_stopped(
- self, _name, stopping_workflow_id, pending, waits, MockBufferWriter, mock_purge
+ self, _name, stopping_workflow_id, pending, deferred_runs, waits
):
source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
+ schema = _make_schema("users", cdc_mode="snapshot" if deferred_runs else "streaming", source=source)
schema.sync_type_config["cdc_reset_pending"] = pending
+ if deferred_runs:
+ schema.sync_type_config["cdc_deferred_runs"] = [{"run_uuid": "r1"}]
events = [_make_event(op="I", position="0/100", columns={"id": 1})]
with (
+ _capture_harness(source, [schema], events) as capture,
patch(
"products.warehouse_sources.backend.temporal.data_imports.cdc.activities.cancel_running_sync",
return_value=stopping_workflow_id,
@@ -4050,15 +2035,16 @@ class TestBufferedIngressCapture:
patch("products.data_warehouse.backend.facade.api.unpause_external_data_schedule") as unpause,
patch("products.data_warehouse.backend.facade.api.trigger_external_data_workflow") as trigger,
):
- reader, _s3, _producer = self._run(MockBufferWriter, events, [schema], source)
+ capture.extract()
- assert mock_purge.called is not waits
+ assert capture.purge.called is not waits
assert unpause.called is not waits
assert trigger.called is (not waits and bool(pending.get("trigger")))
assert schema.sync_type_config.get("reset_pipeline") is (None if waits else True)
assert ("cdc_reset_pending" in schema.sync_type_config) is waits
- assert MockBufferWriter.return_value.write_batch.called is not waits
- reader.confirm_position.assert_called_once_with("0/100")
+ assert ("cdc_deferred_runs" in schema.sync_type_config) is (deferred_runs and waits)
+ assert capture.buffer.write_batch.called is not waits
+ capture.reader.confirm_position.assert_called_once_with("0/100")
@parameterized.expand(
[
@@ -4066,11 +2052,7 @@ class TestBufferedIngressCapture:
("recovery_failed", RuntimeError("temporal down"), True),
]
)
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_a_handed_over_reset_recreates_a_schedule_that_is_gone(
- self, _name, create_error, stays_pending, MockBufferWriter, _mock_purge
- ):
+ def test_a_handed_over_reset_recreates_a_schedule_that_is_gone(self, _name, create_error, stays_pending):
# Unpausing a schedule that is gone succeeds silently, so the trigger is the first call to
# see it missing. Left there, the table would carry a reset with nothing to run it, while
# the request that handed the reset over would have recreated the schedule itself.
@@ -4080,11 +2062,11 @@ class TestBufferedIngressCapture:
events = [_make_event(op="I", position="0/100", columns={"id": 1})]
with (
+ _capture_harness(source, [schema], events) as capture,
patch(
"products.warehouse_sources.backend.temporal.data_imports.cdc.activities.cancel_running_sync",
return_value=None,
),
- patch("products.data_warehouse.backend.facade.api.unpause_external_data_schedule"),
patch(
"products.data_warehouse.backend.facade.api.trigger_external_data_workflow",
side_effect=RPCError("schedule not found", RPCStatusCode.NOT_FOUND, b""),
@@ -4094,7 +2076,7 @@ class TestBufferedIngressCapture:
side_effect=create_error,
) as create_schedule,
):
- self._run(MockBufferWriter, events, [schema], source)
+ capture.extract()
create_schedule.assert_called_once_with(schema, create=True, should_sync=True)
# A snapshot that never started keeps the key, so a later run repeats the reset and its start.
@@ -4106,11 +2088,7 @@ class TestBufferedIngressCapture:
("the_same_reset_again", {"clear_deferred_runs": True, "trigger": True}),
]
)
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_a_reset_staged_while_the_snapshot_was_starting_is_left_pending(
- self, _name, pending, MockBufferWriter, _mock_purge
- ):
+ def test_a_reset_staged_while_the_snapshot_was_starting_is_left_pending(self, _name, pending):
# The unpause lets a sync start, so a request can hand its own reset over before this run
# has dropped the key. Dropping it wholesale would lose that reset with nothing to redo it.
source = _make_source()
@@ -4124,6 +2102,7 @@ class TestBufferedIngressCapture:
staged.update(schema.sync_type_config["cdc_reset_pending"])
with (
+ _capture_harness(source, [schema], events) as capture,
patch(
"products.warehouse_sources.backend.temporal.data_imports.cdc.activities.cancel_running_sync",
return_value=None,
@@ -4134,13 +2113,11 @@ class TestBufferedIngressCapture:
),
patch("products.data_warehouse.backend.facade.api.trigger_external_data_workflow"),
):
- self._run(MockBufferWriter, events, [schema], source)
+ capture.extract()
assert schema.sync_type_config["cdc_reset_pending"] == staged
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_a_reset_waiting_on_a_slot_holds_the_table_out_until_the_slot_reads(self, MockBufferWriter, mock_purge):
+ def test_a_reset_waiting_on_a_slot_holds_the_table_out_until_the_slot_reads(self):
# Recovery leaves this marker when it could not recreate the slot. Finishing the reset here
# would unpause the schedule, and the snapshot would start with no slot to resume from. A
# read that succeeds proves the slot is back, so the next run finishes the reset — recovery
@@ -4151,40 +2128,64 @@ class TestBufferedIngressCapture:
events = [_make_event(op="I", position="0/100", columns={"id": 1})]
with (
+ _capture_harness(source, [schema], events) as capture,
patch(
"products.warehouse_sources.backend.temporal.data_imports.cdc.activities.cancel_running_sync"
) as cancel,
patch("products.data_warehouse.backend.facade.api.unpause_external_data_schedule") as unpause,
):
- self._run(MockBufferWriter, events, [schema], source)
+ capture.extract()
cancel.assert_not_called()
unpause.assert_not_called()
- assert mock_purge.called is False
- assert MockBufferWriter.return_value.write_batch.called is False
+ assert capture.purge.called is False
+ assert capture.buffer.write_batch.called is False
assert schema.sync_type_config["cdc_reset_pending"] == {"clear_deferred_runs": True, "awaiting_slot": False}
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_a_buffer_write_failure_fails_the_run_and_leaves_the_slot(self, MockBufferWriter):
- # The opposite of the shadow lane's policy: swallowing here would advance the slot past
- # changes that reached nothing, losing them for good.
- MockBufferWriter.return_value.write_batch.side_effect = Exception("s3 down")
+ @parameterized.expand(
+ [
+ ("s3_error_on_write", "streaming", [], lambda c: c.buffer.write_batch, RuntimeError("s3 down")),
+ # The dropped connection stays in Django's pool. The failure handler must evict it before
+ # it records the failure, or that write fails too and the friendly message is lost.
+ (
+ "dropped_app_db_connection_on_write",
+ "streaming",
+ [],
+ lambda c: c.buffer.write_batch,
+ OperationalError("the connection is closed"),
+ ),
+ # Runs before the WAL read, outside the read loop's own error handling.
+ ("purge_that_starts_a_snapshot", "snapshot", [], lambda c: c.purge, RuntimeError("s3 down")),
+ # The hand-over keeps every file of a marked schema, so a marker left by a failed purge
+ # would replay the pre-TRUNCATE files over the re-snapshot.
+ ("purge_after_a_truncate", "streaming", ["users"], lambda c: c.purge, RuntimeError("s3 down")),
+ ]
+ )
+ def test_a_buffer_failure_fails_the_run_and_leaves_the_slot(
+ self, _name, cdc_mode, truncated_tables, failing_call, error
+ ):
+ # Swallowing here would advance the slot past changes that reached nothing, losing them for good.
source = _make_source()
- schema = _make_schema("users", cdc_mode="streaming", source=source)
+ schema = _make_schema("users", cdc_mode=cdc_mode, source=source)
events = [_make_event(op="I", position="0/100", columns={"id": 1})]
- captured: dict = {}
- with pytest.raises(Exception, match="s3 down"):
- captured["reader"] = self._run(MockBufferWriter, events, [schema], source, capture=captured)
+ with _capture_harness(source, [schema], events) as capture:
+ capture.reader.truncated_tables = truncated_tables
+ failing_call(capture).side_effect = error
+ capture.activity.info.return_value.attempt = CDC_MAX_EXTRACTION_ATTEMPTS
+ with pytest.raises(type(error), match=str(error)):
+ capture.extract()
- captured["reader_ref"].confirm_position.assert_not_called()
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_a_crash_mid_transaction_leaves_a_file_straddling_the_restart(self, MockBufferWriter):
- from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (
- ChangeEventBatcher as RealBatcher,
- )
+ capture.reader.confirm_position.assert_not_called()
+ # The schema shows the friendly message, never the raw error.
+ assert schema.status == "Failed"
+ assert schema.latest_error == cdc_error_info(CDCErrorCategory.UNKNOWN).friendly_message
+ assert schema.sync_type_config["cdc_mode"] == cdc_mode
+ assert CDC_SNAPSHOT_LANE_KEY not in schema.sync_type_config
+ # Once when the run starts, and once in the failure handler before it writes the failure.
+ assert capture.close_old_connections.call_count == 2
+ def test_a_crash_mid_transaction_leaves_a_file_straddling_the_restart(self):
class _DyingStream:
def __init__(self, events):
self._events = events
@@ -4204,47 +2205,71 @@ class TestBufferedIngressCapture:
_make_event(op="I", position="0/200", columns={"id": 3}),
_make_event(op="I", position="0/200", columns={"id": 4}),
]
- captured: dict = {}
with (
+ _capture_harness(source, [schema], _DyingStream(events)) as capture,
patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ChangeEventBatcher",
- side_effect=lambda **kwargs: RealBatcher(max_events=4, **kwargs),
+ f"{_ACTIVITIES}.ChangeEventBatcher",
+ side_effect=lambda **kwargs: ChangeEventBatcher(max_events=4, **kwargs),
),
pytest.raises(RuntimeError, match="pod killed mid-transaction"),
):
- self._run(MockBufferWriter, _DyingStream(events), [schema], source, capture=captured)
+ capture.extract()
- written = MockBufferWriter.return_value.write_batch.call_args.kwargs["table"]
+ written = capture.buffer.write_batch.call_args.kwargs["table"]
assert written.column(CDC_SEQ_COLUMN).to_pylist() == [0x100, 0x100, 0x200, 0x200]
- captured["reader_ref"].confirm_position.assert_called_once_with("0/100")
- cleanup = MockBufferWriter.return_value.cleanup_superseded_files
- cleanup.assert_called_once_with(team_id=schema.team_id, schema_id=str(schema.id), restart_seq=0x100)
+ capture.reader.confirm_position.assert_called_once_with("0/100")
+ capture.buffer.cleanup_superseded_files.assert_called_once_with(
+ team_id=schema.team_id, schema_id=str(schema.id), restart_seq=0x100
+ )
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_a_source_column_named_like_seq_fails_the_buffered_run(self, MockBufferWriter):
+ def test_a_source_column_named_like_seq_fails_the_buffered_run(self):
# The batcher skips its append on the collision, so the file's name, ordering, and retry
# cleanup would all derive from customer data — cleanup can then delete unconsumed files.
source = _make_source()
schema = _make_schema("users", cdc_mode="streaming", source=source)
events = [_make_event(op="I", position="0/100", columns={"id": 1, CDC_SEQ_COLUMN: 42})]
- captured: dict = {}
- with pytest.raises(Exception, match="_ph_cdc_seq"):
- self._run(MockBufferWriter, events, [schema], source, capture=captured)
+ with (
+ _capture_harness(source, [schema], events) as capture,
+ pytest.raises(NonRetryableException, match=CDC_SEQ_COLUMN),
+ ):
+ capture.extract()
- MockBufferWriter.return_value.write_batch.assert_not_called()
- captured["reader_ref"].confirm_position.assert_not_called()
+ capture.buffer.write_batch.assert_not_called()
+ capture.reader.confirm_position.assert_not_called()
- @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")
- def test_capture_does_not_repaint_a_buffered_schema_healthy(self, MockBufferWriter):
- # The scheduled sync owns a buffered schema's status; capture repainting COMPLETED every
- # tick would erase a failing consumer run within a minute and hide a buffer backlog.
+ @parameterized.expand(
+ [
+ ("quiet_run", [], 0),
+ (
+ "run_with_changes",
+ [_make_event(op="I", position="0/100"), _make_event(op="U", position="0/200")],
+ 2,
+ ),
+ ]
+ )
+ def test_a_completed_run_records_a_heartbeat_but_leaves_the_status_to_the_consumer(
+ self, _name, events, expected_event_count
+ ):
+ # The scheduled sync that consumes the buffer owns the schema's status. Capture repainting it
+ # every tick would erase a failing consumer run within minutes and hide a buffer backlog until
+ # its files expire.
source = _make_source()
- buffered = _make_schema("users", cdc_mode="streaming", source=source)
- events = [_make_event(op="I", position="0/100", columns={"id": 1})]
- captured: dict = {}
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ schema.status = ExternalDataSchema.Status.FAILED
+ schema.latest_error = "The consumer's own failure"
+ schema.sync_type_config["cdc_extraction_paused"] = {"reason": "transaction_too_large"}
- self._run(MockBufferWriter, events, [buffered], source, capture=captured)
+ with _capture_harness(source, [schema], events) as capture:
+ capture.extract()
- captured["complete_schema_run"].assert_not_called()
+ config = schema.sync_type_config
+ # The heartbeat proves a quiet source's extraction is alive, as an ISO-8601 string the
+ # health check parses back.
+ assert config["cdc_last_run_event_count"] == expected_event_count
+ datetime.fromisoformat(config["cdc_last_run_at"])
+ # A completed run proves extraction runs again, and the consumer cannot clear this marker.
+ assert "cdc_extraction_paused" not in config
+ assert schema.status == ExternalDataSchema.Status.FAILED
+ assert schema.latest_error == "The consumer's own failure"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_legacy_conversion.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_legacy_conversion.py
new file mode 100644
index 000000000000..bf21ffb07f5c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_legacy_conversion.py
@@ -0,0 +1,214 @@
+import datetime as dt
+
+import pytest
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.utils import timezone
+
+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.legacy_conversion import (
+ STRANDED_CAPTURE_JOB_MESSAGE,
+ convert_legacy_cdc_state,
+)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import buffer_may_have_expired_unread
+from products.warehouse_sources.backend.temporal.data_imports.cdc.types import parse_ingest_mode
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.cdc.legacy_conversion"
+_FACADE = "products.data_warehouse.backend.facade.api"
+
+
+class TestLegacyConversion(BaseTest):
+ def _source(self, ingest_mode: str | None) -> ExternalDataSource:
+ job_inputs: dict = {"cdc_enabled": True, "cdc_slot_name": "slot"}
+ if ingest_mode is not None:
+ job_inputs["cdc_ingest_mode"] = ingest_mode
+ return ExternalDataSource.objects.create(team=self.team, source_type="Postgres", job_inputs=job_inputs)
+
+ def _schema(self, source: ExternalDataSource, name: str, **overrides) -> ExternalDataSchema:
+ return ExternalDataSchema.objects.create(
+ team=self.team,
+ source=source,
+ name=name,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ sync_type_config=overrides.pop("sync_type_config", {"cdc_mode": "streaming"}),
+ initial_sync_complete=overrides.pop("initial_sync_complete", True),
+ should_sync=overrides.pop("should_sync", True),
+ sync_frequency_interval=overrides.pop("sync_frequency_interval", dt.timedelta(minutes=5)),
+ **overrides,
+ )
+
+ def _job(
+ self,
+ schema: ExternalDataSchema,
+ *,
+ workflow_id: str,
+ age: dt.timedelta,
+ status: str = ExternalDataJob.Status.RUNNING,
+ ) -> ExternalDataJob:
+ job = ExternalDataJob.objects.create(
+ team=self.team,
+ pipeline=schema.source,
+ schema=schema,
+ status=status,
+ rows_synced=0,
+ workflow_id=workflow_id,
+ schema_snapshot={"sync_type_config": schema.sync_type_config},
+ )
+ ExternalDataJob.objects.filter(id=job.id).update(created_at=timezone.now() - age)
+ return job
+
+ def _convert(self, source, schemas, *, queued_batches: int = 0, sync_workflow=None):
+ purge = MagicMock()
+ sync_workflow = sync_workflow or MagicMock()
+ with (
+ patch(f"{_MODULE}.purge_buffer_prefix", purge),
+ patch(f"{_FACADE}.sync_external_data_job_workflow", sync_workflow),
+ patch(f"{_MODULE}.psycopg"),
+ patch(f"{_MODULE}.BatchQueue.count_batches_for_run", return_value=queued_batches),
+ ):
+ convert_legacy_cdc_state(
+ source, schemas, ingest_mode=parse_ingest_mode(source.job_inputs), logger=MagicMock()
+ )
+ return purge, sync_workflow
+
+ def test_a_legacy_source_is_emptied_resumed_and_marked_buffered_once(self):
+ source = self._source(ingest_mode=None)
+ streaming = self._schema(source, "users")
+ sync_off = self._schema(source, "orders", should_sync=False)
+ edited_since_capture_loaded_it = ExternalDataSource.objects.get(id=source.id)
+ edited_since_capture_loaded_it.job_inputs = {
+ **edited_since_capture_loaded_it.job_inputs,
+ "cdc_slot_name": "new",
+ }
+ edited_since_capture_loaded_it.save(update_fields=["job_inputs"])
+
+ purge, sync_workflow = self._convert(source, [streaming])
+
+ assert {call.args[1] for call in purge.call_args_list} == {str(streaming.id), str(sync_off.id)}
+ assert all(call.kwargs["strict"] for call in purge.call_args_list)
+ assert [call.args[0].id for call in sync_workflow.call_args_list] == [streaming.id]
+ assert sync_workflow.call_args.kwargs == {"create": True, "should_sync": True, "trigger_immediately": False}
+ source.refresh_from_db()
+ assert parse_ingest_mode(source.job_inputs) == "buffered"
+ assert source.job_inputs["cdc_slot_name"] == "new"
+
+ purge, sync_workflow = self._convert(source, [streaming])
+
+ purge.assert_not_called()
+ sync_workflow.assert_not_called()
+
+ def test_a_converted_table_reads_its_buffer_instead_of_re_snapshotting(self):
+ source = self._source(ingest_mode="legacy")
+ schema = self._schema(source, "users", last_synced_at=timezone.now() - dt.timedelta(minutes=10))
+ self._job(
+ schema,
+ workflow_id=f"cdc-extraction-{source.id}-run",
+ age=dt.timedelta(minutes=10),
+ status=ExternalDataJob.Status.COMPLETED,
+ )
+
+ self._convert(source, [schema])
+
+ schema.refresh_from_db()
+ assert buffer_may_have_expired_unread(schema, timezone.now()) is False
+
+ @parameterized.expand([("legacy", dt.timedelta(minutes=5)), ("buffered", dt.timedelta(hours=6))])
+ def test_a_converted_table_keeps_the_cadence_the_legacy_lane_gave_it(self, ingest_mode, expected_interval):
+ source = self._source(ingest_mode=ingest_mode)
+ fast = self._schema(source, "users", sync_frequency_interval=dt.timedelta(minutes=5))
+ slow = self._schema(source, "events", sync_frequency_interval=dt.timedelta(hours=6))
+
+ _, sync_workflow = self._convert(source, [fast, slow])
+
+ slow.refresh_from_db()
+ assert slow.sync_frequency_interval == expected_interval
+ rebuilt = {call.args[0].id: call.args[0].sync_frequency_interval for call in sync_workflow.call_args_list}
+ assert rebuilt.get(slow.id, expected_interval) == expected_interval
+
+ def test_a_failed_schedule_rebuild_leaves_the_source_to_convert_again(self):
+ source = self._source(ingest_mode="legacy")
+ schema = self._schema(source, "users")
+
+ with pytest.raises(RuntimeError):
+ self._convert(source, [schema], sync_workflow=MagicMock(side_effect=RuntimeError("temporal down")))
+
+ source.refresh_from_db()
+ assert parse_ingest_mode(source.job_inputs) == "legacy"
+
+ @parameterized.expand([("buffered_source", "buffered"), ("legacy_source", "legacy")])
+ def test_a_table_with_deferred_runs_hands_its_snapshot_restart_to_capture(self, _name, ingest_mode):
+ source = self._source(ingest_mode=ingest_mode)
+ schema = self._schema(
+ source,
+ "users",
+ sync_type_config={"cdc_mode": "snapshot", "cdc_deferred_runs": [{"run_uuid": "r1"}]},
+ initial_sync_complete=False,
+ )
+
+ _, sync_workflow = self._convert(source, [schema])
+
+ sync_workflow.assert_not_called()
+ schema.refresh_from_db()
+ pending = schema.sync_type_config["cdc_reset_pending"]
+ assert pending["clear_deferred_runs"] is True
+ assert pending["trigger"] is True
+
+ @parameterized.expand(
+ [
+ ("billing_paused", {"status": ExternalDataSchema.Status.PAUSED}, False),
+ (
+ "admin_run_in_flight",
+ {"sync_type_config": {"cdc_mode": "streaming", "admin_unpause_schedule_after_run": True}},
+ False,
+ ),
+ (
+ "broken",
+ {"sync_type_config": {"cdc_mode": "streaming", "cdc_broken": {"reason": "slot_missing"}}},
+ False,
+ ),
+ ("no_sync_frequency", {"sync_frequency_interval": None}, False),
+ (
+ "reset_pending",
+ {"sync_type_config": {"cdc_mode": "streaming", "cdc_reset_pending": {"clear_deferred_runs": False}}},
+ False,
+ ),
+ # The conversion runs once, so skipping this schedule would leave it paused for good.
+ (
+ "capture_paused_earlier",
+ {"sync_type_config": {"cdc_mode": "streaming", "cdc_extraction_paused": {"reason": "auth_failed"}}},
+ True,
+ ),
+ ]
+ )
+ def test_the_schedule_resumes_unless_its_pause_is_deliberate(self, _name, overrides, resumed):
+ source = self._source(ingest_mode="legacy")
+ schema = self._schema(source, "users", **overrides)
+
+ _, sync_workflow = self._convert(source, [schema])
+
+ assert sync_workflow.called is resumed
+
+ @parameterized.expand(
+ [
+ ("abandoned_capture_run", "cdc-extraction-", dt.timedelta(hours=1), 0, ExternalDataJob.Status.FAILED),
+ ("loader_still_owns_it", "cdc-extraction-", dt.timedelta(hours=1), 3, ExternalDataJob.Status.RUNNING),
+ ("possibly_still_finishing", "cdc-extraction-", dt.timedelta(minutes=5), 0, ExternalDataJob.Status.RUNNING),
+ ("a_scheduled_sync", "schema-", dt.timedelta(hours=1), 0, ExternalDataJob.Status.RUNNING),
+ ]
+ )
+ def test_only_abandoned_capture_jobs_are_failed(self, _name, workflow_prefix, age, queued_batches, expected):
+ source = self._source(ingest_mode="buffered")
+ schema = self._schema(source, "users")
+ job = self._job(schema, workflow_id=f"{workflow_prefix}{source.id}", age=age)
+
+ self._convert(source, [schema], queued_batches=queued_batches)
+
+ job.refresh_from_db()
+ assert job.status == expected
+ if expected == ExternalDataJob.Status.FAILED:
+ assert job.latest_error == STRANDED_CAPTURE_JOB_MESSAGE
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
index 3872813d5b68..01da74aeb77f 100644
--- 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
@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.companion_jobs
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (
BUFFER_LISTED_AT_KEY,
+ LEGACY_CONVERTED_AT_KEY,
buffer_may_have_expired_unread,
clear_listing,
read_completed_listing_proof,
@@ -104,12 +105,20 @@ class TestCompletedListingProof(BaseTest):
class TestBufferExpiredUnread(BaseTest):
- def _schema(self, *, synced_days_ago: int | None) -> ExternalDataSchema:
+ def _schema(self, *, synced_days_ago: int | None, converted_days_ago: int | None = None) -> ExternalDataSchema:
source = ExternalDataSource.objects.create(
team=self.team, source_id="s", connection_id="c", status="Running", source_type="Postgres"
)
- synced = None if synced_days_ago is None else dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=synced_days_ago)
- return ExternalDataSchema.objects.create(team=self.team, source=source, name="users", last_synced_at=synced)
+ now = dt.datetime.now(tz=dt.UTC)
+ synced = None if synced_days_ago is None else now - dt.timedelta(days=synced_days_ago)
+ config = (
+ {}
+ if converted_days_ago is None
+ else {LEGACY_CONVERTED_AT_KEY: (now - dt.timedelta(days=converted_days_ago)).isoformat()}
+ )
+ return ExternalDataSchema.objects.create(
+ team=self.team, source=source, name="users", last_synced_at=synced, sync_type_config=config
+ )
def _completed_job(self, schema: ExternalDataSchema, *, days_ago: int, snapshot: dict) -> None:
job = ExternalDataJob.objects.create(
@@ -126,23 +135,30 @@ class TestBufferExpiredUnread(BaseTest):
@parameterized.expand(
[
- ("never_synced", None, None, False),
- ("no_completion_since_retention", 15, None, True),
- ("only_stand_downs_since_retention", 1, (1, {}), True),
- ("a_run_listed_the_buffer", 1, (10, {BUFFER_LISTED_AT_KEY: "2026-01-01T00:00:00+00:00"}), False),
- ("a_snapshot_reseeded_the_table", 1, (3, {"sync_type_config": {"cdc_mode": "snapshot"}}), False),
+ ("never_synced", None, None, None, False),
+ ("no_completion_since_retention", 15, None, None, True),
+ ("only_stand_downs_since_retention", 1, (1, {}), None, True),
+ ("a_run_listed_the_buffer", 1, (10, {BUFFER_LISTED_AT_KEY: "2026-01-01T00:00:00+00:00"}), None, False),
+ ("a_snapshot_reseeded_the_table", 1, (3, {"sync_type_config": {"cdc_mode": "snapshot"}}), None, False),
(
"the_last_listing_is_older_than_retention",
1,
(20, {BUFFER_LISTED_AT_KEY: "2026-01-01T00:00:00+00:00"}),
+ None,
True,
),
+ ("a_legacy_conversion_older_than_retention", 1, (1, {}), 20, True),
]
)
def test_only_a_listing_or_a_snapshot_proves_the_buffer_was_read(
- self, _name: str, synced_days_ago: int | None, job: tuple[int, dict] | None, expired: bool
+ self,
+ _name: str,
+ synced_days_ago: int | None,
+ job: tuple[int, dict] | None,
+ converted_days_ago: int | None,
+ expired: bool,
) -> None:
- schema = self._schema(synced_days_ago=synced_days_ago)
+ schema = self._schema(synced_days_ago=synced_days_ago, converted_days_ago=converted_days_ago)
if job is not None:
self._completed_job(schema, days_ago=job[0], snapshot=job[1])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
index 4fc7fdfeef35..ef3cddb7c59e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
@@ -20,6 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.activities imp
from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import ChangeEventBatcher
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.config import PostgresCDCConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.position import PgLSN
_ACTIVITIES = "products.warehouse_sources.backend.temporal.data_imports.cdc.activities"
@@ -46,7 +47,6 @@ class TestMetricsOutsideActivityContext:
metrics.get_sweeper_duration_metric().record(2.0)
def test_gauges_set_without_raising(self):
- metrics.get_deferred_runs_depth_metric(1, "s").set(2)
metrics.get_wal_lag_metric(1, "s").set(1024)
@@ -106,7 +106,6 @@ def _make_schema(cdc_mode="streaming"):
schema.cdc_table_mode = "consolidated"
schema.enabled_columns = None
schema.incremental_field = None
- schema.resolved_s3_folder_name = None
schema.save = MagicMock()
return schema
@@ -123,34 +122,21 @@ def _extract_patches(source, schemas, events):
adapter = MagicMock()
adapter.create_reader.return_value = reader
adapter.is_slot_invalidation_error.return_value = False
-
- s3 = MagicMock()
- batch_result = MagicMock(
- s3_path="s3://b/p.parquet", row_count=len(events), byte_size=512, batch_index=0, timestamp_ns=1
- )
- s3.write_batch.return_value = batch_result
- s3.write_schema.return_value = "s3://b/schema.json"
- s3.get_data_folder.return_value = "s3://b/"
-
- job = MagicMock()
- job.id = uuid.uuid4()
+ adapter.position_to_seq.side_effect = lambda position: PgLSN.deserialize(position).value
with (
patch(f"{_ACTIVITIES}.close_old_connections"),
patch(f"{_ACTIVITIES}.ExternalDataSource") as MockSource,
patch.object(CDCExtractActivity, "_get_cdc_schemas", return_value=schemas),
patch.object(CDCExtractActivity, "_update_schema_sync_type_config"),
- # The success repaint runs a locked DB transaction; these metric smoke tests are DB-less.
- patch(f"{_ACTIVITIES}.complete_schema_run", return_value=True),
- patch(f"{_ACTIVITIES}.mark_schema_running_unless_halted", return_value=True),
+ patch(f"{_ACTIVITIES}.convert_legacy_cdc_state"),
patch(f"{_ACTIVITIES}.get_cdc_adapter", return_value=adapter),
- patch(f"{_ACTIVITIES}.S3BatchWriter", return_value=s3),
- patch(f"{_ACTIVITIES}.PostgresProducer"),
- patch(f"{_ACTIVITIES}.ExternalDataJob") as MockJob,
+ patch(f"{_ACTIVITIES}.CDCBufferWriter") as MockBufferWriter,
):
MockSource.objects.get.return_value = source
- MockJob.objects.create.return_value = job
- yield adapter, reader, s3
+ # The real meter records only a float.
+ MockBufferWriter.return_value.write_batch.return_value.write_duration_seconds = 0.01
+ yield reader
class TestExtractionMetricsSmoke:
@@ -161,10 +147,18 @@ class TestExtractionMetricsSmoke:
with _extract_patches(source, [_make_schema()], events):
env.run(cdc_extract_activity, CDCExtractInput(team_id=1, source_id=source.id))
- names = _emitted_names(buffer)
+ updates = buffer.retrieve_updates()
+ names = {update.metric.name for update in updates}
assert "cdc_events_extracted_total" in names
assert "cdc_slot_advance_total" in names
assert "cdc_extraction_duration_seconds" in names
+ # Dashboards filter the buffer metrics on this label.
+ assert {
+ (u.metric.name, u.attributes.get("lane")) for u in updates if u.metric.name.startswith("cdc_buffer_")
+ } == {
+ ("cdc_buffer_files_written_total", "ingress"),
+ ("cdc_buffer_write_duration_seconds", "ingress"),
+ }
def test_no_changes_run_emits_duration(self, metric_env):
env, buffer = metric_env
@@ -177,7 +171,7 @@ class TestExtractionMetricsSmoke:
def test_failure_run_emits_duration_and_reraises(self, metric_env):
env, buffer = metric_env
source = _make_source()
- with _extract_patches(source, [_make_schema()], []) as (_, reader, _s3):
+ with _extract_patches(source, [_make_schema()], []) as reader:
reader.read_changes.side_effect = RuntimeError("boom")
with pytest.raises(RuntimeError, match="boom"):
env.run(cdc_extract_activity, CDCExtractInput(team_id=1, source_id=source.id))
@@ -188,7 +182,7 @@ class TestExtractionMetricsSmoke:
env, buffer = metric_env
source = _make_source()
events = [_make_event(position="0/100")]
- with _extract_patches(source, [_make_schema()], events) as (_, reader, _s3):
+ with _extract_patches(source, [_make_schema()], events) as reader:
reader.confirm_position.side_effect = RuntimeError("advance failed")
with pytest.raises(RuntimeError, match="advance failed"):
env.run(cdc_extract_activity, CDCExtractInput(team_id=1, source_id=source.id))
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 bad46d08f5f9..eb2942cdadb4 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
@@ -28,13 +28,11 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager
ReplayFilter,
build_output_lanes,
captures_to_buffer,
- consumes_buffer,
has_batches_in_flight,
scheduled_sync_consumes_buffer,
served_lanes,
serves_buffered_lane,
)
-from products.warehouse_sources.backend.temporal.data_imports.cdc.types import CDCJobInputsUnreadableError
_TEAM_ID = 7
_SCHEMA_ID = "3f7c1f4e-0000-0000-0000-000000000001"
@@ -300,39 +298,33 @@ class TestSnapshotCapture:
{"cdc_mode": "snapshot", "sync_type_config": {"cdc_snapshot_lane": "buffer"}},
True,
),
- ("snapshotting_on_deferred_runs", {"cdc_mode": "snapshot", "initial_sync_complete": False}, False),
+ ("snapshotting_not_started_yet", {"cdc_mode": "snapshot", "initial_sync_complete": False}, True),
("not_cdc", {"is_cdc": False}, False),
("unrecognized_table_mode", {"cdc_table_mode": "something_new"}, False),
]
)
- def test_capture_follows_the_snapshot_lane(self, _name, overrides, captured):
+ def test_capture_writes_every_table_in_a_mode_the_buffer_serves(self, _name, overrides, captured):
assert captures_to_buffer(_schema(**overrides)) is captured
@parameterized.expand(
[
- ("streaming_on_a_buffered_source", {}, True, True),
- ("flag_off", {}, False, False),
- ("legacy_source", {"job_inputs": {}}, True, False),
- ("deferred_runs_pending", {"sync_type_config": {"cdc_deferred_runs": [{"run": 1}]}}, True, False),
- ("snapshotting_outside_the_buffer", {"cdc_mode": "snapshot", "initial_sync_complete": False}, True, False),
+ ("streaming", {}, True),
+ ("streaming_with_its_data_deleted", {"initial_sync_complete": False}, True),
+ ("snapshotting_outside_the_buffer", {"cdc_mode": "snapshot", "initial_sync_complete": False}, False),
(
"already_in_the_buffer",
{"cdc_mode": "snapshot", "sync_type_config": {"cdc_snapshot_lane": "buffer"}},
- False,
True,
),
+ # Its buffer holds copies of changes the legacy lane already delivered, until capture converts it.
+ ("streaming_on_a_source_not_converted_yet", {"job_inputs": {"cdc_ingest_mode": "legacy"}}, False),
+ # The previous release skipped these tables' capture, so their buffer has a gap.
+ ("streaming_with_deferred_runs_left", {"sync_type_config": {"cdc_deferred_runs": [{"run": 1}]}}, False),
]
)
- def test_a_resnapshot_stays_in_the_buffer_only_when_the_buffer_holds_every_change(
- self, _name, overrides, flag, stays
- ):
+ def test_a_resnapshot_stays_in_the_buffer_only_when_the_buffer_holds_every_change(self, _name, overrides, stays):
schema = _schema(**{"job_inputs": {"cdc_ingest_mode": "buffered"}, **overrides})
-
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane.is_buffered_snapshot_enabled",
- return_value=flag,
- ):
- assert resnapshot_stays_in_buffer(schema, MagicMock()) is stays
+ assert resnapshot_stays_in_buffer(schema) is stays
class TestBufferedGating:
@@ -344,73 +336,41 @@ class TestBufferedGating:
("no_table_yet", {"initial_sync_complete": False}),
]
)
- def test_ineligible_schemas_stay_on_the_legacy_path(self, _name, overrides):
+ def test_ineligible_schemas_do_not_consume_the_buffer(self, _name, overrides):
assert serves_buffered_lane(_schema(**overrides)) is False
@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 consumes_buffer(_schema(), ingest_mode=ingest_mode) is False
-
- @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
-
- @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
-
+ # A source capture has not converted yet still reads "legacy", and its consumer must run on v3 too.
@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"},
- ),
- ("still_snapshotting", {"job_inputs": {"cdc_ingest_mode": "buffered"}, "cdc_mode": "snapshot"}),
+ (f"{table_mode}_{ingest_mode}", table_mode, ingest_mode)
+ for table_mode in ("consolidated", "cdc_only", "both")
+ for ingest_mode in ("buffered", "legacy")
]
)
- def test_the_scheduled_sync_is_not_forced_off_the_flag_for(self, _name, overrides):
- assert scheduled_sync_consumes_buffer(_schema(**overrides)) is False
+ def test_a_streaming_schema_forces_the_buffered_consumer_on_its_scheduled_sync(
+ self, _name, table_mode, ingest_mode
+ ):
+ schema = _schema(job_inputs={"cdc_ingest_mode": ingest_mode}, cdc_table_mode=table_mode)
+ assert scheduled_sync_consumes_buffer(schema) is True
@parameterized.expand(
[
- ("mapping", {"cdc_ingest_mode": "buffered"}, True),
- ("json_string", '{"cdc_ingest_mode": "buffered"}', True),
- ("json_string_not_flipped", '{"cdc_ingest_mode": "legacy"}', False),
- ("empty_string", "", False),
+ ("unrecognized_table_mode", {"cdc_table_mode": "something_new"}),
+ ("still_snapshotting", {"cdc_mode": "snapshot"}),
]
)
- def test_the_flip_is_read_through_whichever_shape_job_inputs_decrypted_to(self, _name, job_inputs, consumes):
- # EncryptedJSONField hands back a value that was written as a string as that same string,
- # so reading only the mapping shape leaves a flipped source's buffer unconsumed.
- assert scheduled_sync_consumes_buffer(_schema(job_inputs=job_inputs)) is consumes
-
- @parameterized.expand([("not_json", "buffered"), ("json_scalar", "12"), ("not_a_string_either", 7)])
- def test_job_inputs_that_is_no_mapping_at_all_is_an_error(self, _name, job_inputs):
- with pytest.raises(CDCJobInputsUnreadableError):
- scheduled_sync_consumes_buffer(_schema(job_inputs=job_inputs))
+ def test_the_scheduled_sync_is_not_forced_off_the_flag_for(self, _name, overrides):
+ assert scheduled_sync_consumes_buffer(_schema(**overrides)) is False
@pytest.mark.asyncio
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.
-
- def test_deferred_runs_are_a_backlog_without_touching_the_queue(self):
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.psycopg"
- ) as mock_psycopg:
- assert has_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)])
- def test_sourcebatch_state_decides_when_no_deferred_runs(self, _name, age, expected):
+ def test_sourcebatch_state_decides(self, _name, age, expected):
schema = _schema()
schema.team_id = _TEAM_ID
schema.id = _SCHEMA_ID
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md b/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md
index 33af3268f219..d90cf6ba8f80 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md
@@ -34,20 +34,20 @@ Gated by the `warehouse-multi-destination` flag, evaluated once in `create_exter
Writers live in `destinations_load/writers/` and are resolved by type from a registry, so the consumer never names a destination type. Only Postgres ships today; it runs on batch exports' `PostgreSQLClient`.
-CDC is excluded for now: it ticks a final batch continuously, which has no run-scoped commit for a destination to swap into.
+CDC is excluded for now: the source setup flow does not offer destinations for CDC tables.
## The pipelines
-| Pipeline | Lives in | Attaches at |
-| ------------------------------------ | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| v2 extract+load (`PipelineNonDLT`) | `pipeline_v2/` | Step 4 when `pipeline_version == V2`; writes Delta inline per chunk, so extract and load are one activity. The workflow finalizes. |
-| v3 extract (`PipelineV3`) | `pipeline_v3/pipeline.py`, `pipeline_v3/s3/`, `pipeline_v3/postgres_queue/producer.py` | Step 4 when `pipeline_version == V3`, under the sync lock; writes parquet batches to S3 and enqueues them (`ExportSignalMessage`, `pipeline_v3/messages.py`) on the Postgres load queue. |
-| v3 load | `pipeline_v3/postgres_queue/`, `pipeline_v3/load/`, engine in `products/warehouse_sources_queue/backend/core/` | Its own deployment (`run_warehouse_sources_load`), not the workflow: claims queued batches, writes Delta via `core/delta/`, finalizes the job, releases the lock, starts post-import. When the run has destinations it also hands each batch to `destinations_load/delivery.py` before finalizing. |
-| CDC | `../cdc/` | Outside the scheduled flow: the `cdc-extraction` Temporal workflow tails the source WAL and enqueues to the same Postgres queue (jobs are created as V3). The load consumer writes the snapshot table and the `_cdc` SCD2 companion (`core/delta/scd2.py`). |
-| Webhooks | `run_webhook_s3_sink` command; sink behind the `data_warehouse` facade | Buffered ingress: deliveries are buffered to S3 continuously, and the next scheduled sync drains them as ordinary source items (webhook-only schemas skip table resets, `common/extract.py`). |
-| Chunk sinks (CDP, person properties) | `core/sinks.py`, `core/cdp_producer.py`, `core/person_property_row_sink.py` | Gated taps on both write loops, one `stage_chunk` call per chunk (see `ChunkSink`). Downstream: `dwh-cdp-producer-job` produces staged chunks to Kafka for HogFunctions/HogFlows; `sync-warehouse-person-properties` plus `run_person_property_update_consumer` upsert person properties. |
-| Post-import steps | `../post_import_job.py`, children under `../workflow_activities/` | Step 7. Started by whoever finalizes the run (step 6); gates are resolved once in its resolve activity, then the workflow is a loop over recorded step keys. |
-| Repartition | `core/repartition.py`, `core/repartition_controller.py`, `../workflow_activities/repartition_table.py` | Detection is a `POST_LOAD_STEPS` entry (flags oversized partitions); execution is `maybe_repartition_table_activity`, pre-extraction on the next run while the lock is held. |
+| Pipeline | Lives in | Attaches at |
+| ------------------------------------ | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| v2 extract+load (`PipelineNonDLT`) | `pipeline_v2/` | Step 4 when `pipeline_version == V2`; writes Delta inline per chunk, so extract and load are one activity. The workflow finalizes. |
+| v3 extract (`PipelineV3`) | `pipeline_v3/pipeline.py`, `pipeline_v3/s3/`, `pipeline_v3/postgres_queue/producer.py` | Step 4 when `pipeline_version == V3`, under the sync lock; writes parquet batches to S3 and enqueues them (`ExportSignalMessage`, `pipeline_v3/messages.py`) on the Postgres load queue. |
+| v3 load | `pipeline_v3/postgres_queue/`, `pipeline_v3/load/`, engine in `products/warehouse_sources_queue/backend/core/` | Its own deployment (`run_warehouse_sources_load`), not the workflow: claims queued batches, writes Delta via `core/delta/`, finalizes the job, releases the lock, starts post-import. When the run has destinations it also hands each batch to `destinations_load/delivery.py` before finalizing. |
+| CDC | `../cdc/` | Capture runs outside the scheduled flow: the `cdc-extraction` Temporal workflow tails the source WAL and writes change files to the S3 change buffer (`cdc/buffer.py`). Each table's scheduled v3 sync consumes that buffer as its source (`cdc/source_manager.py`); the loader writes the consolidated table and the `_cdc` SCD2 companion (`core/delta/scd2.py`). |
+| Webhooks | `run_webhook_s3_sink` command; sink behind the `data_warehouse` facade | Buffered ingress: deliveries are buffered to S3 continuously, and the next scheduled sync drains them as ordinary source items (webhook-only schemas skip table resets, `common/extract.py`). |
+| Chunk sinks (CDP, person properties) | `core/sinks.py`, `core/cdp_producer.py`, `core/person_property_row_sink.py` | Gated taps on both write loops, one `stage_chunk` call per chunk (see `ChunkSink`). Downstream: `dwh-cdp-producer-job` produces staged chunks to Kafka for HogFunctions/HogFlows; `sync-warehouse-person-properties` plus `run_person_property_update_consumer` upsert person properties. |
+| Post-import steps | `../post_import_job.py`, children under `../workflow_activities/` | Step 7. Started by whoever finalizes the run (step 6); gates are resolved once in its resolve activity, then the workflow is a loop over recorded step keys. |
+| Repartition | `core/repartition.py`, `core/repartition_controller.py`, `../workflow_activities/repartition_table.py` | Detection is a `POST_LOAD_STEPS` entry (flags oversized partitions); execution is `maybe_repartition_table_activity`, pre-extraction on the next run while the lock is held. |
## The shared kernel
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/auto_widen_resync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/auto_widen_resync.py
index 61598121d0d1..d365006ab0a3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/auto_widen_resync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/auto_widen_resync.py
@@ -127,8 +127,8 @@ def _schedule_auto_widen_resync(
return None
if not is_safe_numeric_widening(stored_type, incoming_type):
return None
- # A streaming-mode CDC schema has its per-schema schedule paused (CDCExtractionWorkflow owns
- # it), so a stamped reset would never run; leave it to the manual repair flow.
+ # A streaming-mode CDC schema's run consumes its change buffer, which refuses a stamped reset: a
+ # re-sync has to go through snapshot mode, so leave it to the manual resync flow.
if schema.is_cdc and schema.cdc_mode == "streaming":
return None
# A webhook-only resource consumes reset_pipeline without wiping the table (its rows can't be
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py
index 322f799079fc..8ae4984b3ff0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py
@@ -16,9 +16,9 @@ class PipelineResult(TypedDict):
It is a runtime value, not a pure property of `ExternalDataJob.pipeline_version`, for one
reason: a v3 extraction that produced zero batches never notifies the load consumer, so the
consumer cannot finalize a run it will never hear about — the workflow must. PipelineV3
- therefore reports True iff at least one batch reached the queue. The two other producers of
- True (`import_data_sync`'s terminal-retry skip, and the CDC-handled-externally path) are
- runs some other party already finalized, where True likewise means "workflow: hands off".
+ therefore reports True iff at least one batch reached the queue. The other producer of True,
+ `import_data_sync`'s terminal-retry skip, is a run some other party already finalized, where
+ True likewise means "workflow: hands off".
Making this a pure version property requires an empty-final-batch queue message so the
consumer hears about every v3 run — deferred until the v2 pipeline is deleted.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
index 1b0f923ccb7f..071a4667b0e6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
@@ -233,9 +233,8 @@ def _purge_stale_buffer_then_mark_initial_sync_complete(
with transaction.atomic():
schema = ExternalDataSchema.objects.select_for_update().exclude(deleted=True).get(id=schema_id, team_id=team_id)
# About to flip a CDC schema snapshot→streaming, after which the consumer merges the buffer, so
- # what it must not replay goes first. A table the buffer does not carry gets no ingress writes
- # until the flip commits; the shadow lane writes on its flag alone, so a concurrent capture tick
- # is the one remaining writer, and the consumer's position guard covers what it leaves.
+ # what it must not replay goes first. A concurrent capture tick is the one other writer, and the
+ # consumer's position guard covers what it leaves.
if schema.is_cdc and not schema.initial_sync_complete and schema.cdc_mode == "snapshot":
purge_buffer_before_handover(schema, logger)
mark_initial_sync_complete(schema_id=schema_id, team_id=team_id)
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
index bc0035a5f508..e0dc6ffbed0f 100644
--- 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
@@ -127,9 +127,9 @@ class LanedPipelineV3(PipelineV3[ResumableData]):
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.
+ crash between creating it and staging into it would leave it Running for good. 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:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py
index 7f7ed0bd5607..b9487aa2664b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py
@@ -245,8 +245,8 @@ class PostgresCDCAdapter:
_recreate, _retry_logger, is_retryable=_is_dropped_or_connect_timeout
)
- # Every schema is reset to snapshot before this runs, so no change from the dead slot is owed
- # to the legacy lane: the new slot starts on the buffer, as a new source does.
+ # Every schema is reset to snapshot before this runs, so nothing from the dead slot is owed:
+ # the new slot starts on the buffer, as a new source does, and capture has nothing to convert.
return {"cdc_consistent_point": consistent_point, "cdc_ingest_mode": "buffered"}
def setup_resources(
@@ -273,8 +273,8 @@ class PostgresCDCAdapter:
"cdc_management_mode": management_mode,
"cdc_slot_name": slot_name,
"cdc_publication_name": pub_name,
- # Written with the slot, before capture first runs, so no change reaches the buffer that a
- # legacy batch already delivered.
+ # Written with the slot, before capture first runs, so capture never treats the new source
+ # as one the retired legacy lane still delivered for.
"cdc_ingest_mode": "buffered",
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/exceptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/exceptions.py
index 86a96d357b55..b8c3a2dc1a6d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/exceptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/exceptions.py
@@ -1,14 +1,6 @@
"""Postgres source exceptions."""
-class CDCHandledExternally(Exception):
- """Raised when a CDC streaming schema is encountered in source_for_pipeline.
-
- CDC streaming schemas are handled by CDCExtractionWorkflow, not by the
- regular ExternalDataJobWorkflow pipeline.
- """
-
-
class XminUnsupportedError(Exception):
"""Raised when an xmin sync targets a relation that can't support it.
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 1c833416363d..092fa4590e05 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
@@ -1814,12 +1814,8 @@ class PostgresSource(
inputs.logger.debug(f"probe_new_data: falling back to a full sync: {e}", exc_info=e)
return None
- def _buffered_cdc_source(self, schema: "ExternalDataSchema", inputs: SourceInputs) -> SourceResponse | None:
- """A `SourceResponse` reading this schema's S3 change buffer, or None if it isn't flipped.
-
- Returning None keeps the caller on the legacy `CDCHandledExternally` path, so a source that
- was never flipped — or a lane the buffer doesn't serve — behaves exactly as before.
- """
+ def _buffered_cdc_source(self, schema: "ExternalDataSchema", inputs: SourceInputs) -> SourceResponse:
+ """A `SourceResponse` reading this streaming, seeded schema's S3 change buffer."""
from asgiref.sync import async_to_sync
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
@@ -1833,22 +1829,46 @@ class PostgresSource(
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,
- )
+ from products.warehouse_sources.backend.temporal.data_imports.cdc.types import parse_ingest_mode
- ingest_mode = PostgresCDCConfig.from_source(schema.source).ingest_mode
- if not consumes_buffer(schema, ingest_mode=ingest_mode):
- return None
+ if not served_lanes(schema):
+ raise ValueError(
+ f"CDC schema {schema.name} has cdc_table_mode {schema.cdc_table_mode!r}, which no buffer lane "
+ "writes. Set it to 'consolidated', 'cdc_only' or 'both'."
+ )
+
+ def no_op_tick() -> SourceResponse:
+ # An empty response no-ops this tick and keeps the schedule alive. 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.
+ clear_listing(inputs.job_id, inputs.team_id)
+ first_lane = served_lanes(schema)[0]
+ return SourceResponse(
+ name=first_lane.resource_name,
+ items=lambda: iter(()),
+ primary_keys=schema.primary_key_columns,
+ cdc_write_mode=first_lane.write_mode,
+ # A change stream carries no seekable key, and `supports_resume` defaults to True.
+ supports_resume=False,
+ )
+
+ if parse_ingest_mode(schema.source.job_inputs) != "buffered":
+ # Until capture converts this legacy source, its buffer holds copies of changes the legacy
+ # lane already delivered, which a read would load a second time. Conversion empties the
+ # buffer before it marks the source buffered.
+ inputs.logger.info("cdc_buffered_waiting_for_legacy_conversion", schema_name=schema.name)
+ return no_op_tick()
# 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, 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.
+ # before its table started streaming, 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(
@@ -1857,10 +1877,9 @@ class PostgresSource(
"the next run resumes from."
)
- # A CDC reset must travel through snapshot mode (which purges the buffer and re-seeds the
- # table); every reset writer does that. Standing down here instead would route into
- # CDCHandledExternally, whose handler pauses this schedule — and nothing on a buffered
- # source ever unpauses it, so the buffer would age to the S3 TTL unconsumed.
+ # A CDC reset must travel through snapshot mode, which re-seeds the table before the buffer
+ # replays over it; every reset writer does that. Merging the buffer into a wiped table
+ # instead would leave only the rows changed since.
if inputs.reset_pipeline:
raise ValueError(
f"reset_pipeline is set on buffered CDC schema {schema.name} while cdc_mode is still "
@@ -1868,27 +1887,11 @@ class PostgresSource(
)
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.
+ # Reading now would stage rows alongside a delivery that is still landing: a previous
+ # attempt of this job holds staged batches that are still claimable, which the append
+ # lane would then write twice.
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=first_lane.resource_name,
- items=lambda: iter(()),
- primary_keys=schema.primary_key_columns,
- cdc_write_mode=first_lane.write_mode,
- # A change stream carries no seekable key, and `supports_resume` defaults to True.
- supports_resume=False,
- )
+ return no_op_tick()
if job is None:
raise ValueError(f"Buffered CDC schema {schema.name} has no job row for run {inputs.job_id}")
@@ -1903,18 +1906,8 @@ class PostgresSource(
inputs.logger.warning(
"cdc_buffer_expired_before_consumption", schema_name=schema.name, last_synced_at=schema.last_synced_at
)
- # The workflow completes the job on this empty response, so an earlier attempt's stamp
- # has to come off it first, as it does on the in-flight stand-down above: a Completed
- # job still carrying one would prove a listing that nothing drained.
- clear_listing(inputs.job_id, inputs.team_id)
hand_reset_to_capture(schema, inputs.logger, start_capture=False)
- first_lane = served_lanes(schema)[0]
- return SourceResponse(
- name=first_lane.resource_name,
- items=lambda: iter(()),
- primary_keys=schema.primary_key_columns,
- cdc_write_mode=first_lane.write_mode,
- )
+ return no_op_tick()
# 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.
@@ -1949,7 +1942,6 @@ class PostgresSource(
) -> SourceResponse:
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import (
- CDCHandledExternally,
ForeignServerUnreachableError,
)
@@ -1978,17 +1970,12 @@ class PostgresSource(
source_schema = source_schema or inferred_schema
source_table_name = source_table_name or inferred_table
- # A buffered source's changes are consumed here like any other source; every other CDC
- # streaming schema is still dispatched by CDCExtractionWorkflow.
- if schema.is_cdc and schema.cdc_mode == "streaming":
- buffered_response = self._buffered_cdc_source(schema, inputs)
- if buffered_response is not None:
- return buffered_response
- raise CDCHandledExternally(
- f"Schema {schema.name} is in CDC streaming mode — handled by CDCExtractionWorkflow"
- )
+ # A streaming CDC schema's changes are consumed from the buffer. One that is not seeded, still
+ # snapshotting or with its data deleted, falls through to a full refresh via postgres_source(),
+ # and capture keeps its changes in the buffer until that completes.
+ if schema.is_cdc and schema.cdc_mode == "streaming" and schema.initial_sync_complete:
+ return self._buffered_cdc_source(schema, inputs)
- # CDC snapshot schemas fall through to run initial full_refresh via postgres_source()
require_ssl = source_requires_ssl(schema.source, config)
table_rebuild_pending = inputs.reset_pipeline or schema.delta_revive_required is not None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
index 60fb0330da01..e78474afebf7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
@@ -168,8 +168,8 @@ def _verify_v3_lock_still_held(team_id: int, schema_id: uuid.UUID) -> None:
raise V3PipelineLockLostError("v3 pipeline lock lost to another run before job creation")
-# Per-run state, not configuration. `cdc_deferred_runs` is a notification queue that reaches
-# hundreds of KB on a busy CDC schema, and `schema_metadata` is the source table's column list.
+# Per-run state, not configuration. `cdc_deferred_runs`, left on some schemas by the retired legacy
+# CDC lane, reaches hundreds of KB, and `schema_metadata` is the source table's column list.
# Copying them onto every job row was most of the snapshot's storage cost.
_SNAPSHOT_EXCLUDED_CONFIG_KEYS = frozenset({"cdc_deferred_runs", "schema_metadata"})
@@ -177,8 +177,8 @@ _SNAPSHOT_EXCLUDED_CONFIG_KEYS = frozenset({"cdc_deferred_runs", "schema_metadat
def _build_schema_snapshot(schema: ExternalDataSchema) -> dict[str, Any]:
"""The schema as it was when this job started, for debugging a run after the fact.
- `post_import_job` reads `last_synced_at` back, and CDC extraction adds `cdc_write_mode` for
- the jobs API. The rest is only ever read by a person: the schema audit log does not diff
+ `post_import_job` reads `last_synced_at` back, and a CDC history lane's job adds
+ `cdc_write_mode` for the jobs API. The rest is only ever read by a person: the schema audit log does not diff
`sync_type_config`, so this is the one record of the cursor and reset flags a run ran with.
"""
sync_type_config = {
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 95e1589f52b5..992b43b11947 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
@@ -88,7 +88,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
validate_and_coerce_row_filters,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import CDCHandledExternally
from products.warehouse_sources.backend.temporal.data_imports.util import PostHogInternalDatabaseError
from products.warehouse_sources.backend.temporal.data_imports.workload_report import aworkload_reporting
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -608,31 +607,6 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
raise TypeError(
f"{new_source.__class__.__name__} does not implement either SimpleSource or ResumableSource"
)
- except CDCHandledExternally:
- await logger.ainfo("Schema is in CDC streaming mode — handled by CDCExtractionWorkflow, skipping")
-
- await database_sync_to_async_pool(ExternalDataJob.objects.filter(id=job_inputs.run_id).update)(
- billable=False, status=ExternalDataJob.Status.COMPLETED, finished_at=dt.datetime.now(dt.UTC)
- )
-
- # Pause the per-schema schedule — CDCExtractionWorkflow handles this
- # schema now. The schedule is unpaused if the schema transitions back
- # to snapshot mode (e.g., after a TRUNCATE or re-enable after grace period).
- try:
- from products.data_warehouse.backend.facade.api import pause_external_data_schedule
-
- await database_sync_to_async_pool(pause_external_data_schedule)(str(inputs.schema_id))
- await logger.ainfo("Paused per-schema schedule for CDC streaming schema")
- except Exception:
- await logger.awarning("Failed to pause per-schema schedule for CDC streaming schema")
-
- # This activity finalized the job itself just above, so the workflow must not
- # write a second terminal status — see PipelineResult for the ownership contract.
- return PipelineResult(
- should_trigger_cdp_producer=False,
- consumer_manages_job_status=True,
- skip_post_import_activities=True,
- )
except SourceExtractionNotImplementedError as e:
# Web refuses to create a source whose implementation it does not have, so the
# stub is only reachable while this worker still runs the build from before the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
index fb8f6b75652a..543d18fe0ada 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
@@ -66,12 +66,12 @@ class TestCheckPipelineVersionActivity:
mock_v3_check.assert_called_once_with(TEAM_ID, "Stripe")
@pytest.mark.parametrize(
- "ingest_mode, expected_is_v3",
+ "cdc_mode, expected_is_v3",
[
- ("buffered", True),
- ("legacy", False),
+ ("streaming", True),
+ ("snapshot", False),
],
- ids=["flipped_forces_v3", "unflipped_follows_flag"],
+ ids=["consumer_forces_v3", "snapshot_follows_flag"],
)
@patch(f"{MODULE}.is_pipeline_v3_enabled", return_value=False)
@patch(f"{MODULE}.ExternalDataSchema")
@@ -85,15 +85,14 @@ class TestCheckPipelineVersionActivity:
mock_source_model: MagicMock,
mock_schema_model: MagicMock,
_mock_v3_check: MagicMock,
- ingest_mode: str,
+ cdc_mode: str,
expected_is_v3: bool,
) -> None:
schema = MagicMock()
schema.is_cdc = True
- schema.cdc_mode = "streaming"
+ schema.cdc_mode = cdc_mode
schema.cdc_table_mode = "consolidated"
schema.initial_sync_complete = True
- schema.source.job_inputs = {"cdc_ingest_mode": ingest_mode}
mock_schema_model.objects.filter.return_value.select_related.return_value.first.return_value = schema
mock_source_model.objects.get.return_value = MagicMock(source_type="Postgres")
diff --git a/products/warehouse_sources/backend/tests/api/test_cdc_table_mode_patch.py b/products/warehouse_sources/backend/tests/api/test_cdc_table_mode_patch.py
index 046babc76911..18bd3c104d13 100644
--- a/products/warehouse_sources/backend/tests/api/test_cdc_table_mode_patch.py
+++ b/products/warehouse_sources/backend/tests/api/test_cdc_table_mode_patch.py
@@ -59,9 +59,6 @@ _PATCH_TARGETS = {
"is_any_external_data_schema_paused": (
"products.warehouse_sources.backend.presentation.views.external_data_schema.is_any_external_data_schema_paused"
),
- "is_buffered_snapshot_enabled": (
- "products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane.is_buffered_snapshot_enabled"
- ),
}
@@ -92,7 +89,7 @@ def _make_cdc_source_and_schema(
cdc_last_log_position: str | None = "0/12345",
cdc_deferred_runs: list[dict] | None = None,
initial_sync_complete: bool = True,
- ingest_mode: str | None = None,
+ ingest_mode: str | None = "buffered",
) -> tuple[ExternalDataSource, ExternalDataSchema]:
job_inputs = {
"schema": "public",
@@ -131,26 +128,19 @@ def _make_cdc_source_and_schema(
@pytest.mark.parametrize(
- ("old_mode", "new_mode", "ingest_mode"),
+ ("old_mode", "new_mode"),
[
- ("consolidated", "cdc_only", None),
- ("consolidated", "both", None),
- ("cdc_only", "consolidated", None),
- ("cdc_only", "both", None),
- ("consolidated", "both", "buffered"),
+ ("consolidated", "cdc_only"),
+ ("consolidated", "both"),
+ ("cdc_only", "consolidated"),
+ ("cdc_only", "both"),
],
)
[email protected]("deferred_runs", [None, [{"job_id": "stale", "run_uuid": "stale", "batch_results": []}]])
def test_patch_cdc_table_mode_adding_target_triggers_resnapshot(
- team, user, client: HttpClient, old_mode, new_mode, ingest_mode
+ team, user, client: HttpClient, old_mode, new_mode, deferred_runs
):
- source, schema = _make_cdc_source_and_schema(
- team,
- cdc_table_mode=old_mode,
- # Pending deferred runs keep a buffered source's table on the legacy lane, so only the legacy
- # cases carry them.
- cdc_deferred_runs=None if ingest_mode else [{"job_id": "stale", "run_uuid": "stale", "batch_results": []}],
- ingest_mode=ingest_mode,
- )
+ source, schema = _make_cdc_source_and_schema(team, cdc_table_mode=old_mode, cdc_deferred_runs=deferred_runs)
running_job = ExternalDataJob.objects.create(
team=team,
pipeline=source,
@@ -172,7 +162,6 @@ def test_patch_cdc_table_mode_adding_target_triggers_resnapshot(
) as mock_cancel,
mock.patch(_PATCH_TARGETS["has_queued_batches"], return_value=False),
mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]) as mock_trigger,
- mock.patch(_PATCH_TARGETS["is_buffered_snapshot_enabled"], return_value=True),
):
response = client.patch(
f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",
@@ -184,8 +173,8 @@ def test_patch_cdc_table_mode_adding_target_triggers_resnapshot(
schema.refresh_from_db()
assert schema.cdc_table_mode == new_mode
- # A buffered source's changes keep going to the buffer, which the new snapshot then replays.
- assert (schema.sync_type_config.get("cdc_snapshot_lane") == "buffer") is (ingest_mode == "buffered")
+ # The table's changes keep going to the buffer, which the new snapshot then replays.
+ assert (schema.sync_type_config.get("cdc_snapshot_lane") == "buffer") is (deferred_runs is None)
assert schema.sync_type_config.get("cdc_mode") == "snapshot"
assert schema.sync_type_config.get("cdc_last_log_position") is None
assert schema.sync_type_config.get("cdc_deferred_runs") is None
@@ -346,6 +335,27 @@ def test_toggling_sync_drops_the_snapshot_marker(team, user, client: HttpClient,
assert "cdc_snapshot_lane" not in schema.sync_type_config
[email protected](("sync_frequency", "expected_status"), [("7day", 200), ("30day", 400)])
+def test_a_cdc_table_syncs_before_its_captured_changes_expire(
+ team, user, client: HttpClient, sync_frequency, expected_status
+):
+ _, schema = _make_cdc_source_and_schema(team, cdc_table_mode="consolidated", ingest_mode="buffered")
+ client.force_login(user)
+ with (
+ mock.patch(_PATCH_TARGETS["external_data_workflow_exists"], return_value=True),
+ mock.patch(_PATCH_TARGETS["sync_external_data_job_workflow"]),
+ ):
+ response = client.patch(
+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",
+ data={"sync_frequency": sync_frequency},
+ content_type="application/json",
+ )
+
+ assert response.status_code == expected_status, response.content
+ if expected_status == 400:
+ assert "must sync at least weekly" in str(response.json())
+
+
@pytest.mark.parametrize("ingest_mode", [None, "buffered"])
def test_resync_of_a_streaming_table_keeps_its_buffer_on_a_buffered_source(team, user, client: HttpClient, ingest_mode):
_, schema = _make_cdc_source_and_schema(team, cdc_table_mode="consolidated", ingest_mode=ingest_mode)
@@ -354,7 +364,6 @@ def test_resync_of_a_streaming_table_keeps_its_buffer_on_a_buffered_source(team,
mock.patch(_PATCH_TARGETS["is_any_external_data_schema_paused"], return_value=False),
mock.patch(_PATCH_TARGETS["has_queued_batches"], return_value=False),
mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]),
- mock.patch(_PATCH_TARGETS["is_buffered_snapshot_enabled"], return_value=True),
):
response = client.post(f"/api/environments/{team.pk}/external_data_schemas/{schema.id}/resync")
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
deleted file mode 100644
index 7b8c703887c0..000000000000
--- a/products/warehouse_sources/backend/tests/management/test_migrate_cdc_source_to_buffered.py
+++ /dev/null
@@ -1,614 +0,0 @@
-import io
-from contextlib import contextmanager
-
-import pytest
-from posthog.test.base import BaseTest
-from unittest.mock import MagicMock, patch
-
-from django.core.management import call_command
-from django.core.management.base import CommandError
-
-from parameterized import parameterized
-
-from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
-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.companion_jobs import COMPANION_RETIRED_ERROR
-
-_CMD = "products.warehouse_sources.backend.management.commands.migrate_cdc_source_to_buffered"
-
-
-@contextmanager
-def _mocked_side_effects(
- oldest_batch_age: float | None = None,
- buffer_keys: list[str] | None = None,
- buffer_keys_by_schema: dict[str, list[str]] | None = None,
- extraction_running: bool = False,
-):
- """Stub every outside effect: Temporal schedules, the sourcebatch probe, the flag, and S3.
-
- `buffer_keys` is what any prefix listing returns; None means the prefix does not exist, which is
- both a clean purge and a drained buffer. `buffer_keys_by_schema` answers per schema id instead,
- for the prefixes that hold different files.
- """
- s3 = MagicMock()
- if buffer_keys_by_schema is not None:
-
- def _ls(prefix, **kwargs):
- for schema_id, keys in buffer_keys_by_schema.items():
- if schema_id in prefix:
- return keys
- raise FileNotFoundError(prefix)
-
- s3.ls.side_effect = _ls
- elif buffer_keys is None:
- s3.ls.side_effect = FileNotFoundError()
- else:
- s3.ls.return_value = buffer_keys
- with (
- patch(f"{_CMD}.psycopg.Connection.connect") as mock_connect,
- patch(f"{_CMD}.BatchQueue.get_oldest_non_terminal_batch_age_seconds", return_value=oldest_batch_age),
- patch(f"{_CMD}.purge_buffer_prefix") as mock_purge,
- patch("products.data_warehouse.backend.facade.api.get_s3_client", return_value=s3),
- patch(
- "products.data_warehouse.backend.facade.api.cdc_extraction_schedule_has_running_action",
- return_value=extraction_running,
- ),
- patch("products.data_warehouse.backend.facade.api.pause_cdc_extraction_schedule") as mock_pause,
- patch("products.data_warehouse.backend.facade.api.unpause_cdc_extraction_schedule") as mock_unpause,
- patch("products.data_warehouse.backend.facade.api.pause_external_data_schedule") as mock_pause_schema,
- patch("products.data_warehouse.backend.facade.api.unpause_external_data_schedule") as mock_unpause_schema,
- ):
- mock_connect.return_value = MagicMock()
- yield {
- "purge": mock_purge,
- "pause": mock_pause,
- "unpause": mock_unpause,
- "pause_schema": mock_pause_schema,
- "unpause_schema": mock_unpause_schema,
- "s3": s3,
- }
-
-
-class TestMigrateCDCSourceToBuffered(BaseTest):
- def _source(self, ingest_mode: str | None = None) -> ExternalDataSource:
- job_inputs: dict = {"cdc_enabled": True}
- if ingest_mode:
- job_inputs["cdc_ingest_mode"] = ingest_mode
- return ExternalDataSource.objects.create(team=self.team, source_type="Postgres", job_inputs=job_inputs)
-
- def _schema(self, source: ExternalDataSource, name: str, table_mode: str = "consolidated", **overrides):
- return ExternalDataSchema.objects.create(
- team=self.team,
- source=source,
- name=name,
- sync_type=ExternalDataSchema.SyncType.CDC,
- sync_type_config={
- "cdc_mode": overrides.get("cdc_mode", "streaming"),
- "cdc_table_mode": table_mode,
- },
- initial_sync_complete=overrides.get("initial_sync_complete", True),
- table=overrides.get("table"),
- )
-
- def _run(self, source, **kwargs) -> str:
- out = io.StringIO()
- call_command("migrate_cdc_source_to_buffered", source_id=str(source.id), stdout=out, **kwargs)
- return out.getvalue()
-
- def test_flipping_sets_buffered_and_purges_pre_flip_files(self):
- source = self._source()
- schema = self._schema(source, "users")
-
- with _mocked_side_effects() as mocks:
- self._run(source)
-
- source.refresh_from_db()
- assert source.job_inputs["cdc_ingest_mode"] == "buffered"
- # Pre-flip files were already delivered by the legacy lane; replaying them would re-apply
- # rows against a position the guard has no watermark for yet.
- assert mocks["purge"].call_args.args[:2] == (self.team.pk, str(schema.id))
- mocks["pause"].assert_called_once()
- mocks["unpause"].assert_called_once()
- mocks["unpause_schema"].assert_called_once_with(str(schema.id))
-
- @parameterized.expand([("flip", None, "buffered"), ("rollback", "buffered", "legacy")])
- def test_the_mode_is_written_without_saving_the_source(self, _name, ingest_mode, expected_mode):
- source = self._source(ingest_mode=ingest_mode)
- self._schema(source, "users")
-
- with _mocked_side_effects():
- with patch.object(ExternalDataSource, "save", side_effect=AssertionError("source.save must not run")):
- self._run(source, rollback=ingest_mode == "buffered")
-
- source.refresh_from_db()
- assert source.job_inputs["cdc_ingest_mode"] == expected_mode
- assert source.job_inputs["cdc_buffered_before"]
-
- def test_flip_aborts_when_a_buffer_file_survives_the_purge(self):
- # The purge itself is best-effort; a surviving file would replay legacy-delivered rows
- # against a lane with no watermark, silently. Abort with the mode unchanged.
- source = self._source()
- schema = self._schema(source, "users")
- leftover = f"bucket/cdc_producer/x/{build_buffer_file_name(1, 2, 0)}"
-
- with _mocked_side_effects(buffer_keys=[leftover]) as mocks:
- with pytest.raises(CommandError, match="survived the purge"):
- self._run(source)
-
- source.refresh_from_db()
- assert "cdc_ingest_mode" not in source.job_inputs
- # The mode never changed, so the source is the legacy source it was before the command
- # ran. Keeping its schedules paused would stop the customer's syncs with nothing to
- # report it: no run starts, so there is no job row and no error.
- mocks["unpause_schema"].assert_called_once_with(str(schema.id))
- mocks["unpause"].assert_not_called()
-
- def test_flip_restores_already_paused_schedules_when_a_later_pause_fails(self):
- # `_pause_schema_schedules_strict` pauses schemas one at a time; a later one failing must
- # not strand the ones that already paused. The mode never changed, so the source is still
- # legacy, and leaving any of its schedules paused would stop syncs with nothing anywhere
- # reporting it.
- source = self._source()
- first = self._schema(source, "users")
- second = self._schema(source, "events")
-
- with _mocked_side_effects() as mocks:
- mocks["pause_schema"].side_effect = [None, Exception("boom")]
- with pytest.raises(CommandError, match="Could not pause the schedule"):
- self._run(source)
-
- source.refresh_from_db()
- assert "cdc_ingest_mode" not in source.job_inputs
- assert mocks["pause_schema"].call_count == 2
- assert {c.args[0] for c in mocks["unpause_schema"].call_args_list} == {str(first.id), str(second.id)}
-
- def test_flip_restores_schedules_and_the_mode_when_marking_schemas_served_fails(self):
- # `source.save` and `_mark_schemas` run inside one transaction specifically so a failure
- # partway through marking rolls `job_inputs` back to legacy too, instead of leaving the
- # source buffered with only some schemas marked served and every schedule still paused.
- source = self._source()
- schema = self._schema(source, "users")
-
- with _mocked_side_effects() as mocks:
- with patch(f"{_CMD}.update_sync_type_config_keys", side_effect=Exception("boom")):
- with pytest.raises(Exception, match="boom"):
- self._run(source)
-
- source.refresh_from_db()
- assert "cdc_ingest_mode" not in source.job_inputs
- mocks["unpause_schema"].assert_called_once_with(str(schema.id))
-
- def test_rollback_drains_the_buffer_then_pauses_the_consumer_before_the_mode_flips(self):
- source = self._source(ingest_mode="buffered")
- schema = self._schema(source, "users")
-
- with _mocked_side_effects() as mocks:
- self._run(source, rollback=True)
-
- source.refresh_from_db()
- assert source.job_inputs["cdc_ingest_mode"] == "legacy"
- # Fully-applied leftovers stay: the position guard no-ops a replay, the TTL clears them.
- mocks["purge"].assert_not_called()
- mocks["pause_schema"].assert_called_once_with(str(schema.id))
- # Step 4 paused them, so the rollback has to hand them back, or the source lands on legacy
- # delivery with nothing scheduled to load it.
- mocks["unpause_schema"].assert_called_once_with(str(schema.id))
-
- def test_restoring_schedules_leaves_a_schema_that_stopped_syncing_paused(self):
- # A drain wait runs for minutes, and a user who turns a schema off in that window must not
- # have it turned back on by the abort path.
- source = self._source()
- staying = self._schema(source, "users")
- disabled = self._schema(source, "events")
- leftover = f"bucket/cdc_producer/x/{build_buffer_file_name(1, 2, 0)}"
- ExternalDataSchema.objects.filter(id=disabled.id).update(should_sync=False)
-
- with _mocked_side_effects(buffer_keys=[leftover]) as mocks:
- with pytest.raises(CommandError, match="survived the purge"):
- self._run(source)
-
- mocks["unpause_schema"].assert_called_once_with(str(staying.id))
-
- def test_rollback_refuses_while_the_buffer_holds_unapplied_changes(self):
- # The buffer tail is WAL the slot already advanced past — flipping to legacy before the
- # consumer applies it loses that WAL for good.
- source = self._source(ingest_mode="buffered")
- self._schema(source, "users")
- unapplied = f"bucket/cdc_producer/x/{build_buffer_file_name(100, 200, 0)}"
-
- with _mocked_side_effects(buffer_keys=[unapplied]) as mocks:
- with pytest.raises(CommandError, match="lose them"):
- self._run(source, rollback=True, drain_timeout=0)
-
- source.refresh_from_db()
- assert source.job_inputs["cdc_ingest_mode"] == "buffered"
- # Consumer schedules must still be live so they can catch up for the re-run.
- mocks["pause_schema"].assert_not_called()
- mocks["unpause_schema"].assert_not_called()
-
- @parameterized.expand(
- [
- ("marked_before_the_rollback", False, True),
- ("marked_by_the_run_it_waited_out", True, True),
- ("sync_turned_off", False, False),
- ]
- )
- def test_rollback_restarts_a_snapshot_the_buffer_carries_on_legacy(
- self, _name, started_during_the_wait, should_sync
- ):
- # Only the buffer holds that table's changes since its snapshot began, and legacy's hand-over
- # would purge them. Refusing instead would block the emergency switch for as long as the
- # snapshot cannot finish.
- source = self._source(ingest_mode="buffered")
- self._schema(source, "users")
- snapshotting = self._schema(source, "orders", cdc_mode="snapshot", initial_sync_complete=False)
- ExternalDataSchema.objects.filter(id=snapshotting.id).update(should_sync=should_sync)
-
- def start_snapshot_in_buffer(*_args):
- update_sync_type_config_keys(snapshotting.id, self.team.pk, updates={"cdc_snapshot_lane": "buffer"})
-
- if not started_during_the_wait:
- start_snapshot_in_buffer()
- with (
- _mocked_side_effects() as mocks,
- patch(f"{_CMD}.Command._wait_for_extraction_idle", side_effect=start_snapshot_in_buffer),
- patch(f"{_CMD}.cancel_running_sync") as cancel,
- ):
- self._run(source, rollback=True, drain_timeout=0)
-
- source.refresh_from_db()
- assert source.job_inputs["cdc_ingest_mode"] == "legacy"
- snapshotting.refresh_from_db()
- assert "cdc_snapshot_lane" not in snapshotting.sync_type_config
- assert snapshotting.sync_type_config["reset_pipeline"] is True
- assert cancel.call_args.args[0].id == snapshotting.id
- assert [(c.args[1], c.kwargs.get("strict")) for c in mocks["purge"].call_args_list] == [
- (str(snapshotting.id), True)
- ]
-
- 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")
- 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(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([("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")
- 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):
- if blocks:
- 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)
-
- 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")
- history = self._schema(source, "events", table_mode="cdc_only")
- disabled_history = self._schema(source, "audit", table_mode="both")
- disabled_history.should_sync = False
- disabled_history.save()
-
- with _mocked_side_effects():
- self._run(source, rollback=True)
-
- source.refresh_from_db()
- assert source.job_inputs["cdc_ingest_mode"] == "legacy"
- assert source.job_inputs["cdc_buffered_before"]
- for schema in (history, disabled_history):
- schema.refresh_from_db()
- assert schema.sync_type_config["cdc_buffered_before"] is True
-
- def test_rollback_restores_schedules_even_when_the_extraction_unpause_fails(self):
- # The per-schema restore runs before the single Temporal call that unpauses extraction, so
- # a raise from that call does not also strand the per-schema schedules a second time.
- source = self._source(ingest_mode="buffered")
- schema = self._schema(source, "users")
-
- with _mocked_side_effects() as mocks:
- mocks["unpause"].side_effect = Exception("boom")
- with pytest.raises(Exception, match="boom"):
- self._run(source, rollback=True)
-
- source.refresh_from_db()
- assert source.job_inputs["cdc_ingest_mode"] == "legacy"
- mocks["unpause_schema"].assert_called_once_with(str(schema.id))
-
- 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 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",
- 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_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:
- self._run(source)
-
- purged = [call.args[1] for call in mocks["purge"].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_hybrid_source_leaves_its_ineligible_schemas_on_legacy(self):
- source = self._source()
- eligible = self._schema(source, "users")
- snapshotting = self._schema(source, "events", cdc_mode="snapshot")
-
- with _mocked_side_effects() as mocks:
- output = self._run(source)
-
- 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()
- self._schema(source, "users", cdc_mode="snapshot")
-
- with _mocked_side_effects():
- with pytest.raises(CommandError, match="No schema on this source serves the buffered lane"):
- self._run(source)
-
- # 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")
-
- with _mocked_side_effects() as mocks:
- output = self._run(source, dry_run=True)
-
- source.refresh_from_db()
- assert "cdc_ingest_mode" not in source.job_inputs
- assert "Dry run" in output
- # Default schema interval is not the 5min platform cadence — the report must say so.
- assert "not at the 5min platform cadence" in output
- mocks["pause"].assert_not_called()
- mocks["purge"].assert_not_called()
-
- def test_a_reserved_seq_column_on_the_source_table_refuses_the_flip(self):
- # The batcher cannot stamp the engine position over a same-named source column, and capture
- # hard-errors on it — refusing here keeps the source out of a flip-then-break loop.
- source = self._source()
- table = DataWarehouseTable.objects.create(
- team_id=self.team.pk,
- name="users",
- format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,
- url_pattern="https://bucket/users/*",
- external_data_source=source,
- columns={"id": {"hogql": "IntegerDatabaseField"}, CDC_SEQ_COLUMN: {"hogql": "IntegerDatabaseField"}},
- )
- self._schema(source, "users", table=table)
-
- with _mocked_side_effects():
- with pytest.raises(CommandError, match="reserved for change ordering"):
- self._run(source)
-
- source.refresh_from_db()
- assert "cdc_ingest_mode" not in source.job_inputs
-
- def test_flipping_records_the_buffered_lane_and_rollback_keeps_the_record(self):
- source = self._source()
- history = self._schema(source, "events", table_mode="cdc_only")
- with _mocked_side_effects():
- self._run(source)
- history.refresh_from_db()
- assert history.sync_type_config["cdc_buffered_before"] is True
-
- with _mocked_side_effects():
- self._run(source, rollback=True)
- history.refresh_from_db()
- assert history.sync_type_config["cdc_buffered_before"] is True
-
- def test_marking_keeps_the_keys_a_run_wrote_while_the_command_waited(self):
- # The command waits out an in-flight capture run, and that run appends to the same JSON —
- # under backpressure, the only record of batches it deferred. Saving the copy loaded before
- # the wait would put the JSON back the way it was.
- source = self._source()
- schema = self._schema(source, "users")
-
- 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)
-
- schema.refresh_from_db()
- assert schema.sync_type_config["cdc_deferred_runs"] == [{"run": 1}]
- assert schema.sync_type_config["cdc_buffered_before"] is True
-
- @parameterized.expand([("flip", None, False), ("rollback", "buffered", True)])
- def test_an_orphaned_companion_job_is_retired_instead_of_blocking(self, _name, ingest_mode, rollback):
- # 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_a_stuck_sourcebatch_aborts_the_flip_with_the_source_paused(self):
- source = self._source()
- self._schema(source, "users")
-
- with _mocked_side_effects(oldest_batch_age=9999.0) as mocks:
- with pytest.raises(CommandError, match="still has a batch"):
- self._run(source, drain_timeout=0)
-
- source.refresh_from_db()
- # Flipping on top of a stuck load would let that batch land against a table the buffered
- # lane has already started writing.
- assert "cdc_ingest_mode" not in source.job_inputs
- mocks["pause"].assert_called_once()
- mocks["unpause"].assert_not_called()
-
- def test_the_flip_waits_out_a_running_scheduled_sync(self):
- # A sync that started legacy resolves its pipeline version before the mode changes; letting
- # it straddle the change would consume the buffer on that stale version.
- source = self._source()
- schema = self._schema(source, "users")
- ExternalDataJob.objects.create(
- team_id=self.team.pk,
- pipeline_id=source.id,
- schema_id=schema.id,
- status=ExternalDataJob.Status.RUNNING,
- rows_synced=0,
- )
-
- with _mocked_side_effects() as mocks:
- with pytest.raises(CommandError, match="still running"):
- self._run(source, drain_timeout=0)
-
- source.refresh_from_db()
- assert "cdc_ingest_mode" not in source.job_inputs
- mocks["pause_schema"].assert_called_once_with(str(schema.id))
- mocks["unpause"].assert_not_called()
-
- def test_the_flip_waits_out_an_in_flight_extraction_run(self):
- # A legacy run with the shadow lane on keeps writing buffer files after the schedule pauses;
- # one landing after the purge would be merged on top of rows legacy already delivered.
- source = self._source()
- self._schema(source, "users")
-
- with _mocked_side_effects(extraction_running=True) as mocks:
- with pytest.raises(CommandError, match="still executing"):
- self._run(source, drain_timeout=0)
-
- source.refresh_from_db()
- assert "cdc_ingest_mode" not in source.job_inputs
- mocks["purge"].assert_not_called()
- mocks["unpause"].assert_not_called()
-
- def test_rollback_waits_out_an_in_flight_extraction_run(self):
- # Pausing the schedule does not stop a running workflow — one still executing would keep
- # writing buffer files and advancing the slot behind the drain check.
- source = self._source(ingest_mode="buffered")
- self._schema(source, "users")
-
- with _mocked_side_effects(extraction_running=True):
- with pytest.raises(CommandError, match="still executing"):
- self._run(source, rollback=True, drain_timeout=0)
-
- source.refresh_from_db()
- assert source.job_inputs["cdc_ingest_mode"] == "buffered"
-
- def test_a_user_disabled_schema_is_not_flipped(self):
- # Step 5 unpauses eligible schedules; flipping a disabled schema would reverse the disable.
- source = self._source()
- disabled = self._schema(source, "users")
- disabled.should_sync = False
- disabled.save(update_fields=["should_sync"])
-
- with _mocked_side_effects():
- with pytest.raises(CommandError, match="No schema on this source serves the buffered lane"):
- self._run(source)
diff --git a/products/warehouse_sources/backend/tests/management/test_repair_stalled_schema_schedules.py b/products/warehouse_sources/backend/tests/management/test_repair_stalled_schema_schedules.py
index eb9bb7c7e222..1852cff4d926 100644
--- a/products/warehouse_sources/backend/tests/management/test_repair_stalled_schema_schedules.py
+++ b/products/warehouse_sources/backend/tests/management/test_repair_stalled_schema_schedules.py
@@ -87,29 +87,17 @@ class TestRepairStalledSchemaSchedules(BaseTest):
mock_repair.assert_not_called()
assert "unstick_external_data_jobs" in output
- def test_include_buffered_does_not_override_an_admin_paused_schema(self) -> None:
- # --include-buffered only overrides the buffered-CDC exclusion. A schema still carrying
- # admin_unpause_schedule_after_run is deferred to whatever cleared it, not to this flag.
+ def test_an_admin_paused_schema_is_listed_but_not_repaired(self) -> None:
+ # A schema still carrying admin_unpause_schedule_after_run is deferred to whatever clears it.
schema = self._stalled_schema(sync_type_config={"admin_unpause_schedule_after_run": True})
with patch(f"{_CMD}.repair_stalled_schema") as mock_repair:
- output = self._run(live_run=True, include_buffered=True)
+ output = self._run(live_run=True)
mock_repair.assert_not_called()
assert str(schema.id) in output
assert "admin-triggered run" in output
- def test_a_streaming_cdc_schema_is_excluded_before_it_reaches_the_command(self) -> None:
- # A paused per-schema schedule is a streaming CDC schema's steady state, so it is
- # excluded at the predicate rather than surfaced here for --include-buffered to bypass.
- self._stalled_schema(sync_type=ExternalDataSchema.SyncType.CDC, sync_type_config={"cdc_mode": "streaming"})
-
- with patch(f"{_CMD}.repair_stalled_schema") as mock_repair:
- output = self._run(live_run=True, include_buffered=True)
-
- mock_repair.assert_not_called()
- assert "No stalled schemas match" in output
-
def test_the_cap_stops_an_unexpectedly_wide_repair(self) -> None:
for name in ("users", "events", "orgs"):
self._stalled_schema(name=name)
diff --git a/products/warehouse_sources/backend/tests/management/test_validate_cdc_buffer.py b/products/warehouse_sources/backend/tests/management/test_validate_cdc_buffer.py
deleted file mode 100644
index 8f5983ecca84..000000000000
--- a/products/warehouse_sources/backend/tests/management/test_validate_cdc_buffer.py
+++ /dev/null
@@ -1,320 +0,0 @@
-import io
-import uuid
-import asyncio
-from contextlib import contextmanager
-from datetime import UTC, datetime, timedelta
-
-import pytest
-from unittest.mock import MagicMock, patch
-
-from django.core.management import call_command
-from django.core.management.base import CommandError
-
-import psycopg
-import pyarrow as pa
-import pyarrow.parquet as pq
-
-from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN
-from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import build_buffer_file_name
-
-_CMD = "products.warehouse_sources.backend.management.commands.validate_cdc_buffer"
-
-
-def _parquet_bytes(rows: int) -> bytes:
- buf = io.BytesIO()
- table = pa.table(
- {"id": pa.array(range(rows), type=pa.int64()), CDC_SEQ_COLUMN: pa.array(range(rows), type=pa.int64())}
- )
- pq.write_table(table, buf)
- return buf.getvalue()
-
-
-def _fake_s3(files: dict[str, bytes | tuple[bytes, datetime | None]]) -> MagicMock:
- """files: key (no protocol) -> parquet bytes, or (bytes, LastModified)."""
-
- def _content(value) -> bytes:
- return value[0] if isinstance(value, tuple) else value
-
- def _modified(value) -> datetime | None:
- return value[1] if isinstance(value, tuple) else None
-
- s3 = MagicMock()
-
- def ls(prefix, detail=True):
- matching = [key for key in files if key.startswith(prefix)]
- if not matching:
- raise FileNotFoundError(prefix)
- return [{"Key": key, "type": "file", "LastModified": _modified(files[key])} for key in matching]
-
- @contextmanager
- def open_(key, mode):
- yield io.BytesIO(_content(files[key]))
-
- s3.ls = ls
- s3.open = open_
- return s3
-
-
-def _schema_mock(mode: str = "consolidated", cdc_mode: str = "streaming"):
- schema = MagicMock()
- schema.id = uuid.uuid4()
- schema.team_id = 1
- schema.name = "users"
- schema.cdc_table_mode = mode
- schema.cdc_mode = cdc_mode
- return schema
-
-
-class TestValidateCDCBuffer:
- def _run(self, schema, files, legacy: dict[tuple[str, str], int], retried: dict[str, int] | None = None):
- source = MagicMock()
- source.id = uuid.uuid4()
-
- with (
- patch(f"{_CMD}.ExternalDataSource") as MockSource,
- patch(f"{_CMD}.ExternalDataSchema") as MockSchema,
- patch(f"{_CMD}.get_s3_client", return_value=_fake_s3(files)),
- patch.object(
- __import__(_CMD, fromlist=["Command"]).Command,
- "_fetch_legacy_row_sums",
- return_value=(legacy, retried or {}),
- ),
- ):
- MockSource.objects.get.return_value = source
- MockSchema.objects.filter.return_value = [schema]
- MockSchema.SyncType.CDC = "cdc"
- call_command("validate_cdc_buffer", "--source-id", str(source.id))
-
- def _key(self, schema, name: str) -> str:
- from django.conf import settings
-
- return f"{settings.DATAWAREHOUSE_BUCKET}/cdc_producer/{schema.team_id}/{schema.id}/{name}"
-
- def test_passes_on_consistent_buffer(self):
- schema = _schema_mock(mode="both")
- files = {
- self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(3),
- self._key(schema, build_buffer_file_name(200, 300, 1)): _parquet_bytes(2),
- }
- # scd2 lane keeps one row per event: exact match. consolidated deduped down to 4.
- legacy = {(str(schema.id), "scd2"): 5, (str(schema.id), "consolidated"): 4}
- self._run(schema, files, legacy)
-
- def test_fails_on_scd2_mismatch(self):
- schema = _schema_mock(mode="cdc_only")
- files = {self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(3)}
- with pytest.raises(CommandError, match="violation"):
- self._run(schema, files, {(str(schema.id), "scd2"): 5})
-
- def test_scd2_mismatch_downgrades_to_warning_after_a_retry(self):
- # Legacy re-inserts replayed rows on activity retry while buffer files
- # overwrite, so a re-dispatched batch makes the exact match only warn.
- schema = _schema_mock(mode="cdc_only")
- files = {self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(3)}
- self._run(schema, files, {(str(schema.id), "scd2"): 5}, retried={str(schema.id): 1})
-
- def test_scd2_mismatch_still_fails_when_no_batch_was_retried(self):
- # Regression: the downgrade used to key on the count of distinct run_uuids, which a
- # healthy 5-min source increments every tick — so any window longer than one tick
- # waived the exact match entirely and the gate asserted nothing.
- schema = _schema_mock(mode="cdc_only")
- files = {self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(3)}
- with pytest.raises(CommandError, match="violation"):
- self._run(schema, files, {(str(schema.id), "scd2"): 5}, retried={str(schema.id): 0})
-
- def test_fails_when_buffer_below_consolidated(self):
- schema = _schema_mock(mode="consolidated")
- files = {self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(2)}
- with pytest.raises(CommandError, match="violation"):
- self._run(schema, files, {(str(schema.id), "consolidated"): 5})
-
- def test_fails_on_overlapping_ranges(self):
- schema = _schema_mock(mode="consolidated")
- files = {
- self._key(schema, build_buffer_file_name(100, 250, 0)): _parquet_bytes(1),
- self._key(schema, build_buffer_file_name(200, 300, 0)): _parquet_bytes(1),
- }
- with pytest.raises(CommandError, match="violation"):
- self._run(schema, files, {})
-
- def test_fails_on_inverted_range(self):
- schema = _schema_mock(mode="consolidated")
- # build_buffer_file_name refuses inverted ranges, so name it by hand.
- name = f"{300:020d}-{200:020d}-{0:06d}.parquet"
- files = {self._key(schema, name): _parquet_bytes(1)}
- with pytest.raises(CommandError, match="violation"):
- self._run(schema, files, {})
-
- def test_shared_boundary_is_legal(self):
- # A split transaction's batches share its commit position — not an overlap.
- schema = _schema_mock(mode="consolidated")
- files = {
- self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(1),
- self._key(schema, build_buffer_file_name(200, 200, 1)): _parquet_bytes(1),
- }
- self._run(schema, files, {(str(schema.id), "consolidated"): 2})
-
- def test_buffered_rows_with_no_legacy_dispatches_is_a_violation(self):
- # Streaming flushes dispatch legacy immediately: buffer rows with zero legacy
- # rows means the legacy lane stalled — absence must not skip the comparison.
- schema = _schema_mock(mode="both")
- files = {self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(3)}
- with pytest.raises(CommandError, match="violation"):
- self._run(schema, files, {(str(schema.id), "scd2"): 3}) # scd2 fine, consolidated lane absent
-
- def test_snapshot_schema_skips_row_reconciliation(self):
- # Snapshot phase defers legacy dispatch, so counts legitimately diverge.
- schema = _schema_mock(mode="cdc_only", cdc_mode="snapshot")
- files = {self._key(schema, build_buffer_file_name(100, 200, 0)): _parquet_bytes(3)}
- self._run(schema, files, {(str(schema.id), "scd2"): 99})
-
- def test_empty_buffer_with_legacy_rows_is_a_violation_not_a_crash(self):
- # Day-one state: shadow just enabled, no files yet, legacy still dispatching.
- schema = _schema_mock(mode="cdc_only")
- with pytest.raises(CommandError, match="violation"):
- self._run(schema, {}, {(str(schema.id), "scd2"): 5})
-
- def test_files_older_than_window_are_excluded(self):
- schema = _schema_mock(mode="cdc_only")
- old = datetime.now(UTC) - timedelta(hours=48)
- files = {
- self._key(schema, build_buffer_file_name(1, 50, 0)): (_parquet_bytes(7), old),
- self._key(schema, build_buffer_file_name(100, 200, 0)): (_parquet_bytes(3), None),
- }
- # Reconciles against only the in-window file (3 rows); counting the stale
- # 7 rows would make the exact match pass at the wrong sum.
- self._run(schema, files, {(str(schema.id), "scd2"): 3})
-
- def test_unreadable_file_is_a_violation_not_a_crash(self):
- schema = _schema_mock(mode="consolidated")
- files = {self._key(schema, build_buffer_file_name(100, 200, 0)): b"not a parquet file"}
- with pytest.raises(CommandError, match="violation"):
- self._run(schema, files, {})
-
- def test_fails_on_foreign_file(self):
- schema = _schema_mock(mode="consolidated")
- files = {self._key(schema, "part-0000.parquet"): _parquet_bytes(1)}
- with pytest.raises(CommandError, match="violation"):
- self._run(schema, files, {})
-
-
[email protected]_db(transaction=True)
-class TestFetchLegacyRowSums:
- """DB-backed: the SQL must count only sync_type='cdc' dispatches — snapshots
- (full_refresh) share the sourcebatch table and would otherwise inflate the
- consolidated lane into a guaranteed false violation during onboarding."""
-
- @pytest.fixture(autouse=True)
- def _tables(self):
- from products.warehouse_sources_queue.backend.testing import (
- ensure_queue_tables as _ensure_tables,
- get_test_database_url as _get_test_database_url,
- truncate_queue_tables as _truncate_tables,
- )
-
- url = _get_test_database_url()
- with psycopg.Connection.connect(url, autocommit=True) as conn:
- _ensure_tables(conn)
- _truncate_tables(conn)
- self._url = url
- yield
-
- def _seed(self, rows: list[dict]) -> None:
- from products.warehouse_sources_queue.backend.testing import insert_batch as _insert_batch
-
- async def seed() -> None:
- async with await psycopg.AsyncConnection.connect(self._url, autocommit=True) as conn:
- for row in rows:
- await _insert_batch(conn, **row)
-
- asyncio.run(seed())
-
- def test_counts_only_cdc_dispatches_and_reports_no_retry(self):
- command_module = __import__(_CMD, fromlist=["Command"])
- source = MagicMock()
- source.id = "source-1"
- schema_id = "schema-1"
-
- self._seed(
- [
- {
- "schema_id": schema_id,
- "sync_type": "cdc",
- "resource_name": "users",
- "row_count": 10,
- "run_uuid": "r1",
- },
- {
- "schema_id": schema_id,
- "sync_type": "cdc",
- "resource_name": "users_cdc",
- "row_count": 7,
- "run_uuid": "r1",
- "batch_index": 1,
- },
- # Snapshot dispatch for the same schema: must NOT count.
- {
- "schema_id": schema_id,
- "sync_type": "full_refresh",
- "resource_name": "users",
- "row_count": 9999,
- "run_uuid": "r2",
- "batch_index": 2,
- },
- # Second cdc run: bumps the distinct-run count.
- {
- "schema_id": schema_id,
- "sync_type": "cdc",
- "resource_name": "users",
- "row_count": 5,
- "run_uuid": "r3",
- "batch_index": 3,
- },
- ]
- )
-
- with patch.object(command_module, "WAREHOUSE_SOURCES_DATABASE_URL", self._url):
- sums, retried_batches = command_module.Command()._fetch_legacy_row_sums(
- source, datetime.now(UTC) - timedelta(hours=1)
- )
-
- assert sums == {(schema_id, "consolidated"): 15, (schema_id, "scd2"): 7}
- # Two distinct runs, but every (run_uuid, batch_index) dispatched once: no retry.
- assert retried_batches[schema_id] == 0
-
- def test_detects_a_redispatched_batch_as_a_retry(self):
- command_module = __import__(_CMD, fromlist=["Command"])
- source = MagicMock()
- source.id = "source-1"
- schema_id = "schema-1"
-
- self._seed(
- [
- {
- "schema_id": schema_id,
- "sync_type": "cdc",
- "resource_name": "users_cdc",
- "row_count": 7,
- "run_uuid": "r1",
- "batch_index": 0,
- },
- # Same (run_uuid, batch_index) dispatched again — the replay an activity
- # retry produces, and the only thing that legitimately skews the exact match.
- {
- "schema_id": schema_id,
- "sync_type": "cdc",
- "resource_name": "users_cdc",
- "row_count": 7,
- "run_uuid": "r1",
- "batch_index": 0,
- },
- ]
- )
-
- with patch.object(command_module, "WAREHOUSE_SOURCES_DATABASE_URL", self._url):
- sums, retried_batches = command_module.Command()._fetch_legacy_row_sums(
- source, datetime.now(UTC) - timedelta(hours=1)
- )
-
- assert sums == {(schema_id, "scd2"): 14}
- assert retried_batches[schema_id] == 1
diff --git a/products/warehouse_sources/backend/tests/test_ad_hoc_sync.py b/products/warehouse_sources/backend/tests/test_ad_hoc_sync.py
index af0e49565f73..ca52f59c940e 100644
--- a/products/warehouse_sources/backend/tests/test_ad_hoc_sync.py
+++ b/products/warehouse_sources/backend/tests/test_ad_hoc_sync.py
@@ -117,10 +117,6 @@ def test_a_reset_of_a_streaming_cdc_table_keeps_its_buffer_and_concurrent_keys(
with (
patch(f"{MODULE}.is_schedule_paused", return_value=True),
patch(f"{MODULE}.start_external_data_workflow"),
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane.is_buffered_snapshot_enabled",
- return_value=True,
- ),
):
trigger_ad_hoc_sync(MagicMock(), schema, billable=False, reset_pipeline=True, workflow_id_prefix="test")
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index ea7f56742de3..cda8a6c60e8c 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -32,7 +32,6 @@ from products.warehouse_sources.backend.models.external_data_schema import (
STAGED_CURSOR_PENDING_LIMIT,
ExternalDataSchema,
apply_incremental_lookback,
- complete_schema_run,
mark_initial_sync_complete,
mark_schema_running_unless_halted,
process_incremental_value,
@@ -843,85 +842,6 @@ class TestMarkSchemaRunningUnlessHalted(BaseTest):
assert schema.status == expected
-class TestCompleteSchemaRun(BaseTest):
- """The success repaint checks the broken marker under the row lock: the sweeper can mark the
- source broken while a run is in flight, and an unlocked check on a stale instance would
- overwrite the sweeper's FAILED with COMPLETED, hiding the breakage from the failure digest."""
-
- def _schema(self, sync_type_config: dict) -> ExternalDataSchema:
- source = ExternalDataSource.objects.create(
- team_id=self.team.pk,
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- status="Completed",
- source_type="Postgres",
- )
- return ExternalDataSchema.objects.create(
- team_id=self.team.pk,
- source=source,
- name="users",
- sync_type="cdc",
- sync_type_config=sync_type_config,
- status=ExternalDataSchema.Status.FAILED,
- latest_error="boom",
- )
-
- @parameterized.expand(
- [
- (
- # The sweeper marked the source broken after this run's instance was loaded;
- # the stale instance must not repaint FAILED away.
- "broken_marker_blocks_repaint",
- {"cdc_mode": "streaming", "cdc_broken": {"reason": "slot_missing"}},
- False,
- ExternalDataSchema.Status.FAILED,
- {"cdc_mode": "streaming", "cdc_broken": {"reason": "slot_missing"}},
- ),
- (
- # A successful run proves extraction resumed: the pause marker is cleared in the
- # same transaction as the repaint.
- "paused_marker_cleared_on_repaint",
- {"cdc_mode": "streaming", "cdc_extraction_paused": {"reason": "auth_failed"}},
- True,
- ExternalDataSchema.Status.COMPLETED,
- {"cdc_mode": "streaming"},
- ),
- (
- "healthy_schema_repaints",
- {"cdc_mode": "streaming"},
- True,
- ExternalDataSchema.Status.COMPLETED,
- {"cdc_mode": "streaming"},
- ),
- ]
- )
- def test_repaint_respects_markers(
- self,
- _name: str,
- config: dict,
- expected_repainted: bool,
- expected_status: str,
- expected_config: dict,
- ) -> None:
- schema = self._schema({"cdc_mode": "streaming"})
- # The instance the activity holds predates the sweeper's marker write — a check against
- # its in-memory config would see no marker and repaint every case below.
- stale_instance = ExternalDataSchema.objects.get(id=schema.id)
- ExternalDataSchema.objects.filter(id=schema.id).update(sync_type_config=config)
-
- now = timezone.now()
- repainted = complete_schema_run(stale_instance, last_synced_at=now)
-
- assert repainted is expected_repainted
- schema.refresh_from_db()
- assert schema.status == expected_status
- assert schema.sync_type_config == expected_config
- assert schema.latest_error == ("boom" if not expected_repainted else None)
- # The passed instance mirrors the persisted outcome either way.
- assert stale_instance.status == expected_status
- assert stale_instance.sync_type_config == expected_config
-
-
@pytest.mark.parametrize(
"clickhouse_type,expected",
[
diff --git a/products/warehouse_sources/backend/tests/test_stalled_schedules.py b/products/warehouse_sources/backend/tests/test_stalled_schedules.py
index c911b131e867..168b075db131 100644
--- a/products/warehouse_sources/backend/tests/test_stalled_schedules.py
+++ b/products/warehouse_sources/backend/tests/test_stalled_schedules.py
@@ -82,15 +82,6 @@ class TestStalledSchedules(BaseTest):
("deleted source", {}, {"deleted": True}),
# A direct-query source has no schedule to stall.
("direct query source", {}, {"access_method": ExternalDataSource.AccessMethod.DIRECT}),
- # A paused per-schema schedule is a streaming CDC schema's steady state:
- # CDCExtractionWorkflow owns it and pauses it again on its own next tick
- # (CDCHandledExternally). A source marked cdc_broken can drift the schema's status
- # away from FAILED, so this is excluded here rather than relying on that status.
- (
- "streaming cdc schema",
- {"sync_type": ExternalDataSchema.SyncType.CDC, "sync_type_config": {"cdc_mode": "streaming"}},
- {},
- ),
# cdc_halted is a configuration marker independent of should_sync and status: a
# broken source's schema can still read should_sync=True and a self-reporting status.
("cdc broken source", {"sync_type_config": {"cdc_broken": True}}, {}),
@@ -155,16 +146,20 @@ class TestStalledSchedules(BaseTest):
assert stalled[str(schema.id)].kind == "stuck_job"
assert stalled[str(schema.id)].repairable_here is False
- def test_a_buffered_cdc_schema_is_reported_but_not_repairable_here(self) -> None:
+ def test_a_streaming_cdc_schema_whose_consumer_stopped_is_reported_and_repairable(self) -> None:
+ # Its schedule consumes the change buffer, so a stall lets the buffer age toward its expiry.
source = self._source(job_inputs={"cdc_ingest_mode": "buffered"})
- schema = self._schema(source, synced_ago=timedelta(days=5))
+ schema = self._schema(
+ source,
+ synced_ago=timedelta(days=5),
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ sync_type_config={"cdc_mode": "streaming"},
+ )
stalled = {s.schema_id: s for s in find_stalled_schemas()}
- # Its schedule paces buffer consumption, so restarting it out of sequence merges files
- # against a table the buffered lane already writes.
assert stalled[str(schema.id)].kind == "no_runs"
- assert stalled[str(schema.id)].repairable_here is False
+ assert stalled[str(schema.id)].repairable_here is True
def test_a_schema_with_no_sync_interval_is_reported_but_not_repairable_here(self) -> None:
# get_sync_schedule passes sync_frequency_interval straight into ScheduleIntervalSpec,
@@ -284,21 +279,6 @@ class TestStalledSchedules(BaseTest):
mock_sync.assert_not_called()
- def test_repair_skips_a_schema_that_flipped_to_cdc_streaming_since_it_was_discovered(self) -> None:
- # initial_sync_complete (and so the snapshot-to-streaming flip) can land in the window
- # between discovery and this call. A paused schedule is streaming's steady state, so
- # unpausing it here would just race CDCExtractionWorkflow for nothing.
- schema = self._schema(synced_ago=timedelta(days=5), sync_type=ExternalDataSchema.SyncType.CDC)
- stalled = next(s for s in find_stalled_schemas() if s.schema_id == str(schema.id))
-
- schema.sync_type_config = {"cdc_mode": "streaming"}
- schema.save(update_fields=["sync_type_config"])
-
- with patch("products.data_warehouse.backend.facade.api.sync_external_data_job_workflow") as mock_sync:
- repair_stalled_schema(stalled)
-
- mock_sync.assert_not_called()
-
def test_repair_skips_a_schema_marked_cdc_broken_since_it_was_discovered(self) -> None:
# The halt marker exists precisely to stop anything else from touching the schedule
# until repair_cdc clears it, so it is re-checked for the same staleness reason as the
diff --git a/products/warehouse_sources/skills/setting-up-a-data-warehouse-source/references/sync-types.md b/products/warehouse_sources/skills/setting-up-a-data-warehouse-source/references/sync-types.md
index 3ef41c88ea59..cd5ccbb4954f 100644
--- a/products/warehouse_sources/skills/setting-up-a-data-warehouse-source/references/sync-types.md
+++ b/products/warehouse_sources/skills/setting-up-a-data-warehouse-source/references/sync-types.md
@@ -47,10 +47,11 @@ Works the same way — new rows have higher ids.
Append preserves every version. Useful when the source updates records and you want to track the history rather than
latest-state only.
-**Postgres, you need sub-minute freshness** → `cdc`.
-CDC streams WAL changes instead of polling. Requires primary keys on each table and Postgres logical replication
-setup. Run `external-data-sources-check-cdc-prerequisites-create` first — unmet prerequisites cause the sync to fail
-immediately on first run.
+**Postgres, you need changes within minutes, including deletes** → `cdc`.
+CDC streams WAL changes instead of polling, and loads them on the table's sync frequency, every 5 minutes at the
+fastest. Requires primary keys on each table and Postgres logical replication setup. Run
+`external-data-sources-check-cdc-prerequisites-create` first — unmet prerequisites cause the sync to fail immediately
+on first run.
**Stripe (or any source where `supports_webhooks: true`)** → consider `webhook` for real-time push.
Set `sync_type: "webhook"` on the tables that support it. Note that a webhook-type schema _still_ does an initial
@@ -129,7 +130,8 @@ The `supports_webhooks` flag on each table in the db-schema response is the sour
frequencies are usually wasteful for full refresh.
- For `incremental` / `append`: `1hour` or `6hour` is a reasonable default on reasonably sized tables. The `5min`
floor exists but is rarely needed — if the user wants real-time, prefer `cdc` or `webhook`.
-- For `cdc`: frequency doesn't really apply — CDC streams continuously.
+- For `cdc`: changes are captured continuously, and the frequency sets how often they load into the table. `5min` keeps the table close to real time.
+ The API rejects anything slower than `7day` for `cdc`, because captured changes expire after 14 days.
- For cold archive tables: `7day` or `30day` keeps the schedule alive without wasting runs.
The `never` value freezes the schema — it won't sync automatically, but can still be triggered manually via
diff --git a/products/warehouse_sources/skills/tuning-incremental-sync-config/SKILL.md b/products/warehouse_sources/skills/tuning-incremental-sync-config/SKILL.md
index e5a89da501b3..1b0451c5e06b 100644
--- a/products/warehouse_sources/skills/tuning-incremental-sync-config/SKILL.md
+++ b/products/warehouse_sources/skills/tuning-incremental-sync-config/SKILL.md
@@ -45,16 +45,16 @@ chosen at creation time there.
From the partial-update endpoint:
-| Field | Values | Notes |
-| ------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------ |
-| `sync_type` | `full_refresh`, `incremental`, `append`, `cdc`, `webhook` | Source must support the target type — check via incremental-fields |
-| `incremental_field` | Column name from the source | Must appear in `incremental_fields` list for the schema |
-| `incremental_field_type` | `datetime`, `date`, `timestamp`, `integer`, `numeric`, `objectid` | Must match the column's real type |
-| `primary_key_columns` | Array of column names | Required for CDC. Used for upsert dedup on incremental |
-| `cdc_table_mode` | `consolidated`, `cdc_only`, `both` | Only meaningful when sync_type=cdc |
-| `sync_frequency` | `1min`, `5min`, `15min`, `30min`, `1hour`, `6hour`, `12hour`, `24hour`, `7day`, `30day`, `never` | Applies to all non-CDC types |
-| `sync_time_of_day` | `HH:MM:SS` | When sync_frequency is daily/weekly-scale |
-| `should_sync` | `true` / `false` | Pause the schema without deleting it |
+| Field | Values | Notes |
+| ------------------------ | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
+| `sync_type` | `full_refresh`, `incremental`, `append`, `cdc`, `webhook` | Source must support the target type — check via incremental-fields |
+| `incremental_field` | Column name from the source | Must appear in `incremental_fields` list for the schema |
+| `incremental_field_type` | `datetime`, `date`, `timestamp`, `integer`, `numeric`, `objectid` | Must match the column's real type |
+| `primary_key_columns` | Array of column names | Required for CDC. Used for upsert dedup on incremental |
+| `cdc_table_mode` | `consolidated`, `cdc_only`, `both` | Only meaningful when sync_type=cdc |
+| `sync_frequency` | `5min`, `15min`, `30min`, `1hour`, `6hour`, `12hour`, `24hour`, `7day`, `30day`, `never` | How often the table syncs. CDC: how often changes load, `7day` max |
+| `sync_time_of_day` | `HH:MM:SS` | When sync_frequency is daily/weekly-scale |
+| `should_sync` | `true` / `false` | Pause the schema without deleting it |
## Workflow