Repository navigation
[Fix][Connector-V2] Fail fast when the Postgres-CDC replication slot has been invalidated - #12587
Conversation
…has been invalidated
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks @goutamadwant for this contribution, and for the unusually clear before/after table and the manual verification on PostgreSQL 17 and 18. This is a well-targeted fix.
What Problem Does This PR Solve?
When PostgreSQL invalidates a logical replication slot (max_slot_wal_keep_size on 13+, idle_replication_slot_timeout on 18), Postgres-CDC used to hand that slot to Debezium anyway. Debezium then either spins on the slot state for a long time or fails after stream retries, with no message that names the slot. Because the slot can never stream again, every pipeline restore repeats the same futile work.
Fix approach: before Debezium touches the slot, query pg_replication_slots and fail immediately with a dedicated error code (POSTGRES-04) that names the reason and the recovery steps.
Example: a job restored from a checkpoint against a slot with wal_status = 'lost' previously looped for minutes; now it fails in seconds with an actionable message.
1. Code Change Review
1.1 Core Logic Analysis
Runtime path (PR head):
Reader task start / pipeline restore
-> PostgresSourceFetchTaskContext.configure(...) (PostgresSourceFetchTaskContext.java ~line 185-190)
-> checkReplicationSlotNotInvalidated(snapshotter.shouldStream(), dataConnection, slotName) (~line 318)
- shouldStream == false (snapshot-only): return, no query
- else PostgresUtils.checkReplicationSlotNotInvalidated(connection, slotName) (PostgresUtils.java ~line 334)
SELECT * FROM pg_replication_slots WHERE slot_name = ? AND database = current_database()
-> readSlotInvalidationReason(rs)
invalidation_reason (PG17+) non-null | conflicting (PG16+) true | wal_status (PG13+) = 'lost'
-> reason present: throw SeaTunnelRuntimeException(POSTGRES-04, ...)
-> no row / healthy: continue
- SQLException: log warn, rollback, continue (previous behavior)
-> existing getReplicationSlotState(...) and Debezium streaming
Findings:
- The change is placed in configure(), which is reached on both the normal start path and the restore path, so the normal user path (not only a recovery edge) is covered. The check runs before the existing
getReplicationSlotStatecall, which is exactly where the old behavior started retrying. SELECT *plus column discovery throughResultSetMetaDatais a reasonable way to support PG 13 to 18 with one statement; columns that do not exist on older servers are simply skipped, so older servers behave exactly as before.- The
database = current_database()filter is correct: slot names are unique per cluster but a logical slot belongs to one database, and this avoids a false positive on an unrelated slot. - Failure of the check query itself is deliberately non-fatal and the transaction is rolled back so the following Debezium metadata queries on the shared connection are not poisoned by an aborted transaction. This is a justified, documented degrade-to-previous-behavior path, not a swallowed root cause.
- The thrown exception is a SeaTunnelRuntimeException and is not caught by the surrounding
catch (SQLException)blocks, so it propagates and fails the task as intended.
1.2 Compatibility Impact
Fully compatible. No config option, default, serialization format or checkpoint/savepoint state is touched. The only behavior change is that a job on an already-unusable slot fails fast instead of hanging/failing late. A new error-code enum constant (POSTGRES-04) is appended after POSTGRES-03; existing codes are unchanged.
1.3 Performance / Side-Effect Analysis
One small catalog query per configure() call on a streaming-capable job. In initial mode configure() also runs per snapshot split, so the query is repeated per split; it is an indexed-by-name read of a tiny catalog view and the cost is negligible next to the existing serverInfo() and slot-state queries in the same method. No new threads, buffers, retries or locks; statement and result set are closed with try-with-resources.
1.4 Error Handling and Logging
No blocking issues found. Formal issues (all non-blocking):
Issue 1: No end-to-end test for the invalidated-slot path
- Location:
seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/test/.../PostgresSourceFetchTaskContextTest.javaandPostgresUtilsTest.java(new) - Problem: Coverage is unit-level and relies on mocked
Connection/ResultSet/ResultSetMetaData. The project guide asks for the existing IT to be extended when the connector has one (PostgresCDCITexists). The mocks prove column handling and the error code, but not that real PostgreSQL returns those column names and that the exception reaches the job as a failure. - Potential risk: A server-side column rename/shape difference would not be caught in CI. The PR description says this was verified manually on PG 17.9 and 18.6, which is good evidence but not a regression guard.
- Best improvement: If a deterministic invalidation is feasible in the testcontainer (for example a tiny
max_slot_wal_keep_sizepluspg_switch_wal()and a checkpoint on PG 13+), add one IT case; otherwise note in the PR why it is not feasible. - Severity: Medium
- Raised by another reviewer: No
Issue 2: PostgresSourceFetchTaskContextTest mostly verifies mock interactions
- Location:
PostgresSourceFetchTaskContextTest.java(testSlotIsNotCheckedWhenJobDoesNotStream,testFailedCheckRollsBackAndContinues) - Problem: These two assert only
verify(never())/verify(rollback()). They do fail if theshouldStreamguard or the rollback call is deleted, so they are not empty, but they would not notice a wrong query or wrong condition. - Potential risk: Low; the other two tests assert the real exception code and pass-through.
- Best improvement: Optional; fine to keep as is given the IT limitation above.
- Severity: Low
- Raised by another reviewer: No
Issue 3: Doc wording could mention the conflicting reason
- Location:
docs/en/connectors/source/PostgreSQL-CDC.mdnew FAQ entry (and the zh counterpart) - Problem: The FAQ lists
wal_status = 'lost'andinvalidation_reason, but the code also treatsconflicting = true(PG 16+) as invalidated. - Potential risk: A user who hits the
conflict with recoveryreason will not find it mentioned. - Best improvement: Add a half-sentence mentioning conflicts with recovery on standbys.
- Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
Good. New methods carry Javadoc that explains why (retry loop avoidance) and the per-version column availability. Logging uses the existing @Slf4j logger with slot-name context, and no credentials are logged. The SQL statement string is a long line, but spotless handles that.
2.2 Test Coverage and Test Stability
Unit tests cover PostgreSQL 17+ reasons, conflicting, wal_status = lost, servers without those columns, snapshot-only skip, invalidated, healthy and query-error rollback. Stability: Stable. They are pure mock-based unit tests with no sleeps, no static state and no containers. See Issue 1 for the missing real-server guard.
2.3 Documentation Updates
en and zh FAQ entries are added and consistent with each other and with the code (error code, recovery steps, startup.mode = initial). See Issue 3 for a small gap. No option changes, so no option tables need updating.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix. It sits at the single point where the slot state is first consulted, adds no connector-specific logic to shared engine/core code, and degrades safely.
3.2 Maintainability
Good. The version-dependent column logic is isolated in one small, testable static method in PostgresUtils.
3.3 Extensibility
New invalidation signals added by future PostgreSQL versions can be added as another column check in readSlotInvalidationReason.
3.4 Historical-Version Compatibility
No impact on checkpoint/savepoint state, config or serialization. Older PostgreSQL servers (below 13) lack the columns and are treated as never invalidated, exactly as before. No registration-chain changes are required because no connector or factory is added.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | No real-server (IT) guard for the invalidated-slot path | PostgresCDCIT / new unit tests | Medium |
| 2 | Two tests assert mock interactions only | PostgresSourceFetchTaskContextTest | Low |
| 3 | FAQ does not mention the conflicting reason |
PostgreSQL-CDC.md (en, zh) | Low |
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers - must be fixed: none.
- Recommended fixes - non-blocking: Issues 1 to 3 above.
Overall assessment: a minimal, correct and well-documented fail-fast improvement with no compatibility risk and no new runtime cost of note. No existing maintainer approvals or change requests exist to respond to.
CI/sync status: all checks on this head completed successfully. The branch is 15 commits behind dev with no conflicts; the merge state is BLOCKED only because required review is pending. Next step: a committer approval.
nzw921rx
left a comment
There was a problem hiding this comment.
Thanks for the fix. One small compatibility concern: in PostgresSourceFetchTaskContext.configure(), the new pre-check calls snapshotter.shouldStream() before snapshotter.init(...).
The built-in snapshotters return a constant here, so normal configurations are unaffected. However, a custom snapshotter configured through debezium.snapshot.mode = custom may depend on state populated by init(). This earlier call could then fail during startup even with a healthy slot, or return a default false and skip the check.
Could we avoid calling shouldStream() before initialization while keeping the invalidation check ahead of getReplicationSlotState()? A focused regression test with a custom snapshotter that depends on initialization would help cover this case.
…init Check the slot before reading its state, but decide whether the job streams after snapshotter.init(), so a custom snapshotter is never asked before it is initialized. An invalidated slot's state is no longer read, so snapshot-only jobs on such a slot no longer wait in Debezium's slot retry loop.
…an invalidated slot
@nzw921rx Thanks, good catch. addressed it. pls have a re-look and let me know. |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks @goutamadwant for the quick follow-up commits. Sorry for missing something in my last review: I approved the earlier head e3b47dc7dc7, where snapshotter.shouldStream() was called before snapshotter.init(...), and @nzw921rx was right to flag it (+1 to that point). That was my miss, not a newly introduced issue. I re-reviewed the whole PR at the latest head fe87185e12c0 from scratch (full diff, not only the new commits), and I also read @nzw921rx's review and your reply.
What Problem Does This PR Solve?
- User pain point: when PostgreSQL invalidates a logical replication slot (
wal_status = 'lost',conflicting, orinvalidation_reasonon PG 17+, for examplemax_slot_wal_keep_sizeoridle_replication_slot_timeout), Postgres-CDC handed it to Debezium anyway. Debezium then loops on the slot state (the PR reports about 30 minutes per attempt) or fails late with a generic error, on every pipeline restore. - Fix approach: before the slot state is read, query
pg_replication_slots; if the slot is invalidated and the job streams, fail immediately with the new error codePOSTGRES-04that names the reason and the recovery steps. Snapshot-only jobs skip the failure, and a failing check query degrades to the old behavior. - One-sentence summary: turn a long, opaque hang or late failure on an unusable slot into a fast, actionable error.
Simple example: restoring a job against a slot with invalidation_reason = 'idle_timeout' used to fail after several minutes of Debezium retries; now it fails in seconds and tells the operator to drop the slot and restart.
1. Code Change Review
1.1 Core Logic Analysis
Before (dev), in PostgresSourceFetchTaskContext.configure: serverInfo() and getReplicationSlotState(...) in one try block, then snapshotter.init(config, offsetState, slotInfo).
After (PostgresSourceFetchTaskContext.java:198, :303-342): the new static initSnapshotter does the invalidation lookup first, skips reading the slot state if the slot is invalidated, calls snapshotter.init(...), and only then asks snapshotter.shouldStream() to decide whether to throw.
Runtime path:
Reader task start / pipeline restore / every snapshot split
-> PostgresSourceFetchTaskContext.configure(split)
-> initSnapshotter(snapshotter, config, offsetState, dataConnection) :198, :303
-> findSlotInvalidationReason(dataConnection, slotName) :310, :345
-> PostgresUtils.getReplicationSlotInvalidationReason(connection, slot) PostgresUtils.java:334
SELECT * FROM pg_replication_slots WHERE slot_name = ? AND database = current_database()
-> readSlotInvalidationReason: invalidation_reason (PG17+) / conflicting (PG16+) / wal_status = 'lost' (PG13+) :364
-> SQLException: warn, dataConnection.rollback(), Optional.empty() :351-357 (old behavior)
-> serverInfo() logged; invalidated -> warn and slotInfo stays null; else getReplicationSlotState :318-330
-> snapshotter.init(config, offsetState, slotInfo) :336
-> invalidated && snapshotter.shouldStream() -> throw SeaTunnelRuntimeException POSTGRES-04 :338-339
-> existing: if (snapshotter.shouldStream()) create replication connection / slot, commit, build queue and dispatchers
Key findings:
- The normal start path is covered, not only restore:
configureruns for every split reader and for the stream reader, so a fresh job that finds a leftover invalidated slot with the same name also fails fast, which is the better behavior. - The ordering concern from @nzw921rx is fixed:
initruns beforeshouldStream, andtestSnapshotterIsInitializedBeforeItIsAskeduses a snapshotter that throws if it is asked beforeinit, so it fails if anyone reorders the calls again. Built-in snapshotters are unaffected either way. - When the slot is invalidated,
initreceivesslotInfo == nullinstead of the real (lost) state. For the built-in snapshotters this is irrelevant (they decide from the offset state and mode), and a streaming job throws right after, so I do not see a behavior difference for them. A custom snapshotter that reads the slot state would see "no slot" for a snapshot-only job on an invalidated slot; that is an acceptable edge and the Javadoc at:296-302explains why the state is not read. - The check is read-only. A failing check query is not swallowed silently: it logs a warning with the exception, rolls the shared connection back so the following Debezium queries are not poisoned by an aborted transaction, and continues exactly as before. The new exception is a
SeaTunnelRuntimeException, so it is not caught by the surroundingcatch (SQLException)blocks and fails the task as intended. The failure happens before the queue, dispatchers and replication connection are created, so nothing is leaked. - The
database = current_database()filter is right (logical slots belong to one database), andSELECT *with column discovery supports PG 13 to 18 in one statement, with older servers simply skipping missing columns.
1.2 Compatibility Impact
Fully compatible. No option, default, serialization format, checkpoint or savepoint state changes; the new enum constant POSTGRES-04 is appended after POSTGRES-03 (PostgresConnectorErrorCode.java). The only behavior change is intended: a streaming job on an already unusable slot fails fast instead of hanging or failing late. One nuance worth knowing: a job whose slot is invalidated while it is still in the snapshot phase will now fail when the next split calls configure, rather than only after the snapshot ends. That job could not have streamed anyway, so the fail-fast outcome is the same, just earlier.
1.3 Performance / Side-Effect Analysis
One small catalog query per configure call, next to the existing serverInfo() and slot-state queries that already run per call, so the relative cost is small even for many snapshot splits. No new threads, buffers, retries or locks; the statement and result set use try-with-resources. No effect on checkpoint or state size.
1.4 Error Handling and Logging
No source blocker. Formal issues:
Issue 1: Merge conflicts with dev in the PostgreSQL-CDC docs
- Location:
docs/en/connectors/source/PostgreSQL-CDC.mdanddocs/zh/connectors/source/PostgreSQL-CDC.md, the FAQ section after the replication-slot paragraph. - Problem description: GitHub reports this PR as
DIRTY(mergeable false). The branch is 62 commits behinddev. A dry-run three-way merge against currentdevshows conflict markers only in these two files:devadded the FAQ entry about transaction boundaries during savepoint recovery at the same spot where this PR adds its "replication slot ... has been invalidated" entry.PostgresSourceFetchTaskContext.javaalso changed ondev(#12454, inloadStartingOffsetState), but in a different region and it merges textually without conflict (this is from my dry-run merge, not a build). - Potential risk: the PR cannot be merged until this is resolved.
- Best improvement: please sync with the latest
devand resolve the two docs conflicts by keeping both FAQ entries (they are independent), then re-check thatconfigurestill compiles and reads as intended after the merge. - Severity: High (merge blocker, no code logic involved)
- Raised by another reviewer: No
Issue 2: A WARN is logged for every configure call when the slot is invalidated, including snapshot-only jobs
- Location:
PostgresSourceFetchTaskContext.java:318-323 - Problem description: for a streaming job the warning is followed by the exception, so it appears once. For a snapshot-only job that runs on a stale invalidated slot name,
configureruns per snapshot split, so the same warning is repeated for every split. - Potential risk: log noise proportional to the split count, for a situation that is by design harmless for these jobs.
- Best improvement: log at WARN only when the job streams (just before throwing) and at DEBUG, or once per reader, when it does not.
- Severity: Low
- Raised by another reviewer: No
Issue 3 (carried over from my previous review, still open): No real-server guard for the invalidated-slot path
- Location:
PostgresCDCIT(no new case) and the new unit tests. - Problem description: coverage is unit level with mocked
Connection,ResultSetandResultSetMetaData. They prove the column handling, the error code, the ordering and the rollback, but not that a real PostgreSQL returns those column names and that the exception reaches the job as a failure. The PR description saysPostgresCDCITpasses and that PG 17.9 and 18.6 were verified manually, which is good evidence but not a regression guard. - Potential risk: a server-side column rename or shape change would not be caught in CI.
- Best improvement: if a deterministic invalidation is feasible in the test container (a tiny
max_slot_wal_keep_sizepluspg_switch_wal()and a checkpoint on PG 13+), add one IT case; otherwise a short note in the PR on why it is not feasible would be enough. - Severity: Medium (non-blocking, as before)
- Raised by another reviewer: No
My earlier low-severity notes are resolved: the FAQ now mentions the conflict-with-recovery reason, and the tests that were mock-interaction only now assert the thrown error code, the snapshotter call order and the returned slot state, so they fail if the guard, the order or the rollback is removed.
2. Code Quality Assessment
2.1 Coding Standards
Good. The new methods have Javadoc that explains why (slot-state retry loop, per-version columns, why shouldStream is asked after init), logging uses @Slf4j with slot-name context and no credentials, imports are explicit. The long SQL string is a single constant line and spotless handles it.
2.2 Test Coverage and Test Stability
Unit coverage: PG 17+ reasons, conflicting, wal_status = 'lost', servers without these columns, no row for the slot, the SQL parameter binding, error code and message, snapshot-only on an invalidated slot, invalidated streaming job (no slot-state read), healthy slot, and a failing check that rolls back and continues. I verified that all test changes are additions and that no existing assertion was weakened.
Stability rating: Stable. Pure mock-based unit tests with no sleeps, no static state, no containers and no ordering dependence (PostgresSourceFetchTaskContextTest.java, PostgresUtilsTest.java).
2.3 Documentation Updates
EN and ZH FAQ entries are consistent with each other and with the code (error code POSTGRES-04, recovery steps, startup.mode = initial, snapshot-only note, conflict with recovery). No option changes, so no option tables to update. Only the conflict in Issue 1 needs attention.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix. It sits at the single point where the slot state is first read, adds no connector-specific logic to shared engine, core or CDC base code, and degrades to the previous behavior if the check cannot run.
3.2 Maintainability
Good. The version-dependent column logic is isolated in one small, testable static method, and initSnapshotter is a package-private static that tests can call directly.
3.3 Extensibility
A future PostgreSQL invalidation signal can be added as another column check in readSlotInvalidationReason.
3.4 Historical-Version Compatibility
No impact on old checkpoints, savepoints, configs or serialization. PostgreSQL versions below 13 lack the columns and are treated as never invalidated, exactly as before. No connector, factory or registration changes are involved.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Merge conflicts with dev in the EN and ZH PostgreSQL-CDC docs |
docs/en and docs/zh PostgreSQL-CDC.md |
High (merge blocker) |
| 3 | No real-server (IT) guard for the invalidated-slot path (carried over) | PostgresCDCIT |
Medium (non-blocking) |
| 2 | WARN repeated per split for snapshot-only jobs on an invalidated slot | PostgresSourceFetchTaskContext.java:318-323 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers - must be fixed:
- Issue 1: sync with the latest
devand resolve the two docs conflicts. There is no source-level blocker in the connector code itself.
- Issue 1: sync with the latest
- Recommended fixes - non-blocking: Issue 3 (IT or a note on why not), Issue 2 (log level).
Overall assessment: a minimal, correct fail-fast improvement with no compatibility risk, and the review feedback from @nzw921rx is properly addressed and pinned by a test. There are no maintainer approvals or change requests to respond to besides @nzw921rx's comment-level review, which I agree with and consider resolved at this head.
CI and sync status at head fe87185e12c0: the apache-side Build check is timed_out; it points to the fork run https://github.com/goutamadwant/seatunnel/actions/runs/37155854578. I read the job list: all unit-test jobs (JDK 8 and 11, ubuntu and windows) and every executed integration-test job, including all updated-modules-integration-test shards and the CDC and connector ITs, completed successfully. The only non-success job is Build website, which was cancelled after running about 90 minutes (the log ends in an orphaned npm run build). This is not caused by the diff, and dev already contains the fix for that lane: #12614 (build only the current and latest released docs in the website check, merged 2026-10-05) and #12639 (ignore deepwiki.com in the dead-link check, merged 2026-10-07), neither of which is in this branch. So the next step is the same as for Issue 1: sync the latest dev (this brings both fixes) and push, which will rerun CI; after that a simple rerun of any single failing job should be enough. Thanks again for the careful work, and happy to take another look once it is rebased!
Signed-off-by: Goutam Adwant <workwithgoutam@gmail.com>
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks @goutamadwant for syncing with dev and resolving the docs conflicts! I re-reviewed the latest head 0a54255bcb from scratch (full PR diff against current dev, not only the new merge commit). The head only differs from my previous round (fe87185e12) by that dev merge: I compared the PR's own added and removed lines against the previous head and they are identical (connector code, tests, EN and ZH docs). So my earlier technical conclusion stands, and the merge-conflict blocker is now cleared.
What Problem Does This PR Solve?
- User pain point: when PostgreSQL invalidates a logical replication slot (
wal_status = 'lost',conflicting, orinvalidation_reasonon PG 17+), Postgres-CDC handed the slot to Debezium anyway, which retried for a long time or failed late with a generic error on every restore. - Fix approach: query
pg_replication_slotsbefore the slot state is read; if the slot is invalidated and the job streams, fail immediately with the new error codePOSTGRES-04and recovery steps. Snapshot-only jobs are not failed, and a failing check query degrades to the old behavior. - One-sentence summary: turn a long, opaque hang or late failure on an unusable slot into a fast, actionable error.
1. Code Change Review
1.1 Core Logic Analysis
Reader task start / restore / every snapshot split
-> PostgresSourceFetchTaskContext.configure(split)
-> initSnapshotter(...) (PostgresSourceFetchTaskContext.java:198, :303)
-> PostgresUtils.getReplicationSlotInvalidationReason (read-only catalog query, database = current_database())
-> SQLException: warn, rollback, behave as before
-> invalidated: do not read slot state; else getReplicationSlotState
-> snapshotter.init(config, offsetState, slotInfo) (:336)
-> invalidated && snapshotter.shouldStream() -> throw POSTGRES-04 (:338)
-> existing streaming setup (replication connection, queue, dispatchers) only if shouldStream()
- The normal start path reaches this logic, not only restore.
initruns beforeshouldStream(the ordering point raised by @nzw921rx), pinned bytestSnapshotterIsInitializedBeforeItIsAsked.- After the
devmerge the file still contains a singleloadStartingOffsetState(from #12454) and a singleinitSnapshottercall site, with no conflict markers left, so the two changes sit side by side in different regions as I expected. - The docs diff against
devis pure additions: both FAQ entries are kept in EN and ZH, and no existingdevtext was dropped.
1.2 Compatibility Impact
Fully compatible. No option, default, serialization format, checkpoint or savepoint change; POSTGRES-04 is appended after POSTGRES-03. The only behavior change is intended: a streaming job on an already unusable slot fails fast. PostgreSQL versions below 13 are treated as never invalidated, as before.
1.3 Performance / Side-Effect Analysis
One small catalog query per configure call next to the existing serverInfo() and slot-state queries. No new threads, buffers, retries or locks; statement and result set use try-with-resources.
1.4 Error Handling and Logging
No source blocker. Carried over from my previous round and still open (this is the same diff, so nothing new is being added):
Issue 1: No real-server guard for the invalidated-slot path
- Location:
PostgresCDCIT(no new case) and the new unit tests. - Problem description: coverage is mock-based (
Connection,ResultSet,ResultSetMetaData). It proves the column handling, error code, ordering and rollback, but not that a real PostgreSQL returns those column names. Your manual PG 17 and 18 checks are good evidence but not a CI guard. - Best improvement: if a deterministic invalidation is feasible in the test container (a tiny
max_slot_wal_keep_sizeplus WAL switches and a checkpoint on PG 13+), add one IT case; otherwise a short PR note on why it is not feasible is enough. - Severity: Medium (non-blocking)
- Raised by another reviewer: No
Issue 2: The WARN is repeated per snapshot split for snapshot-only jobs on an invalidated slot (PostgresSourceFetchTaskContext.java:318-323)
- Severity: Low (non-blocking). Log at WARN only when the job streams and at DEBUG otherwise, or once per reader.
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
Good: Javadoc explains why (per-version columns, why shouldStream is asked after init), @Slf4j, slot-name context in logs, no credentials, explicit imports.
2.2 Test Coverage and Test Stability
Unit coverage covers PG 17+ reasons, conflicting, wal_status = 'lost', servers without these columns, no row for the slot, parameter binding, error code and message, snapshot-only on an invalidated slot, healthy slot, and a failing check that rolls back and continues. All test changes are additions; nothing was weakened. Stability rating: Stable (mock-based, no sleeps, no static state, no containers, no ordering dependence).
2.3 Documentation Updates
EN and ZH FAQ entries are consistent with the code (POSTGRES-04, recovery steps, startup.mode = initial, snapshot-only note). No option changes.
3. Architectural Soundness
Precise fix at the single point where the slot state is first read, with no connector-specific logic leaking into shared code; easy to extend with another invalidation signal; no historical-version impact.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | No real-server IT guard for the invalidated-slot path (carried over) | PostgresCDCIT |
Medium (non-blocking) |
| 2 | WARN repeated per split for snapshot-only jobs | PostgresSourceFetchTaskContext.java:318-323 |
Low (non-blocking) |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers - must be fixed
- No source-level blockers. The only remaining gate is CI (see below).
- Recommended fixes - non-blocking
- Issue 1 and Issue 2 above.
Overall assessment: a minimal, correct fail-fast improvement with no compatibility risk, and @nzw921rx's feedback is addressed and pinned by a test. The branch is 0 commits behind dev and has no conflicts; GitHub reports it mergeable, with the merge state blocked only by review and checks.
CI state at the time of this review, for head 0a54255bcb (fork run https://github.com/goutamadwant/seatunnel/actions/runs/38089069569): still in progress. All unit-test jobs (JDK 11 and 17, ubuntu and windows), Code style, Build website, Dead links, the updated-modules-integration-test shards, mysql-cdc, oracle-cdc, paimon, iceberg, doris and redis connector ITs are green; kafka-connector-it was still running. elasticsearch-connector-it failed on both JDKs with ElasticsearchIT.testElasticsearchWithScrollSlice (count and ordering mismatch on a scroll-slice read). That test lives in the Elasticsearch connector, which this PR does not touch, so I read it as unrelated to this diff. Once the run finishes, a rerun of just that failed job should be enough; if it keeps failing after a rerun, please paste the new failing link here and I will help narrow it down. I am leaving this as a comment rather than an approval, since a maintainer with write access needs to do the final approval. Thanks again for the careful work!
…idated-slot Signed-off-by: Goutam Adwant <workwithgoutam@gmail.com>
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks again, @goutamadwant, for keeping this branch in sync with dev. I re-read the whole PR diff from scratch on head b3f42ea2 (7 files), not only the new merge commit. The head differs from my previous round (0a54255b) only by another merge of dev: I compared the PR's own added and removed lines against both heads and they are identical (connector code, tests, EN and ZH docs). This is a static review; I did not run the PR.
What Problem Does This PR Solve?
- User pain point: when PostgreSQL invalidates a logical replication slot (
wal_status = 'lost',conflicting, orinvalidation_reasonon PG 17+), Postgres-CDC still handed the slot to Debezium, which retried for a long time or failed late with a generic error. - Fix approach: query
pg_replication_slotsbefore the slot state is read; if the slot is invalidated and the job streams, fail immediately with the new error codePOSTGRES-04and recovery steps. Snapshot-only jobs are not failed, and a failing check query degrades to the old behavior. - One sentence: turn a long, opaque hang or late failure on an unusable slot into a fast, actionable error.
1. Code Change Review
1.1 Core Logic Analysis
Reader task start / restore / every snapshot split
-> PostgresSourceFetchTaskContext.configure(split)
-> initSnapshotter(...) (PostgresSourceFetchTaskContext.java:198, :303)
-> findSlotInvalidationReason -> PostgresUtils.getReplicationSlotInvalidationReason
(read-only catalog query, database = current_database())
-> SQLException: warn, rollback, behave as before
-> invalidated: skip getReplicationSlotState; else read slot state
-> snapshotter.init(config, offsetState, slotInfo)
-> invalidated && snapshotter.shouldStream() -> throw POSTGRES-04
-> replication connection / slot creation only if shouldStream()
- The normal start path reaches this code, not only recovery.
initruns beforeshouldStream(), which was the ordering point raised by @nzw921rx;testSnapshotterIsInitializedBeforeItIsAskedpins it.- The PostgreSQL version handling is correct: columns missing on older servers are skipped (
PostgresUtils.javareadSlotInvalidationReason), so PG < 13 is never reported as invalidated, exactly as before the change.
1.2 Compatibility Impact
Fully compatible. No option, default, serialization, checkpoint or savepoint change; POSTGRES-04 is appended after POSTGRES-03. The only behavior change is intended: a streaming job on an already unusable slot fails fast.
1.3 Performance / Side-Effect Analysis
One small catalog query per configure call next to the existing serverInfo() and slot-state queries. No new threads, buffers, retries or locks; statement and result set use try-with-resources.
1.4 Error Handling and Logging
No source-level blocker. Two carryovers from my earlier rounds (the diff is unchanged, so nothing new is added):
Issue 1: No real-server guard for the invalidated-slot path
- Location:
PostgresCDCIT(no new case) and the new unit tests. - Description: coverage is mock-based (
Connection,ResultSet,ResultSetMetaData). It proves the column handling, error code, ordering and rollback, but not that a real PostgreSQL returns those column names. Your manual PG 17 and 18 checks are good evidence but not a CI guard. - Best fix: if a deterministic invalidation is feasible in the test container (tiny
max_slot_wal_keep_size, WAL switches, checkpoint on PG 13+), add one IT case; otherwise a short PR note on why it is not feasible is enough. - Severity: Medium (non-blocking). Raised by another reviewer: No.
Issue 2: The WARN is repeated per snapshot split for snapshot-only jobs on an invalidated slot (PostgresSourceFetchTaskContext.java:318-323)
- Severity: Low (non-blocking). Log at WARN only when the job streams, and at DEBUG otherwise (or once per reader).
- Raised by another reviewer: No.
2. Code Quality Assessment
2.1 Coding Standards
Good: Javadoc explains why (per-version columns, why shouldStream is asked after init), @Slf4j, slot name in logs, no credentials, explicit imports.
2.2 Test Coverage and Test Stability
PostgresSourceFetchTaskContextTest covers init-before-ask, fail-fast on an invalidated streaming job, snapshot-only on an invalidated slot, and a failing check that rolls back and still reads the slot state. PostgresUtilsTest covers PG 17+ reasons, conflicting, wal_status = 'lost' and servers without these columns. All changes are additions; no existing assertion was weakened. Stability rating: Stable (mock-based, no sleeps, no static state, no containers). The tests have failing power: calling shouldStream() before init makes the InitRequiredSnapshotter throw, and dropping the invalidation branch breaks the fail-fast test.
CI on head b3f42ea2: the Build run in the fork is still in progress (8 jobs done and green, others queued), so there is no final result yet. The previous head's run failed only in elasticsearch-connector-it (11 and 17), which does not touch Postgres-CDC.
2.3 Documentation Updates
EN and ZH FAQ entries match the code (POSTGRES-04, recovery steps, startup.mode = initial, snapshot-only note). No option changes.
3. Architectural Soundness
- 3.1 The fix sits at the single point where the slot state is first read, with no connector-specific logic leaking into shared code.
- 3.2 It is easy to extend if PostgreSQL adds another invalidation signal.
- 3.3 No effect on engine, checkpoint format or already released versions.
- 3.4 The branch is up to date with
dev(0 behind), no conflicts.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | No real-server IT guard for the invalidated-slot path (carryover) | PostgresCDCIT |
Medium (non-blocking) |
| 2 | WARN repeated per split for snapshot-only jobs (carryover) | PostgresSourceFetchTaskContext.java:318-323 |
Low (non-blocking) |
5. Merge Recommendation
Conclusion: Ready to merge
Blockers - must be fixed
- None in the source. The only remaining gate is CI: please wait for the current
Buildrun on this head to finish (the earlier ES IT failure was unrelated; if it recurs, rerun only the failed job).
Recommended fixes - non-blocking
- Issues 1 and 2 above.
Overall assessment: the change is small, correctly placed, compatible and well tested at unit level. Alternative considered: failing inside Debezium's own slot handling would need a fork of Debezium code, so the current approach is the right trade-off. Thanks for the careful work, and happy to take another look if you push an update!
DanielLeens
left a comment
There was a problem hiding this comment.
Following up on my earlier review of head b3f42ea: the only remaining gate I listed was CI, because the fork Build run was still in progress. That run has now completed successfully for this head, so the CI blocker is cleared. I have no remaining source, test, docs, or compatibility blockers (Issues 1 and 2 stay as non-blocking follow-ups), so I am changing my conclusion to approve. Thanks again, @goutamadwant!
davidzollo
left a comment
There was a problem hiding this comment.
Thank you @goutamadwant for this contribution, and for failing fast when the Postgres-CDC replication slot is unusable, which turns a confusing downstream failure into a clear, actionable error.
CI is green on the current head and the code-side review has no remaining blockers, so I am approving. Really appreciate the time and care you put into this PR - contributions like this make SeaTunnel better for everyone. Looking forward to more from you!
Purpose of this pull request
Fix #12585.
PostgreSQL 13+ can invalidate a replication slot (
max_slot_wal_keep_size,idle_replication_slot_timeouton 18). Postgres-CDC passed such a slot to Debezium, which then either looped on the slot state for about 30 minutes (wal_removed) or failed after a minute of stream retries (idle_timeout), on every pipeline restore and with no hint about the slot.PostgresSourceFetchTaskContext.configure()now checkspg_replication_slotsbefore Debezium uses the slot, when the job streams:invalidation_reason(PostgreSQL 17+) is set,conflicting(16+) is true, orwal_status(13+) islost. Only columns the server returns are read, so older servers are unaffected.POSTGRES-04, which names the reason and how to recover (drop the slot, restart without restoring state).Does this PR introduce any user-facing change?
Yes. A job on an invalidated slot now fails quickly with
POSTGRES-04instead of hanging or failing with a Debezium error. Documented in the PostgreSQL-CDC FAQ (en, zh).job.retry.times = 3)idle_timeout, restorePOSTGRES-04wal_removed, restorePOSTGRES-04How was this patch tested?
PostgresUtilsTest(PostgreSQL 17+ reasons,conflicting,wal_status = lost, servers without these columns) and a newPostgresSourceFetchTaskContextTest(snapshot-only skips the query, invalidated slot throws, healthy slot passes, query error rolls back)../mvnw -pl seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres testpasses on JDK 8 and JDK 11.PostgresCDCITpasses locally.Check list
New License Guide
incompatible-changes.mdto describe the incompatibility caused by this PR.