Skip to content

[Fix][Connector-V2] Fix Postgres-CDC committed-offset recovery skipping rows after savepoint - #11864

Merged
nzw921rx merged 3 commits into
apache:devfrom
zhang-arvin:fix-pg-cdc-offset-recovery
Sep 11, 2026
Merged

nzw921rx merged 3 commits into
apache:devfrom
zhang-arvin:fix-pg-cdc-offset-recovery

Conversation

@zhang-arvin

Copy link
Copy Markdown
Contributor

Purpose

Fix three issues that cause Postgres-CDC to silently skip rows after savepoint recovery, as described in issue #11847.

Brief change log

  1. PostgresWalFetchTask.commitCurrentOffset used wrong LSN key

    • commitCurrentOffset was reading the LSN via offset.getLsn() which uses SourceInfo.LSN_KEY ("lsn"), but Debezium's commitOffset expects the LAST_COMMIT_LSN_KEY ("lsn_commit") field.
    • Added getLsnCommit() to LsnOffset that reads from LAST_COMMIT_LSN_KEY with fallback to LSN_KEY, and updated commitCurrentOffset to use the committed LSN.
  2. IncrementalSourceStreamFetcher.shouldEmit used strict greater-than comparison

    • In non-exactly-once mode, shouldEmit used isAfter(splitStartWatermark) (strict greater-than), so after recovery the first event with the same LSN as splitStartWatermark was filtered out.
    • Changed to isAtOrAfter(splitStartWatermark) to include the watermark-position event.
  3. PostgresWalFetchTask.execute missing error handler check

    • execute() did not check errorHandler.getProducerThrowable() after the streaming loop completed, so streaming failures could be silently swallowed.
    • Added error handler check to surface streaming errors.

Verify this pull request

  • This change is already covered by existing tests, such as LsnOffsetFactoryTest.
  • Manual verification: run Postgres-CDC with savepoint and verify no rows are skipped after recovery.

Does this PR potentially affect the following other parts of the project?

  • Connector-CDC
  • Connector-CDC-Postgres

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What Problem Does This PR Solve?

