Metadata-Version: 2.5
Name: pg-cdc-doctor
Version: 0.1.0
Summary: Read-only checker: is this PostgreSQL database ready for logical-replication CDC, and what will break.
Author: Basant Bhattarai
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: cdc,debezium,logical-replication,pgoutput,postgresql,replication-slot
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: psycopg[binary]>=3.2
Description-Content-Type: text/markdown

# pg-cdc-doctor

pg-cdc-doctor connects to a PostgreSQL database with a read-only session and lists what will stop
a logical-replication CDC consumer (Debezium or any pgoutput client) from starting or keeping up:
server settings, the connecting role, replication slots, tables without a usable replica identity,
publication definitions, failover and standby settings (PostgreSQL 17 and later), and a Debezium
connector configuration compared with the database. Every finding has a stable ID (CDC001 to
CDC066), a severity, an explanation and a fix. It runs on PostgreSQL 13 to 18.

## Install

```sh
pip install pg-cdc-doctor
```

or run it without installing:

```sh
uvx pg-cdc-doctor check --help
```

Python 3.10 or later. The only dependency is psycopg 3.

From a checkout: `uv sync`, then `uv run pg-cdc-doctor check --help`.

## Quick start

```sh
pg-cdc-doctor check --dsn "postgresql://user@host:5432/app" --publication cdc_pub --slot cdc_slot
```

Without `--dsn` the libpq environment variables (`PGHOST`, `PGUSER`, `PGPASSWORD`, ...) are used.
The password is never printed; a DSN that appears in an error message is masked.

