Metadata-Version: 2.5
Name: pg-cdc-doctor
Version: 0.2.1
Summary: Read-only PostgreSQL CDC checker: finds what fills the disk, loses the slot on failover or drops rows, for Debezium, Kafka Connect, native logical replication and 13 CDC services.
Author: Basant Bhattarai
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: aws-dms,cdc,change-data-capture,data-engineering,debezium,failover,kafka-connect,logical-replication,pgoutput,postgresql,replication-slot,wal
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

Change data capture from PostgreSQL tends to fail in the same few ways: a stalled slot keeps WAL
until the disk fills, a failover leaves the logical slot behind, a slot created again starts past
the consumer's position and rows go missing, a subscriber without a new column stops replicating.
pg-cdc-doctor finds these before they happen and while the pipeline runs. It reads the database
with a read-only session, and, when you point it at them, the Kafka Connect cluster, a standby and
the subscriber, and reports each finding with a stable ID, a severity, the reason and the fix.
`--fix-sql` writes the SQL behind the fixes to a file for you to review; the tool never runs it.

It works with whatever reads the changes: Debezium on Kafka Connect, native logical replication,
or one of 13 CDC services (AWS DMS, Google Datastream, Fivetran, Airbyte, ClickHouse ClickPipes,
Confluent Cloud, Databricks Lakeflow Connect, Snowflake Openflow, Estuary, Materialize, Redpanda
Connect, RisingWave, Striim). `--consumer NAME` judges the findings by the rules that consumer's
own documentation states. PostgreSQL 13 to 19, self-hosted or on a managed service.

## The failures it looks for

