Repository navigation
[Fix][Connector-V2] Backfill PostgreSQL WAL during CDC snapshots - #13310
DanielLeens wants to merge 33 commits into
Conversation
…res-snapshot-backfill
ForkJoinPool.commonPool() has only three workers on 4-vCPU GitHub runners. The blocking job future plus three gate-blocked concurrent DML futures need four workers at once, so the third DML never started and countSourceChangesWaitingForTableLock could never reach 3.
…rom a non-terminal enumerator close SnapshotSplitAssigner#close() unconditionally called dialect.closeEnumerator(), which for PostgreSQL can drop the persistent streaming replication slot created for an exactly-once initial snapshot (guarded by slot.drop.on.stop). The enumerator's close() fires whenever Zeta tears down the split enumerator for ANY reason - genuine job stop, a master failover, or a stop-with-savepoint restart - and the framework gives no signal distinguishing these. Dropping the slot on a non-terminal close silently breaks the job's ability to resume: the restarted job needs that exact slot and its confirmed_flush_lsn to continue WAL backfill without a gap. The real risk window is when a HybridSplitAssigner's snapshot phase is closed: its incremental phase depends on the very same slot for the rest of the job's lifetime, so this assigner can never safely be the one to drop it - unlike a SnapshotOnlySplitAssigner (bounded jobs), where a durably, checkpoint-confirmed completed snapshot really does mean there is no later phase left to protect. Fix: thread a releasesEnumeratorResourcesOnCompletion flag through SnapshotSplitAssigner, set false when constructed by HybridSplitAssigner and true when constructed by SnapshotOnlySplitAssigner. close() now only releases dialect-owned enumerator resources when that flag is true AND the snapshot phase has durably completed (assignerCompleted), instead of on every close() call - closing the same failure class for a mid-snapshot restart on bounded jobs too, using state the assigner already tracks and checkpoints. PostgresDialect is the only DataSourceDialect implementation that overrides closeEnumerator() today, so no other CDC connector's behavior changes. Adds 3 unit tests on SnapshotSplitAssigner proving: a standalone (SnapshotOnlySplitAssigner-shaped) assigner releases resources once completed; a Hybrid-shaped assigner never releases them even once completed; and a standalone assigner does not release them before completion.
…59a984 # Conflicts: # seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/reader/PostgresSourceFetchTaskContext.java
…SQL CDC backfill Addresses non-blocking follow-ups 3, 5, 7 and 8 (and folds in 2/6) from the SEZ9 review round on PR apache#11556, on top of the already-merged fix for the blocking Issue 1 (terminal-vs-transient enumerator close): - Issue 8: HybridSplitAssigner.close() now uses try/finally so a failure closing the snapshot assigner (which can do replication-slot network I/O) no longer skips closing the incremental assigner and leaking whatever it owns. - Issues 2/6: SnapshotSplitAssigner tracks whether dialect.openEnumerator has an outstanding, not-yet-closed call. open()'s catch-block cleanup and close()'s completion-gated cleanup now share that guard, so dialect.closeEnumerator can no longer be invoked twice for one openEnumerator (previously a slot-dropping dialect would fail with "slot does not exist" on the second call). openEnumerator is now called from inside open()'s try block so a partial failure there is also covered by the catch-side cleanup. - Issue 3 (and 5, which it subsumes): PostgresSourceConfigFactory now validates slot.name against [a-z0-9_]{1,63} at config-factory time, failing fast at job submission instead of a late failure once the backfill slot lifecycle starts. This also makes the existing char-count-based truncation in PostgresSourceConfig provably byte-accurate, since the validated charset is guaranteed single-byte ASCII -- documented on both call sites instead of duplicating the length-limit logic. - Issue 7: documented the max_replication_slots capacity requirement (parallelism + 1) in all four PostgreSQL/OpenGauss EN/ZH docs. - Updated the three existing close() gating tests to call open() first, matching real enumerator lifecycle usage now that close() only releases resources open() actually acquired, and added a regression test for the double-close fix. Issue 4 (deterministic backfill slot name collision after a reader crash) is intentionally not addressed here: a correct fix needs a drop-if-exists-with-retry (or per-attempt naming) change inside Debezium's own replication-connection construction path, which I can't safely design and verify without a real PostgreSQL failure- injection test bed. Flagging it in the PR comment as a follow-up rather than guessing at retry/backoff semantics. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Resolve the merge conflicts with dev: SnapshotSplitAssignerTest keeps both sides' new tests, and the shared helper takes dev's currentParallelism parameter together with this branch's releasesEnumeratorResourcesOnCompletion argument. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Thanks for preserving the review continuity from #11556 in this Apache SeaTunnel resubmission. +1 to @nzw921rx's existing bounded-WAL finding. Sorry for missing the test-cleanup failure path in the earlier review; the additional test item below is a carryover in unchanged code, not a newly introduced issue.
What problem does this PR solve?
User pain: snapshot-time DML can be omitted when PostgreSQL skips the low-to-high WAL reconciliation. Fix: create the persistent streaming slot before assigning snapshots and read a separate bounded per-reader backfill slot before END. In one sentence: reconcile the snapshot with changes committed during its read. Example: a row deleted while the snapshot query runs must not survive forever downstream after incremental reading starts at the high watermark.
1. Code changes
1.1 Core logic
Before: PostgresSnapshotFetchTask used if (true) to emit END without WAL reconciliation.
After: it skips only when low/high are unchanged or streaming is disabled; otherwise PostgresWalSplitReadTask sets streamingStoppingLsn and invokes Debezium.
Hybrid/SnapshotSplitAssigner.open -> dialect.openEnumerator -> persistent streaming slot
-> snapshot reader configure: exact table filter + isolated per-subtask backfill slot
-> LOW -> snapshot SELECT -> HIGH
-> changed && shouldStream: bounded WAL reader from LOW to HIGH
-> PostgresStreamingChangeEventSource.processMessages (268-281)
-> lastCompletelyProcessedLsn reaches stop -> END watermark
-> snapshot reconciliation buffer finishes -> incremental split starts
finally -> verify/drop backfill slot; cancellation stops reader context
Key findings: exactly-once initial snapshots reach the fix; ordinary streaming and non-exactly-once filters keep their config. Streaming slot bootstrap precedes LOW. Publication replication retains the complete captured-table filter while dispatch scopes to one split. Pattern.quote protects regex metacharacters. Removing txid_current avoids artificial WAL generation but cannot prove completion when other databases advance instance WAL. END is still dependent on a decodable event progressing lastCompletelyProcessedLsn.
1.2 Compatibility
Mostly compatible: APIs add a default no-op hook, legacy fetch-context constructor remains, task/state format is unchanged, and the removed optional txid watermark key is tolerated by offset loading. Invalid effective slot names fail earlier. Operators now need parallelism+1 slots during initial snapshots and must clean abandoned persistent slots; these operational prerequisites are documented.
1.3 Performance and side effects
One persistent streaming slot plus a bounded reader slot per parallel reader, with additional WAL reads and per-split slot create/drop overhead. The server slot is persistent and can retain WAL after abrupt loss; manual orphan cleanup is documented. No new shared engine lock. The unfinished bounded reader can hold the snapshot/reconciliation pipeline and retain server WAL indefinitely, so the existing peer blocker is significant.
1.4 Errors, logging, and findings
+1 to @nzw921rx's predecessor change request: PostgresStreamingChangeEventSource.java:268-281 advances completion only while processing decoded messages. If only another database advances WAL between LOW/HIGH, this source can receive no event that reaches HIGH; the loop never returns, END is never emitted, and snapshot completion stalls. Removing txid_current does not close that independent trigger. Please establish a decoder-aware progress/boundary protocol and add the cross-database WAL regression; an idle timeout that emits END without proof would risk data loss. This is the same peer point, not a new numbered duplicate.
Issue 1: test cleanup can exit before shutting down its pool (High, blocking; earlier omission). Location: seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-postgres-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/PostgresCDCIT.java:551-589. In the new test's finally block, waiting a DML future, asserting the job future, cancelling the job or asserting slot cleanup can throw before shutdownNow and table cleanup execute. The fixed pool uses non-daemon workers; a failure can therefore leave its job wait/pool running and contaminate later tests. Wrap the whole cleanup in a nested finally that always shuts down the executor and closes remaining JDBC gates, preserving the first failure with suppressed cleanup errors. This is the smallest fix at the test-owned resource boundary; the global principle is unconditional cleanup, not a larger production change. No peer has raised this cleanup point.
2. Code quality
2.1 Conventions
Core backfill fields and lifecycle methods explain ownership and slot limits. The existing fully-qualified PostgresSchema local and some helper commentary remain minor follow-ups; they do not replace the completion protocol blocker.
2.2 Test coverage and stability
Stability rating: high risk for PostgresCDCIT.java:551-589 because failing cleanup can leak the non-daemon executor (Issue 1). The normal test uses lock observation, explicit futures and actual source/sink equality instead of fixed sleeps, which is good. It covers concurrent source-table DML, but lacks the other-database-only WAL regression required by the peer review. Unit tests pin effective slot validation, length/collision behavior and regex quoting. Longer existing CDC wait budgets are visible and must remain tied to the same exact data assertions.
2.3 Documentation
All four EN/ZH PostgreSQL/OpenGauss pages document persistent streaming/backfill slots, orphan cleanup, pass-through syntax and slot capacity. The documented cleanup is normal/handled-failure behavior, not an abrupt-crash guarantee.
3. Architecture
3.1 Change location
The PostgreSQL reader is the correct owner of bounded-WAL progress and slot lifecycle. A generic default enumerator-open hook supplies the necessary ordering without putting PostgreSQL behavior in the engine. The smallest safe completion fix needs decoder progress proof; a broad CDC rewrite or arbitrary timeout is not justified.
3.2 Maintainability
Keep replication connection config separate from per-split dispatch config, and preserve cleanup failures rather than reporting successful snapshot completion when cleanup did not finish.
3.3 Extensibility
A decoder-aware bounded-progress contract should be reusable across PostgreSQL/OpenGauss; each vendor still needs real native validation. Do not infer cross-database decoder progress from the cluster current-LSN query alone.
3.4 Upgrade impact
This resubmission retains the exact predecessor head and therefore its outstanding peer blocker. Earlier ready-to-merge/approval conclusions are superseded. No claim of independent approval is made for this self-authored draft.
4. Findings summary
| # | Finding | Location | Severity |
|---|---|---|---|
| 1 | Unconditional test executor cleanup is missing | PostgresCDCIT.java:551 |
High |
5. Merge recommendation
Do not merge until bounded WAL completion and test cleanup are fixed.
Blocking items: The existing @nzw921rx bounded-progress blocker and Issue 1, followed by exact-head CI and independent maintainer review. Keep the PR draft while these remain.
Non-blocking suggestions: Track per-split slot churn and deterministic per-reader slot reuse after a crash; the current docs already require operator cleanup.
The snapshot-loss defect is real, but completion must be safe even when this database has no decodable event. Preserving the predecessor finding avoids treating resubmission or old green CI as a fix.
Current CI diagnosis. The exact-head fork Build fails before connector tests: Code style fails compiling seatunnel-ci-tools with Lombok TypeTag :: UNKNOWN, and changes cannot install Python 3.11.0 on Ubuntu 26.04. The current branch predates upstream #12964, which pins JDK 17 for Code style and selects the supported Python 3.11 patch series. That fix is in dev and absent from this head. Please sync the latest dev and rerun Build first; no unrelated connector dependency patch is needed for these two workflow failures. The bounded-WAL and test-cleanup source blockers above remain independent. The Apache success shown below does not override this failed fork execution.
CI and repository state: Label PRs when reviewed: SUCCESS; Notify test workflow: SUCCESS; labeler: SUCCESS; Build: SUCCESS; Build: failure. GitHub reports BLOCKED / REVIEW_REQUIRED.
Verification: Reviewed all changed files and the referenced call sites at dbc53649a3c17794d692ecc972db54a12401ace8 against merge base 4dcfa28ccc85837edf8ca08e459ae56ddc1b34fd. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for continuing the Apache SeaTunnel backfill work. I re-read the complete current diff and the repository-owned Debezium loop. The slot isolation, lifecycle documentation and numeric offset handling are useful, but the previously identified completion blocker and cleanup Issue 1 remain; the current changes do not close them.
What problem does this PR solve?
User pain: DML committed while an initial PostgreSQL snapshot is scanned can fall between the scanned rows and the incremental HIGH position when backfill is unconditionally skipped.
Proposed fix: Prepare the streaming slot before LOW; give each snapshot reader an isolated bounded-backfill slot and reconcile LOW..HIGH before END.
In one sentence: The PR tries to preserve writes made while the initial snapshot is being read. For example, an update to an already-scanned customer should appear in the reconciled snapshot rather than disappear at the transition to streaming.
1. Code changes
1.1 Core logic
Complete runtime path:
SnapshotSplitAssigner.open -> dialect.openEnumerator -> prepare configured persistent streaming slot
-> per-reader PostgresSourceFetchTaskContext.configure -> derived backfill slot, exact dispatch table filter
-> snapshot SELECT: LOW -> rows -> HIGH
-> PostgresSnapshotFetchTask.execute: non-exactly-once returns; unchanged/snapshot-only emits END
-> changed exactly-once range -> PostgresWalSplitReadTask.execute -> stopping LSN=HIGH
-> repository PostgresStreamingChangeEventSource.processMessages: decoded messages advance lastCompletelyProcessedLsn
-> only after reader returns without producer error: END
-> IncrementalSourceScanFetcher.pollSplitRecordsIfExactlyOnce merges keyed changes and releases normalized rows
-> finally drops the backfill slot; incremental reader retains configured slot; shutdown flips taskRunning and closes context
Key findings and correctness:
The normal exactly-once initial-snapshot path reaches this change when HIGH exceeds LOW. This is a real correctness repair, rather than a cosmetic switch: the previous unconditional branch prevented reconciliation. The new enumerator hook is a default no-op for other dialects; PostgreSQL enables it only for INITIAL plus exactly_once. Backfill names retain the reader suffix within 63 ASCII bytes and hash the full configured slot before truncation. Configuration validation checks the effective Debezium override as well as the SeaTunnel option.
The dispatch table filter is Pattern.quote(schema + dot + table), while replication setup preserves the original capture set; this avoids rewriting a shared pgoutput publication to one reader table. Heartbeats and Debezium automatic slot dropping are disabled for the bounded reader, and cleanup verifies the derived slot separately. Serialized string offsets are converted to numeric values, preserving the message-operation enum. Producer failures are propagated; cleanup failure is suppressed onto an existing failure. These are useful improvements.
The completion proof has not changed: PostgresStreamingChangeEventSource.java:268-281 compares HIGH with lastCompletelyProcessedLsn, which advances inside the decoded-message callback; the no-message branch at 380-389 does not advance it. Removing txid_current from currentLsn avoids one artificial-WAL source, but does not prove that every cluster-wide HIGH is decodable by this database. The existing cross-database finding therefore remains blocking. No idle timeout should fabricate END, because that could release an incompletely reconciled snapshot.
Before:
if (true) {
dispatchBinlogEndEvent(...);
return;
}After (key branches):
if (!changed || !sourceFetchContext.getSnapshotter().shouldStream()) {
sourceFetchContext.closeReplicationConnection();
dispatchBinlogEndEvent(...);
return;
}
backfillReadTask.execute(...);
// Reader: setStreamingStoppingLsn(HIGH); super.execute(...); emit END only afterward.1.2 Compatibility
Partially incompatible operationally: existing option names and defaults, public row formats and saved split offsets remain intact, but an exactly-once INITIAL job transiently needs N+1 replication slots and can retain orphan backfill slots after abrupt failure. Effective invalid slot names now fail early. The bilingual PG/OpenGauss documentation explains slot capacity and manual orphan handling. Coordinate capacity before upgrading such jobs; this is not a new mixed-version wire protocol.
1.3 Performance and side effects
The new initial-snapshot path adds one replication connection/slot per active reader and retains the snapshot reconciliation buffer until END; the unresolved wait can therefore retain both memory and server WAL indefinitely. Hashing is initialization-only. Snapshot dispatch remains reader-local; no new per-row global lock is introduced. Normal cleanup drops temporary slots, but process loss explicitly requires operator cleanup. CPU/network traffic increase during intentional backfill; concurrency is separated by derived slot names.
1.4 Errors, logging, and findings
Issue 1: Ensure cleanup survives an earlier cleanup assertion
- Location:
seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-postgres-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/PostgresCDCIT.java:533. - Description and risk: Retained Issue 1 from my previous review: in the test finally block, waitForAsyncTask, join/assertJobHasNoAsyncFailure, cancel-job exit assertions and slot-disappearance waits may throw before asyncTaskExecutor.shutdownNow and both clearTable calls. A failing test can therefore leave its non-daemon pool and shared source/sink state behind, obscuring the first failure and contaminating later cases.
- Best improvement: Put executor shutdown and shared-table cleanup in nested unconditional finally blocks; attempt every cleanup, retain the original failure and attach cleanup failures as suppressed exceptions.
- Responsibility and trade-off: The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
- Severity: High; blocking: true.
- Previously raised by another reviewer: No, unless explicitly attributed above.
+1 to @nzw921rx's predecessor review 5647827945 and inline P1. This resubmission still uses the same decoded-event completion condition. In the current head, see PostgresWalFetchTask.java:203-216, PostgresStreamingChangeEventSource.java:268-281 and IncrementalSourceScanFetcher.java:148-201. If another database alone advances cluster WAL during this database's snapshot, HIGH can exceed LOW without a decoded source-database event to advance the stopping condition. END and buffered snapshot delivery then wait indefinitely. Please implement a decoder-aware, transaction-complete boundary protocol and add the idle-captured-database/cross-database-WAL regression. PostgreSQL documents that a logical slot streams changes from a single database. I agree with that change request; I am not duplicating it as a new Daniel issue. There is no independent approval on this resubmission to override this blocker.
2. Code quality
2.1 Conventions
Reviewed all changed files for license, imports, naming, core-method and state-field comments. See the numbered findings for the required changes.
2.2 Test coverage and stability
Stability rating: High risk. Read both changed UT classes, both CDC IT changes and the complete new configuration. Slot length/hash/isolation and regex-metacharacter cases are deterministic. The PostgreSQL IT uses an observed slot, a table-lock gate, three observed queued DML operations, bounded futures, exact ordered source/sink equality and slot cleanup; the dedicated four-thread executor avoids common-pool starvation. Longer OpenGauss/PostgreSQL waits retain the original equality oracle. However, the new IT always writes to the captured database, so it does not cover the peer cross-database idle case. Its finally block still has the failure-cleanup defect below. Observing the slot and then acquiring the lock is also not an atomic snapshot-start handshake: a sufficiently fast snapshot may finish before the gate is acquired; a test-controlled pre-SELECT signal would make that gate stronger. No local tests were run.
2.3 Documentation
Read all four changed English/Chinese PG and OpenGauss sections. They consistently describe the configured streaming slot, per-reader persistent backfill slots, N+1 capacity, slot.drop.on.stop pass-through and manual crash cleanup. Their normal/handled-failure cleanup promise still needs the bounded reader to complete. No unrelated documentation change is needed.
3. Architecture
3.1 Change location
The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
3.2 Maintainability
Keep the behavior, lifecycle ownership, and failure contract together. The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
3.3 Extensibility
Prefer the existing component boundary and tests over unrelated shared abstractions.
3.4 Upgrade impact
Partially incompatible operationally: existing option names and defaults, public row formats and saved split offsets remain intact, but an exactly-once INITIAL job transiently needs N+1 replication slots and can retain orphan backfill slots after abrupt failure. Effective invalid slot names now fail early. The bilingual PG/OpenGauss documentation explains slot capacity and manual orphan handling. Coordinate capacity before upgrading such jobs; this is not a new mixed-version wire protocol.
4. Findings summary
Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.
| # | Finding | Location | Severity |
|---|---|---|---|
| Peer P1 | Bounded backfill may never emit END | PostgresStreamingChangeEventSource.java:268-281 |
High |
| 1 | Ensure cleanup survives an earlier cleanup assertion | seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-postgres-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/PostgresCDCIT.java:533 |
High |
5. Merge recommendation
Merge after fixes
Blocking items: The existing peer P1 cross-database bounded-backfill completion blocker, plus retained Issue 1. Current-head CI and write-capable maintainer review remain independent requirements.
Non-blocking suggestions: None beyond the validation limits above.
Overall: the approach addresses a real path, but the listed blockers must be closed. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.
CI and repository state: Signal pull request update: SUCCESS; Build: IN_PROGRESS; Build: queued. GitHub reports BLOCKED / REVIEW_REQUIRED.
Verification: Reviewed all changed files and the referenced call sites at 89f5df44290a53dae01505ce99d6c6b9516e153b against merge base efecb179a100d0a621566ba1b0c015357f55c168. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.
Review time: 2026-11-23T08:31:19.597842-05:00
Local evidence: git fetch obtained head 89f5df44290a53dae01505ce99d6c6b9516e153b; git merge-base returned efecb179a100d0a621566ba1b0c015357f55c168; git diff --stat reports 18 files changed, 1310 insertions(+), 33 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for keeping this moving. The CI fact in my previous full review has changed: Build 45016489435 has completed as FAILURE, rather than remaining queued. All four unit-test lanes failed; I inspected Windows/JDK11 job 137296258642. IncrementalSourceEnumeratorTest.shouldEnterIncrementalPhaseWithMultipleReadersAndEnumeratorCheckpoints fails at 139 with Failed to open snapshot split assigner, caused by UnsupportedOperationException: openEnumerator from its testDialect proxy at 401.
The source chain explains this result: this PR adds dialect.openEnumerator(sourceConfig) in SnapshotSplitAssigner.open at 152, while that existing test proxy does not support the hook. I compared the affected assigner/test with latest dev dfdee68: neither has a matching upstream change from this PR base, so a blind sync is not a verified fix. Update the existing controlled dialect fixture to honor the new lifecycle call and rerun the unit lanes; do not weaken or remove the regression assertion.
The earlier peer bounded-backfill completion blocker and my retained cleanup Issue 1 remain unchanged. This note updates the newly available CI evidence; it does not claim those source blockers are closed or start another full source review on this head.
5. Merge recommendation
Conclusion: Merge after the retained fixes and repository gates
Blocking items: The retained source/test/documentation requests referenced above, plus completed applicable CI.
Non-blocking suggestions: No new source finding is added in this CI follow-up.
Checked unchanged head 89f5df44290a53dae01505ce99d6c6b9516e153b against dev: compare diverged, ahead 25 / behind 13. Branch drift is recorded independently. Daniel has READ permission; this COMMENT cannot dismiss historical change requests or replace write-capable maintainer approval. No local build, test, or runtime execution was performed.
Implementation Notes and Trade-offsHead: Problem and execution pathThe original backfill implementation now reads WAL between snapshot LOW and HIGH, but its completion condition advanced only inside decoded-message callbacks. PostgreSQL WAL positions are cluster-wide while a logical slot decodes one database. Therefore, WAL generated only in another database can make HIGH greater than LOW without producing a callback for the captured database, leaving the snapshot reader waiting forever and never emitting END. The corrected path is: Final implementation
The no-event completion rule follows PostgreSQL own Alternatives evaluated and not used
Assumptions and constraintsVerified from source:
Pending remote verification:
Verification performed
Exact-head CI feedback and follow-up
Follow-up verification performed
Restore-safety follow-upFinal current-head review found one additional correctness boundary in the same persistent-slot lifecycle. On enumerator restore, a missing configured streaming slot was previously recreated at the server's current position. PostgreSQL's logical replication protocol starts at the greater of the requested LSN and the slot's Commit Verification for this follow-up:
Bounded resume-search follow-upThe exact-head Java 11 part-2 run showed that the other-database WAL E2E still timed out before the new bounded completion proof ran. Logs showed the backfill entering Debezium Commit The branch was then merged normally with current Exact-head CI result and external XA prerequisiteExact-head CI for
The MySQL CDC Java 17 lane failed twice at This failure is outside the PostgreSQL changes and already has contributor-owned fixes:
The #13109 diff matches the observed missing-middle-XID failure, so this PR will not duplicate or absorb that contributor work. #13310 remains Draft until the prerequisite lands, latest Live prerequisite reconciliation: #13109 is 182 commits behind current |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for contributing to Apache SeaTunnel! I reviewed the complete current diff and followed its entry points and failure paths. The items below need attention before merging; I hope the concrete paths make the next step straightforward.
What problem does this PR solve?
User pain: PostgreSQL exactly-once snapshots skip WAL reconciliation (the old branch is literally if (true)), so a row changed during a snapshot can be stale or missing when incremental reading starts at its high watermark.
Change: Prepare a durable streaming slot before snapshot watermarks, give each snapshot reader a separate bounded backfill slot, replay LOW..HIGH through the existing reconciliation buffer, and detect WAL progress even when no captured-table message is decoded.
In one sentence: Reconcile concurrent source changes before publishing snapshot rows. Example: id=5000 updated during its scan must leave the new value in the snapshot output before incremental reading advances.
1. Code changes
1.1 Core logic
Complete runtime path:
IncrementalSource.createEnumerator / restoreEnumerator -> DataSourceDialect.openEnumerator(config, restored)
PostgresDialect -> exactly-once INITIAL: create/validate persistent configured streaming slot before split assignment
Reader config(factory subtask ID) -> PostgresSourceFetchTaskContext.configure(snapshot) -> per-reader derived slot + exact split-table dispatcher; replication connection retains full captured-table publication filter
PostgresSnapshotFetchTask -> LOW -> SELECT rows -> HIGH
unchanged or snapshot-only -> close unused connection/drop backfill slot -> END
changed exactly-once -> PostgresWalSplitReadTask -> load numeric LOW offset -> bounded stop HIGH
PostgresStreamingChangeEventSource -> no recovery search for fresh bounded reader -> decode messages / raw WAL receipt progress -> stop
-> propagate producer error; successful running context emits END -> scan fetcher merges CREATE/UPDATE and removes DELETE by key -> normalized snapshot output
Finally -> explicit idempotent backfill slot drop/check; configured streaming slot retained for incremental phase
Non-exactly-once and unbounded incremental reader retain their existing selection/lifecycle paths
Key findings and correctness:
- This activates a real previously bypassed branch on the normal exactly-once snapshot path; it is not merely a log change. IncrementalSourceScanFetcher consumes LOW/snapshot/HIGH/WAL/END and JdbcSourceFetchTaskContext rewrites inserts/updates and removes deletes in its reconciliation map.
- Separate reader slots avoid PostgreSQL's single-active-consumer restriction. Name hashing preserves the 63-byte ASCII limit and reader suffix; exact table regex prevents accidental wildcard matches. Full publication filtering remains on the replication connection to avoid competing per-table publication replacement.
- Bounded backfill starts fresh at LOW without unbounded resume-position search; stopping uses processed LSN or observed received WAL after idle reads, handling other-database WAL without inventing a decoded row. OpenGauss exposes raw receive progress through its wrapper.
- Cleanup explicitly checks the backfill slot instead of relying only on Debezium's swallowed shutdown errors; producer errors are rethrown before END. A crash can still leave a persistent orphan, correctly documented.
- Restored exactly-once INITIAL jobs now reject a missing configured streaming slot instead of recreating it at a later position. This is a safety improvement with a real upgrade contract. The two remaining requests are deterministic regression proof and the central migration entry, not an objection to enabling reconciliation.
Before:
// todo Add backfill task
if (true) {
dispatchBinlogEndEvent(...);
taskRunning = false;
return;
}After:
if (!changed || !sourceFetchContext.getSnapshotter().shouldStream()) {
sourceFetchContext.closeReplicationConnection();
dispatchBinlogEndEvent(...);
return;
}
backfillReadTask.execute(context, partition, loadOffsetContext(lowOffset));1.2 Compatibility
Partially incompatible operationally: existing valid slots/checkpoints keep their formats, and the new dialect hook is a default method, but restored exactly-once INITIAL jobs with missing slots now fail rather than recreate. Snapshot slot consumption grows to at least parallelism+1; temporary application-managed slots are persistent server objects requiring crash cleanup. The old public context constructor is retained as a delegating overload. Numeric offset conversion retains serialized string keys; removal of newly generated txid_current calls avoids artificial WAL progress without removing old checkpoint loader support.
1.3 Performance and side effects
Exactly-once snapshots now incur bounded WAL reads, per-reader replication connections/slots, reconciliation CPU and queue/buffer work already owned by the scan fetcher. Idle PostgreSQL progress polling adds status-update/catalog queries; it is bounded-mode only but should be validated with least-privilege users and actual drivers. Configured streaming slot intentionally retains WAL across snapshot; orphan slots retain disk until operator cleanup. Cancellation context exits the Debezium loop; no claimed measured throughput or global exactly-once target guarantee.
1.4 Errors, logging, and findings
Issue 1: Make the snapshot/backfill regression window deterministic
- Location:
seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-postgres-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/PostgresCDCIT.java:515. - Description and risk: The new tests first start the asynchronous job, then poll for its backfill slot and acquire a table lock. There is no barrier preventing the snapshot SELECT from completing before the polling thread acquires that lock. The test can subsequently wait for a SELECT that has already finished. Further, the final upserting target can be repaired by incremental events if the queued DML commits after HIGH, so equality alone does not prove LOW..HIGH reconciliation. This is a timing-dependent acceptance oracle for the main correctness change.
- Best improvement: Establish an observable test-owned barrier after LOW and before snapshot completion, ensure INSERT/UPDATE/DELETE commits before HIGH, and verify the backfilled snapshot image or show the case fails when backfill is disabled. Retain the other-database/no-decoded-message case with the same reliable window.
- Responsibility and trade-off: The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
- Severity: High; blocking: true.
- Previously raised by another reviewer: No, unless explicitly attributed above.
Issue 2: Record the changed restore and slot-capacity contract in upgrade notes
- Location:
seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresDialect.java:127. - Description and risk: Existing exactly-once INITIAL checkpoint restores can now fail when the configured slot is missing, and initial snapshots require an additional slot per parallel reader. The connector FAQs explain this, but neither incompatible-changes.md is updated. Operators upgrading an existing checkpoint need this behavior change in the central migration checklist.
- Best improvement: Add matching EN/ZH incompatible-change entries identifying affected modes, the fail-closed missing-slot behavior, parallelism+1 capacity, crash-orphan cleanup, and migration to a valid original slot/checkpoint or fresh initial snapshot. No new configuration or unrelated redesign is needed.
- Responsibility and trade-off: The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
- Severity: Medium; blocking: true.
- Previously raised by another reviewer: No, unless explicitly attributed above.
Community input: no independent technical finding or maintainer approval/change request was present in the collected discussion.
2. Code quality
2.1 Conventions
Reviewed all changed files for license, imports, naming, core-method and state-field comments. See the numbered findings for the required changes.
2.2 Test coverage and stability
Stability rating: High risk. High risk at the new PostgreSQL concurrency fixtures: observing a slot and only then acquiring ACCESS EXCLUSIVE races an independently running snapshot SELECT. Twenty thousand rows/fetch-size 1 extends a timing window but does not establish a happens-before edge. A fast reader can finish first and make the subsequent lock-wait assertion time out; DML completion is also not explicitly fenced before HIGH, so incremental reading can repair the target and mask missing backfill. Existing result equality and job health checks are useful but insufficient to prove this specific window. Dedicated four-worker executor correctly avoids common-pool starvation, waits are condition-based and cleanup attempts each resource with suppressed failures. Unit tests deterministically cover naming, invalid names, restored-slot rejection, exact regex and bounded/unbounded locator selection; they do not cover actual received-LSN stopping or backfill merge lifecycle. No local test ran. The exact-head fork Build attempt 2 is cancelled, not passing acceptance.
2.3 Documentation
The four EN/ZH PostgreSQL/OpenGauss connector guides agree on persistent streaming slots, bounded per-reader slots, orphan cleanup, drop-on-stop limits and capacity. Add the central bilingual upgrade entries in Issue 2; avoid wording suggesting missing-slot validation applies to every startup/exactness mode when the code gates exactly-once INITIAL.
3. Architecture
3.1 Change location
The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
3.2 Maintainability
Keep the behavior, lifecycle ownership, and failure contract together. The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
3.3 Extensibility
Prefer the existing component boundary and tests over unrelated shared abstractions.
3.4 Upgrade impact
Partially incompatible operationally: existing valid slots/checkpoints keep their formats, and the new dialect hook is a default method, but restored exactly-once INITIAL jobs with missing slots now fail rather than recreate. Snapshot slot consumption grows to at least parallelism+1; temporary application-managed slots are persistent server objects requiring crash cleanup. The old public context constructor is retained as a delegating overload. Numeric offset conversion retains serialized string keys; removal of newly generated txid_current calls avoids artificial WAL progress without removing old checkpoint loader support.
4. Findings summary
Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.
| # | Finding | Location | Severity |
|---|---|---|---|
| 1 | Make the snapshot/backfill regression window deterministic | seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-postgres-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/PostgresCDCIT.java:515 |
High |
| 2 | Record the changed restore and slot-capacity contract in upgrade notes | seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresDialect.java:127 |
Medium |
5. Merge recommendation
Merge after fixes
Blocking items: Issues 1, 2. Current-head CI and write-capable maintainer review remain independent requirements.
Non-blocking suggestions: None beyond the validation limits above.
Overall: the approach addresses a real path, but the listed blockers must be closed. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.
CI and repository state: Signal pull request update: SUCCESS; Build: CANCELLED; Build: cancelled. GitHub reports BLOCKED / REVIEW_REQUIRED.
Verification: Reviewed all changed files and the referenced call sites at e453034b33f155e7bb751bc3bd8d6fcfe44f7ba1 against merge base 39c74ce48b0fb5e0318326b8d57a42c7380c40c8. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.
Review time: 2026-11-27T04:51:40.764302-05:00
Local evidence: git fetch obtained head e453034b33f155e7bb751bc3bd8d6fcfe44f7ba1; git merge-base returned 39c74ce48b0fb5e0318326b8d57a42c7380c40c8; git diff --stat reports 25 files changed, 1743 insertions(+), 38 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.
Resubmission and review continuity
This PR resubmits #11556 under DanielLeens with the exact same head commit (
dbc53649a3c17794d692ecc972db54a12401ace8) and unchanged code/commit authorship. Please retain the original review history at #11556.Outstanding blocker carried forward: the latest P1 review by @nzw921rx notes that bounded WAL backfill can wait indefinitely when only another database produces WAL and the source database has no decodable events. That finding is not fixed by this resubmission; the boundary protocol and regression test still need work. Earlier ready-to-merge conclusions were withdrawn. This replacement is opened as a draft.
Purpose
PostgreSQL/OpenGauss exactly-once initial snapshots recorded low and high watermarks but unconditionally skipped the bounded WAL backfill between them. Because the incremental split starts from the minimum high watermark, concurrent DML not observed by the snapshot query could be lost.
Changes
table.include.list, so legal PostgreSQL names containing regex metacharacters cannot be silently filtered from backfill.slot.name, including values supplied throughdebezium.slot.name, against PostgreSQL's[a-z0-9_]{1,63}constraint.devPG-base CDC abstraction introduced by [Feature][Connector-V2] Introduce PG base CDC abstraction for Postgres and OpenGauss #11029.OpenGauss uses the shared PostgreSQL incremental source path and receives the same bounded-backfill fix.
Compatibility and operational notes
No user-facing option, default value, serialized split format, or public constructor is changed.
Invalid effective PostgreSQL slot names now fail during source configuration instead of failing later at runtime.
The configured streaming slot remains available for the incremental phase. Setting the Debezium pass-through option as
requests cleanup by the incremental reader on a normal shutdown; it is not a crash-recovery guarantee.
Backfill slots are application-managed server-persistent slots. They are explicitly removed when the reader completes or handles an exception, but process termination, OOM, or node loss can bypass JVM cleanup and leave an inactive
*_st_backfill_*slot. Operators should monitor and manually remove confirmed-orphaned inactive slots. Sizemax_replication_slots >= parallelism + 1.Snapshot watermarks no longer call
txid_current()or persistTXID_KEY. Callingtxid_current()can create WAL beyond the intended stop LSN and make bounded backfill wait for a record that does not exist. Restored older checkpoints may still containtxId; the offset loader accepts both old and new map shapes, so mixed restored/new watermark state is intentional.Validation
devconflicts and verified thatdevis an ancestor of this headgit diff --check, conflict-marker scan, and final changed-file scope auditI am contributing this fix to Apache SeaTunnel.