Repository navigation
[Fix][Translation] Support CDC sources on the Spark engine - #12776
Conversation
…gine CDC sources exchange source events between readers and the enumerator, which the Spark parallel source path rejects. Mark IncrementalSource with SupportCoordinate so Spark runs one enumerator for all readers, and fix the coordinated path: report the configured parallelism, fail the task on reader or construction errors, run an enumerator-only checkpoint so the snapshot phase completes at parallelism above one, and reject micro-batch reads of coordinated sources. Enable MySQL-CDC E2E coverage on Spark and document the Spark limits.
| value = {}, | ||
| type = {EngineType.SEATUNNEL, EngineType.FLINK}, | ||
| disabledReason = "Covered by testMysqlCdcCheckDataE2e") | ||
| public void testMysqlCdcCheckDataE2eOnSpark(TestContainer container) { |
There was a problem hiding this comment.
Hello, I think it has the same semantics as the other two engines — otherwise there would be a divergence. And as for CDC's position that it can't be restored from a checkpoint, I think that's unacceptable too.
There was a problem hiding this comment.
Thanks for checking @Carl-Zhou-CN I agree that Spark should behave like Zeta and Flink. this gap isn't specific to CDC, though:
- The Spark starter only uses
spark.read()and neverreadStream, so no source gets checkpoint restore on Spark today, and STREAMING jobs run as one long batch task. The Spark 4.1 PR [Feature][Translation] Add Spark 4.1 support #11174 documents the same: checkpoint settings such ascheckpoint.intervalare not applied by the Spark starter. - That's also why the shared JDBC-sink tests can't pass on Spark unchanged: they rely on checkpoint-triggered flushes that never happen there.
- This PR changes CDC on Spark from failing on the first snapshot split to running correctly, without changing Zeta or Flink, and documents the restore limit.
For matching semantics, I see two options:
- Land this as a first step, and follow up with micro-batch streaming on Spark (enumerator and reader state saved per batch, sink committed per batch), so CDC and other sources get checkpoint restore.
- Keep this PR open and add that work over here.
Which one should we prefer?
DanielLeens
left a comment
There was a problem hiding this comment.
Hi @goutamadwant, thank you for digging into #9063. Tracing CDC on Spark down to the coordinated-source path, and adding unit tests that fail before the change and pass after it, is exactly the kind of root-cause work this area needs. I re-read the full diff against dev and followed the runtime path on the Spark side. The translation-layer fixes look right to me; my concerns are about how widely the marker is switched on, and about the restart semantics that @Carl-Zhou-CN has already raised.
What Problem Does This PR Solve?
User pain point: A MySQL-CDC job on Spark fails as soon as the first snapshot split finishes, because the reader sends a SourceEvent to the enumerator and the parallel source path rejects it with UnsupportedOperationException ... SupportCoordinate.
Fix approach: Mark IncrementalSource with SupportCoordinate so Spark runs one enumerator for all readers in a single task. Fix the coordinated path itself (configured parallelism reported to the enumerator, reader/construction errors now fail the task, enumerator-only checkpoints every second so the snapshot phase can finish at parallelism > 1), and reject micro-batch reads of coordinated sources.
One-sentence summary: Makes CDC sources start and finish their snapshot phase on Spark batch reads, without any checkpoint or restore support.
Before / after example:
before: MySQL-CDC -> JDBC on Spark: fails at the first finished snapshot split
after : same job runs: snapshot rows copied, then binlog insert/update/delete applied;
a restarted job starts again from startup.mode (no checkpoint restore)
1. Code Change Review
1.1 Core Logic Analysis
Does the normal user path reach the changed logic? Yes, for Spark. The Spark starter reads every source with spark.read() (SourceExecuteProcessor.java:99), so any SupportCoordinate source now goes through CoordinatedBatchPartitionReader in both the 2.4 and 3.3 translation modules. Zeta and Flink do not branch on the marker (PipelineGenerator only mentions it in a TODO), so their behavior is unchanged.
Key findings:
- The marker is added to the shared base class
IncrementalSource(IncrementalSource.java:100). Every subclass inherits it: MySQL, PostgreSQL/openGauss (PgBaseIncrementalSource), Oracle, SQL Server, Db2 and MongoDB CDC. Only MySQL is covered by tests and docs (Issue 1). CoordinatedSourcefixes are correct as far as I can trace:currentParallelism()now returns the configured parallelism instead of the number of readers that happen to exist while the enumerator is being constructed; construction errors are rethrown (before:log.warnand a half-built source) and created resources are closed; reader-thread failures are captured inreaderFailureand rethrown fromrun();handleNoMoreElementno longer removes the reader context, which also avoids a null lookup inclose().- The enumerator-only checkpoint (
CoordinatedSource.java:253-263,checkpointEnumeratorat line 290) callssnapshotState(id)andnotifyCheckpointComplete(id)back to back on the run thread. InSnapshotSplitAssignerthe firstsnapshotStateafter all splits complete setscheckpointIdToFinish, and the immediately followingnotifyCheckpointComplete(id)marks the assigner completed. So the guard described inSnapshotSplitAssigner.onCompletedSplits("wait for a complete checkpoint ... so no incremental record can overtake a snapshot record of the same key") is no longer enforced by a barrier on Spark; it is replaced by the FIFO order of the single sharedHandover(collectorMapcollectors all use the samehandover). I believe that holds, but it is a different guarantee and nothing tests it (Issue 3). - Reader state is never snapshotted or committed on this path, so
IncrementalSourceReader.notifyCheckpointComplete(line 132, which callsdataSourceDialect.commitChangeLogOffset) is never reached on Spark.
Runtime path (Spark, MySQL-CDC at parallelism 2):
SourceExecuteProcessor (spark.read) -> BatchSourceReader / SeaTunnelBatch: one partition for a SupportCoordinate source
-> CoordinatedBatchPartitionReader.prepare()
-> InternalCoordinatedSource (CoordinatedSource) creates 1 enumerator + 2 readers, all in this task
-> run(): each reader polls on a pooled thread, emitting into the shared Handover
enumerator.run() assigns snapshot splits
reader --SourceEvent(finished splits)--> handleReaderEvent --> enumerator.handleSourceEvent
every 1s on the run thread: enumerator.snapshotState(id) ; enumerator.notifyCheckpointComplete(id)
-> snapshot assigner completes -> incremental split assigned -> binlog read
-> Spark pulls rows from the Handover -> sink (no source checkpoint ever, no restore)
reader exception -> readerFailure -> run() rethrows -> Handover.reportError -> Spark task fails
1.2 Compatibility Impact
Partially incompatible in a benign direction, with one real exposure.
- Zeta/Flink and all non-CDC sources: unchanged.
SeaTunnelMicroBatch,SeaTunnelScan.toMicroBatchStreamandSeaTunnelSourceSupport.createMicroBatchReadernow rejectSupportCoordinatesources. No connector inseatunnel-connectors-v2implemented the marker before this PR, so I found no previously working micro-batch job that is affected. - CDC jobs on Spark failed before, so no running job changes behavior. The exposure is the other direction: PostgreSQL, Oracle, SQL Server, Db2 and MongoDB CDC jobs now start on Spark although their docs list only Zeta and Flink, and they are untested (Issue 1).
IncrementalSourcehas no explicitserialVersionUID, so adding the interface changes the computed value. I could not find a place where a serialized source object is persisted across versions, so I see this as low risk, as the PR notes.
1.3 Performance / Side-Effect Analysis
- All readers of a "parallel" CDC source run as threads inside one Spark task, so
parallelismis not a scale-out knob here: a very large snapshot is read through one executor core budget and one JVM heap, and theHandoveris single-slot. This is acceptable for a first step but should be stated plainly in the docs (Issue 5). - Every second,
SnapshotSplitAssigner.snapshotState(line 253) copiesremainingSplitsinto a newArrayList. For a snapshot with millions of remaining chunks this is a repeated large allocation; the ticks also continue for the whole streaming phase. It is not a correctness issue, only avoidable churn (Issue 6). - The enumerator-only checkpoint runs on the run thread, so a slow
notifyCheckpointComplete(it callsassignSplits()) delays failure detection by at most that call.
1.4 Error Handling and Logging
Failures are now surfaced instead of swallowed, which is a clear improvement. Formal issues:
Issue 1: The marker enables every CDC connector on Spark, but only MySQL is validated, and PostgreSQL silently pins WAL
- Location:
IncrementalSource.java:100;IncrementalSourceReader.java:132;PostgresDialect.commitChangeLogOffset(the only place that confirms an LSN to the replication slot); docsdocs/en/connectors/source/PostgreSQL-CDC.mdnew section - Problem: Putting
SupportCoordinateon the shared base class changes PostgreSQL/openGauss, Oracle, SQL Server, Db2 and MongoDB CDC from "fails immediately on Spark" to "starts on Spark". For PostgreSQL the slot's confirmed LSN is only advanced fromIncrementalSourceReader.notifyCheckpointComplete, which never runs on Spark (the PR docs confirm this). A long-running STREAMING job therefore leaves the replication slot at its startingrestart_lsnand PostgreSQL retains all WAL until the disk fills. The PR text says PostgreSQL "is not covered by end-to-end tests" and relies on the user reading a doc FAQ. The other connectors' docs still list only Zeta and Flink. - Potential risk: A source database outage, which is an operational incident rather than a job failure, caused by a job that SeaTunnel itself started without a warning.
- Best improvement: Narrow the behavior to what is verified. For example, keep the marker off the shared base class and enable it only for
MySqlIncrementalSource, or keep it on the base class and reject other connectors on Spark with a clear error until each one has Spark tests and docs. At the very least, fail fast for PostgreSQL on Spark (or log a prominent warning and require an explicit opt-in option) until the slot can be advanced. - Severity: High
- Raised by another reviewer: No
Issue 2: No checkpoint restore means a restart is not equivalent to Zeta/Flink (open maintainer concern)
- Location: whole feature; docs
MySQL-CDC.mdsection "Can MySQL CDC run on the Spark engine?"; discussion onMysqlCDCIT.java:46 - Problem: +1 to @Carl-Zhou-CN: Spark should not silently differ from the other two engines. The author's reply is accurate on the facts: the Spark starter only uses batch
read(), so no source on Spark restores from a checkpoint today, and the PR documents it. The consequence for CDC is that a restarted job starts again fromstartup.mode: withinitialit re-snapshots (duplicates for sinks without a primary key), withlatestit skips changes made while the job was down. That is a data-correctness gap, not just a feature gap. - Potential risk: Users migrating CDC pipelines to Spark expect Zeta/Flink resume semantics.
- Best improvement: Please get an explicit decision from the maintainers on the author's question (land this as a first step with the limit documented, or keep the PR open for micro-batch state). My view: landing as a first step is reasonable only if Issue 1 is addressed and the docs state the duplicate/gap behavior of
startup.modeon restart in plain words; the restore work should then be tracked as a follow-up issue. @Carl-Zhou-CN and @davidzollo, please confirm or overrule. - Severity: High (needs maintainer sign-off)
- Raised by another reviewer: Yes (@Carl-Zhou-CN)
Issue 3: The ordering guarantee that replaces the checkpoint gate is not tested
- Location:
CoordinatedSource.java:290-297,SnapshotSplitAssigner.java:271-277 - Problem: At parallelism above 1 the "wait for a complete checkpoint" gate now completes in the same tick as the first
snapshotState, so the only thing preventing an incremental record from overtaking a snapshot record of the same key is FIFO order in the sharedHandover.IncrementalSourceEnumeratorTestchecks that the phase transition happens; the Spark e2e cases check final table equality on a few rows. Nothing deliberately interleaves a late snapshot split with an early binlog change for the same key. - Potential risk: A rare out-of-order write (older snapshot row overwriting a newer incremental update) on large tables, which a final-state check on seven rows will not catch.
- Best improvement: Add a deterministic unit test with a fake reader whose snapshot record is emitted after the incremental one is already assigned, or document why the reader-side emission order makes that impossible, with a code comment next to
checkpointEnumerator. - Severity: Medium
- Raised by another reviewer: No
Issue 4: Spark 2.4 translation changes and the micro-batch rejection have no unit tests
- Location:
seatunnel-translation-spark-2.4/.../CoordinatedBatchPartitionReader.java:91,SeaTunnelSourceSupport.java:97;seatunnel-translation-spark-3.3/.../SeaTunnelScan.java:72 - Problem: The new unit test
CoordinatedBatchPartitionReaderTestexists only in the 3.3 module. The 2.4 copy of the same logic and both newUnsupportedOperationExceptionguards (2.4 and 3.3) are only touched by the MySQL e2e, which does not usereadStream. - Potential risk: The guard, which exists to protect users from silently wrong micro-batch behavior, can regress unnoticed.
- Best improvement: Add a small test per module that a
SupportCoordinatesource is rejected by the micro-batch entry point, and port the reader test to the 2.4 module. - Severity: Medium
- Raised by another reviewer: No
Issue 5: Docs do not state that parallelism is thread concurrency inside one task
- Location:
docs/en/connectors/source/MySQL-CDC.md(new FAQ), same indocs/zh - Problem: The text says "one Spark task holds the split enumerator and all readers", but does not tell users that this bounds snapshot throughput and memory to one task, and the "Yes" answer reads like full parity.
- Potential risk: Users size jobs for a large snapshot as if it scaled across executors.
- Best improvement: Add one sentence on the scale-out limit and on the restart behavior from Issue 2.
- Severity: Low
- Raised by another reviewer: No
Issue 6: Per-second copy of the remaining split list
- Location:
SnapshotSplitAssigner.java:253viaCoordinatedSource.checkpointEnumerator - Problem:
new ArrayList<>(remainingSplits)is rebuilt every second, for the whole life of the job. - Potential risk: Avoidable GC churn on snapshots with a very large number of chunks.
- Best improvement: Stop ticking once the enumerator no longer waits on a checkpoint (for example after the assigner reports completion), or note the cost in the Javadoc of
getEnumeratorCheckpointInterval. - Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
ASF headers, Javadoc on the new protected hooks (getEnumeratorCheckpointInterval, getReaderCollector) and the explanatory comments around the enumerator checkpoint are good. The duplicated Spark 2.4 / 3.3 reader classes follow the existing structure.
2.2 Test Coverage and Test Stability
Positive: unit tests cover event exchange, configured parallelism, reader-failure propagation, construction failure with resource cleanup, checkpoint-gated enumerators, and close-time failure suppression, and the author reports they fail before the change.
Stability rating: Risk present.
AbstractMysqlCDCITBase.checkSnapshotThenIncrementalDatastarts the streaming job with an un-joinedCompletableFuture.runAsync(...)and polls with 3 and 2 minuteawait()budgets; a failed submission only surfaces as a timeout, and the long-running job outlives the test method. This mirrors sibling tests, but it is the pattern behind the Flink 1.20 timeout the author saw.CoordinatedSourceTestusesThread.sleep(5L/200L)inside fake readers andassertTimeoutPreemptively, which are bounded and local, so I rate them low risk.- Coverage blind spots: only a happy-path MySQL job runs on Spark; five shared base tests are disabled on Spark with a reason (they were not running on Spark before either, so this is not a weakening); no PostgreSQL/Oracle/etc. test (Issue 1); no ordering test (Issue 3); no micro-batch guard test (Issue 4).
CI on this head: red, but the failing jobs are unrelated to the diff. In the fork run, engine-v2-it (11) fails in SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck (Zeta cancel path), all-connectors-it-6 (11) fails in DatabendCDCSinkIT.testDatabendSinkCDC (Databend sink timeout), and engine-v2-it (17) died with "Could not find or load main class org.apache.maven.wrapper.MavenWrapperMain" (runner/infrastructure). None of them touches CDC base, the translation modules or the MySQL CDC e2e.
2.3 Documentation Updates
English and Chinese docs are updated for MySQL-CDC and PostgreSQL-CDC. The "Support Those Engines" list is updated for MySQL-CDC only; the other CDC docs are unchanged (Issue 1). See Issue 5 for missing scale-out/restart wording.
3. Architectural Soundness
3.1 Elegance
A precise fix for the coordinated-source defects (the getReaderCollector hook removes a copy of the whole run() loop from the Spark readers). Enabling the marker on the shared base class is the part that is broader than the verified scope.
3.2 Maintainability
Good: the Spark readers no longer duplicate the run loop. Both Spark modules still carry near-identical code (pre-existing).
3.3 Extensibility
A proper follow-up is state handling for Spark micro-batch; the new rejection message already points users in the right direction.
3.4 Historical-Version Compatibility
No impact on Zeta/Flink jobs, savepoints or checkpoints. No previously working Spark CDC job existed.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Marker enables all CDC connectors on Spark; PostgreSQL slot never advances (unbounded WAL) | IncrementalSource.java:100, IncrementalSourceReader.java:132 |
High |
| 2 | No restore: restart repeats snapshot or skips changes; maintainer decision pending | feature / MysqlCDCIT.java:46 thread |
High |
| 3 | Snapshot-vs-incremental ordering guarantee replaced by FIFO, untested | CoordinatedSource.java:290, SnapshotSplitAssigner.java:271 |
Medium |
| 4 | No unit tests for Spark 2.4 reader and micro-batch guards | spark-2.4 / spark-3.3 translation | Medium |
| 5 | Docs omit single-task scale-out limit | MySQL-CDC.md FAQ (en/zh) |
Low |
| 6 | Per-second remainingSplits copy |
SnapshotSplitAssigner.java:253 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers - must be fixed
- Issue 1: limit the Spark enablement to what is validated (or fail fast for the other connectors, PostgreSQL first).
- Issue 2: maintainer decision on restart semantics, recorded in the PR, plus plain documentation of the
startup.modeconsequences. - Branch status: the PR is 8 commits behind
dev; please sync before the next CI run. The currently red jobs are unrelated to this diff (named above), so rerunning only the failed jobs after the sync should be enough.
- Recommended fixes - non-blocking
- Issues 3, 4, 5 and 6.
Overall assessment: the diagnosis and the coordinated-source fixes are solid, and the unit tests are well targeted. The risk is not in the translation code but in the breadth of the switch and in the semantics gap that a maintainer has already flagged. A narrower enablement plus a clear decision on restarts would make this a good first step. On the author's open question, I lean to option 1 (land a gated first step, then micro-batch state as a follow-up), but that is for the maintainers to decide.
DanielLeens
left a comment
There was a problem hiding this comment.
Reviewed current head 327b06c21a39 against dev (CDC base, translation base, Spark 2.4/3.3, docs, unit tests, and Spark MySQL CDC E2E).
The change makes incremental CDC sources explicitly coordinated, so Spark uses one shared enumerator rather than one per reader. I traced the event round trip (reader split-finished report -> enumerator acknowledgement -> next split request), configured parallelism exposure before reader creation, and the enumerator-only checkpoint path needed for the CDC snapshot-to-incremental transition on Spark batch. The base source now propagates pooled-reader failures back through run, keeps reader contexts available for event delivery until all readers end, and suppresses close-induced failures only after closing begins.
The Spark micro-batch rejection is deliberate and explains the unsupported restore semantics; the normal SeaTunnel Spark path uses batch reading. Tests cover event exchange, checkpoint-gated progression, reader failure propagation, construction cleanup, plus MySQL CDC Spark runs with and without parallelism. I found no source-level blocker.
CI: Build is still in progress on this head.
Conclusion: ready from code review; merge after the active CI gate turns green and a maintainer applies final approval.
|
The CI fact cited in my previous review has changed: Build for the current unchanged head is now passing. CI was previously the only remaining blocker; CI is now passing, so my technical conclusion changes to approve. I do not see a new source-side blocker from Daniel's review. This branch is behind the latest dev base, which I have recorded as merge metadata only; because the current head CI is green, that fact alone does not call for an additional source change. I have read-only review controls, so this COMMENT does not change GitHub's displayed review decision; a write-capable maintainer must perform any final approval or dismissal action. |
DanielLeens
left a comment
There was a problem hiding this comment.
This is a CI re-check on the unchanged head 327b06c21. In my previous review on this head, CI was the only remaining blocker and I had no source-side finding (ready from code review: shared enumerator for incremental CDC on Spark, reader failure propagation, and the Spark micro-batch rejection). CI on this head is now passing: the apache-side Build check completed successfully for this exact SHA, including the Spark MySQL CDC E2E coverage that was still in progress when I wrote the review. Since CI was the only remaining blocker and it is now green, my conclusion changes to approve.
My earlier CHANGES_REQUESTED review was against a previous commit; the current head closes those findings, and the semantics question raised by @Carl-Zhou-CN (Spark behaving like Zeta and Flink) was answered by the author and is reflected in the design.
As a read-only reviewer I cannot merge or satisfy branch protection myself, so a maintainer with write access still needs to do the final approval and merge. Thanks again for the contribution!
|
@Carl-Zhou-CN a quick follow-up on the two options from 10-15: land this PR as the first step and add micro-batch streaming with per-batch restore in a follow-up, or keep it open and add that work here. I lean to the first because the restore gap exists for every source on Spark today, not only CDC, and this change fixes the immediate failure without touching Zeta or Flink. Either way works for me; which do you prefer? |
|
Thanks @goutamadwant for laying out the two delivery choices. My existing technical approval covers the current first-step scope; it does not claim Spark micro-batch restore is implemented. Landing that scoped correction and tracking micro-batch restoration separately remains consistent with my review, but @Carl-Zhou-CN and the maintainers should make the scope/merge decision. Build remains green on this unchanged head. This is an unchanged-head discussion/CI update, not a second full source review. No local tests were run. Daniel has READ permission; any approval records my technical conclusion, while effective maintainer approval, dismissal and merge remain separate. |
davidzollo
left a comment
There was a problem hiding this comment.
+1
LGTM, appreciate your solid contribution, keep up the excellent work
Thanks for your contribution! This is a solid addition to the project, and your attention to detail really shows. Contributors like you are what keep this community moving forward. Feel free to keep the PRs coming — we're always glad to have you here!
Please ignore the following message if you have joined in the Slack~
To facilitate focused communication among contributors, we’ve created a brand-new dedicated #contributors channel in official Slack workspace.
Slack workspace link: https://s.apache.org/seatunnel-slack
This channel is designed for technical discussions, feature design brainstorming, roadmap sync and direct communication with project core Contributors. Everyone who contributes code, docs, test cases or community ideas is warmly invited to join, share thoughts and collaborate together under The Apache Way. Welcome to join 😄
Resolve PostgreSQL-CDC FAQ conflicts by keeping both the connection-reset recovery FAQ from this branch and the Spark engine FAQ from apache#12776. Co-authored-by: panda <LeonYoah@users.noreply.github.com>
Purpose of this pull request
Fix #9063.
CDC sources exchange source events between readers and the enumerator. On Spark they ran through the parallel source path, which rejects these events with
UnsupportedOperationException ... SupportCoordinate.IncrementalSourcenow implementsSupportCoordinate, so Spark runs one enumerator for all readers in a single task. Zeta only references the marker in a TODO comment and Flink does not use it.readStream) reads of coordinated sources are rejected with a clear error, since state is not restored between micro-batches.The marker-only change in #4269 is not enough on its own: it hangs at parallelism > 1 and hides reader errors.
Does this PR introduce any user-facing change?
Yes. MySQL-CDC jobs run on Spark 2.4 and 3.3 instead of failing at the first finished snapshot split.
Spark limits are documented in en and zh: no checkpoint restore, sinks that flush only on checkpoints need
batch_size, and Postgres-CDC does not advance the replication slot.Adding the interface changes the computed
serialVersionUIDofIncrementalSource.How was this patch tested?
CoordinatedSourceTest,CoordinatedBatchPartitionReaderTest,IncrementalSourceEnumeratorTest(real enumerator at parallelism 2), JDK 11 and 17MysqlCDCITon Zeta, Flink 1.18, Flink 1.20, Spark 3.3Mysql8_4CDCITshared methodsFive shared base tests stay disabled on Spark because their JDBC sink flushes only on checkpoints.
Check list
seatunnel-translation-baseadded toconnector-cdc-basein test scope).