feather-cdc-postgres 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. feather_cdc_postgres-0.1.0/.gitignore +21 -0
  2. feather_cdc_postgres-0.1.0/PKG-INFO +239 -0
  3. feather_cdc_postgres-0.1.0/README.md +212 -0
  4. feather_cdc_postgres-0.1.0/pyproject.toml +85 -0
  5. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/__init__.py +6 -0
  6. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/__main__.py +9 -0
  7. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/adapters/__init__.py +44 -0
  8. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/adapters/featherbase.py +126 -0
  9. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/cli.py +247 -0
  10. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/destination.py +640 -0
  11. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/discovery.py +216 -0
  12. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/drift.py +207 -0
  13. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/generate_dbt.py +106 -0
  14. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/lifecycle.py +79 -0
  15. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/manifest.py +587 -0
  16. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/ownership.py +103 -0
  17. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/publication.py +157 -0
  18. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/runner.py +1399 -0
  19. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/schema_registry.py +283 -0
  20. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/selectors.py +347 -0
  21. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/snapshot.py +448 -0
  22. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/stream.py +162 -0
  23. feather_cdc_postgres-0.1.0/src/feather_cdc_postgres/telemetry.py +172 -0
  24. feather_cdc_postgres-0.1.0/src/pg_replication/LICENSE +201 -0
  25. feather_cdc_postgres-0.1.0/src/pg_replication/README.md +100 -0
  26. feather_cdc_postgres-0.1.0/src/pg_replication/__init__.py +106 -0
  27. feather_cdc_postgres-0.1.0/src/pg_replication/decoders.py +428 -0
  28. feather_cdc_postgres-0.1.0/src/pg_replication/exceptions.py +6 -0
  29. feather_cdc_postgres-0.1.0/src/pg_replication/helpers.py +1405 -0
  30. feather_cdc_postgres-0.1.0/src/pg_replication/schema_types.py +156 -0
  31. feather_cdc_postgres-0.1.0/tests/conftest.py +182 -0
  32. feather_cdc_postgres-0.1.0/tests/fixtures/control_plane_control_schema.sql +158 -0
  33. feather_cdc_postgres-0.1.0/tests/fixtures/featherbase_namespaced_schema.sql +76 -0
  34. feather_cdc_postgres-0.1.0/tests/fixtures/featherbase_public_schema.sql +943 -0
  35. feather_cdc_postgres-0.1.0/tests/fixtures/registrations/control_plane.yml +55 -0
  36. feather_cdc_postgres-0.1.0/tests/fixtures/registrations/demo_app.yml +113 -0
  37. feather_cdc_postgres-0.1.0/tests/fixtures/registrations/demo_app_dev.yml +108 -0
  38. feather_cdc_postgres-0.1.0/tests/fixtures/registrations/demo_app_staging.yml +106 -0
  39. feather_cdc_postgres-0.1.0/tests/test_adapter_selection_pg.py +154 -0
  40. feather_cdc_postgres-0.1.0/tests/test_baseline_blocked_pg.py +127 -0
  41. feather_cdc_postgres-0.1.0/tests/test_cli_plan_pg.py +174 -0
  42. feather_cdc_postgres-0.1.0/tests/test_destination_catalog_lag.py +85 -0
  43. feather_cdc_postgres-0.1.0/tests/test_destination_create_database.py +348 -0
  44. feather_cdc_postgres-0.1.0/tests/test_destination_credentials.py +53 -0
  45. feather_cdc_postgres-0.1.0/tests/test_dev_registration.py +231 -0
  46. feather_cdc_postgres-0.1.0/tests/test_dev_registration_pg.py +65 -0
  47. feather_cdc_postgres-0.1.0/tests/test_discovery_pg.py +351 -0
  48. feather_cdc_postgres-0.1.0/tests/test_drift_pg.py +410 -0
  49. feather_cdc_postgres-0.1.0/tests/test_e2e_pg.py +2391 -0
  50. feather_cdc_postgres-0.1.0/tests/test_generate_dbt.py +153 -0
  51. feather_cdc_postgres-0.1.0/tests/test_lifecycle.py +123 -0
  52. feather_cdc_postgres-0.1.0/tests/test_manifest.py +255 -0
  53. feather_cdc_postgres-0.1.0/tests/test_old_key_delete.py +57 -0
  54. feather_cdc_postgres-0.1.0/tests/test_ownership_pg.py +87 -0
  55. feather_cdc_postgres-0.1.0/tests/test_pilot_handoff_pg.py +163 -0
  56. feather_cdc_postgres-0.1.0/tests/test_publication_pg.py +173 -0
  57. feather_cdc_postgres-0.1.0/tests/test_rename_at_source_pg.py +444 -0
  58. feather_cdc_postgres-0.1.0/tests/test_reviewed_layout.py +131 -0
  59. feather_cdc_postgres-0.1.0/tests/test_run_log_dsn.py +38 -0
  60. feather_cdc_postgres-0.1.0/tests/test_runner_cli_pg.py +416 -0
  61. feather_cdc_postgres-0.1.0/tests/test_schema_registry.py +137 -0
  62. feather_cdc_postgres-0.1.0/tests/test_selectors.py +293 -0
  63. feather_cdc_postgres-0.1.0/tests/test_snapshot_pg.py +343 -0
  64. feather_cdc_postgres-0.1.0/tests/test_staging_registration.py +60 -0
  65. feather_cdc_postgres-0.1.0/tests/test_stream_pg.py +1032 -0
  66. feather_cdc_postgres-0.1.0/tests/test_telemetry.py +242 -0
  67. feather_cdc_postgres-0.1.0/tests/test_wal_reading.py +93 -0
@@ -0,0 +1,21 @@
1
+ .worktrees/
2
+ .claude/worktrees/
3
+ __pycache__/
4
+ *.pyc
5
+ *.egg-info/
6
+ dist/
7
+ .venv/
8
+ *.duckdb.wal
9
+ feather_data.duckdb
10
+ feather_state.duckdb
11
+ feather_validation.json
12
+ feather_discover_state.json
13
+ .env
14
+ .DS_Store
15
+ .coverage
16
+ .testmondata
17
+ .testmondata-journal
18
+ .nvmrc
19
+ repomix-output.xml
20
+ .playwright-mcp/
21
+ .superpowers/
@@ -0,0 +1,239 @@
1
+ Metadata-Version: 2.5
2
+ Name: feather-cdc-postgres
3
+ Version: 0.1.0
4
+ Summary: Declarative PostgreSQL -> MotherDuck CDC runtime: one registration file per source database, no per-source extractor
5
+ Project-URL: Homepage, https://github.com/siraj-samsudeen/feather-flow
6
+ Project-URL: Repository, https://github.com/siraj-samsudeen/feather-flow
7
+ Project-URL: Issues, https://github.com/siraj-samsudeen/feather-flow/issues
8
+ Author-email: Siraj Samsudeen <mailsiraj@gmail.com>
9
+ License-Expression: MIT
10
+ Keywords: cdc,duckdb,etl,logical-replication,motherduck,postgresql
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Database
18
+ Classifier: Topic :: Database :: Database Engines/Servers
19
+ Requires-Python: >=3.12
20
+ Requires-Dist: dlt[motherduck,sql-database]>=1.0.0
21
+ Requires-Dist: duckdb==1.5.2
22
+ Requires-Dist: feather-control-plane[postgres]<0.2,>=0.1.0
23
+ Requires-Dist: psycopg2-binary>=2.9.9
24
+ Requires-Dist: psycopg[binary]>=3.1
25
+ Requires-Dist: pyyaml>=6.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # feather-cdc-postgres
29
+
30
+ Mirror a PostgreSQL database into MotherDuck from one declaration file, with no extractor
31
+ written for it.
32
+
33
+ Point it at a source database and a destination, say which relations you want, and it does the
34
+ rest: creates the replication slot and publication, takes a consistent baseline of every
35
+ selected table, then drains the write-ahead log on a schedule. A table with a primary key is
36
+ merged; a table with none is kept as an append-only history. Schema changes, renames and
37
+ `TRUNCATE` are followed. Columns you name are withheld before they ever leave the process.
38
+
39
+ One code artifact, one **registration** per source database, one service instance per
40
+ registration. Adding a source is a reviewed YAML file, not a new codebase.
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install feather-cdc-postgres
46
+ ```
47
+
48
+ ## Commands
49
+
50
+ ```bash
51
+ python -m feather_cdc_postgres validate <registration>.yml # static + read-only checks
52
+ python -m feather_cdc_postgres plan <registration>.yml # every change a run would make
53
+ python -m feather_cdc_postgres generate-dbt <registration>.yml --out PATH
54
+ python -m feather_cdc_postgres run|status|resnapshot <registration>.yml
55
+ ```
56
+
57
+ `feather-cdc-postgres <command> ...` is installed as a console script and does the same thing.
58
+
59
+ `validate` and `plan` **mutate nothing** — they open read-only connections and print.
60
+ `plan` is safe to run against production; `tests/test_cli_plan_pg.py` fingerprints the source
61
+ catalog before and after to keep that claim true. `--json` on any command gives machine output.
62
+ `run`/`status`/`resnapshot` apply the same static validation first and refuse — before opening
63
+ any connection — on an error-severity problem (an unknown `api_version`, say).
64
+
65
+ `generate-dbt --out` is **required**: the runtime has no opinion about where your dbt project
66
+ lives.
67
+
68
+ Exit codes: `0` clean, `1` at least one error-severity problem or an unexpected failure (printed
69
+ redacted, never as a raw traceback), `2` a malformed manifest.
70
+
71
+ ## Running one instance
72
+
73
+ Registrations are **yours**, not this package's: none ship here. Each instance is selected
74
+ entirely by environment:
75
+
76
+ | var | set to |
77
+ |---|---|
78
+ | `<manifest source.dsn_env>` | the source PostgreSQL DSN |
79
+ | `<manifest destination.token_env>` | the MotherDuck token |
80
+ | `CDC_LOG_PG_DSN` | the PostgreSQL database this mirror's runs and events are logged to. A hard dependency unless `--dev`; `CONTROL_PG_DSN` is accepted as a fallback |
81
+ | `CONTROL_WAL_DIR` | a mounted (non-ephemeral) path — only needed when `control.event_durability: persistent_local_wal` |
82
+ | `RAILWAY_ENVIRONMENT_NAME` | where set, must equal the registration's `environment`, or `run`/`resnapshot` exit before any connection |
83
+
84
+ The source needs `wal_level = logical` and a role with `REPLICATION`.
85
+
86
+ ## What a registration declares
87
+
88
+ | Block | Decides |
89
+ |---|---|
90
+ | `environment` | `production` (default), `staging` or `dev` |
91
+ | `source` | which relations: `include`/`exclude`/`deny` globs on `schema.table`, plus an optional catalog `discovery.adapter` |
92
+ | `destination` | MotherDuck database, **`owner`** (required: the MotherDuck account the token must sign in as; `run`/`resnapshot` check `current_user()` against it before creating the database on a first run or writing anything), `schema_mapping` (default: source schemas preserved), **`table_schemas`** (per-table target schema, `[{match: "schema.table" glob, schema: target}]`, first match wins), dlt pipeline name (only with a single target schema), retirement policy |
93
+ | `replication` | slot, publication, cadence, key policy for unkeyed tables, replica identity, batch size |
94
+ | `control` | the extractor identity, run-log availability policy, event durability, `reconcile_exclude` |
95
+ | `classification` | optional first-match rules overriding the default `table_class` |
96
+
97
+ Secrets are **references**: `dsn_env` and `token_env` name environment variables. A manifest
98
+ carrying a value is rejected, and no environment value is ever printed or written into an event.
99
+
100
+ `tests/fixtures/registrations/` holds four worked examples.
101
+
102
+ ## Selection semantics
103
+
104
+ - A relation is `(schema, table)`, always together — two schemas may hold the same table name.
105
+ - Patterns are `fnmatch` globs over the qualified name (`public._dlt_*`). `include` is a
106
+ conjunction (schema **and**, when given, table pattern); `exclude` and `deny` are disjunctions.
107
+ - **`deny` is evaluated on the compiled set**, after the adapter narrows it — a deny rule is a
108
+ tripwire that fires only when something really would have been replicated.
109
+ - **`deny.columns`** (`{"schema.table": [column, ...]}`, exact names) withholds columns:
110
+ they are left out of the baseline select list, dropped by name from every decoded record and
111
+ from dlt's hints, and kept out of the drift signature. The deny follows the table's OID and
112
+ the column's attnum, so a table or column rename cannot release it. Every decoded description
113
+ of a table that carries a deny must match, exactly, the column layout its baseline recorded;
114
+ any column DDL there (an added column included) quarantines the table until a resnapshot.
115
+ Every run checks the destination (and each `_staging` twin) and reports a denied column found
116
+ there as an error. It is a projection *inside the CDC process*, not a publication column list:
117
+ under `replica_identity: full` that list must name every column, or every UPDATE/DELETE of the
118
+ table fails at the source.
119
+ - A discovery adapter supplies policy only ("which relations, and what does the source call
120
+ them"). It never supplies types, keys or load behaviour. The Featherbase adapter's
121
+ `options.system_tables` switches on the **two-way rule**: a `table_def."system" = true` table
122
+ (the platform's own) is offered only when named there, a `"system" = false` (user-created)
123
+ table always is — so a new user table flows with no manifest edit. `plan` prints each
124
+ relation's `origin=` (`user_created` / `named_system`); user-created relations classify as
125
+ `application` whatever they are called. Absent, the adapter offers everything.
126
+ - One dlt pipeline per **target** schema (`<source_id>_cdc__<target_schema>`), never per
127
+ source schema: `_cdc_runtime.*`, lifecycle and control events keep the **source**
128
+ identity `schema.table`; the destination side is the relation's compiled `target_schema`.
129
+ - `selection_hash` covers the relation set **and** each table's key policy, so a table that
130
+ silently dropped from merge to append-only changes the hash.
131
+
132
+ ## Key policy
133
+
134
+ Primary key → merge. Otherwise a **NOT NULL** non-partial, non-expression unique index → merge on
135
+ its **key** columns (`INCLUDE` columns carry no uniqueness and are never part of the key;
136
+ `NULL = NULL` is never true, so a nullable key would insert a duplicate on every load).
137
+ Otherwise `replication.tables_without_key`: `reject` (default, an error naming the table) or
138
+ `append_only`. `key_overrides` can force `append_only` per table. `full_row` is **rejected**
139
+ (`full_row_unsupported`): an all-column merge key cannot mirror an UPDATE — pgoutput emits only
140
+ the new tuple, so the old row is never matched and both versions would stay.
141
+
142
+ `append_only` is a load contract, not "no key": on the CDC path the relation **merges on `lsn`**
143
+ (unique per WAL record), so a batch replayed after a crash lands exactly once. An UPDATE lands as
144
+ an additional row version and a DELETE record removes nothing — updates and deletes are recorded
145
+ as arrivals, not applied. A re-baseline (resnapshot, a resumed interrupted snapshot, a slot-loss
146
+ re-init) therefore REPLACES the destination copy: a snapshot row has no `lsn` to dedup on.
147
+
148
+ **Every baseline has a boundary.** The initial snapshot reads the slot's exported snapshot, so
149
+ nothing below its consistent point is ever streamed. Every later baseline — a table added
150
+ mid-life, a resumed snapshot, a resnapshot — reads a table the publication already carries, so
151
+ it overlaps the WAL; `snapshot.consistent_baseline` takes it from a throwaway slot `<slot>_bl`
152
+ whose consistent point PostgreSQL guarantees matches its snapshot ("in the snapshot" ⟺ "commit
153
+ LSN < boundary", with in-flight transactions waited out), stores that boundary per relation in
154
+ `_cdc_runtime.baseline`, and the drain drops that relation's transactions below it. That is what
155
+ makes the overlap exact for `append_only`, where no key could dedup it.
156
+
157
+ **`TRUNCATE`** is published and applied: a keyed mirror is emptied before the rows that followed
158
+ the truncate load (batch order preserved); an `append_only` history keeps every arrival. Both
159
+ emit a `truncate` control event. **Partitioned tables** replicate as their partitions (`relkind
160
+ 'r'`); the parent is a named `partitioned_parent_skipped` warning, never a relation.
161
+
162
+ **Run outcome**: the run's status is `ok` only when every selected relation drained with no
163
+ error-class event; `partial` when a table is drift-blocked or a reconcile count did not tie;
164
+ `failed` when nothing drained (slot lost under `slot_loss_policy: pause`, or a selection that
165
+ compiled to nothing — which `run` refuses rather than leaving an undrained slot behind).
166
+
167
+ `control.reconcile_exclude` names `schema.table` globs the reconcile counts skip — for relations
168
+ written while this mirror runs, which can never tie source-now against destination-now.
169
+ `append_only` relations are skipped too (`extra.append_only`): their destination keeps every row
170
+ version, so a count can never tie once the source is edited. Both still emit a `reconcile` event
171
+ with `skipped` and a reason, so the gap is visible rather than silently passed.
172
+
173
+ Merging on a unique index needs the source to publish those columns on DELETE — set
174
+ `replica_identity: full` or `ALTER TABLE ... REPLICA IDENTITY USING INDEX`. The compiler warns
175
+ when neither is in place.
176
+
177
+ ## Type matrix
178
+
179
+ `schema_registry.compile_column` maps every OID in use on the sources it has met exactly, and
180
+ labels how faithful the mapping is: `exact`, `widened`, `exact_as_text` (uuid, name),
181
+ `lossy_text` (interval, timetz), `text_fallback`. Arrays and undeclared OIDs land as text and
182
+ **always** raise a warning naming `schema.table.column` and the OID — never silently.
183
+
184
+ The integer family (`int2/int4/int8/oid`) compiles to plain `BIGINT`. dlt renders
185
+ `{"data_type": "bigint", "precision": 32}` as `INTEGER` on duckdb while the snapshot path
186
+ reflects every integer as `BIGINT`, so dropping the precision hint pins one spelling, in the
187
+ widening direction.
188
+
189
+ ## The run log
190
+
191
+ Runs, per-relation events and budget telemetry go to
192
+ [`feather-control-plane`](../feather-control-plane), a hard dependency of this package, writing
193
+ to whatever `CDC_LOG_PG_DSN` points at — deliberately **not** the database being mirrored. Pass
194
+ `--dev` for a local, WAL-only run that writes no run rows at all.
195
+
196
+ ## Vendored code
197
+
198
+ `src/pg_replication/` is the `pg_replication` verified source from
199
+ [dlt-hub/verified-sources](https://github.com/dlt-hub/verified-sources), Apache-2.0, **modified**.
200
+ Upstream is a `dlt init` template rather than a distribution, so there is nothing on PyPI to pin.
201
+ See `src/pg_replication/README.md` for the attribution and `src/pg_replication/LICENSE` for the
202
+ licence text.
203
+
204
+ ## Tests
205
+
206
+ ```bash
207
+ cd packages/feather-cdc-postgres && uv run --package feather-cdc-postgres pytest -q
208
+ ```
209
+
210
+ `--package` picks the *environment*; it does not pick the tests. pytest takes its config from the
211
+ nearest `pyproject.toml` above the working directory, so a bare `pytest` run from the repo root
212
+ collects feather-flow's own suite no matter what `--package` says. Either `cd` in or name the
213
+ path.
214
+
215
+ 522 tests. 275 are pure logic and run anywhere; **247 need a real PostgreSQL with
216
+ `wal_level = logical`** and are skipped without one — they create and drop replication slots,
217
+ publications, schemas and tables, so never point them at a database you care about. The suite
218
+ finds a server in this order:
219
+
220
+ 1. `PG_MD_CDC_TEST_DSN` — a superuser DSN for a server you own.
221
+ 2. a local PostgreSQL binary (`pg_ctl` on `PATH`, else Homebrew's keg-only `postgresql@N`),
222
+ `initdb`'d into a temp directory on a throwaway port and torn down afterwards.
223
+ `PG_MD_CDC_TEST_PORT` picks the port (default 54331) so parallel sessions do not collide.
224
+ 3. otherwise skip.
225
+
226
+ A container works for (1):
227
+
228
+ ```bash
229
+ docker run -d -p 55432:5432 -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=cdc_test \
230
+ -e POSTGRES_INITDB_ARGS="-c wal_level=logical -c max_replication_slots=20 -c max_wal_senders=20" \
231
+ postgres:17
232
+ PG_MD_CDC_TEST_DSN=postgresql://postgres:postgres@127.0.0.1:55432/cdc_test uv run pytest -q
233
+ ```
234
+
235
+ Three tests additionally need PostgreSQL 18 (`publish_generated_columns`) and skip below it.
236
+
237
+ The destination in tests is dlt's `duckdb` destination (a temp file) — the same load path
238
+ MotherDuck takes minus credentials, so merge, hard-delete and schema-evolution behaviour is
239
+ exercised for real.
@@ -0,0 +1,212 @@
1
+ # feather-cdc-postgres
2
+
3
+ Mirror a PostgreSQL database into MotherDuck from one declaration file, with no extractor
4
+ written for it.
5
+
6
+ Point it at a source database and a destination, say which relations you want, and it does the
7
+ rest: creates the replication slot and publication, takes a consistent baseline of every
8
+ selected table, then drains the write-ahead log on a schedule. A table with a primary key is
9
+ merged; a table with none is kept as an append-only history. Schema changes, renames and
10
+ `TRUNCATE` are followed. Columns you name are withheld before they ever leave the process.
11
+
12
+ One code artifact, one **registration** per source database, one service instance per
13
+ registration. Adding a source is a reviewed YAML file, not a new codebase.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ pip install feather-cdc-postgres
19
+ ```
20
+
21
+ ## Commands
22
+
23
+ ```bash
24
+ python -m feather_cdc_postgres validate <registration>.yml # static + read-only checks
25
+ python -m feather_cdc_postgres plan <registration>.yml # every change a run would make
26
+ python -m feather_cdc_postgres generate-dbt <registration>.yml --out PATH
27
+ python -m feather_cdc_postgres run|status|resnapshot <registration>.yml
28
+ ```
29
+
30
+ `feather-cdc-postgres <command> ...` is installed as a console script and does the same thing.
31
+
32
+ `validate` and `plan` **mutate nothing** — they open read-only connections and print.
33
+ `plan` is safe to run against production; `tests/test_cli_plan_pg.py` fingerprints the source
34
+ catalog before and after to keep that claim true. `--json` on any command gives machine output.
35
+ `run`/`status`/`resnapshot` apply the same static validation first and refuse — before opening
36
+ any connection — on an error-severity problem (an unknown `api_version`, say).
37
+
38
+ `generate-dbt --out` is **required**: the runtime has no opinion about where your dbt project
39
+ lives.
40
+
41
+ Exit codes: `0` clean, `1` at least one error-severity problem or an unexpected failure (printed
42
+ redacted, never as a raw traceback), `2` a malformed manifest.
43
+
44
+ ## Running one instance
45
+
46
+ Registrations are **yours**, not this package's: none ship here. Each instance is selected
47
+ entirely by environment:
48
+
49
+ | var | set to |
50
+ |---|---|
51
+ | `<manifest source.dsn_env>` | the source PostgreSQL DSN |
52
+ | `<manifest destination.token_env>` | the MotherDuck token |
53
+ | `CDC_LOG_PG_DSN` | the PostgreSQL database this mirror's runs and events are logged to. A hard dependency unless `--dev`; `CONTROL_PG_DSN` is accepted as a fallback |
54
+ | `CONTROL_WAL_DIR` | a mounted (non-ephemeral) path — only needed when `control.event_durability: persistent_local_wal` |
55
+ | `RAILWAY_ENVIRONMENT_NAME` | where set, must equal the registration's `environment`, or `run`/`resnapshot` exit before any connection |
56
+
57
+ The source needs `wal_level = logical` and a role with `REPLICATION`.
58
+
59
+ ## What a registration declares
60
+
61
+ | Block | Decides |
62
+ |---|---|
63
+ | `environment` | `production` (default), `staging` or `dev` |
64
+ | `source` | which relations: `include`/`exclude`/`deny` globs on `schema.table`, plus an optional catalog `discovery.adapter` |
65
+ | `destination` | MotherDuck database, **`owner`** (required: the MotherDuck account the token must sign in as; `run`/`resnapshot` check `current_user()` against it before creating the database on a first run or writing anything), `schema_mapping` (default: source schemas preserved), **`table_schemas`** (per-table target schema, `[{match: "schema.table" glob, schema: target}]`, first match wins), dlt pipeline name (only with a single target schema), retirement policy |
66
+ | `replication` | slot, publication, cadence, key policy for unkeyed tables, replica identity, batch size |
67
+ | `control` | the extractor identity, run-log availability policy, event durability, `reconcile_exclude` |
68
+ | `classification` | optional first-match rules overriding the default `table_class` |
69
+
70
+ Secrets are **references**: `dsn_env` and `token_env` name environment variables. A manifest
71
+ carrying a value is rejected, and no environment value is ever printed or written into an event.
72
+
73
+ `tests/fixtures/registrations/` holds four worked examples.
74
+
75
+ ## Selection semantics
76
+
77
+ - A relation is `(schema, table)`, always together — two schemas may hold the same table name.
78
+ - Patterns are `fnmatch` globs over the qualified name (`public._dlt_*`). `include` is a
79
+ conjunction (schema **and**, when given, table pattern); `exclude` and `deny` are disjunctions.
80
+ - **`deny` is evaluated on the compiled set**, after the adapter narrows it — a deny rule is a
81
+ tripwire that fires only when something really would have been replicated.
82
+ - **`deny.columns`** (`{"schema.table": [column, ...]}`, exact names) withholds columns:
83
+ they are left out of the baseline select list, dropped by name from every decoded record and
84
+ from dlt's hints, and kept out of the drift signature. The deny follows the table's OID and
85
+ the column's attnum, so a table or column rename cannot release it. Every decoded description
86
+ of a table that carries a deny must match, exactly, the column layout its baseline recorded;
87
+ any column DDL there (an added column included) quarantines the table until a resnapshot.
88
+ Every run checks the destination (and each `_staging` twin) and reports a denied column found
89
+ there as an error. It is a projection *inside the CDC process*, not a publication column list:
90
+ under `replica_identity: full` that list must name every column, or every UPDATE/DELETE of the
91
+ table fails at the source.
92
+ - A discovery adapter supplies policy only ("which relations, and what does the source call
93
+ them"). It never supplies types, keys or load behaviour. The Featherbase adapter's
94
+ `options.system_tables` switches on the **two-way rule**: a `table_def."system" = true` table
95
+ (the platform's own) is offered only when named there, a `"system" = false` (user-created)
96
+ table always is — so a new user table flows with no manifest edit. `plan` prints each
97
+ relation's `origin=` (`user_created` / `named_system`); user-created relations classify as
98
+ `application` whatever they are called. Absent, the adapter offers everything.
99
+ - One dlt pipeline per **target** schema (`<source_id>_cdc__<target_schema>`), never per
100
+ source schema: `_cdc_runtime.*`, lifecycle and control events keep the **source**
101
+ identity `schema.table`; the destination side is the relation's compiled `target_schema`.
102
+ - `selection_hash` covers the relation set **and** each table's key policy, so a table that
103
+ silently dropped from merge to append-only changes the hash.
104
+
105
+ ## Key policy
106
+
107
+ Primary key → merge. Otherwise a **NOT NULL** non-partial, non-expression unique index → merge on
108
+ its **key** columns (`INCLUDE` columns carry no uniqueness and are never part of the key;
109
+ `NULL = NULL` is never true, so a nullable key would insert a duplicate on every load).
110
+ Otherwise `replication.tables_without_key`: `reject` (default, an error naming the table) or
111
+ `append_only`. `key_overrides` can force `append_only` per table. `full_row` is **rejected**
112
+ (`full_row_unsupported`): an all-column merge key cannot mirror an UPDATE — pgoutput emits only
113
+ the new tuple, so the old row is never matched and both versions would stay.
114
+
115
+ `append_only` is a load contract, not "no key": on the CDC path the relation **merges on `lsn`**
116
+ (unique per WAL record), so a batch replayed after a crash lands exactly once. An UPDATE lands as
117
+ an additional row version and a DELETE record removes nothing — updates and deletes are recorded
118
+ as arrivals, not applied. A re-baseline (resnapshot, a resumed interrupted snapshot, a slot-loss
119
+ re-init) therefore REPLACES the destination copy: a snapshot row has no `lsn` to dedup on.
120
+
121
+ **Every baseline has a boundary.** The initial snapshot reads the slot's exported snapshot, so
122
+ nothing below its consistent point is ever streamed. Every later baseline — a table added
123
+ mid-life, a resumed snapshot, a resnapshot — reads a table the publication already carries, so
124
+ it overlaps the WAL; `snapshot.consistent_baseline` takes it from a throwaway slot `<slot>_bl`
125
+ whose consistent point PostgreSQL guarantees matches its snapshot ("in the snapshot" ⟺ "commit
126
+ LSN < boundary", with in-flight transactions waited out), stores that boundary per relation in
127
+ `_cdc_runtime.baseline`, and the drain drops that relation's transactions below it. That is what
128
+ makes the overlap exact for `append_only`, where no key could dedup it.
129
+
130
+ **`TRUNCATE`** is published and applied: a keyed mirror is emptied before the rows that followed
131
+ the truncate load (batch order preserved); an `append_only` history keeps every arrival. Both
132
+ emit a `truncate` control event. **Partitioned tables** replicate as their partitions (`relkind
133
+ 'r'`); the parent is a named `partitioned_parent_skipped` warning, never a relation.
134
+
135
+ **Run outcome**: the run's status is `ok` only when every selected relation drained with no
136
+ error-class event; `partial` when a table is drift-blocked or a reconcile count did not tie;
137
+ `failed` when nothing drained (slot lost under `slot_loss_policy: pause`, or a selection that
138
+ compiled to nothing — which `run` refuses rather than leaving an undrained slot behind).
139
+
140
+ `control.reconcile_exclude` names `schema.table` globs the reconcile counts skip — for relations
141
+ written while this mirror runs, which can never tie source-now against destination-now.
142
+ `append_only` relations are skipped too (`extra.append_only`): their destination keeps every row
143
+ version, so a count can never tie once the source is edited. Both still emit a `reconcile` event
144
+ with `skipped` and a reason, so the gap is visible rather than silently passed.
145
+
146
+ Merging on a unique index needs the source to publish those columns on DELETE — set
147
+ `replica_identity: full` or `ALTER TABLE ... REPLICA IDENTITY USING INDEX`. The compiler warns
148
+ when neither is in place.
149
+
150
+ ## Type matrix
151
+
152
+ `schema_registry.compile_column` maps every OID in use on the sources it has met exactly, and
153
+ labels how faithful the mapping is: `exact`, `widened`, `exact_as_text` (uuid, name),
154
+ `lossy_text` (interval, timetz), `text_fallback`. Arrays and undeclared OIDs land as text and
155
+ **always** raise a warning naming `schema.table.column` and the OID — never silently.
156
+
157
+ The integer family (`int2/int4/int8/oid`) compiles to plain `BIGINT`. dlt renders
158
+ `{"data_type": "bigint", "precision": 32}` as `INTEGER` on duckdb while the snapshot path
159
+ reflects every integer as `BIGINT`, so dropping the precision hint pins one spelling, in the
160
+ widening direction.
161
+
162
+ ## The run log
163
+
164
+ Runs, per-relation events and budget telemetry go to
165
+ [`feather-control-plane`](../feather-control-plane), a hard dependency of this package, writing
166
+ to whatever `CDC_LOG_PG_DSN` points at — deliberately **not** the database being mirrored. Pass
167
+ `--dev` for a local, WAL-only run that writes no run rows at all.
168
+
169
+ ## Vendored code
170
+
171
+ `src/pg_replication/` is the `pg_replication` verified source from
172
+ [dlt-hub/verified-sources](https://github.com/dlt-hub/verified-sources), Apache-2.0, **modified**.
173
+ Upstream is a `dlt init` template rather than a distribution, so there is nothing on PyPI to pin.
174
+ See `src/pg_replication/README.md` for the attribution and `src/pg_replication/LICENSE` for the
175
+ licence text.
176
+
177
+ ## Tests
178
+
179
+ ```bash
180
+ cd packages/feather-cdc-postgres && uv run --package feather-cdc-postgres pytest -q
181
+ ```
182
+
183
+ `--package` picks the *environment*; it does not pick the tests. pytest takes its config from the
184
+ nearest `pyproject.toml` above the working directory, so a bare `pytest` run from the repo root
185
+ collects feather-flow's own suite no matter what `--package` says. Either `cd` in or name the
186
+ path.
187
+
188
+ 522 tests. 275 are pure logic and run anywhere; **247 need a real PostgreSQL with
189
+ `wal_level = logical`** and are skipped without one — they create and drop replication slots,
190
+ publications, schemas and tables, so never point them at a database you care about. The suite
191
+ finds a server in this order:
192
+
193
+ 1. `PG_MD_CDC_TEST_DSN` — a superuser DSN for a server you own.
194
+ 2. a local PostgreSQL binary (`pg_ctl` on `PATH`, else Homebrew's keg-only `postgresql@N`),
195
+ `initdb`'d into a temp directory on a throwaway port and torn down afterwards.
196
+ `PG_MD_CDC_TEST_PORT` picks the port (default 54331) so parallel sessions do not collide.
197
+ 3. otherwise skip.
198
+
199
+ A container works for (1):
200
+
201
+ ```bash
202
+ docker run -d -p 55432:5432 -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=cdc_test \
203
+ -e POSTGRES_INITDB_ARGS="-c wal_level=logical -c max_replication_slots=20 -c max_wal_senders=20" \
204
+ postgres:17
205
+ PG_MD_CDC_TEST_DSN=postgresql://postgres:postgres@127.0.0.1:55432/cdc_test uv run pytest -q
206
+ ```
207
+
208
+ Three tests additionally need PostgreSQL 18 (`publish_generated_columns`) and skip below it.
209
+
210
+ The destination in tests is dlt's `duckdb` destination (a temp file) — the same load path
211
+ MotherDuck takes minus credentials, so merge, hard-delete and schema-evolution behaviour is
212
+ exercised for real.
@@ -0,0 +1,85 @@
1
+ [project]
2
+ name = "feather-cdc-postgres"
3
+ version = "0.1.0"
4
+ description = "Declarative PostgreSQL -> MotherDuck CDC runtime: one registration file per source database, no per-source extractor"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ authors = [
8
+ { name = "Siraj Samsudeen", email = "mailsiraj@gmail.com" }
9
+ ]
10
+ # The distribution is `feather-cdc-postgres` and so is the IMPORT name,
11
+ # `feather_cdc_postgres`. This differs from feather-control-plane, which kept its old import
12
+ # name on purpose: ~40 call sites already said `from control_plane import ...`. Nothing outside
13
+ # this tree imports `pg_md_cdc` — the only external references are twelve `python -m pg_md_cdc`
14
+ # command strings — so there was no adoption cost to paying off the acronym here.
15
+ #
16
+ # `>=3.12` matches feather-control-plane and the feather-flow root. uv locks a workspace at the
17
+ # INTERSECTION of its members' ranges, so all three move together (#85).
18
+ requires-python = ">=3.12"
19
+ keywords = ["cdc", "postgresql", "logical-replication", "motherduck", "duckdb", "etl"]
20
+ classifiers = [
21
+ "Development Status :: 3 - Alpha",
22
+ "Intended Audience :: Developers",
23
+ "License :: OSI Approved :: MIT License",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Topic :: Database",
28
+ "Topic :: Database :: Database Engines/Servers",
29
+ ]
30
+ dependencies = [
31
+ # The run log. A workspace dependency (see [tool.uv.sources]) so the two version together
32
+ # in-repo. The CDC writes real run/event/budget rows through it — ~50 `cp_status.*`
33
+ # constants and a `ControlPlane` factory with four call sites in runner.py. What #4078
34
+ # decoupled was the DATABASE (this logs to its own CDC log DB via CDC_LOG_PG_DSN), not the
35
+ # client library; a different DSN satisfies that.
36
+ # Bounded below 0.2 deliberately. `[tool.uv.sources]` makes this the local member in-repo, but
37
+ # uv strips sources from published metadata, so an unbounded spec would let a released CDC pick
38
+ # up any future control plane. This uses its internals — ~50 `cp_status.*` constants and the
39
+ # `ControlPlane` factory — and pre-1.0 a minor is where breakage is allowed to land.
40
+ "feather-control-plane[postgres]>=0.1.0,<0.2",
41
+ # sql_database extra is a real requirement of the vendored pg_replication source
42
+ # (upstream dlt-hub/verified-sources#685 — `dlt init` ships incomplete requirements).
43
+ "dlt[motherduck,sql_database]>=1.0.0",
44
+ # Pin EXACT — an open top end lets a rebuild grab a duckdb MotherDuck has no extension
45
+ # build for, which fails at CONNECT time and reads like an outage.
46
+ "duckdb==1.5.2",
47
+ # pgoutput replication protocol lives in psycopg2 only (psycopg3 has no replication
48
+ # support) — used by the vendored pg_replication source.
49
+ "psycopg2-binary>=2.9.9",
50
+ # Source catalog reads and the advisory owner session.
51
+ "psycopg[binary]>=3.1",
52
+ # Registration manifests are YAML.
53
+ "pyyaml>=6.0",
54
+ ]
55
+
56
+ [project.scripts]
57
+ feather-cdc-postgres = "feather_cdc_postgres.cli:main"
58
+
59
+ [project.urls]
60
+ Homepage = "https://github.com/siraj-samsudeen/feather-flow"
61
+ Repository = "https://github.com/siraj-samsudeen/feather-flow"
62
+ Issues = "https://github.com/siraj-samsudeen/feather-flow/issues"
63
+
64
+ [tool.uv.sources]
65
+ feather-control-plane = { workspace = true }
66
+
67
+ [build-system]
68
+ requires = ["hatchling"]
69
+ build-backend = "hatchling.build"
70
+
71
+ [tool.hatch.build.targets.wheel]
72
+ # `pg_replication` ships beside the runtime: it is vendored third-party code (Apache-2.0,
73
+ # dlt-hub/verified-sources), not an implementation detail that could be imported from PyPI —
74
+ # the upstream is a `dlt init` template, not a distribution. src/pg_replication/README.md
75
+ # carries the attribution.
76
+ packages = ["src/feather_cdc_postgres", "src/pg_replication"]
77
+
78
+ [tool.hatch.build.targets.sdist]
79
+ include = ["src/", "tests/", "README.md", "pyproject.toml"]
80
+
81
+ [dependency-groups]
82
+ dev = ["pytest>=8.0"]
83
+
84
+ [tool.pytest.ini_options]
85
+ testpaths = ["tests"]
@@ -0,0 +1,6 @@
1
+ """feather_cdc_postgres — declarative PostgreSQL → MotherDuck CDC runtime (#3079).
2
+
3
+ One code artifact, one isolated service instance per registration (`<source_id>.yml`). The
4
+ registrations are the DEPLOYER's, not this package's. Mechanism: slot-based logical replication
5
+ (pgoutput) drained cron-shaped into a bronze database, source namespaces preserved.
6
+ """
@@ -0,0 +1,9 @@
1
+ """`python -m feather_cdc_postgres` entry point."""
2
+ from __future__ import annotations
3
+
4
+ import sys
5
+
6
+ from .cli import main
7
+
8
+ if __name__ == "__main__":
9
+ sys.exit(main())
@@ -0,0 +1,44 @@
1
+ """Discovery adapters: source-specific POLICY that narrows the generic set of relations.
2
+
3
+ An adapter may only answer "which of the source's relations are in scope, and what does the
4
+ source call them" — it never supplies types, keys, or load behaviour. That keeps the CDC
5
+ mechanism single-implementation (#3079 D4); a fork of the mechanism per source is the failure
6
+ this design exists to prevent.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Callable, Dict, List, NamedTuple
11
+
12
+
13
+ # How an adapter came to offer a relation. `user_created` = the source's own users declared
14
+ # it (always application data); `named_system` = one of the source's platform tables the
15
+ # manifest names explicitly. None = the adapter applied no such distinction.
16
+ USER_CREATED = "user_created"
17
+ NAMED_SYSTEM = "named_system"
18
+
19
+
20
+ class AdapterRelation(NamedTuple):
21
+ """(schema, table, module) — plus a description the source itself owns, when it has one,
22
+ and the `origin` the adapter selected it under (see USER_CREATED / NAMED_SYSTEM)."""
23
+
24
+ schema: str
25
+ table: str
26
+ module: str | None = None
27
+ description: str | None = None
28
+ origin: str | None = None
29
+
30
+
31
+ AdapterFn = Callable[[str, Dict[str, Any]], List[AdapterRelation]]
32
+
33
+
34
+ def get(name: str) -> AdapterFn:
35
+ """Resolve an adapter by manifest name. Unknown names fail loudly at validate time."""
36
+ if name == "featherbase":
37
+ from .featherbase import select as featherbase_select
38
+
39
+ return featherbase_select
40
+ raise KeyError(name)
41
+
42
+
43
+ def known() -> tuple:
44
+ return ("featherbase",)