| What goes wrong | Reported by | Checks |
|---|---|---|
| A slot whose consumer stopped keeps WAL until the disk fills and the server goes read-only | [400 GB of pg_wal after a Debezium pod crash](https://www.michal-drozd.com/en/blog/postgresql-replication-slot-bloat/); [Azure server switched to read-only](https://haiderzdbre.substack.com/p/postgresql-logical-replication-slots-disk-space); [a connector FAILED for nine days](https://www.datalane-data.blog/blog/debezium-cdc-postgres-guide/) | CDC004, CDC020 to CDC022, CDC027, CDC081, CDC083 |
| A failover leaves the logical slot behind and replication restarts from scratch | [slots gone after a Patroni failover](https://pocketgamer.biz/how-world-war-heroes-merged-100m-player-accounts-and-reshaped-matchmaking); [Patroni drops slots it does not know](https://stormatics.tech/blogs/when-patroni-silently-deletes-your-replication-slots); measured here: no logical slot on the promoted server on 13 to 16 | CDC050 to CDC059, CDC065, CDC078 |
| A slot created again starts past the consumer's offset and the rows in between are lost | [the event-gap risk after promotion](https://franejelavic.github.io/writing/debezium-postgresql-production-lessons/); measured here with Debezium 3.7.1: a connector resumed `RUNNING` and lost them without an error | CDC082 |
| A column added on the publisher but not on the subscriber stops replication and pins `catalog_xmin` | [catalog autovacuum churn from a stalled slot](https://blog.keikooda.net/2023/03/05/xmin-horizon/) | CDC071, CDC074, CDC025 |
| A table without a usable replica identity makes UPDATE and DELETE fail on the publisher, or reach the consumer without a key | the PostgreSQL documentation on replica identity | CDC030, CDC031, CDC036, CDC037, CDC042, CDC043 |
| An unchanged TOAST value arrives as a placeholder and overwrites the real value downstream | [data loss with no errors](https://dev.to/pipelinewhiteboard/the-silent-cdc-bug-data-loss-with-no-errors-5ahh) | CDC033 |
| A heartbeat that should keep a quiet slot moving fails, and the task stays `RUNNING` | measured here with Debezium 3.7.1 | CDC066, CDC067 |

The full list is under [What it checks](#what-it-checks); [The evidence](#the-evidence) says what
was measured on real servers and how.

## When to run it

- **Before a consumer is connected**: settings, the role, slots, publications, replica identity
  and the consumer's own rules, with the SQL to fix them.
- **In CI**: the GitHub Action, run against a database migrated to the pull request's schema,
  fails the pull request when a migration adds a table without a key or leaves a captured table
  out of the publication ([docs/ci.md](docs/ci.md)).
- **On a schedule**: `--format prometheus` writes the findings and per-slot figures (retained WAL,
  `xmin` age, time inactive) for alerting; with `--connect-url` the connector's state is a finding
  too ([docs/monitoring.md](docs/monitoring.md)).
- **Before a failover or a cutover**: `--standby-dsn` for slot synchronization on PostgreSQL 17 and
  later, `--target-dsn` for the subscriber and the cutover summary (CDC079).

## Install

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

or run it without installing:

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

To pin a version, which is what a scheduled job or a CI run should do:

```sh
pip install pg-cdc-doctor==0.2.1
uvx pg-cdc-doctor@0.2.1 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 of 0.2.0 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.2.0: PostgreSQL 17.12
target: postgres@127.0.0.1:50690/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

Runtime health
  INFO  CDC027  max_slot_wal_keep_size  max_slot_wal_keep_size retains about 92.4 h of WAL
  ok    CDC024  1 slots  1 logical slot(s), none invalidated or conflicting
  ok    CDC025  1 slots  slot xmin and catalog_xmin are at most 1 transaction old (autovacuum_freeze_max_age is 200,000,000)
  ok    CDC026  1 slots  no decoded data spilled to disk (168 B decoded in total)

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.
  INFO  CDC038  scope  Initial snapshot: about 32.0 KB across 3 tables
        fix: Plan the snapshot window and the slot's WAL budget for this volume.
              max_slot_wal_keep_size is 5120 MB here.
  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, 6 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.2.0: PostgreSQL 17.12
target: postgres@127.0.0.1:50715/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  10 free replication slots (0 of 10 in use)
  ok    CDC003  max_wal_senders  10 free WAL senders (0 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  0 slots  0 logical slot(s), none inactive, lost or over the retention limit

Runtime health
  INFO  CDC027  max_slot_wal_keep_size  max_slot_wal_keep_size retains about 92.8 h of WAL

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.
  INFO  CDC038  scope  Initial snapshot: about 24.0 KB across 2 tables
        fix: Plan the snapshot window and the slot's WAL budget for this volume.
              max_slot_wal_keep_size is 5120 MB here.
  ok    CDC034  2 tables  no unlogged table in scope

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

`-v` adds the detail of each finding. Findings with severity `ok` are shown so a clean report shows
what was checked. Further headings (Managed service, Consumer fit, Debezium config, Kafka Connect,
Native logical replication) appear when the run detects a service or is given `--consumer`,
`--debezium`, `--connect-url` or `--target-dsn`; see [What it checks](#what-it-checks).

### 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, Runtime health and Tables sections of the same
report are left out here):

```text
pg-cdc-doctor 0.2.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, Runtime health 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, 6 info
```

### With Kafka Connect

```sh
export PGCDC_CONNECT_USER=connect-reader      # only when the REST API needs basic authentication
export PGCDC_CONNECT_PASSWORD='...'
pg-cdc-doctor check --dsn "postgresql://user@host:5432/app" \
                    --connect-url https://connect.internal.example:8083 \
                    --connector app-connector
```

`--connect-url` reads the Kafka Connect REST API with GET requests only. The connector's live
configuration goes through the Debezium checks CDC060 to CDC069 (when `--debezium` also gives a
file, the file is used instead), and CDC080 to CDC083 add whether the cluster answers and the
connector exists, whether the connector and its tasks are `RUNNING`, whether the slot is ahead of
the connector's committed offset or gone, and whether a slot is shared by several connectors or
read by none. `--connector NAME` picks one connector; without it, the PostgreSQL connectors on the
cluster that point at the connected database are checked. `--connector` without `--connect-url`
exits 2. The user and password come only from `PGCDC_CONNECT_USER` and `PGCDC_CONNECT_PASSWORD`; a
URL that contains credentials is refused.

### With a consumer profile

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

`--consumer NAME` judges the findings by what that consumer's documentation says: the output
plugin, the PostgreSQL versions it supports, the replica identity it accepts, whether it needs a
primary key, how it treats TRUNCATE, `wal_sender_timeout`, worker settings and WAL retention. The
profiles are `airbyte`, `clickpipes`, `confluent`, `datastream`, `debezium`, `dms`, `estuary`,
`fivetran`, `generic` (the default, which applies no consumer rule), `lakeflow`, `materialize`,
`native`, `openflow`, `redpanda`, `risingwave` and `striim`. Each rule and the vendor page it was
read from are in [docs/profiles.md](docs/profiles.md).

### On a managed service

```sh
pg-cdc-doctor check --dsn "postgresql://user@host:5432/app" --service rds
```

The tool looks for names that managed services document (a role, a setting, a function, an
extension). It reports the service it finds (CDC011), the risks that service's documentation
describes (CDC012) and a DSN that goes through a connection pooler (CDC013). Detection is
best-effort. Crunchy Bridge, DigitalOcean and Timescale document no SQL marker, so they are never
detected: name them with `--service`. `--service` takes `aiven`, `alloydb`, `aurora`, `azure`,
`cloudsql`, `crunchy`, `digitalocean`, `neon`, `rds`, `supabase` or `timescale`, or `none`, which
switches detection off. On a detected or named service, an `ALTER SYSTEM` statement in the
`--fix-sql` file becomes a comment that names the setting to change on that service.

### With native logical replication

```sh
pg-cdc-doctor check --dsn "postgresql://user@publisher/app" \
                    --target-dsn "postgresql://user@subscriber/app" \
                    --publication app_pub --slot app_sub
```

`--target-dsn` opens a second read-only connection, to the subscriber, and adds CDC070 to CDC075,
CDC078 and CDC079: worker and origin capacity, published tables and columns on the subscriber, an
index the apply worker can use for UPDATE and DELETE, sequences, subscription state and errors,
the subscription's slot on the publisher, failover, and a cutover summary. The tool matches a
subscription to the publisher by publication name and slot name (see [Limits](#limits)).

### Writing the SQL for review

```sh
pg-cdc-doctor check --dsn "$DSN" --publication cdc_pub --fix-sql fix.sql
```

`--fix-sql FILE` writes the SQL behind the findings to `FILE` for a person to read and run. The
tool never runs it. It refuses to overwrite an existing file (exit code 2, before it connects) and
prints the path on stderr. With `--target-dsn`, the statements that belong on the subscriber go to
a second file, `fix.target.sql` (the name with `.target` before the extension); that file must not
exist either. See [docs/fix-sql.md](docs/fix-sql.md) for what the file contains and what it never
contains.

### Report formats and CI

```sh
pg-cdc-doctor check --dsn "$DSN" --format markdown --json-out report.json > report.md
```

`--format` is `text` (the default), `json`, `markdown` (for a GitHub job summary or a pull request
comment) or `prometheus` (for the node_exporter textfile collector or a Pushgateway; see
[docs/monitoring.md](docs/monitoring.md)). `--json-out FILE` also writes the JSON report to `FILE`,
whatever `--format` is, and replaces an existing file. The exit code is the same in every format.

A composite GitHub Action (`action.yml` at the repository root) runs one check, writes the Markdown
report to the job summary and fails the step with the tool's exit code. Its inputs, a pull request
comment example and a GitLab example are in [docs/ci.md](docs/ci.md).

### Ignoring known findings

```sh
pg-cdc-doctor check --dsn "$DSN" --ignore CDC004 --ignore CDC033:public.audit_log
```

`--ignore ID[:SUBJECT]` drops findings before the summary and the exit code, and can be repeated.
`CDC004` drops every finding of that check; `CDC033:public.audit_log` drops only the findings about
that subject. An ID that is not a check exits 2. The report counts what was dropped: the text
report says "N finding(s) ignored by --ignore" and the JSON report lists them under `ignored`.
[docs/ci.md](docs/ci.md) shows how to baseline a first run.

### Sampling the WAL rate

```sh
pg-cdc-doctor check --dsn "$DSN" --consumer debezium --sample 60
```

`--sample SECONDS` waits that long and reads the WAL position twice. The rate gives CDC027 its
figure for how many hours of WAL the retention budget covers. Without it, the rate comes from
`pg_stat_wal` on PostgreSQL 14 and later (an average since the statistics were last reset) and
there is no rate on 13. The default is 0: a point-in-time check that does not wait.

### Explaining a check

```sh
pg-cdc-doctor explain CDC082
```

prints the check's name, area, severity, versions, what it means, why it matters for CDC, the fix
and the documentation link. It does not connect to a database. The first lines of the output:

```text
CDC082: the slot is ahead of the connector's committed offset, or gone
area: connect
severity: fail (gap, slot missing) / info
versions: 13-19
what: With --connect-url: the slot's confirmed_flush_lsn is ahead of the position the connector ...
```

## What it checks

75 checks in twelve areas. 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`. `fail` means the consumer will
not start or the product's writes will break; `warn` is a risk to the consumer's health; `info` is
something to know.

### Server

Always run.

| ID | Severity | Finding | PostgreSQL |
|---|---|---|---|
| CDC001 | fail (warn on PostgreSQL 19 when wal_level is replica) | wal_level is not logical | 13-19 (19: replica is a warn) |
| CDC002 | fail (0 free) / warn (1 free) | no free replication slots | 13-19 |
| CDC003 | fail | no free WAL sender processes | 13-19 |
| CDC004 | warn | max_slot_wal_keep_size is unbounded | 13-19 |
| CDC005 | warn | wal_sender_timeout is 0 | 13-19 |
| CDC008 | warn | prepared transactions exist | 13-19 |
| CDC009 | warn (info when other sessions are not visible) | long-running transactions | 13-19 |
| CDC010 | info (fail below 13) | server version | 13-19 |

### Managed service

Always run. The service is detected from SQL markers, or set with `--service`.

| ID | Severity | Finding | PostgreSQL |
|---|---|---|---|
| CDC011 | info | managed service detected | 13-19 |
| CDC012 | warn (per risk) | managed-service CDC risk | 13-19 |
| CDC013 | warn | DSN goes through a connection pooler | 13-19 |

### Role

Always run.

| ID | Severity | Finding | PostgreSQL |
|---|---|---|---|
| CDC006 | fail | connecting role cannot replicate | 13-19 |
| CDC007 | fail (per table) | role lacks SELECT on a captured table | 13-19 |

### Replication slots

Always run. `--slot` adds CDC023.

| ID | Severity | Finding | PostgreSQL |
|---|---|---|---|
| CDC020 | fail (lost, unreserved) / warn (extended) | slot WAL status | 13-19 |
| CDC021 | warn | inactive logical slot | 13-19 |
| CDC022 | warn | slot retains more WAL than the limit | 13-19 |
| CDC023 | warn (other plugin) / info (slot absent) | named slot | 13-19 |

### Runtime health

Always run. `--sample SECONDS` gives CDC027 a measured WAL rate.

| ID | Severity | Finding | PostgreSQL |
|---|---|---|---|
| CDC014 | warn | idle_replication_slot_timeout can invalidate the consumer's slot (18+) | 18-19 |
| CDC024 | fail (per slot) | slot invalidated or conflicting | 13-19 |
| CDC025 | warn/fail (per slot) | slot pins xmin/catalog_xmin (vacuum and wraparound) | 13-19 |
| CDC026 | warn/info (per slot) | decoding spills to disk | 14-19 |
| CDC027 | info/warn | WAL retention budget in hours vs the consumer | 13-19 |
| CDC029 | fail/warn/info | decoding from a standby | 13-19 |

### Tables

Always run.

| ID | Severity | Finding | PostgreSQL |
|---|---|---|---|
| CDC030 | fail (per table) | no primary key and replica identity DEFAULT | 13-19 |
| CDC031 | fail (per table) | replica identity NOTHING, or USING INDEX with the index gone | 13-19 |
| CDC032 | info (per table) | replica identity FULL | 13-19 |
| CDC033 | info (per table) | TOASTed values omitted on UPDATE | 13-19 |
| CDC034 | fail (per table) | unlogged table | 13-19 |
| CDC035 | warn (per table) | partitioned table published by leaf partition | 13-19 |
| CDC038 | info | initial snapshot size | 13-19 |
| CDC045 | info (per table) | generated columns | 13-19 (publish_generated_columns: 18) |
| CDC077 | warn (per table) | large objects are not replicated | 13-19 |

### Consumer fit

Run with `--consumer NAME`; `generic` (the default) states no rule.

| ID | Severity | Finding | PostgreSQL |
|---|---|---|---|
| CDC016 | warn | worker settings below the consumer's rule | 13-19 |
| CDC017 | fail (below the range) / warn (above it) | consumer does not support this PostgreSQL version | 13-19 |
| CDC036 | fail (per table) | replica identity does not meet the consumer | 13-19 |
| CDC037 | fail (per table) | consumer needs a primary key | 13-19 |
| CDC039 | warn (consumer errors on TRUNCATE) / info (consumer ignores it) | TRUNCATE handling of the consumer | 13-19 |
| CDC046 | fail | publish_via_partition_root vs the consumer | 13-19 |
| CDC047 | fail | FOR ALL TABLES / TABLES IN SCHEMA vs the consumer | 13-19 |

### Publication

Skipped for a consumer profile whose consumer reads no publication.

| ID | Severity | Finding | PostgreSQL |
|---|---|---|---|
| CDC040 | fail | publication does not exist | 13-19 |
| CDC041 | warn (per missing action) | publication does not publish an action | 13-19 |
| CDC042 | fail (per table) | column list does not cover the replica identity | 15-19 |
| CDC043 | fail (per table) | row filter uses a column outside the replica identity | 15-19 |
| CDC044 | fail (per table) | listed table is not in the publication | 13-19 |

### Failover and standby

CDC050 to CDC053 read the primary. CDC055 to CDC059 need `--standby-dsn`.

| ID | Severity | Finding | PostgreSQL |
|---|---|---|---|
| CDC050 | warn (ok when pg_failover_slots is preloaded) | logical slots are not carried to a standby before PostgreSQL 17 | 13-16 |
| CDC051 | warn (per slot) | logical slot is not failover-enabled but a standby exists | 17-19 |
| CDC052 | warn | failover slots exist but synchronized_standby_slots is empty | 17-19 |
| CDC053 | fail (per slot) | synchronized_standby_slots names a slot that cannot confirm WAL | 17-19 |
| CDC055 | fail (info when no failover slot exists) | sync_replication_slots is off on the standby | 17-19 |
| CDC056 | fail (info when no failover slot and no sync) | hot_standby_feedback is off on the standby | 17-19 |
| CDC057 | fail (info when no failover slot and no sync) | primary_slot_name is empty on the standby | 17-19 |
| CDC058 | fail (info when no failover slot and no sync, or when unreadable) | primary_conninfo has no dbname on the standby | 17-19 |
| CDC059 | warn (per slot) | failover slot is not ready to promote | 17-19 |

### Debezium config

Run with `--debezium FILE` or `--connect-url`. Versions below are PostgreSQL's; the property names and defaults are those of Debezium 3.7.

| ID | Severity | Finding | PostgreSQL |
|---|---|---|---|
| CDC060 | warn | plugin.name is not pgoutput | 13-19 |
| CDC061 | fail | database.dbname differs from the connected database | 13-19 |
| CDC062 | fail | publication prerequisites of publication.autocreate.mode are not met | 13-19 |
| CDC063 | fail (per table) / warn / info | captured tables versus the publication | 13-19 |
| CDC064 | fail (warn when the slot is only active) | the connector's slot exists with another plugin, or is in use | 13-19 |
| CDC065 | warn | slot.failover does not match the server | 13-19 (failover slots: 17) |
| CDC066 | warn | no heartbeat, or the connector never advances the slot | 13-19 |
| CDC067 | fail (table missing or not writable) / warn | heartbeat.action.query table is missing, not writable or not published | 13-19 |
| CDC068 | fail (table missing, wrong columns, not published) / warn | signal.data.collection table is missing, has wrong columns or is not published | 13-19 |
| CDC069 | warn (per table) | incremental snapshot: a captured table has no primary key and no surrogate key | 13-19 |

### Kafka Connect

Run with `--connect-url`.

| ID | Severity | Finding | PostgreSQL |
|---|---|---|---|
| CDC080 | fail (unreachable, connector missing) / warn / info | Kafka Connect does not answer, or the connector is not on it | 13-19 |
| CDC081 | fail (FAILED) / warn | connector or task is not RUNNING | 13-19 |
| CDC082 | fail (gap, slot missing) / info | the slot is ahead of the connector's committed offset, or gone | 13-19 |
| CDC083 | fail (shared slot) / warn (orphan slot) / info | a slot is shared by connectors, or read by no connector | 13-19 |

### Native logical replication

Run with `--target-dsn`, the subscriber.

| ID | Severity | Finding | PostgreSQL |
|---|---|---|---|
| CDC070 | fail/warn | subscriber worker and origin capacity | 13-19 |
| CDC071 | fail (missing) / warn (type differs) | published table or column missing on the subscriber | 13-19 |
| CDC072 | fail / warn (per table) | subscriber table lacks the replica identity key | 13-19 |
| CDC073 | warn | sequences not synchronized | 13-19 |
| CDC074 | fail/warn | subscription state, apply/sync errors, conflicts | 13-19 |
| CDC075 | fail/warn | subscription's slot on the publisher | 13-19 |
| CDC078 | warn | subscription failover vs publisher standby (17+) | 17-19 |
| CDC079 | ok/fail | cutover readiness summary | 13-19 |

Debezium checks follow the property names and defaults of the Debezium 3.7 PostgreSQL connector
documentation. Consumer profiles follow each vendor's documentation, one page per rule
([docs/profiles.md](docs/profiles.md)). The managed-service markers and risks follow the vendors'
documentation, and [docs/checks.md](docs/checks.md) links each page.

## 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.

`--standby-dsn` and `--target-dsn` open a second connection with the same read-only session and the
same guard. The Kafka Connect client (`--connect-url`) sends only GET requests, verifies TLS
certificates, follows no redirect, and refuses a URL that contains credentials.

A test runs the whole tool against a database, with `--publication`, `--slot`, `--tables` and
`--debezium` (a connector file), and on 17, 18 and 19 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, 18 and 19
(`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 the scenarios on PostgreSQL 13 to 19
(`uv run python scripts/matrix.py`, needs Docker). The counts are scenarios, not checks.

171 scenarios, run on 2026-12-01 against the plain `postgres:<major>` images:

| PostgreSQL | pass | fail | error | n/a |
|---|---|---|---|---|
| 13 | 109 | 0 | 0 | 62 |
| 14 | 113 | 0 | 0 | 58 |
| 15 | 119 | 0 | 0 | 52 |
| 16 | 120 | 0 | 0 | 51 |
| 17 | 131 | 0 | 0 | 40 |
| 18 | 137 | 0 | 0 | 34 |
| 19 | 139 | 0 | 0 | 32 |

`n/a` means the scenario does not apply to that version: column lists and row filters exist from
15, failover slots from 17, CDC050 is about servers older than 17, and `wal_level = replica`
is a `fail` up to 18 and a `warn` on 19 (`cdc001_wal_level_replica` runs on 13 to 18,
`cdc001_pg19_replica_slot` and `cdc001_pg19_replica_noslot` on 19). The native logical replication
scenarios are `n/a` in every column: they run in their own harness (below). Four scenarios (`clean`,
`clean_all_tables`, `clean_debezium`, `clean_failover`) are negative controls: each must produce no
`fail` and no `warn` wherever it runs.

Two kinds of scenario need more than one server and have their own harness. The native logical
replication scenarios need a publisher and a subscriber: `tests/harness_subscriber.py` runs them,
by default on PostgreSQL 13, 16, 17 and 19. The Kafka Connect scenarios run Debezium on a real
Connect worker: `tests/harness_connect.py` starts PostgreSQL, one Kafka 4.0.0 broker in KRaft mode
and Debezium Connect 3.7.1.Final, and the CI job for it runs on PostgreSQL 17. The shared harness
does not run either kind.
On 2026-12-01 every one of them passed: the native scenarios 19 on PostgreSQL 13, 23 on 16, 22 on
17 and 22 on 19 (`results/subscriber.json`; `cdc072_pk_fallback` was added after that run and
passed on 13 and 16 on its own); the Kafka Connect scenarios 10 each on 13, 17 and 19.

### Measured on real servers in 0.2

- **Debezium offset versus slot (CDC082), Debezium 3.7.1.Final.** After the slot is dropped and
  created again, a connector whose stored offset was written while streaming fails when it resumes
  ("no longer available on the server") and the rows written in between never reach Kafka. A
  connector whose stored offset was written only by the initial snapshot resumes as `RUNNING`, and
  the rows written while the slot was gone are lost without an error. CDC082 fails in both cases.
- **A failing `heartbeat.action.query` (CDC067), Debezium 3.7.1.Final.** A missing table or a
  permission error does not fail the task. It stays `RUNNING`, and only the worker log shows the
  error.
- **`lsn.flush.mode=manual` (CDC066), Debezium 3.7.1.Final.** The slot's `confirmed_flush_lsn` does
  not move, and the server retains WAL without bound.
- **The signal table (CDC068), Debezium 3.7.1.Final.** It works when it is in the publication,
  whatever `table.include.list` says. In `table.include.list` but not published, it does nothing.
- **Slots after a promotion (CDC050), `tests/measure_cdc050.py`.** On PostgreSQL 13.23, 14.24,
  15.19 and 16.15 a logical slot is absent on the standby after it is promoted. On 17.12 a failover
  slot survives the promotion once it is synchronized.
- **Subscription failover (CDC078), PostgreSQL 19.** `ALTER SUBSCRIPTION ... SET (failover =
  true)` is refused on an enabled subscription and inside a transaction block. The fix is
  `DISABLE`, `SET` and `ENABLE` as three separate statements.
- **PostgreSQL 19.0 and `wal_level` (CDC001, CDC073).** With `wal_level = replica`, the first
  logical slot turns logical decoding on (`effective_wal_level` becomes `logical`), and it falls
  back within about 50 ms after the last one is dropped on an idle server. CDC001 is a `warn` for
  `replica` on 19 and a `fail` on 13 to 18. Version 19 also synchronizes sequences through
  subscriptions (CDC073).

## 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 (an unknown `--consumer`, `--service` or `--format`, an `--ignore` ID that is not a check, `--connector` without `--connect-url`), a connection failure to `--dsn`, `--standby-dsn` or `--target-dsn`, a query that hit the statement timeout, 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, a `--fix-sql` file (or its `.target` file) that already exists or cannot be written, a `--json-out` file that cannot be written |

A Kafka Connect cluster that does not answer is not exit 2: CDC080 reports it as a finding.
`pg-cdc-doctor explain` exits 2 for an ID that is not a check.

## JSON output

`--format json` prints one object with the keys `version`, `server_version`, `scope`, `findings`,
`summary` and `ignored`. Findings are ordered by area, then severity, then ID. The report never
contains a connection string or a password. One finding from the second 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",
  "fix_sql": [
    "-- A primary key is the better fix: FULL writes the whole old row to WAL on every UPDATE and DELETE.\nALTER TABLE public.no_pk REPLICA IDENTITY FULL;"
  ],
  "fix_kind": "online"
}
```

and its `summary` is `{"fail": 1, "warn": 0, "info": 5}`. Each finding has `id`, `severity`
(`fail`, `warn`, `info` or `ok`), `area`, `subject`, `title`, `detail`, `fix`, `docs_url`, `fix_sql`
(a list of SQL statements, empty when the finding has none) and `fix_kind` (`online`, `restart` or
`destructive` when there is SQL). `ignored` lists the findings dropped by `--ignore`, each with
`id`, `subject` and `severity`. `--json-out FILE` writes the same object to a file.

## Limits

- No run has been made against a managed service (RDS, Aurora, Cloud SQL, AlloyDB, Azure Database
  for PostgreSQL, Supabase, Neon, Aiven, Crunchy Bridge, DigitalOcean, Timescale). The rules, the
  risks and the parameter names in the findings and the fix SQL come from vendor documentation. The
  scenarios imitate the detection markers (roles such as `rds_superuser`, settings such as
  `rds.extensions`, `cloudsql.logical_decoding` and `azure.extensions`) with roles and settings
  created on a plain PostgreSQL server, so the detection is simulated.
- Managed-service detection is best-effort and reads SQL markers. Crunchy Bridge, DigitalOcean and
  Timescale have none: use `--service`. A pooler in front of the server is guessed from the host
  name and port of the DSN (CDC013).
- Consumer profile rules were read from the vendor pages linked in
  [docs/profiles.md](docs/profiles.md). A page can change, and a rule a page does not state is not
  applied.
- Plain `postgres:<major>` Docker images only: no extensions beyond the bundled ones, and no
  Patroni, pgBackRest or connection pooler in front of the server.
- The Kafka Connect checks were measured on Debezium 3.7.1.Final with Kafka 4.0.0 only. The offsets
  endpoint that CDC082 reads needs Kafka 3.6 or later.
- The Kafka Connect REST client was tested against fakes for TLS and authentication, not against a
  live worker with TLS or authentication.
- Debezium table filters are evaluated with Python's `re`, which approximates the Java regular
  expressions Debezium uses. An unusual pattern could match differently.
- PostgreSQL 13 and 14 do not expose subscription apply and sync error counts
  (`pg_stat_subscription_stats` exists from 15), so on a subscriber of those versions CDC074 sees
  the subscription's state only.
- The tool cannot prove that a subscription points at the `--dsn` server: `subconninfo` is
  readable by superusers only. It matches a subscription to the publisher by publication name and
  slot name.
- The tool reads a point in time; `--sample` adds two readings of the WAL position. 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 or the contents of tables, and it does not look at the downstream
  (Kafka topics, the sink). It reads the connector's committed offsets only through the Kafka
  Connect REST API.

## Related tools

Other tools cover part of the same ground. They fall into two groups.

**Readiness checks that belong to one pipeline.** Each checks what its own product needs, when
its own task starts:

- [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_easy_replicate](https://github.com/shayonj/pg_easy_replicate) moves a database with logical
  replication; its `config_check` command "prints if source and target database have the required
  config".

**Monitoring that measures the slot.** [check_postgres](https://bucardo.org/check_postgres/check_postgres.pl.html)
has a `replication_slots` action that checks "the quantity of WAL retained for any replication
slots", and Prometheus exporters chart server statistics. They say that a slot is growing, not why:
whether its consumer is down, failed, pointed at another slot, or never advancing it.

pg-cdc-doctor is not tied to one pipeline and reads both sides. It judges the database by the rules
of 15 consumers, and it reads the consumer as well: the connector's configuration, state and
committed offset on Kafka Connect, the subscriber of a native subscription, and the standby a slot
must survive on. That is how it catches the failures that each side alone reports as healthy, such
as a connector that is `RUNNING` after its slot was created again (CDC082). It changes nothing on
either side. Its Prometheus output can sit next to an existing exporter.

## License

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