The two outputs below are real runs against PostgreSQL 17.12 in Docker, from the scenario databases
`clean` and `cdc030_no_pk_default` (see [The evidence](#the-evidence)). The first, run with
`--publication cdc_pub --slot cdc_slot` while a consumer streams from the slot, exits 0:

```text
pg-cdc-doctor 0.1.0: PostgreSQL 17.12
target: postgres@127.0.0.1:57414/sc_clean
scope:  tables of publication 'cdc_pub': 3 table(s)

Server
  INFO  CDC010  server_version  PostgreSQL 17.12
  ok    CDC001  wal_level  wal_level is logical
  ok    CDC002  max_replication_slots  9 free replication slots (1 of 10 in use)
  ok    CDC003  max_wal_senders  9 free WAL senders (1 of 10 in use)
  ok    CDC004  max_slot_wal_keep_size  max_slot_wal_keep_size is bounded (5120 MB)
  ok    CDC005  wal_sender_timeout  wal_sender_timeout is positive
  ok    CDC008  pg_prepared_xacts  no prepared transactions
  ok    CDC009  pg_stat_activity  no transaction with an ID open longer than 15 min

Role
  ok    CDC006  postgres  role 'postgres' can replicate (superuser)
  ok    CDC007  3 tables  role 'postgres' can SELECT from every captured table

Replication slots
  ok    CDC020  1 slots  1 logical slot(s), none inactive, lost or over the retention limit
  ok    CDC023  cdc_slot  slot 'cdc_slot' exists and uses pgoutput

Tables
  INFO  CDC033  public.customers  unchanged TOASTed values arrive without their value on UPDATE
        fix: If consumers need the value on every update: ALTER TABLE public.customers REPLICA
              IDENTITY FULL, or merge with the previous state downstream.
  INFO  CDC033  public.order_items  unchanged TOASTed values arrive without their value on UPDATE
        fix: If consumers need the value on every update: ALTER TABLE public.order_items REPLICA
              IDENTITY FULL, or merge with the previous state downstream.
  INFO  CDC033  public.orders  unchanged TOASTed values arrive without their value on UPDATE
        fix: If consumers need the value on every update: ALTER TABLE public.orders REPLICA IDENTITY
              FULL, or merge with the previous state downstream.
  ok    CDC030  3 tables  every captured table has a usable replica identity
  ok    CDC034  3 tables  no unlogged table in scope

summary: 0 fail, 0 warn, 4 info
```

The second, run with `--publication p`, has a table without a primary key in a publication that
publishes updates. The tool exits 1:

```text
pg-cdc-doctor 0.1.0: PostgreSQL 17.12
target: postgres@127.0.0.1:57414/sc_cdc030_no_pk_default
scope:  tables of publication 'p': 2 table(s)

Server
  INFO  CDC010  server_version  PostgreSQL 17.12
  ok    CDC001  wal_level  wal_level is logical
  ok    CDC002  max_replication_slots  9 free replication slots (1 of 10 in use)
  ok    CDC003  max_wal_senders  9 free WAL senders (1 of 10 in use)
  ok    CDC004  max_slot_wal_keep_size  max_slot_wal_keep_size is bounded (5120 MB)
  ok    CDC005  wal_sender_timeout  wal_sender_timeout is positive
  ok    CDC008  pg_prepared_xacts  no prepared transactions
  ok    CDC009  pg_stat_activity  no transaction with an ID open longer than 15 min

Role
  ok    CDC006  postgres  role 'postgres' can replicate (superuser)
  ok    CDC007  2 tables  role 'postgres' can SELECT from every captured table

Replication slots
  ok    CDC020  1 slots  1 logical slot(s), none inactive, lost or over the retention limit

Tables
  FAIL  CDC030  public.no_pk  no primary key and replica identity DEFAULT: UPDATE and DELETE will fail once published
        fix: Add a primary key, or ALTER TABLE public.no_pk REPLICA IDENTITY USING INDEX <unique
              not-null index>, or as a last resort ALTER TABLE public.no_pk REPLICA IDENTITY FULL.
  INFO  CDC033  public.no_pk  unchanged TOASTed values arrive without their value on UPDATE
        fix: If consumers need the value on every update: ALTER TABLE public.no_pk REPLICA IDENTITY
              FULL, or merge with the previous state downstream.
  INFO  CDC033  public.with_pk  unchanged TOASTed values arrive without their value on UPDATE
        fix: If consumers need the value on every update: ALTER TABLE public.with_pk REPLICA
              IDENTITY FULL, or merge with the previous state downstream.
  ok    CDC034  2 tables  no unlogged table in scope

summary: 1 fail, 0 warn, 3 info
```

`-v` adds the detail of each finding. Findings with severity `ok` are shown so a clean report shows
what was checked.

### With a standby

```sh
pg-cdc-doctor check --dsn "postgresql://user@primary/app" \
                    --standby-dsn "postgresql://user@standby/app" \
                    --publication cdc_pub --slot cdc_slot
```

`--standby-dsn` adds the slot-synchronization checks CDC055 to CDC059. The standby must be in
recovery, run PostgreSQL 17 or later and have the same system identifier as the primary, otherwise
the exit code is 2. Without it, CDC051 to CDC053 still read the primary's side of failover.

### With a Debezium connector file

```sh
pg-cdc-doctor check --dsn "postgresql://user@host:5432/app" --debezium connector.json
```

`--debezium` takes the Kafka Connect JSON (`{"name": ..., "config": {...}}`), a flat JSON object or a
`.properties` file. The connector decides the scope: its `table.include.list`,
`table.exclude.list` and schema filters pick the tables, its `publication.name` (default
`dbz_publication`) the publication and its `slot.name` (default `debezium`) the slot.
`--tables` cannot be combined with `--debezium`, and `--publication` or `--slot` are accepted only
when they equal the file's value; otherwise the exit code is 2. `database.password` and every key
containing `password` or `secret` are never printed.

With this file, whose passwords are placeholders:

```json
{
  "name": "app-connector",
  "config": {
    "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
    "plugin.name": "pgoutput",
    "database.hostname": "db.internal.example",
    "database.port": "5432",
    "database.user": "postgres",
    "database.password": "change-me",
    "database.dbname": "app",
    "topic.prefix": "app",
    "slot.name": "dbz_slot",
    "publication.name": "dbz_pub",
    "publication.autocreate.mode": "disabled",
    "table.include.list": "public\\.(customers|orders)",
    "heartbeat.interval.ms": "10000"
  }
}
```

against a database where `public.orders` is not in the publication, the Debezium section reads as
follows (the Server, Role, Replication slots and Tables sections of the same report are left out
here):

```text
pg-cdc-doctor 0.1.0: PostgreSQL 17.12
target: postgres@127.0.0.1:57414/app
scope:  tables captured by connector.json (Debezium schema and table filters): 2 table(s)

(Server, Role, Replication slots and Tables sections omitted)

Debezium config
  FAIL  CDC063  public.orders  public.orders matches the connector filters but is not in publication 'dbz_pub'
        fix: ALTER PUBLICATION dbz_pub ADD TABLE public.orders;
  INFO  CDC063  dbz_pub  1 table(s) in 'dbz_pub' are excluded by the connector filters
  ok    CDC060  plugin.name  plugin.name is pgoutput
  ok    CDC061  database.dbname  database.dbname is 'app'
  ok    CDC062  dbz_pub  publication 'dbz_pub' exists; autocreate is disabled, so it is used as is
  ok    CDC064  dbz_slot  slot 'dbz_slot' does not exist yet; the connector creates it with plugin pgoutput
  ok    CDC065  slot.failover  slot.failover is not set and no standby exists
  ok    CDC066  heartbeat.interval.ms  heartbeat every 10000 ms

summary: 1 fail, 0 warn, 4 info
```

## What it checks

42 checks. The full text of each (what it means, why it matters for CDC, the fix, the versions,
the documentation it rests on) is in [docs/checks.md](docs/checks.md), which is generated from the
catalog in `src/pg_cdc_doctor/checks/catalog.py`.

| ID | Area | Finding | PostgreSQL |
|---|---|---|---|
| CDC001 | Server | wal_level is not logical | 13-18 |
| CDC002 | Server | no free replication slots | 13-18 |
| CDC003 | Server | no free WAL sender processes | 13-18 |
| CDC004 | Server | max_slot_wal_keep_size is unbounded | 13-18 |
| CDC005 | Server | wal_sender_timeout is 0 | 13-18 |
| CDC006 | Role | connecting role cannot replicate | 13-18 |
| CDC007 | Role | role lacks SELECT on a captured table | 13-18 |
| CDC008 | Server | prepared transactions exist | 13-18 |
| CDC009 | Server | long-running transactions | 13-18 |
| CDC010 | Server | server version | 13-18 |
| CDC020 | Replication slots | slot WAL status | 13-18 |
| CDC021 | Replication slots | inactive logical slot | 13-18 |
| CDC022 | Replication slots | slot retains more WAL than the limit | 13-18 |
| CDC023 | Replication slots | named slot | 13-18 |
| CDC030 | Tables | no primary key and replica identity DEFAULT | 13-18 |
| CDC031 | Tables | replica identity NOTHING, or USING INDEX with the index gone | 13-18 |
| CDC032 | Tables | replica identity FULL | 13-18 |
| CDC033 | Tables | TOASTed values omitted on UPDATE | 13-18 |
| CDC034 | Tables | unlogged table | 13-18 |
| CDC035 | Tables | partitioned table published by leaf partition | 13-18 |
| CDC040 | Publication | publication does not exist | 13-18 |
| CDC041 | Publication | publication does not publish an action | 13-18 |
| CDC042 | Publication | column list does not cover the replica identity | 15-18 |
| CDC043 | Publication | row filter uses a column outside the replica identity | 15-18 |
| CDC044 | Publication | listed table is not in the publication | 13-18 |
| CDC045 | Tables | generated columns | 13-18 (publish_generated_columns: 18) |
| CDC050 | Failover and standby | logical slots are not carried to a standby before PostgreSQL 17 | 13-16 |
| CDC051 | Failover and standby | logical slot is not failover-enabled but a standby exists | 17-18 |
| CDC052 | Failover and standby | failover slots exist but synchronized_standby_slots is empty | 17-18 |
| CDC053 | Failover and standby | synchronized_standby_slots names a slot that cannot confirm WAL | 17-18 |
| CDC055 | Failover and standby | sync_replication_slots is off on the standby | 17-18 |
| CDC056 | Failover and standby | hot_standby_feedback is off on the standby | 17-18 |
| CDC057 | Failover and standby | primary_slot_name is empty on the standby | 17-18 |
| CDC058 | Failover and standby | primary_conninfo has no dbname on the standby | 17-18 |
| CDC059 | Failover and standby | failover slot is not ready to promote | 17-18 |
| CDC060 | Debezium config | plugin.name is not pgoutput | 13-18 |
| CDC061 | Debezium config | database.dbname differs from the connected database | 13-18 |
| CDC062 | Debezium config | publication prerequisites of publication.autocreate.mode are not met | 13-18 |
| CDC063 | Debezium config | captured tables versus the publication | 13-18 |
| CDC064 | Debezium config | the connector's slot exists with another plugin (fail), or is in use (warn) | 13-18 |
| CDC065 | Debezium config | slot.failover does not match the server | 13-18 (failover slots: 17) |
| CDC066 | Debezium config | no heartbeat | 13-18 |

Debezium checks follow the property names and defaults of the Debezium 3.7 PostgreSQL connector
documentation.

## Read-only guarantee

The tool sends only `SELECT` and `SHOW`. Two mechanisms enforce it, and a test checks the result:

1. The session is opened with `default_transaction_read_only = on`, so the server refuses data and
   schema writes with SQLSTATE `25006`. It also sets `statement_timeout` and `lock_timeout`
   (default 10 s, `--statement-timeout`) and `application_name = pg-cdc-doctor`.
2. Every statement goes through a guard. It accepts one `SELECT` or `SHOW`, refuses a semicolon,
   and then checks every `name(` in the text against an allowlist of the functions and SQL
   keywords the tool's own queries use (`pg_catalog.` is the only qualifier allowed). A function
   that is not on the list is refused, whether or not anyone knows it to be dangerous, so a new
   server function, an extension function or a user-defined function cannot get through. Things
   that could hide a call from that scan are refused too: comments, a double-quoted name followed
   by `(`, dollar quoting, `U&"..."` and `E'...'`. A longer deny-list (slot creation and removal,
   `pg_reload_conf`, `pg_switch_wal`, `set_config`, `nextval`, advisory locks, `query_to_xml`,
   large-object writes, `pg_terminate_backend`, and others) stays as a second layer.

A test runs the whole tool against a database, with `--publication`, `--slot`, `--tables` and
`--debezium` (a connector file), and on 17 and 18 also with `--standby-dsn` against a live standby.
Before and after, it compares the per-table write counters (`pg_stat_user_tables`), the slot list
including each slot's `restart_lsn`, `confirmed_flush_lsn` and `wal_status`, the walsender
connections in `pg_stat_replication`, the publications and their tables, and the entries in
`postgresql.auto.conf`; with a standby it also compares the standby's slots.

Mechanism 1 alone is not enough, and the gap is measured. On PostgreSQL 13, 14, 15, 16, 17 and 18
(`tests/test_pg.py`, run on each version):

| Statement in a session with `default_transaction_read_only = on` | Result |
|---|---|
| `INSERT`, `UPDATE`, `DELETE`, `TRUNCATE` | refused, SQLSTATE 25006 |
| `CREATE TABLE`, `DROP TABLE`, `CREATE ROLE`, `CREATE PUBLICATION`, `CREATE TABLE AS`, `SELECT INTO` | refused, SQLSTATE 25006 |
| `SELECT ... FOR UPDATE`, `COMMENT ON`, `GRANT` | refused, SQLSTATE 25006 |
| `SELECT pg_create_logical_replication_slot(...)` | succeeds |
| `ALTER SYSTEM SET ...` | succeeds |

A read-only session therefore does not stop a slot from being created or the server configuration
from being rewritten. That is why mechanism 2 exists, and why the tool does not send either
statement. A test confirms that the guard refuses both before they reach the server.

The role you connect with decides what the tool can see. It needs `SELECT` on the captured tables
(CDC007). Without `pg_read_all_stats` or superuser, other sessions' transactions are hidden in
`pg_stat_activity`: CDC009 still warns about the long transactions it can see (those of the same
role or of roles it is a member of) and adds an `info` finding that it could not look at the rest.

## The evidence

Every check has at least one scenario in `tests/scenarios/`: a `setup.sql` that builds the broken
(or correct) state, and an `expect.json` that says which findings must appear, with what severity,
and sometimes what the database really does. For the replica-identity checks the harness runs the
`UPDATE` and `DELETE` and asserts the server's error text; for the slot checks it asserts the slot
state it produced; for CDC053 it asserts the WAL sender's wait event. The failover scenarios start
a primary and a streaming standby (`pg_basebackup -R`) in Docker.

`results/matrix.md` is the result of running all scenarios on PostgreSQL 13.23, 14.24, 15.19,
16.15, 17.12 and 18.7 (`uv run python scripts/matrix.py`, needs Docker):

| PostgreSQL | Server | Pass | Fail | Error | n/a |
|---|---|---|---|---|---|
| 13 | 13.23 | 55 | 0 | 0 | 23 |
| 14 | 14.24 | 55 | 0 | 0 | 23 |
| 15 | 15.19 | 60 | 0 | 0 | 18 |
| 16 | 16.15 | 60 | 0 | 0 | 18 |
| 17 | 17.12 | 71 | 0 | 0 | 7 |
| 18 | 18.7 | 75 | 0 | 0 | 3 |

Each version ran 78 scenarios; the counts are scenarios, not checks.

`n/a` means the scenario does not apply to that version: column lists and row filters exist from
15, failover slots from 17, and CDC050 is about servers older than 17. Four scenarios (`clean`,
`clean_all_tables`, `clean_debezium`, `clean_failover`) are negative controls: each must produce no
`fail` and no `warn` wherever it runs.

## Exit codes

| Code | Meaning |
|---|---|
| 0 | No finding at or above `--fail-on` (default `fail`; `warn` also fails on warnings) |
| 1 | At least one finding at or above `--fail-on` |
| 2 | The tool could not run: bad arguments, connection failure, an unreadable or invalid `--debezium` file, `--tables` combined with `--debezium`, `--publication` or `--slot` that differs from the connector file, a `--standby-dsn` that is not a standby, older than 17, or of another cluster |

## JSON output

`--format json` prints one object with the keys `version`, `server_version`, `scope`, `findings` and
`summary`. Findings are ordered by area, then severity, then ID. The report never contains a
connection string or a password. One finding from the run above:

```json
{
  "id": "CDC030",
  "severity": "fail",
  "area": "tables",
  "subject": "public.no_pk",
  "title": "no primary key and replica identity DEFAULT: UPDATE and DELETE will fail once published",
  "detail": "public.no_pk has no primary key and its replica identity is DEFAULT, so once the table is in a publication that publishes updates or deletes, UPDATE and DELETE on it fail in the application with: cannot update table \"no_pk\" because it does not have a replica identity and publishes updates, and cannot delete from table \"no_pk\" because it does not have a replica identity and publishes deletes. INSERT keeps working. This breaks the product's writes, not only CDC.",
  "fix": "Add a primary key, or ALTER TABLE public.no_pk REPLICA IDENTITY USING INDEX <unique not-null index>, or as a last resort ALTER TABLE public.no_pk REPLICA IDENTITY FULL.",
  "docs_url": "https://www.postgresql.org/docs/17/logical-replication-publication.html"
}
```

and its `summary` is `{"fail": 1, "warn": 0, "info": 3}`. Each finding has `id`, `severity`
(`fail`, `warn`, `info` or `ok`), `area`, `subject`, `title`, `detail`, `fix` and `docs_url`.

## Limits

- No run has been made against a managed service (RDS, Aurora, Cloud SQL, Azure Database for
  PostgreSQL or others). Managed-service detection (CDC001 and the role check CDC006) looks for
  markers such as the role `rds_superuser` or `rds_replication` and the settings `rds.extensions`,
  `cloudsql.logical_decoding` and `azure.extensions`. The scenarios imitate those markers with
  roles and settings created on a plain PostgreSQL server, so the detection is simulated, and the
  parameter names in the fix text come from vendor documentation that was not exercised.
- Plain `postgres:<major>` Docker images only: no extensions beyond the bundled ones, and no
  Patroni, pgBackRest or connection pooler in front of the server.
- CDC050 rests on the PostgreSQL 17 release notes ("Enable the failover of logical slots"), because
  the 13 to 16 documentation has no sentence that says logical slots are not carried to a standby.
- Debezium table filters are evaluated with Python's `re`, which approximates the Java regular
  expressions Debezium uses. An unusual pattern could match differently.
- The tool reads a point in time. A transaction that opens after the check, or a slot that stops
  being consumed, is not seen until the next run.
- The tool does not read WAL, tables' contents or the connector's offsets, and it does not look at
  the downstream (Kafka, the sink).

## Related tools

Two other tools check part of the same ground, each as part of a larger product:

- [AWS DMS premigration assessments for PostgreSQL](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.AssessmentReport.PG.html)
  run for a DMS migration task. Several read the same source settings as this tool (`wal_level`,
  `max_wal_senders`, `max_slot_wal_keep_size`, `wal_sender_timeout`, free replication slots,
  prepared and long-running transactions, tables without a primary key); many others are about DMS
  itself (LOB modes, batch apply, the target database, data masking).
- [burnside-project/pg-cdc](https://github.com/burnside-project/pg-cdc) is a CDC server that writes
  PostgreSQL changes to Parquet files. Its `pg-cdc preflight` command checks `wal_level`, the
  replication privilege, CREATE on the database, slot headroom and replica identity, with
  remediation for RDS and Aurora.

pg-cdc-doctor is not tied to a pipeline. It reads the database without changing it, runs on
PostgreSQL 13 to 18, checks failover readiness on a primary and a standby (17 and later), and
compares a Debezium connector file with the live database.

## License

Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