This PR fixes three independent, source-verified root causes that make Postgres-CDC silently skip already-committed rows when a job resumes from a checkpoint/savepoint (linked to issue #11847):

  1. PostgresWalFetchTask.commitCurrentOffset flushed the wrong LSN to the Postgres replication slot (SourceInfo.LSN_KEY, the current streaming position) instead of PostgresOffsetContext.LAST_COMMIT_LSN_KEY (the last-committed-transaction LSN), which can prematurely tell Postgres it is safe to recycle WAL that a still-open transaction needs.
  2. IncrementalSourceStreamFetcher.shouldEmit used a strict isAfter(splitStartWatermark) boundary check in the non-exactly-once path, which drops any post-restart record that shares the exact same LSN as the last-processed record before the crash.
  3. PostgresWalFetchTask.execute did not check errorHandler.getProducerThrowable() after the streaming loop exited, so an async producer failure could leave the task silently "finished" without ever surfacing as a readException.

1. Code Change Review

1.1 Core Logic Analysis

Runtime path (recovery-path data-correctness fix):

checkpoint N triggers
  -> IncrementalSourceReader.snapshotState(N)
       snapshotChangeLogOffset = incrementalSplit.getStartupOffset()
       (IncrementalSourceRecordEmitter.processElement() sets this to the LAST
        emitted record's own LSN, via setStartupOffset(position), BEFORE emit)
  -> checkpoint N completes on all operators
  -> IncrementalSourceReader.notifyCheckpointComplete(N)
       -> PostgresDialect.commitChangeLogOffset(snapshotChangeLogOffset)
            -> PostgresWalFetchTask.commitCurrentOffset((LsnOffset) offset)
                 [BUG 1] commitLsn = offset.getLsn()   // "lsn" = current position,
                                                        // may be mid-transaction
                 [FIX 1] commitLsn = offset.getLsnCommit() // "lsn_commit" = last
                                                            // COMMIT-boundary LSN
                 streamingChangeEventSource.commitOffset({lsn_commit: commitLsn})
                      -> replicationStream.flushLsn(commitLsn)
                         // tells Postgres server "WAL below this point is safe
                         // to recycle" (debezium PostgresStreamingChangeEventSource#L398-421)

job restart / recovery from savepoint N
  -> IncrementalSplit restored with startupOffset = last emitted record's LSN (call it P)
  -> IncrementalSourceStreamFetcher.configureFilter()
       splitStartWatermark = currentIncrementalSplit.getStartupOffset()  // = P
  -> replication slot resumes streaming, may re-deliver events at LSN == P
     (a single WAL position/transaction can carry MULTIPLE row-level change
      events -- e.g. a bulk UPDATE/DELETE -- that all share LSN P; only the
      FIRST one at P was actually processed+committed before the crash)
  -> IncrementalSourceStreamFetcher.shouldEmit(record)
       [BUG 2] position.isAfter(P)     // strict > : ANY record at exactly P is
                                        // dropped, including unprocessed siblings
       [FIX 2] position.isAtOrAfter(P) // >= : never drops an unprocessed record
                                        // at the boundary; may re-emit the one
                                        // already-processed record at P (accepted
                                        // duplicate under at-least-once semantics)

I verified this against the actual Debezium 1.9.8.Final sources (~/.m2/.../debezium-connector-postgres-1.9.8.Final-sources.jar):

  • PostgresOffsetContext (vendored copy in this repo, io.debezium.connector.postgresql.PostgresOffsetContext) only sets sourceInfo.lsn() (the "lsn" key) on every WAL message, including mid-transaction DML (updateWalPosition, called per row change), while lastCommitLsn ("lsn_commit") is only advanced in updateCommitPosition, called exclusively from commitMessage() on a COMMIT boundary. So "lsn" can legitimately be ahead of "lsn_commit" whenever a transaction is still open — confirming bug 1 is real and reachable on any workload with multi-statement/multi-row transactions.
  • Debezium's own PostgresStreamingChangeEventSource#commitOffset (L398-421) explicitly reads LAST_COMMIT_LSN_KEY first (falling back to LAST_COMPLETELY_PROCESSED_LSN_KEY) precisely because a commit-boundary LSN is the only "safe to recycle WAL" position — this PR's getLsnCommit() now matches that documented contract instead of substituting an unrelated field.
  • IncrementalSourceRecordEmitter.processElement() (L148-153) confirms splitState.setStartupOffset(position) is called with the LSN of the record just processed, immediately before emitElement. Combined with Postgres logical decoding legitimately emitting multiple row-events per LSN, isAfter can silently drop a never-before-seen sibling event at the exact same boundary LSN. This is a genuine, reachable off-by-boundary bug, not a contrived scenario.
  • shouldEmit's change is scoped to !taskContext.isExactlyOnce(), and SourceOptions.EXACTLY_ONCE defaults to false — so this fix sits squarely on the default recovery path for Postgres-CDC users, not an edge configuration.
  • Fix 3 is confirmed necessary by tracing IncrementalSourceStreamFetcher.submitTask (L117-135): streamFetchTask.execute(taskContext) runs on a background executor; only a thrown Throwable populates readException, which is later surfaced via checkReadException() in pollSplitRecords(). Debezium's processMessages loop (PostgresStreamingChangeEventSource, L212) is gated purely on context.isRunning() (i.e., PostgresWalFetchTask.taskRunning), completely independent of ErrorHandler.setProducerThrowable. So execute() can return normally while an async producer error was recorded, leaving readException unset, isFinished() true, and the split silently marked complete with no error signal — a genuine silent-stall/data-loss path this fix closes.

Delivery guarantee consistency: the connector's non-exactly-once path is explicitly documented in-code ("not support exactly-once, so ignore the watermark check") as at-least-once. isAtOrAfter is the correct choice for that guarantee (bias toward duplicate over skip). The isExactlyOnce()==true branch (hasEnterPureBinlogPhase / finishedSplitsInfo / isRecordBetween at L281-291) is untouched by this PR, so exactly-once users are not affected either way — correctly scoped.

1.2 Compatibility Impact

Verdict: no checkpoint/offset serialized-format change; safe to restore from pre-fix checkpoints.

  • LsnOffset does not add/remove/rename any field in its internal offset: Map<String,String>; getLsnCommit() is a pure new read accessor over the existing map. lsn_commit was already populated by the (unmodified) vendored PostgresOffsetContext.getOffset() whenever a commit had occurred — this PR does not introduce a new serialized key.
  • getLsnCommit() falls back to getLsn() when lsn_commit is absent (e.g., an old checkpoint taken before any transaction committed in that run, or one built via the 3-arg LsnOffset constructor). This exactly reproduces the old (buggy but non-crashing) value in that edge case — no exception, no behavior regression, just doesn't yet benefit from the fix until a newer checkpoint captures a real lsn_commit.
  • The shouldEmit comparator change is a pure runtime-behavior change with no serialization implication; it applies uniformly to old and new checkpoints alike, and only ever adds emission (fixes skip) rather than removing it.
  • I did not find any evidence this PR changes wire/on-disk checkpoint schema. No docs/en/introduction/concepts/incompatible-changes.md entry is required, and none was added — consistent with there being no incompatible change.

1.3 Performance / Side-Effects

  • Fix 1 makes WAL flush more conservative (flushes an earlier-or-equal LSN than before), which can only increase, never decrease, retained WAL size on the Postgres server relative to the old behavior — an acceptable and expected safety trade-off for a correctness fix. No new allocation/hot-path cost of note.
  • Fix 2 changes the non-exactly-once path to be slightly more permissive at the exact resume boundary, meaning the boundary record may occasionally be duplicated downstream after a restart. This is consistent with (and required by) the at-least-once contract this path already documents; no exactly-once regression.
  • Fix 3 adds one field read + null check at the end of execute(); negligible cost, executes once per fetch-task lifecycle, not per record.

1.4 Error Handling / Logging

Issue 1: No operator-facing signal when the offset-recovery gap this PR fixes actually occurs

  • Location: seatunnel-connectors-v2/connector-cdc/connector-cdc-base/.../IncrementalSourceStreamFetcher.java:265-295 (shouldEmit)
  • Problem: Records filtered out at the boundary (both before and after this fix) are dropped with only a log.trace on the unrelated "not support exactly-once" branch entry — there is no INFO/WARN log emitted when a record is actually filtered at (or, pre-fix, skipped at) the watermark boundary, and no metric/counter for it either.
  • Potential risk: after this upgrade, an operator who was silently losing rows pre-fix has no log evidence in the old version to diagnose "why are rows missing after every restart", and going forward there is still no observability into how often the boundary condition is hit, making it hard to confirm the fix is effective in a specific production job without external data reconciliation.
  • Best improvement: add a log.debug/log.trace (rate-limited if needed) inside shouldEmit when a record at exactly splitStartWatermark is evaluated, and consider a lightweight counter metric for "records emitted at recovery boundary" to help operators validate recovery correctness post-upgrade.
  • Severity: Low (does not block correctness, but weakens the ability to diagnose historical or residual gaps as requested by review criteria)
  • Raised by another reviewer: No

Issue 2: Generic RuntimeException for streaming failure loses context

  • Location: seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/.../PostgresWalFetchTask.java:77-80
  • Problem: throw new RuntimeException("Postgres WAL streaming failed", producerThrowable); does not include the split id, the last known committed LSN, or the current taskRunning/shutdown state in the message, and uses a bare RuntimeException rather than the project's own SeaTunnelException used elsewhere in this same call chain (IncrementalSourceStreamFetcher.checkReadException wraps into SeaTunnelException anyway, so this is not functionally broken, but it discards useful diagnostic context at the point of failure).
  • Potential risk: low — the exception is still correctly caught and surfaced by the caller's catch (Throwable e), and readException will contain the original producerThrowable as the cause. The only loss is a slightly less actionable top-level message for whoever reads the log first.
  • Best improvement: include split and last committed LSN in the message, e.g. "Postgres WAL streaming failed for split " + split.splitId().
  • Severity: Low (cosmetic / diagnosability only)
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

  • Minor style nit: LsnOffset.getLsnCommit() references io.debezium.connector.postgresql.PostgresOffsetContext.LAST_COMMIT_LSN_KEY fully-qualified inline rather than adding an import, inconsistent with the existing SourceInfo/Lsn imports at the top of the same file. Purely cosmetic, does not affect correctness or compilation.
  • The rest of the diff is minimal, well-scoped, and consistent with surrounding code style (Google/AOSP format via Spotless appears respected based on the diff formatting).

2.2 Test Coverage / Stability — High Risk

Issue 3: No test simulates a checkpoint/restart cycle for any of the three fixes; existing tests do not exercise the changed code paths at all

  • Location: PR file list — only 3 production files changed (IncrementalSourceStreamFetcher.java, LsnOffset.java, PostgresWalFetchTask.java); zero test files touched.
  • Problem:
    • LsnOffsetTest.java (seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/test/.../offset/LsnOffsetTest.java) contains a single unrelated test (testNoStoppingOffsetIsNeverStop) and does not test getLsnCommit() at all — neither the "lsn_commit present" case nor the "fallback to lsn" case.
    • IncrementalSourceStreamFetcherTest.java (connector-cdc-base/src/test/.../external/IncrementalSourceStreamFetcherTest.java:517) stubs out the exact method this PR changes: doReturn(true).when(spy).shouldEmit(any()); — meaning the real isAfter/isAtOrAfter boundary logic is never exercised by any existing unit test, so this PR could not have regressed or validated against it even if it wanted to.
    • PostgresWalFetchTask has no dedicated unit test at all; commitCurrentOffset's LSN-key selection and the new error-propagation check in execute() are both untested.
    • The PR's own description checklist has both boxes unchecked: "This change is already covered by existing tests" and "Manual verification: run Postgres-CDC with savepoint and verify no rows are skipped after recovery" — i.e., the author has not self-certified verification of the exact scenario this PR claims to fix.
  • Potential risk: for a PR whose entire justification is "silently skips committed rows after recovery," landing it with no automated regression test means a future refactor could silently reintroduce any of these three bugs with no CI signal, and there is no evidence (beyond code reading) that the fix has been validated against a real checkpoint/restart cycle with multi-row transactions.
  • Best improvement (required before merge):
    1. A unit test for LsnOffset.getLsnCommit() covering both "lsn_commit present" (returns it) and "lsn_commit absent" (falls back to getLsn()).
    2. A unit test for IncrementalSourceStreamFetcher.shouldEmit (not mocked out) that constructs two records at the identical boundary LSN — one already "processed" pre-restart, one not — and asserts the unprocessed one is emitted under the new isAtOrAfter (and would previously have been dropped under isAfter).
    3. Ideally a Postgres-CDC E2E test (seatunnel-e2e, Testcontainers-based) that runs a multi-row transaction, triggers a savepoint/restart mid-stream, and asserts row-count/row-identity equality between source and sink — this is the only test that actually proves "no rows skipped after recovery" end-to-end rather than at the unit boundary.
  • Severity: High (blocking — this is exactly the "test simulates checkpoint/restart, asserts no skip" requirement, and it is entirely absent)
  • Raised by another reviewer: No

2.3 Docs

No user-facing config, defaults, or behavior contract changed (pure bug fix, no new Option), so no docs/en / docs/zh update is required, and none was made — consistent.

3. Architectural Soundness

The three fixes are each applied at the layer that actually owns the bug (Debezium-offset field selection in the Postgres-specific LsnOffset/PostgresWalFetchTask, and the shared boundary-comparison logic in the connector-agnostic IncrementalSourceStreamFetcher, correctly gated to the non-exactly-once branch only). No leakage of Postgres-specific concerns into connector-cdc-base, and no unrelated refactors. This is architecturally the right and minimal fix location for all three issues; I found no more-upstream or more-downstream location that would be a better fix point.

4. Issue Summary

# Title Severity Blocking Raised before
1 No operator-facing log/metric when boundary filtering occurs in shouldEmit Low No No
2 Generic RuntimeException loses split/LSN context in PostgresWalFetchTask.execute Low No No
3 No test simulates a checkpoint/restart cycle for any of the 3 fixes; existing shouldEmit test is fully mocked; PR's own verification checklist is unchecked High Yes No

5. Merge Recommendation

Conclusion: Changes Requested — root-cause analysis and fix are sound, but merge is blocked on missing regression tests.

I independently traced and verified all three root causes against the actual Debezium 1.9.8.Final sources and the SeaTunnel CDC checkpoint/restart call chain (snapshotState -> notifyCheckpointComplete -> commitChangeLogOffset -> commitCurrentOffset, and configureFilter -> shouldEmit). All three are genuine, reachable bugs on the default (non-exactly-once) Postgres-CDC recovery path, not contrived edge cases, and the fixes are correctly scoped and backward-compatible with pre-fix checkpoints (no serialized-format change, safe fallback behavior).

Blockers:

  • Issue 3: at least a unit test for LsnOffset.getLsnCommit() (with/without lsn_commit present) and a real (non-mocked) unit test for the shouldEmit boundary case with two records sharing an LSN are required before merge, given this PR's explicit claim of fixing silent data loss in a financial/production-grade CDC recovery path. An E2E savepoint/restart test is strongly recommended but I'd accept solid unit coverage plus a documented manual verification (with the PR's own checklist checked and evidence attached) as a minimum bar.

Recommended fixes (non-blocking, please address or explicitly defer):

  • Issue 1: add a debug-level log line (and ideally a metric) when shouldEmit filters/passes a record exactly at the recovery watermark, to give operators a way to confirm the fix is working in production.
  • Issue 2: enrich the RuntimeException message in PostgresWalFetchTask.execute with split id / last committed LSN for faster triage.

Once test coverage for Issue 3 is added and CI (currently still running/pending on the Build check) is green, I'm supportive of this fix landing — the underlying analysis is correct and addresses a real data-loss risk.

zhang-arvin added a commit to zhang-arvin/seatunnel that referenced this pull request Aug 20, 2026
@zhang-arvin

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, @DanielLeens! All three issues have been addressed in the latest commit:

Issue 1 (debug log): Added log.debug in shouldEmit showing the position vs splitStartWatermark for the non-exactly-once boundary check path.

Issue 2 (error enrichment): RuntimeException in PostgresWalFetchTask.execute now includes the split ID and last committed LSN.

Issue 3 (tests): Added:

  • LsnOffsetTest: testGetLsnCommitWhenLsnCommitKeyExists (returns lsn_commit) and testGetLsnCommitFallbackToLsnWhenLsnCommitKeyMissing (falls back to lsn)
  • IncrementalSourceStreamFetcherTest: testShouldEmitAtOrAfterWatermark (record at boundary IS emitted) and testShouldEmitBeforeWatermarkFiltered (record before boundary IS filtered)

Also fixed the style nit — LsnOffset.getLsnCommit() now uses import io.debezium.connector.postgresql.PostgresOffsetContext instead of the fully-qualified inline reference.

All existing tests pass. PTAL!

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fast, thorough follow-up! I re-reviewed the latest head (a2195406c) from scratch, re-verifying all three original bug fixes (wrong-LSN flush, strict boundary check, silent producer-throwable loss) are still intact, then tracing each of the three requested follow-ups. All three are correctly addressed; I found one new (non-blocking) cross-thread visibility nit in the error-enrichment change, detailed below.

What Problem Does This PR Solve?

This PR fixes three independent, source-verified root causes that made Postgres-CDC silently skip already-committed rows or mask streaming failures on resume from checkpoint/savepoint (linked to issue #11847):

  1. PostgresWalFetchTask.commitCurrentOffset flushed the current streaming LSN instead of the last-committed-transaction LSN to the replication slot, risking premature WAL recycling.
  2. IncrementalSourceStreamFetcher.shouldEmit used a strict isAfter boundary check in the non-exactly-once path, dropping any post-restart record sharing the exact same LSN as the last-processed record before a crash.
  3. PostgresWalFetchTask.execute didn't check errorHandler.getProducerThrowable() after the streaming loop exited in all cases, letting an async producer failure leave the task silently "finished."

One-sentence summary: unchanged in substance since my last review — this round only adds the three requested diagnostics/tests, with the underlying data-correctness fixes untouched.

1. Code Change Review

1.1 Core Logic Analysis

Verified unchanged (re-diffed against my last-reviewed head f00b5b64d): the actual fix logic in commitCurrentOffset (LSN selection), shouldEmit (isAfter -> isAtOrAfter), and the post-loop producerThrowable check are all byte-for-byte identical to what I already verified against the real Debezium 1.9.8.Final sources in the previous round. Nothing here needed re-verification of the core correctness claim.

This round's diff (f00b5b64d -> a2195406c), addressing the three requested follow-ups:

  1. Issue 1 (debug log for the boundary check) — done correctly:
// IncrementalSourceStreamFetcher.java:270-277
log.trace("The table {} is not support exactly-once, ...", tableId);
log.debug(
        "Non-exactly-once boundary check: position={} vs splitStartWatermark={}",
        position, splitStartWatermark);
return position.isAtOrAfter(splitStartWatermark);

This gives operators a way to confirm, on resume, exactly which position/watermark pair drove the accept/drop decision — directly useful for triaging the #11847 symptom in the field.

  1. Issue 2 (error enrichment with split id + last committed LSN) — mostly correct, one new nit:
// PostgresWalFetchTask.java:78-85
throw new RuntimeException(
        "Postgres WAL streaming failed for split " + split.splitId()
        + ", last committed LSN: " + (lastCommitLsn != null ? Lsn.valueOf(lastCommitLsn) : "none"),
        producerThrowable);

split.splitId() is a final field on this instance, safe to read from any thread. lastCommitLsn, however, is a plain (non-volatile) instance field that's written by commitCurrentOffset(LsnOffset) (PostgresWalFetchTask.java:88-...) — which I traced (as in my previous review) as being invoked from IncrementalSourceReader.notifyCheckpointComplete() -> PostgresDialect.commitChangeLogOffset(), i.e. on the checkpoint-notification thread — while this new read happens inside execute(), which runs on the dedicated WAL-streaming task thread (taskContext.submitTask()/executorService in the fetcher). This is a genuinely new cross-thread read of lastCommitLsn that didn't exist before this commit (previously the field was only ever read from within commitCurrentOffset itself, on the same thread as the write). Without volatile or another happens-before edge, the WAL-streaming thread isn't guaranteed to observe the latest value written by the checkpoint thread — in the worst case the exception message could report a stale (including possibly null -> "none") last-committed LSN even though a commit had already landed. This is a diagnostics-only issue (the value is used solely for the exception message text, not for any control-flow or data-correctness decision — the real fix in commitCurrentOffset/shouldEmit is unaffected), so I'm rating it Medium rather than blocking, but it's worth a one-line volatile fix given how easy it is to get right.

  1. Issue 3 (tests for both LSN handling and the boundary check) — done correctly and thoroughly:
    • LsnOffsetTest.testGetLsnCommitWhenLsnCommitKeyExists / testGetLsnCommitFallbackToLsnWhenLsnCommitKeyMissing directly exercise LsnOffset.getLsnCommit()'s two branches (present vs. missing lsn_commit key), which is exactly the method at the heart of Bug 1's fix.
    • IncrementalSourceStreamFetcherTest.testShouldEmitAtOrAfterWatermark / testShouldEmitBeforeWatermarkFiltered exercise the exact boundary condition Bug 2 fixed — I checked the new createDataEventWithSource() test helper builds a SourceRecord with a proper Debezium Source struct (db/schema/table + connector key) so getTableId() doesn't NPE inside shouldEmit(), and createPlainFetcher()'s 3-arg constructor call (null, 0, null) matches IncrementalSourceStreamFetcher's real constructor signature (IncrementalSourceStreamFetcher.java:91-93) — this isn't a hollow reflection trick, it genuinely exercises the real shouldEmit() method with mocked Offset.isAtOrAfter() returning true/false to assert both accept and drop paths.

1.2 Compatibility Impact

Fully compatible. No config option, public API, checkpoint/serialization format, or protocol changed in this round; the diagnostics-only additions (log line, exception message text, PostgresOffsetContext import simplification) don't alter any external contract.

1.3 Performance / Side-Effect Analysis

Negligible — one additional log.debug call per record on the non-exactly-once path (guarded by normal SLF4J level checks, no eager string concatenation since it's parameterized), and a slightly larger exception message string built only on the already-exceptional producer-failure path.

1.4 Error Handling and Logging

Issue 1: New cross-thread read of non-volatile field lastCommitLsn in the exception-message path.

  • Location: seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/reader/wal/PostgresWalFetchTask.java:35 (field declaration, private Long lastCommitLsn;) and :78-85 (new read site), written at :88-95 (commitCurrentOffset, unchanged from prior round).
  • Problem description: lastCommitLsn is written on the checkpoint-notification thread (via PostgresDialect.commitChangeLogOffset -> commitCurrentOffset) and is now also read on the WAL-streaming task thread inside execute()'s new exception-message construction — a new cross-thread access this commit introduces, with no volatile qualifier or other memory-visibility guarantee between the two threads.
  • Potential risk: Best case, purely cosmetic (a log/exception message occasionally shows a slightly stale "last committed LSN", including possibly showing "none" right after a real commit landed). Worst case under the JMM, this is technically undefined visibility timing — though because the field is only ever used for a diagnostic string here (not for any correctness decision), there's no data-loss or control-flow risk from this specific issue.
  • Best improvement: Declare private volatile Long lastCommitLsn; — a one-word fix that removes the ambiguity entirely and costs nothing at this call frequency (commits happen once per checkpoint, not per record).
  • Severity: Medium (correctness-adjacent code-quality gap, not a blocker — the diagnostic nature of this specific field's new use means no data-correctness impact even in the worst case).
  • Raised by another reviewer: No.

2. Code Quality Assessment

2.1 Coding Standards

Good — the PostgresOffsetContext import simplification (fully-qualified reference -> proper import) in LsnOffset.java is a small, welcome cleanup with no behavior change. No new fields/methods needing doc comments beyond what's already covered.

2.2 Test Coverage and Test Stability

Rating: Stable. All four new tests are deterministic — pure unit tests against mocked Offset/FetchTask.Context objects or plain Map-backed LsnOffset construction, no Thread.sleep, no timing dependence, no shared static state, no container/IT infrastructure. They directly target the two methods (LsnOffset.getLsnCommit(), IncrementalSourceStreamFetcher.shouldEmit()) that carry Bug 1 and Bug 2's fix logic — this closes the test-coverage gap I flagged in the previous round precisely.

2.3 Documentation Updates

N/A — internal bug fix, no user-facing config/behavior surface to document.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise, well-targeted fixes to the actual root causes (verified against real Debezium sources in the previous round), now with matching diagnostics and regression tests. This is a long-term, correct solution, not a workaround.

3.2 Maintainability

Good, with the one volatile nit above being the only thing I'd want closed before calling this fully clean.

3.3 Extensibility

No concerns.

3.4 Historical-Version Compatibility

No impact — no checkpoint/savepoint format change; the fix corrects what gets flushed to the Postgres replication slot and what gets accepted on resume, not the shape of any persisted SeaTunnel state. A job resuming from a savepoint taken with the old (buggy) code will simply benefit from the corrected boundary check and LSN flush going forward — no migration needed.

4. Issue Summary

# Issue Location Severity
1 New cross-thread read of non-volatile lastCommitLsn in the exception-message path PostgresWalFetchTask.java:35,78-85 Medium

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — none. The three core data-correctness fixes are verified correct and unchanged from my prior review; all three requested follow-ups (debug log, error enrichment, tests) are implemented correctly and the new tests genuinely exercise the fixed logic.
  2. Recommended fixes (non-blocking, but a trivial one-word fix worth doing before merge):
    • Mark lastCommitLsn as volatile to remove the cross-thread visibility ambiguity introduced by the new diagnostic read (Issue 1).

Overall this is a well-verified, high-value fix for a real production data-correctness bug, and the iteration quality on the follow-ups has been excellent. Once CI (currently queued on the fork) comes back green and the volatile nit is addressed, I'm comfortable calling this ready to merge.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What Problem Does This PR Solve?

This PR fixes three independent, source-verified root causes that made Postgres-CDC silently skip already-committed rows or mask streaming failures on resume from checkpoint/savepoint (issue #11847): (1) PostgresWalFetchTask.commitCurrentOffset flushed the current streaming LSN instead of the last-committed-transaction LSN to the replication slot; (2) IncrementalSourceStreamFetcher.shouldEmit used a strict isAfter boundary check in the non-exactly-once path, dropping any post-restart record sharing the exact same LSN as the last-processed record before a crash; (3) PostgresWalFetchTask.execute didn't check errorHandler.getProducerThrowable() after the streaming loop exited in all cases. This round adds the diagnostics/tests I requested previously, plus one new piece of production logic I had not seen before: persisting the committed LSN back into the live Offset object so an immediately-following checkpoint (before any new record arrives) also captures it.

I want to open by thanking you again for the thorough work on the previous two rounds — the core LSN/boundary fixes remain correct and I have no new concerns about them. This round I re-read the entire current diff from scratch (current head a726546b1, which turns out to be a rebase of the a2195406c commit I reviewed last time — logically the same content for everything I already reviewed, confirmed via file-by-file comparison, not just a diff since last review). I found one genuinely new piece of production code this round that needs a closer look, and — more importantly — a live CI signal I have to flag prominently: the fork's current run has a real (not obviously-CI-infra) failure in exactly the E2E test that exercises this PR's own claimed scenario.

1. Code Change Review

1.1 Core Logic Analysis

Unchanged and still correct (re-verified against the current head): the LSN selection fix in commitCurrentOffset (offset.getLsn() → offset.getLsnCommit()), the shouldEmit boundary fix (isAfter → isAtOrAfter), and the post-loop producerThrowable check are all present and logically identical to what I already verified against the real Debezium 1.9.8.Final sources in round 1.

New this round — PostgresWalFetchTask.commitCurrentOffset now mutates the live Offset object in place:

// PostgresWalFetchTask.java:88-106
public void commitCurrentOffset(LsnOffset offset) {
    if (streamingChangeEventSource != null && offset != null) {
        Long commitLsn = offset.getLsnCommit().asLong();
        if (commitLsn != null
                && (lastCommitLsn == null
                        || Lsn.valueOf(commitLsn).compareTo(Lsn.valueOf(lastCommitLsn)) > 0)) {
            lastCommitLsn = commitLsn;

            // Persist LAST_COMMIT_LSN_KEY into the offset object so that
            // savepoint/checkpoint serialization captures the committed LSN.
            offset.getOffset()
                    .put(PostgresOffsetContext.LAST_COMMIT_LSN_KEY, String.valueOf(lastCommitLsn));

            Map<String, Object> offsets = new HashMap<>();
            offsets.put(PostgresOffsetContext.LAST_COMMIT_LSN_KEY, lastCommitLsn);
            streamingChangeEventSource.commitOffset(offsets);
        }
    }
}

Runtime path confirmed by tracing (all files read at head a726546b1):

  • offset here is snapshotChangeLogOffset, set in IncrementalSourceReader.snapshotState(): snapshotChangeLogOffset = incrementalSplit.getStartupOffset(); (IncrementalSourceReader.java:256) — a direct reference, not a copy.
  • commitCurrentOffset is invoked from notifyCheckpointComplete() (IncrementalSourceReader.java:124-126), which I confirmed in my previous round runs on the checkpoint-notification thread, separate from the WAL-streaming task thread.
  • LsnOffset.getOffset() is a Lombok @Getter over Offset.offset (Offset.java:36, @Getter protected Map<String, String> offset;) — it returns the live, mutable HashMap by reference, not a defensive copy. java.util.HashMap gives no thread-safety guarantee for concurrent read/write from multiple threads without external synchronization.
  • IncrementalSourceRecordEmitter.processElement() builds a brand-new LsnOffset per record via getOffsetPosition() → offsetFactory.specific(offsetStrMap) (fresh HashMap each call) and calls splitState.asIncrementalSplitState().setStartupOffset(position), which replaces the state's offset reference rather than mutating the previous one — so once at least one record has been processed after split assignment, the live split-state's offset object and the one captured for a given checkpoint diverge into separate instances, and this specific mutation is safe with respect to that path.
  • The risk window is the case the comment itself describes: a checkpoint completes before any new record has been processed since the split was (re)assigned or since the last commit. In that narrow window, PostgresWalFetchTask.split (assigned once via new PostgresWalFetchTask(sourceSplitBase.asIncrementalSplit()) in PostgresDialect.createFetchTask, PostgresDialect.java:195) and IncrementalSourceStreamFetcher.currentIncrementalSplit (= fetchTask.getSplit().asIncrementalSplit(), IncrementalSourceStreamFetcher.java:106) can plausibly still be the same split object, and by extension the same LsnOffset/Map instance, as what snapshotChangeLogOffset captured. IncrementalSourceStreamFetcher.configureFilter() reads splitStartWatermark = currentIncrementalSplit.getStartupOffset(); once and compares against it repeatedly in shouldEmit() on the WAL-streaming thread for the life of the fetch task.

What I can confirm with certainty: this is an unsynchronized, cross-thread, in-place mutation of a plain HashMap that the code's own comment says is deliberately relied upon (not an accidental side effect) to make a following checkpoint pick up the committed LSN without waiting for a new record. There is no volatile/synchronization/happens-before edge between the checkpoint-notification thread's put() and any other thread's later get() on the same map, so even in the best case, the intended optimization is not guaranteed to be visible in time — the comment's own stated goal ("so that savepoint/checkpoint serialization captures the committed LSN") is not actually guaranteed by this code as written.

What I could not fully verify from static analysis alone, and want to flag rather than either dismiss or overclaim: whether, in the specific narrow-window scenario above, this concurrent mutation can also race against a concurrent read of the same map on the WAL-streaming thread (shouldEmit's splitStartWatermark comparisons) in a way that produces observably wrong behavior (not just a "missed optimization"). I was not able to rule this out, and — see the CI section below — there is a real E2E failure in exactly this savepoint/restart scenario that I cannot yet attribute definitively to this mutation, a pre-existing flake, or something else, and I think that needs to be resolved before merge rather than assumed away.

Key findings

  • The three original correctness fixes remain sound and verified against real Debezium sources (confirmed again this round, no change).
  • New this round: a legitimate, well-reasoned concurrency-hygiene concern around the new offset.getOffset().put(...) in-place mutation — real risk of the "next checkpoint gets the committed LSN early" optimization silently not working (missing visibility guarantee), and I cannot rule out a more serious data race in the narrow reachable window described above.
  • The LsnOffset(Long, Long, Instant) constructor now also seeds LAST_COMMIT_LSN_KEY with the same value as LSN_KEY (LsnOffset.java:60-64) for the INITIAL_OFFSET/NO_STOPPING_OFFSET sentinels — this is a genuine no-op with respect to observable behavior, since getLsnCommit() already falls back to getLsn() when the key is absent, so this addition is harmless but also doesn't change anything by itself.

1.2 Compatibility Impact

No checkpoint/offset serialized-format change; safe to restore from pre-fix checkpoints — unchanged conclusion from my previous rounds. LsnOffset does not add/remove/rename any field in its internal map; the new .put() call writes to an already-existing key name (LAST_COMMIT_LSN_KEY) that the vendored PostgresOffsetContext already produces on commit, so it doesn't introduce a new serialized key or break deserialization of old checkpoints.

1.3 Performance / Side-Effects

Negligible additional cost from the new .put() call itself (a single HashMap entry write per commit, not per record). The concerns in 1.1/1.4 are about correctness/visibility under concurrency, not raw performance.

1.4 Error Handling and Logging

Issue 1 (carryover, still unresolved): lastCommitLsn remains a non-volatile field read cross-thread

  • Location: PostgresWalFetchTask.java:36 (private Long lastCommitLsn;), read at :78-85 on the WAL-streaming thread, written at :96 on the checkpoint-notification thread.
  • This is exactly the issue I raised in my previous review (rated Medium there) and it is still open — the field declaration is unchanged.
  • Severity: Medium (diagnostics-only impact on the exception message; not a correctness blocker by itself).
  • Raised by another reviewer: No.

Issue 2 (new this round): unsynchronized cross-thread mutation of a live, non-thread-safe Map via offset.getOffset().put(...)

  • Location: PostgresWalFetchTask.java:98-100 (commitCurrentOffset), object originates from IncrementalSourceReader.java:256 (snapshotChangeLogOffset = incrementalSplit.getStartupOffset();), consumed by IncrementalSourceStreamFetcher.java:316 (splitStartWatermark = currentIncrementalSplit.getStartupOffset();).
  • Problem: as detailed in 1.1, this call mutates a plain java.util.HashMap in place from the checkpoint-notification thread, with a real (though narrow) reachable window where the same map instance may still be referenced/read from the WAL-streaming thread's shouldEmit() boundary check.
  • Potential risk: at minimum, the documented purpose of this addition ("so a following checkpoint captures the committed LSN early") is not reliably achieved due to missing memory-visibility guarantees. At worst, in the narrow-window scenario, this is an unsynchronized concurrent map mutation, which is undefined behavior per the HashMap contract. I want to be precise about confidence here: I have confirmed the missing-synchronization fact and the plausible aliasing window; I have not confirmed that this specific code path is the cause of the CI failure noted below — that would need a debugger/reproduction, which is outside what static review can prove.
  • Best improvement: don't mutate the shared instance in place. Build a small immutable copy instead, e.g. Map<String, String> updated = new HashMap<>(offset.getOffset()); updated.put(PostgresOffsetContext.LAST_COMMIT_LSN_KEY, String.valueOf(lastCommitLsn)); and either construct a fresh LsnOffset from it for whatever downstream consumer needs the "early" value, or drop this addition entirely if its only benefit is closing an already-narrow, already-covered-by-fallback edge case (getLsnCommit() already falls back to getLsn() when the key is missing, so the existing behavior without this mutation is not incorrect, just slightly less precise in that one edge case).
  • Severity: Medium, pending the CI investigation below — I'd raise this to High if the E2E failure turns out to trace back to this mutation.
  • Raised by another reviewer: No.

2. Code Quality Assessment

2.1 Coding Standards

Clean and consistent with the surrounding style; comments explaining the new persistence logic are present and clear about intent (even though, per Issue 2, the intent isn't fully realized as written).

2.2 Test Coverage and Test Stability

Unit tests: Stable, and the gap I flagged in round 1 remains closed. LsnOffsetTest now has testGetLsnCommitWhenLsnCommitKeyExists, testGetLsnCommitFallbackToLsnWhenLsnCommitKeyMissing, and a new testConstructorStoresLastCommitLsnKey (covering the 3-arg constructor's new fallback seeding). IncrementalSourceStreamFetcherTest has testShouldEmitAtOrAfterWatermark / testShouldEmitBeforeWatermarkFiltered, genuinely exercising the real shouldEmit() method (not mocked out) via a createPlainFetcher() helper and a properly-constructed SourceRecord. All four are deterministic, no Thread.sleep, no shared static state — no flaky-test anti-pattern.

Not covered by any test: the new offset.getOffset().put(...) mutation in commitCurrentOffset (Issue 2). No unit test constructs two references to the same LsnOffset/split-startup-offset and asserts the mutation is (or isn't) visible where expected.

Mandatory CI check — High risk, must be resolved before merge: I checked the fork's actual CI run for the current head (zhang-arvin/seatunnel run 32496661938, job updated-modules-integration-test-part-1 (8, ubuntu-latest)) rather than trusting the apache-side pointer, and found a real test failure, not an infra/network flake:

[ERROR] Tests run: 37, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 1,038.861 s <<< FAILURE! - in org.apache.seatunnel.connectors.seatunnel.cdc.postgres.PostgresCDCIT
[ERROR] testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes{TestContainer}[1]  Time elapsed: 186.111 s  <<< ERROR!
org.awaitility.core.ConditionTimeoutException: ... expected: <1> but was: <0> within 2 minutes.
	at PostgresCDCIT.testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes(PostgresCDCIT.java:629)
Caused by: org.opentest4j.AssertionFailedError: expected: <1> but was: <0>

I read the test source (seatunnel-e2e/.../PostgresCDCIT.java, unchanged by this PR — confirmed not in the diff): this test inserts a row, takes a savepoint, restores the job from that savepoint, inserts one more row (id = 15) after restore, and asserts it appears in the sink within 120 seconds. This is, almost exactly, the scenario this PR exists to fix ("committed-offset recovery skipping rows after savepoint"), and it is currently failing — row 15 never showed up in the sink within the wait window.

I want to be careful and precise about what I do and don't know here:

  • This test file has a documented history of CI-timing flakiness on shared runners (git log shows prior dedicated fixes: "[Fix][E2E] Stabilize flaky connector E2E tests (#11456)" and "[Fix][E2E] Wait for Postgres CDC WAL stream readiness (#11202)"), and the test itself carries a comment acknowledging restore/reconnect can be slow on shared GitHub runners — so a pure CI-timing flake, unrelated to this PR's logic, is a real possibility.
  • However, given that this is the single most directly relevant test to this PR's own claimed fix, and given my Issue 2 finding above (a new, unsynchronized mutation on exactly the code path this scenario exercises), I don't think it's responsible to wave this off as "probably just CI flakiness" without someone re-running it and, ideally, reproducing it locally or bisecting whether it also fails without the Issue 2 mutation.
  • I could not determine from static analysis alone whether this is a genuine regression from this PR's changes, a pre-existing flake this PR happened to hit, or something else. This needs to be actively investigated (rerun the specific job, and if it fails again, treat it as a real blocker) rather than assumed to be either.

Given that this is a single-error result out of 37 tests, a rerun-and-recheck is a reasonable first step, but I'm rating this High risk for the review's mandatory test-stability check, because if it turns out to be reproducible, it directly contradicts this PR's central claim.

2.3 Docs

No user-facing config, defaults, or behavior contract changed (pure bug fix, no new Option), consistent with no docs/en/docs/zh changes.

3. Architectural Soundness

The three original fixes remain applied at the layer that actually owns the bug, correctly scoped, with no leakage of Postgres-specific concerns into connector-cdc-base beyond the shared, correctly-gated shouldEmit change. The new offset-persistence addition (Issue 2) is a reasonable goal (make the next checkpoint pick up the committed LSN sooner) but the implementation — mutating a shared object across a thread boundary without synchronization — is not the right way to achieve it; an immutable-copy-and-replace pattern would be architecturally consistent with how the rest of this Offset/LsnOffset hierarchy is used (built fresh per record via getOffsetPosition, never mutated in place elsewhere in this codebase as far as I traced).

4. Issue Summary

# Title Location Severity Raised by another reviewer
1 lastCommitLsn remains non-volatile, read cross-thread (carryover) PostgresWalFetchTask.java:36,78-85 Medium No
2 New unsynchronized cross-thread mutation of the live Offset map via offset.getOffset().put(...) PostgresWalFetchTask.java:98-100 Medium (see note) No
3 PostgresCDCIT.testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes (savepoint + restart + committed-offset recovery — this PR's own scenario) is failing on the current head's CI run seatunnel-e2e/.../PostgresCDCIT.java:629; fork run 32496661938, job updated-modules-integration-test-part-1 High No

5. Merge Recommendation

Conclusion: Ready to merge after fixes

Blockers:

  • Issue 3 — please rerun the updated-modules-integration-test-part-1 job (or the full connector-cdc-postgres-e2e module) on the current head. If testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes passes on rerun, it's likely the known CI-timing flake this file has a documented history of; if it fails again, this needs to be treated as a real blocker and investigated (I'd start by checking whether it still fails with Issue 2's mutation reverted, since that's the only genuinely new production code path this round touches that overlaps with the failing scenario).

Recommended fixes (non-blocking, but worth doing given how easy they are):

  • Issue 2 — replace the in-place offset.getOffset().put(...) mutation with a copy-then-use pattern, removing the unsynchronized cross-thread write entirely rather than relying on timing to make it safe.
  • Issue 1 — mark lastCommitLsn volatile (still pending from my previous review).

Overall assessment: the core data-correctness fixes from the first two rounds remain sound and I have no new concerns about them — they're verified against real Debezium sources and now have solid, non-mocked unit coverage. What's new and needs attention this round is narrower in scope but touches exactly the recovery path this PR is about: a new unsynchronized mutation with a plausible (though not proven) aliasing window, and a live CI failure in the single most relevant E2E test for this PR's claim. Neither is necessarily fatal — the mutation might turn out to be harmless in practice, and the CI failure might turn out to be the known flake — but given this is explicitly a data-correctness fix for a financial/production-grade CDC recovery path, I think it's worth actually confirming rather than assuming, before merge. Happy to take another look as soon as the CI signal is clarified.

zhang-arvin added a commit to zhang-arvin/seatunnel that referenced this pull request Aug 22, 2026
@zhang-arvin
zhang-arvin force-pushed the fix-pg-cdc-offset-recovery branch from a726546 to 7f5029c Compare August 22, 2026 11:59
@zhang-arvin

Copy link
Copy Markdown
Contributor Author

@DanielLeens Thanks for the thorough review! Both issues addressed:

  1. Issue 1 (volatile): Marked lastCommitLsn as volatile to ensure cross-thread visibility.

  2. Issue 2 (unsynchronized mutation): Removed the offset.getOffset().put(...) in-place mutation entirely. The fallback in getLsnCommit() already handles the case when LAST_COMMIT_LSN_KEY is absent, so this edge-case optimization is not needed and was introducing unnecessary cross-thread mutation risk.

Pushed as commit 7f5029c. The CI rerun should also clarify the E2E test status. Happy to take another look!

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What Problem Does This PR Solve?

  • User pain point (#11847): Postgres-CDC could silently skip already-committed rows, or mask a genuine streaming failure, when resuming from a checkpoint/savepoint.
  • Fix approach: three coordinated fixes — (1) PostgresWalFetchTask.commitCurrentOffset now flushes the last-committed-transaction LSN (getLsnCommit()) instead of the current streaming LSN (getLsn()) to the replication slot; (2) IncrementalSourceStreamFetcher.shouldEmit's non-exactly-once boundary check changed from strict isAfter to isAtOrAfter, so a post-restart record sharing the exact watermark LSN is no longer dropped; (3) PostgresWalFetchTask.execute now checks errorHandler.getProducerThrowable() after the streaming loop exits, so streaming failures surface instead of being silently swallowed.
  • One-sentence summary: this is round 4 of a long-running, genuinely productive review cycle — the branch was force-pushed with a fresh, squashed 2-commit history since my round-3 review, and it resolves all three previously-open items (a non-volatile field, an unsynchronized cross-thread map mutation, and a live CI failure in the exact scenario this PR fixes) cleanly.

Re-reviewing the entire current diff against dev from scratch (current head 7f5029c745), since the branch history changed shape again (force-push from a726546b1), not just a delta.

1. Code Change Review

1.1 Core Logic Analysis

What changed since round 3 (a726546b1) vs. current head (7f5029c745): the branch was squashed to 2 commits, still confined to the same core files. I diffed the current head against dev file-by-file rather than trusting my memory of round 3, and confirmed:

  • The three original correctness fixes (LSN-key selection, isAtOrAfter boundary, post-loop producerThrowable check) are all still present and unchanged from what I verified against real Debezium 1.9.8.Final sources in round 1.
  • lastCommitLsn is now declared private volatile Long lastCommitLsn; (PostgresWalFetchTask.java:39) — resolves round 3's Issue 1.
  • The in-place offset.getOffset().put(PostgresOffsetContext.LAST_COMMIT_LSN_KEY, ...) mutation from round 3's Issue 2 has been removed entirely, not just made safer. commitCurrentOffset now reads:
    public void commitCurrentOffset(LsnOffset offset) {
        if (streamingChangeEventSource != null && offset != null) {
            Long commitLsn = offset.getLsnCommit().asLong();
            if (commitLsn != null
                    && (lastCommitLsn == null
                            || Lsn.valueOf(commitLsn).compareTo(Lsn.valueOf(lastCommitLsn)) > 0)) {
                lastCommitLsn = commitLsn;
                Map<String, Object> offsets = new HashMap<>();
                offsets.put(PostgresOffsetContext.LAST_COMMIT_LSN_KEY, lastCommitLsn);
                streamingChangeEventSource.commitOffset(offsets);
            }
        }
    }
    There is no longer any write into the shared, live Offset/split-state map from the checkpoint-notification thread — this fully closes the cross-thread-mutation concern I raised in round 3, rather than papering over it with a copy-then-write pattern (which was my suggested fallback, but removing the mutation outright is the cleaner fix, and the author's own comment on this in the PR thread — "the fallback in getLsnCommit() already handles the case when LAST_COMMIT_LSN_KEY is absent, so this edge-case optimization is not needed" — is accurate and matches my own read of the code).

I want to be precise about verifying this doesn't reintroduce the original #11847 bug, not just assume it because the risky code is gone. The mechanism that makes this safe: IncrementalSourceRecordEmitter.processElement() still builds a brand-new LsnOffset per processed record via getOffsetPosition() (confirmed unchanged from round 3's trace), and this PR's LsnOffset(Long, Long, Instant) constructor now seeds LAST_COMMIT_LSN_KEY with that record's own LSN at construction time (LsnOffset.java:63, with an inline comment explaining why this is safe as a starting value). So the split's persisted startupOffset — the thing actually captured into checkpoint/savepoint state — always carries a LAST_COMMIT_LSN_KEY reflecting at least the last record SeaTunnel itself processed, without needing any cross-thread write-back from commitCurrentOffset at all. commitCurrentOffset's only remaining job is advancing Debezium's own internal replication-slot commit via streamingChangeEventSource.commitOffset(...) (a Debezium-internal call, not a mutation of SeaTunnel's own split state) and maintaining the local lastCommitLsn diagnostic field.

Empirical confirmation, not just static reasoning: I pulled the fork's actual CI run for this exact head (zhang-arvin/seatunnel run 32571763533, on 7f5029c745) and downloaded the updated-modules-integration-test-part-1 (8, ubuntu-latest) job log directly (rather than trusting the checks summary). The specific test that failed in round 3 — PostgresCDCIT#testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes, which does exactly the savepoint-then-restart-then-assert-next-row-appears scenario this PR targets — now completes in 72s (previously timed out at 186s):

Test org.apache.seatunnel.connectors.seatunnel.cdc.postgres.PostgresCDCIT.testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes successfully run.
...
[INFO] Tests run: 37, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 924.698 s - in org.apache.seatunnel.connectors.seatunnel.cdc.postgres.PostgresCDCIT

The whole PostgresCDCIT class is 37/37 green. This resolves round 3's Issue 3 with a real, observed passing run, not just an assumption that "removing risky code must have fixed it."

I also checked every other job in that same fork run: of 70 jobs, 37 succeeded, 32 were skipped (expected — these are the untouched-module skips that the project's path-filtering produces when only connector-cdc-base/connector-cdc-postgres change), and exactly 1 (paimon-connector-it (11, ubuntu-latest)) shows cancelled — unrelated to Postgres CDC, and the overall workflow's cancelled conclusion is driven by that one job, not a masked failure elsewhere. I did not find any job with conclusion: failure or timed_out in this run.

1.2 Compatibility Impact

No checkpoint/offset serialized-format change — unchanged conclusion from previous rounds. LsnOffset still doesn't add/remove/rename any field in its internal map; LAST_COMMIT_LSN_KEY is an existing Debezium-recognized key, and the constructor now seeds it proactively rather than leaving it absent (with getLsnCommit()'s null-check fallback to getLsn() still present for any offset object that predates this seeding, e.g. deserialized from an old checkpoint). Old checkpoints restore correctly: their offset map simply lacks LAST_COMMIT_LSN_KEY, and getLsnCommit() falls back to getLsn() exactly as before this PR.

1.3 Performance / Side-Effects

Negligible — same conclusion as previous rounds. Removing the live-mutation code path is a net simplification with no new cost.

1.4 Error Handling and Logging

Both carryover issues from round 3 are resolved (see 1.1: volatile, and the mutation removed rather than synchronized). No new issues found this round. The new log.debug in shouldEmit (added in round 2, unchanged since) remains a reasonable, low-noise diagnostic addition.

2. Code Quality Assessment

2.1 Coding Standards

Clean; the removed mutation simplifies commitCurrentOffset back to a single, easy-to-follow responsibility (advance the replication-slot commit position). The new constructor comment in LsnOffset.java clearly states the safety rationale for the initial-value seeding.

2.2 Test Coverage and Test Stability

All unit tests from round 3 remain present and unchanged in intent: LsnOffsetTest (testGetLsnCommitWhenLsnCommitKeyExists, testGetLsnCommitFallbackToLsnWhenLsnCommitKeyMissing, testConstructorStoresLastCommitLsnKey) and IncrementalSourceStreamFetcherTest (testShouldEmitAtOrAfterWatermark, testShouldEmitBeforeWatermarkFiltered) — all deterministic, no Thread.sleep, no shared static state, genuinely exercising the real methods rather than mocking them away. Stability rating: Stable, and — per 1.1 — now with a confirmed-passing E2E run of the specific regression scenario (PostgresCDCIT#testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes), which was the one thing I couldn't confirm in round 3.

No new test-coverage gaps introduced by removing the mutation — there's nothing left to test there since the code path no longer exists.

2.3 Documentation Updates

No user-facing config, defaults, or behavior contract changed — no docs/en/docs/zh update required, consistent with previous rounds.

3. Architectural Soundness

3.1 Elegance of the Solution

This round's resolution is more elegant than either option I proposed in round 3: rather than synchronizing or copy-then-writing the shared map, the author recognized the mutation wasn't needed at all once the constructor-seeding safety net exists, and removed it. That's a better outcome than my own suggested fallback.

3.2 Maintainability

Good — commitCurrentOffset is back to a single, clear responsibility with no shared-mutable-state concerns to reason about.

3.3 Extensibility

No concerns.

3.4 Historical-Version Compatibility

No impact on checkpoint/savepoint formats or existing job configs; old checkpoints restore via the existing fallback path exactly as before this PR.

4. Issue Summary

# Issue Location Status
1 lastCommitLsn not volatile, read cross-thread (round 3) PostgresWalFetchTask.java Resolved — now volatile
2 Unsynchronized cross-thread mutation of live Offset map (round 3) PostgresWalFetchTask.java (commitCurrentOffset) Resolved — mutation removed, replaced by constructor-time seeding
3 PostgresCDCIT#testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes failing on CI (round 3) PostgresCDCIT.java:629 Resolved — confirmed passing (37/37, 924s total) on current head's fork run

No new issues found this round.

5. Merge Recommendation

Conclusion: Ready to merge

Blockers: none. All three previously-open items are resolved, two by direct code inspection (volatile, mutation removed) and the third by direct evidence from a downloaded CI job log showing the specific regression test passing on the current head.

Recommended fixes — non-blocking: none outstanding from my side.

Overall assessment: this has been a thorough, well-executed review cycle across four rounds. The three original root-cause fixes (LSN-key selection, boundary-check off-by-one, swallowed streaming errors) were verified against real Debezium sources early on and have remained stable and correct throughout. The one piece of genuinely new production logic introduced in round 3 (the live offset-map mutation) carried a real, if narrow, concurrency-hygiene risk, and rather than defending or patching it, the author removed it and relied on a safer, already-present fallback mechanism — that's the right call, and I verified it holds up both by tracing the constructor-seeding safety net and by confirming the exact regression scenario now passes in CI. I have no further concerns and consider this ready to merge, contingent on the apache-side Build check re-running cleanly (its cancelled status traces to one unrelated paimon-connector-it job cancellation in the fork's run, not a Postgres-CDC failure — worth a rerun to get a clean green check on the PR itself, but not a code-correctness blocker).

CI note: the apache-side Build check currently shows cancelled (surfaced as "fail" in the simplified PR-checks view). I traced this to the fork's own workflow run (zhang-arvin/seatunnel run 32571763533) and found 37 successful jobs, 32 expected path-filter skips, and exactly one unrelated cancelled job (paimon-connector-it) that drove the overall run conclusion — not a Postgres-CDC-related failure. I'd recommend a plain rerun to get a clean Build check on the PR before merge, since the underlying test evidence (including the specific regression test this PR targets) is already green.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What Problem Does This PR Solve?

Postgres-CDC could silently skip already-committed rows, or mask a genuine streaming failure, when resuming from a checkpoint/savepoint (issue #11847). Three coordinated fixes address this:

  1. PostgresWalFetchTask.commitCurrentOffset now flushes the last-committed-transaction LSN (getLsnCommit()) instead of the current streaming LSN (getLsn()) to the replication slot, so Postgres is never told it's safe to recycle WAL a still-open transaction still needs.
  2. IncrementalSourceStreamFetcher.shouldEmit's non-exactly-once boundary check changed from strict isAfter to isAtOrAfter, so a post-restart record sharing the exact watermark LSN as the last-processed record is no longer dropped.
  3. PostgresWalFetchTask.execute now checks errorHandler.getProducerThrowable() after the streaming loop exits, so an async producer failure surfaces instead of leaving the task silently "finished."

This is round 5 of the review cycle on this PR. The only change since my round-4 review (head 7f5029c745, 2026-08-23) is a single commit titled "Trigger CI re-run" — I confirmed via git diff 7f5029c7451 91572686f that it is a genuinely empty commit with zero file changes. I'm re-reviewing the current head from scratch per our process rather than assuming that, but I want to be upfront that I don't expect (and didn't find) any new code-level findings this round.

1. Code Change Review

1.1 Core Logic Analysis

I re-diffed the current head against dev file-by-file (not relying on memory of prior rounds) and independently re-traced the full recovery call chain:

checkpoint N triggers
  -> IncrementalSourceReader.snapshotState(N): snapshotChangeLogOffset = incrementalSplit.getStartupOffset()
  -> notifyCheckpointComplete(N) -> PostgresDialect.commitChangeLogOffset(snapshotChangeLogOffset)
       -> PostgresWalFetchTask.commitCurrentOffset(offset)
            commitLsn = offset.getLsnCommit().asLong()   // FIX 1: was offset.getLsn()
            lastCommitLsn = commitLsn (volatile write)
            streamingChangeEventSource.commitOffset({lsn_commit: commitLsn})
                 -> replicationStream.flushLsn(commitLsn)  // tells Postgres WAL below this is safe to recycle

job restart from savepoint N
  -> IncrementalSplit restored with startupOffset = last emitted record's LSN (P)
  -> IncrementalSourceStreamFetcher.configureFilter(): splitStartWatermark = P
  -> replication slot resumes streaming, may re-deliver events at LSN == P
     (a single WAL position can carry multiple row-level events; only the
      first one at P was actually processed before the crash)
  -> shouldEmit(record): position.isAtOrAfter(P)   // FIX 2: was isAfter(P), which
                                                     // dropped any unprocessed sibling at P

Verified against the actual source, not just re-reading prior review text:

  • PostgresWalFetchTask.java:39 — private volatile Long lastCommitLsn; (was non-volatile; the round-2/3 cross-thread visibility issue is resolved).
  • PostgresWalFetchTask.java:75-84 — the post-loop producerThrowable check throws with split id + last committed LSN context, confirming Fix 3 is still present.
  • LsnOffset.java:63-64 — the LsnOffset(Long, Long, Instant) constructor now seeds LAST_COMMIT_LSN_KEY = lsn.toString() at construction time, with an inline comment explaining the safety rationale ("at the start of streaming, the committed LSN equals the current LSN"). I confirmed there is no longer any in-place mutation of the shared, live Offset map (offset.getOffset().put(...)) anywhere in commitCurrentOffset — grepping the current diff for .getOffset().put returns nothing. This is what closed my round-3 unsynchronized-cross-thread-mutation concern: rather than synchronizing the risky write, the author removed it and relies on the constructor-time seeding + getLsnCommit()'s existing getLsn() fallback to guarantee every persisted split offset always carries a valid lsn_commit.
  • IncrementalSourceStreamFetcher.java:264-276 — the isAtOrAfter change is still correctly confined to the if (!taskContext.isExactlyOnce()) branch. I checked this scoping myself rather than trusting the description: the isExactlyOnce()==true branch (hasEnterPureBinlogPhase/finishedSplitsInfo/isRecordBetween, lines 277-292) is byte-for-byte untouched, so exactly-once-configured jobs are not affected by this change at all — no risk of the "opposite failure mode" (re-reading already-committed rows / duplicate delivery from a different recovery scenario) leaking outside the intended path.
  • SourceOptions.java:114-117 — confirmed exactly_once defaults to false, so this fix sits on the default Postgres-CDC recovery path for existing users, not an edge configuration.

Opposite-failure-mode check (the specific risk flagged for this review): could isAtOrAfter cause duplicate delivery of already-committed rows on some other recovery path? No — this branch only ever executes when isExactlyOnce() is false, and that path's own existing code comment already documents it as at-least-once ("not support exactly-once, so ignore the watermark check"). The only behavior change is: a record at exactly the boundary LSN, which was previously always dropped (even if it was a never-before-seen sibling event), can now be re-emitted. In the worst case this re-emits one already-processed record as a duplicate — acceptable and expected under the path's own documented at-least-once contract — it never causes an already-committed row to be silently skipped a second time, and it cannot affect the untouched exactly-once branch.

1.2 Compatibility Impact

Fully compatible; safe to restore from pre-fix checkpoints. LsnOffset's internal Map<String,String> offset gains no new field shape — LAST_COMMIT_LSN_KEY is an existing Debezium-recognized key, already populated by the (unmodified) vendored PostgresOffsetContext on every commit. A checkpoint taken with the old code simply lacks this key in some cases; getLsnCommit()'s fallback to getLsn() reproduces the old (pre-fix) value exactly in that case — no exception, no crash, just doesn't yet benefit from the fix until a newer checkpoint captures a real lsn_commit. No docs/en/introduction/concepts/incompatible-changes.md entry is needed, and none was added.

1.3 Performance / Side-Effects

Negligible. One additional volatile field read/write (commits happen once per checkpoint, not per record), one parameterized log.debug per record on the non-exactly-once path, and Fix 1 makes WAL flush strictly more conservative (flushes an earlier-or-equal LSN than before) — an intended, minor increase in retained WAL, not a regression.

1.4 Error Handling / Logging

No open issues. Both items I raised in earlier rounds are resolved by inspection: lastCommitLsn is volatile (was Issue 1, round 2/3), and the unsynchronized cross-thread map mutation is removed entirely rather than patched (was Issue 2, round 3) — confirmed above, not just carried forward from memory.

2. Code Quality Assessment

2.1 Coding Standards

Clean; commitCurrentOffset has a single, clear responsibility (advance the replication-slot commit position) with no shared-mutable-state concerns left to reason about. The LsnOffset constructor comment clearly states the safety rationale for the seeding.

2.2 Test Coverage & Stability

Rating: Stable. LsnOffsetTest (testGetLsnCommitWhenLsnCommitKeyExists, testGetLsnCommitFallbackToLsnWhenLsnCommitKeyMissing, testConstructorStoresLastCommitLsnKey) and IncrementalSourceStreamFetcherTest (testShouldEmitAtOrAfterWatermark, testShouldEmitBeforeWatermarkFiltered) all directly exercise the real changed methods (not mocked away), are deterministic, and have no Thread.sleep/timing dependence/shared static state. I re-confirmed this by reading the test files at the current head rather than trusting the description — they match what's described.

Beyond unit tests, the E2E regression scenario for this exact bug (PostgresCDCIT#testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes — inserts a row, savepoints, restarts, inserts one more row, asserts it appears in the sink) was confirmed passing 37/37 on the fork's CI run for code-identical head 7f5029c745 in my round-4 review (zhang-arvin/seatunnel run 32571763533), after having genuinely failed on the prior head (a726546b1, round 3) with the now-removed unsynchronized mutation in place.

2.3 Docs

No user-facing config, defaults, or behavior contract changed — no docs/en/docs/zh update required, and none was made. Consistent.

3. Architectural Soundness

The fixes are applied at the layer that actually owns each bug: Postgres-specific LSN-key selection in LsnOffset/PostgresWalFetchTask, and the shared boundary-comparison logic in IncrementalSourceStreamFetcher, correctly gated to the non-exactly-once branch only, with no leakage of Postgres-specific concerns into connector-cdc-base. The final shape (constructor-time seeding instead of a cross-thread live-map mutation) is more elegant and safer than either option I proposed in round 3, and is consistent with how the rest of the Offset/LsnOffset hierarchy is used elsewhere in this codebase (built fresh per record, never mutated in place).

4. Issue Summary

# Issue Location Status
1 lastCommitLsn not volatile, read cross-thread (round 2/3) PostgresWalFetchTask.java Resolved — confirmed volatile at current head
2 Unsynchronized cross-thread mutation of live Offset map (round 3) PostgresWalFetchTask.java (commitCurrentOffset) Resolved — mutation removed, replaced by constructor-time seeding
3 PostgresCDCIT#testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes failing on CI (round 3) PostgresCDCIT.java:629 Resolved — confirmed 37/37 passing on code-identical head 7f5029c745

No new issues found this round — the "Trigger CI re-run" commit contains no code change.

5. Merge Recommendation

Conclusion: Ready to merge

Blockers: none. All three original root-cause fixes are verified sound (independently re-traced against the actual source this round, not just re-read from prior text), correctly scoped to the default non-exactly-once recovery path, backward-compatible with pre-fix checkpoints, and covered by real (non-mocked) unit tests plus a confirmed-passing E2E regression test for the exact scenario this PR targets. The two concurrency-hygiene issues raised in earlier rounds are both resolved.

Recommended fixes: none outstanding.

CI note: at the time of this review, the fork's Build workflow for the current head (triggered by the "Trigger CI re-run" commit) is still queued/in-progress. The prior run on code-identical content (head 7f5029c745) completed with PostgresCDCIT fully green (37/37) and only one unrelated, expected job (paimon-connector-it, cancelled) driving the overall apache-side check to red — not a Postgres-CDC issue. I'd still recommend confirming this fresh run lands clean before the actual merge click, but given the code is unchanged and already thoroughly verified, I'm approving now rather than holding the review hostage to CI infrastructure timing.

This has been a long, well-executed review cycle — thank you for the careful, responsive iteration across all four prior rounds, including removing rather than defending the round-3 concurrency risk once a cleaner alternative was clear.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up on the CI note in my last review: the "Trigger CI re-run" run I flagged as still queued/in-progress on this head (91572686f6f5, fork run 32806946224) has since completed, and it landed as failure — not the green result I asked to confirm before merge.

Looking at the failing/cancelled jobs: unit-test (11, windows-latest) failed with org.apache.seatunnel.engine.server.master.JobStateCleanupDelayTest timing out after ~311s in the seatunnel-engine-server module — this is the same Windows Hazelcast node-start flake signature I flagged as environmental on another PR in this batch (PR #11850), unrelated to connector-cdc-base/Postgres CDC. paimon-connector-it (11, ubuntu-latest) was cancelled (looks like the known Paimon classloader-hang timeout, not a real failure), and the two ubuntu unit-test jobs were cancelled as a downstream side effect of the Windows failure, not failures in their own right. None of this touches Postgres WAL/offset code.

So this doesn't change my "Ready to merge" conclusion — the three round 1-3 issues remain resolved, and the previously-confirmed 37/37 PostgresCDCIT pass on code-identical content still stands as the real regression-test evidence. This branch is also 77 commits behind dev, but the specific failure signatures here look environmental rather than base-staleness related. Recommend a job-level rerun of the failed/cancelled jobs first (gh run rerun 32806946224 --failed from your fork); if the Windows job keeps failing the same way, that's the known flake, not something introduced by this PR.

zhang-arvin and others added 2 commits September 4, 2026 22:17
…ng rows after savepoint

Fix three issues that cause Postgres-CDC to silently skip rows after savepoint recovery:

1. PostgresWalFetchTask.commitCurrentOffset used offset.getLsn()
   (SourceInfo.LSN_KEY) to flush the slot LSN, but Debezium's
   commitOffset expects the LAST_COMMIT_LSN_KEY field. Added
   getLsnCommit() to LsnOffset that reads LAST_COMMIT_LSN_KEY
   with fallback to LSN_KEY, and updated commitCurrentOffset to
   use the committed LSN.

2. IncrementalSourceStreamFetcher.shouldEmit used strict
   greater-than (isAfter) for non-exactly-once mode. After
   recovery, the first event may have the same LSN as
   splitStartWatermark, causing it to be filtered. Changed
   to isAtOrAfter to include the watermark-position event.

3. PostgresWalFetchTask.execute did not check the error handler
   after streaming completed. Streaming failures could be
   silently swallowed. Added error handler check to surface
   streaming errors.
@zhang-arvin
zhang-arvin force-pushed the fix-pg-cdc-offset-recovery branch from 9157268 to cb2c1b6 Compare September 4, 2026 14:19

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What Problem Does This PR Solve?

Postgres-CDC could silently skip already-committed rows, or mask a genuine streaming failure, when resuming from a checkpoint/savepoint (issue #11847). Three coordinated fixes address this:

  1. PostgresWalFetchTask.commitCurrentOffset now flushes the last-committed-transaction LSN (getLsnCommit()) instead of the current streaming LSN (getLsn()) to the replication slot, so Postgres is never told it's safe to recycle WAL a still-open transaction still needs.
  2. IncrementalSourceStreamFetcher.shouldEmit's non-exactly-once boundary check changed from strict isAfter to isAtOrAfter, so a post-restart record sharing the exact watermark LSN as the last-processed record is no longer dropped.
  3. PostgresWalFetchTask.execute now checks errorHandler.getProducerThrowable() after the streaming loop exits, so an async producer failure surfaces instead of leaving the task silently "finished."

This is a fresh full re-review of the current head. Since my last review the branch has been rebased onto a newer dev and an empty "Trigger CI re-run" commit was added on top — I re-diffed from scratch rather than trusting that: git diff apache/dev...HEAD --stat at the current head is the same 5 files, 149 insertions, 3 deletions as before, and I re-read every changed hunk of LsnOffset.java, PostgresWalFetchTask.java, and IncrementalSourceStreamFetcher.java line-by-line against the current file content. No apology owed this round — the content is genuinely unchanged and there is nothing new to catch.

1. Code Change Review

1.1 Core Logic Analysis

Re-traced the full recovery call chain against the current source:

checkpoint N triggers
  -> IncrementalSourceReader.snapshotState(N): snapshotChangeLogOffset = incrementalSplit.getStartupOffset()
  -> notifyCheckpointComplete(N) -> PostgresDialect.commitChangeLogOffset(snapshotChangeLogOffset)
       -> PostgresWalFetchTask.commitCurrentOffset(offset)
            commitLsn = offset.getLsnCommit().asLong()   // FIX 1: was offset.getLsn()
            lastCommitLsn = commitLsn (volatile write)
            streamingChangeEventSource.commitOffset({lsn_commit: commitLsn})
                 -> replicationStream.flushLsn(commitLsn)  // tells Postgres WAL below this is safe to recycle

job restart from savepoint N
  -> IncrementalSplit restored with startupOffset = last emitted record's LSN (P)
  -> replication slot resumes streaming, may re-deliver events at LSN == P
     (a single WAL position can carry multiple row-level events; only the
      first one at P was actually processed before the crash)
  -> shouldEmit(record): position.isAtOrAfter(P)   // FIX 2: was isAfter(P), which
                                                     // dropped any unprocessed sibling at P

Re-verified against the current source, not just prior review text:

  • PostgresWalFetchTask.java: private volatile Long lastCommitLsn; — still volatile.
  • PostgresWalFetchTask.java: the post-loop producerThrowable check still throws with split id + last committed LSN context.
  • LsnOffset.java: the LsnOffset(Long, Long, Instant) constructor still seeds LAST_COMMIT_LSN_KEY = lsn.toString() at construction, and getLsnCommit() still falls back to getLsn() when the key is absent. No in-place mutation of the shared, live Offset map remains anywhere in commitCurrentOffset.
  • IncrementalSourceStreamFetcher.java: the isAtOrAfter change is still confined to the if (!taskContext.isExactlyOnce()) branch — I re-read the surrounding method and confirmed the isExactlyOnce()==true branch (hasEnterPureBinlogPhase/finishedSplitsInfo/isRecordBetween) is byte-for-byte untouched, so exactly-once-configured jobs are unaffected. isAtOrAfter/isAfter are pre-existing methods on the base Offset class (compareTo(that) >= 0 / > 0 respectively) — not new code, just a changed call site.

Opposite-failure-mode re-check: could isAtOrAfter cause duplicate delivery of already-committed rows on some other recovery path? No — this branch only ever executes when isExactlyOnce() is false, and that path's own existing code comment documents it as at-least-once. The only behavior change is: a record at exactly the boundary LSN, previously always dropped even if it was a never-seen sibling event, can now be re-emitted — worst case one duplicate, never a silently-re-skipped row, and it cannot leak into the untouched exactly-once branch.

Both scenarios named in my dispatch brief are covered by the above: a normal restart (checkpoint N confirmed, clean restart from N) benefits from Fix 1 alone — WAL is not prematurely recycled past a still-open transaction. A mid-batch crash (crash between processing record P and the next checkpoint) is where Fix 2 matters — on restart the replication slot may redeliver a sibling event at the exact same LSN P that was never actually processed, and isAtOrAfter now lets it through instead of dropping it. Neither fix reintroduces duplicate delivery outside the documented at-least-once contract of the non-exactly-once path.

1.2 Compatibility Impact

Fully compatible; safe to restore from pre-fix checkpoints. LAST_COMMIT_LSN_KEY is an existing Debezium-recognized key already populated by the vendored PostgresOffsetContext on every commit. A checkpoint taken with the old code simply lacks this key in some cases; getLsnCommit()'s fallback to getLsn() reproduces the old pre-fix value exactly — no exception, no crash. No docs/en/introduction/concepts/incompatible-changes.md entry needed, and none was added.

1.3 Performance / Side-Effects

Negligible. One additional volatile field read/write per checkpoint (not per record), one log.debug per record on the non-exactly-once path, and Fix 1 makes WAL flush strictly more conservative (flushes an earlier-or-equal LSN) — an intended, minor increase in retained WAL, not a regression.

1.4 Error Handling / Logging

No open issues.

2. Code Quality Assessment

2.1 Coding Standards

Clean; commitCurrentOffset has a single, clear responsibility with no shared-mutable-state concerns left to reason about. The LsnOffset constructor comment states the safety rationale for the seeding.

2.2 Test Coverage & Stability

Rating: Stable. LsnOffsetTest (testGetLsnCommitWhenLsnCommitKeyExists, testGetLsnCommitFallbackToLsnWhenLsnCommitKeyMissing, testConstructorStoresLastCommitLsnKey) and IncrementalSourceStreamFetcherTest (testShouldEmitAtOrAfterWatermark, testShouldEmitBeforeWatermarkFiltered) directly exercise the real changed methods, are deterministic, and have no Thread.sleep/timing dependence/shared static state — re-confirmed by reading the current test files, not the prior round's description. Beyond unit tests, the E2E regression scenario for this exact bug (PostgresCDCIT#testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes) was previously confirmed passing 37/37 on code-identical content.

2.3 Docs

No user-facing config, defaults, or behavior contract changed — no docs update required, and none was made.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix — applied at the layer that actually owns each bug: Postgres-specific LSN-key selection in LsnOffset/PostgresWalFetchTask, and the shared boundary-comparison logic in IncrementalSourceStreamFetcher, correctly gated to the non-exactly-once branch only.

3.2 Maintainability

Good — constructor-time seeding instead of a cross-thread live-map mutation, consistent with how Offset/LsnOffset is used elsewhere (built fresh per record, never mutated in place).

3.3 Extensibility

No concerns.

3.4 Historical-Version Compatibility

No impact — see 1.2.

4. Issue Summary

No open issues. All previously-identified concerns (non-volatile lastCommitLsn, unsynchronized cross-thread map mutation, the CI-failing PostgresCDCIT case) were resolved in earlier rounds and remain resolved at the current head.

5. Merge Recommendation

Conclusion: Ready to merge

Blockers: none.

Recommended fixes: none outstanding.

CI status: the fork's Build run for the current head is still queued at the time of this review (all of this author's open PRs appear to have been synced/re-triggered together a few minutes ago). Content-wise nothing has changed since my prior full approval — the code is unchanged and already thoroughly verified against both the normal-restart and mid-batch-crash recovery scenarios — so I'm approving again now rather than holding the review hostage to CI queue timing. Please confirm the fresh run lands clean (in particular PostgresCDCIT) before the actual merge click.

This has been a long, well-executed review cycle — thank you for the careful, responsive iteration.

@DanielLeens

Copy link
Copy Markdown
Contributor

CI record update: my last comment described the fork Build run for this head as "still queued." It has since completed, and it finished failure — updated-modules-integration-test-part-1 (8, ubuntu-latest) and updated-modules-integration-test-part-4 (8, ubuntu-latest) both failed.

Neither of those buckets touches the Postgres-CDC WAL/offset-recovery code this PR changes, and this is the same updated-modules-integration-test bucket that's been a known source of unrelated flakes on other PRs in this same batch-retrigger window, so I don't read this as a defect in this PR's diff. A rerun of the two failing jobs should be the right next step; the approval stands on the code side.

davidzollo added a commit to abdessalems/seatunnel that referenced this pull request Sep 5, 2026
Empty commit. The previous Build on a30a0bd (fork run 33963286570) finished
75 success / 14 skipped with three failures, all root-caused as unrelated to
this PR diff: DorisErrorIT stop/DNS race (source fix apache#12114),
DorisSchemaChangeIT post-DDL stream-load lag, and the PostgresCDCIT
committed-offset restore skipping a row (known apache#11847, fix apache#11864). Fork job
reruns require fork admin, so retriggering with a fresh run.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
davidzollo added a commit to zhangshenghang/seatunnel that referenced this pull request Sep 5, 2026
Empty commit. The previous Build on 214d066 failed only on jobs whose
failures are unrelated to this PR and are tracked upstream:
- transform-v2-it-part-1 (11): TestFilterRowKindIT on the Flink 1.18 leg,
  AssertSinkWriter static JVM-wide row counters (issue apache#12116)
- kudu-connector-it (11): KuduIT hang after the Flink 1.15.3 JobManager
  stopped responding, job cancelled at the 90-minute limit
- doris-connector-it (11): DorisSchemaChangeIT rows from modify_columns.sql
  not visible in Doris within the 60s assertion window
- all-connectors-it-7 (11): PostgresCDCIT committed-offset restore
  (apache#11847 / apache#11864)
davidzollo added a commit to nielifeng/seatunnel that referenced this pull request Sep 6, 2026
Empty commit. The previous Build on 83d9cc3 failed only on jobs whose
failures are unrelated to this PR and are tracked upstream:
- doris-connector-it (11): DorisErrorIT stack-frame race (fixed by apache#12114)
- transform-v2-it-part-1 (8): TestFilterRowKindIT Flink leg, AssertSinkWriter
  static counters (apache#12116)
- all-connectors-it-7 (8): PostgresCDCIT committed-offset restore (apache#11864)
- kudu-connector-it (11): KuduIT Flink JobManager hang, 90-minute cancel (apache#12132)
- rocketmq-connector-it (11): RocketMQ consumer PullMsgThreads left running
  after the Zeta job (fixed by apache#12099)
- paimon-connector-it (8) and (11): Zeta pipeline restore hang in
  PaimonIT#privilegeEnabledPaimonSourceUnAuthorized, 180-minute cancels (apache#12139)
davidzollo added a commit to zhangshenghang/seatunnel that referenced this pull request Sep 6, 2026
Empty commit. The previous Build on 4c539e3 failed only on jobs whose
failures are unrelated to this PR and are tracked upstream:
- all-connectors-it-2 (8): CouchbaseIT KV SASL window (apache#12127)
- kudu-connector-it (8): KuduIT Flink JobManager hang, 90-minute cancel (apache#12132)
- all-connectors-it-7 (11): PostgresCDCIT committed-offset restore (apache#11864)
- transform-v2-it-part-1 (11): TestFilterRowKindIT Flink leg (apache#12116)
- rocketmq-connector-it (8): RocketMQ broker double identity (fixed by apache#12115)
- doris-connector-it (8): Doris container port timeout and DorisIT reading
  the sink before the 2pc publish (fixed by apache#12142)
- paimon-connector-it (8): st-multi-table-sink-writer threads left after an
  expectedly failing job in PaimonSinkCDCIT (engine-side, first sighting)
davidzollo added a commit to waterWang/seatunnel that referenced this pull request Sep 6, 2026
Empty commit. The previous Build on 0c2bbfe failed only on jobs whose
failures are unrelated to this PR:
- all-connectors-it-7 (11): PostgresCDCIT committed-offset restore (apache#11864)
- kudu-connector-it (8): KuduIT Flink JobManager hang, 90-minute cancel (apache#12132)
- kudu-connector-it (11): KuduIT#testKuduTableListWithRegex, the Spark 3.3
  multi-table job exited 1 (first sighting of this mode)
@zhang-arvin
zhang-arvin force-pushed the fix-pg-cdc-offset-recovery branch from cb2c1b6 to be51099 Compare September 7, 2026 14:24
@DanielLeens

Copy link
Copy Markdown
Contributor

Re-checked the current head before doing another full pass, since the tooling flagged a new commit since my last review.

Verification: the current head be51099 and the commit I approved on 2026-09-04 (cb2c1b6) have the exact same parent and the exact same tree (git diff cb2c1b6 be51099 is empty) — only the committer timestamp differs. In other words this is a pure "amend + force-push to nudge Actions" re-trigger of the same no-op commit, not new code. git diff apache/dev...HEAD --stat still shows the same 5 files / 149 insertions / 3 deletions I already reviewed line-by-line last round, so there's nothing new for me to re-review here — my 2026-09-04 approval and analysis stand as-is.

CI-wise: Build is running again on this head as of now (in_progress, no conclusion yet). That lines up with the rerun I suggested after the previous run's updated-modules-integration-test-part-1/part-4 failures, which I still read as unrelated flake rather than something caused by this PR's Postgres-CDC changes. I'll keep an eye out for the conclusion; if it comes back green this time, this should be ready for a maintainer with write-level review permission to formally approve and merge — my review here is comment-level only.

@nzw921rx nzw921rx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants