Repository navigation
[Improve][Flink] Replace the local schema coordinator with a checkpointed data-plane protocol - #11960
Conversation
1dd5a2b to
996c50b
Compare
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
The Flink CDC schema-evolution feature previously relied on LocalSchemaCoordinator, a process-local, JVM-singleton coordinator (ConcurrentHashMap/WeakReference-based, its own class-level Javadoc states it "only manages temporary communication ... All persistent state is managed by BroadcastSchemaSinkOperator in Flink State") to serialize schema-change requests across sink subtasks before applying DDL. The PR replaces that coordinator entirely with a fully checkpointed data-plane protocol: schema control messages travel inline with data rows (via SeaTunnelRow options), one sink subtask per table is elected as the physical DDL owner, dependent rows are buffered until their schema control has been applied, and all of this (applied sequences, latest target schema, out-of-order controls, pending rows) is now Flink-managed ListState, so the whole protocol can survive TaskManager failure and rescale without a custom OperatorCoordinator.
1. Code Change Review
1.1 Core Logic Analysis
This is a large, coherent rewrite (4368 insertions / 1059 deletions across 38 files, 2 commits). Rather than attempt a line-by-line narrative of every file, I traced the specific pieces that matter most for correctness and compatibility:
Deleted component (LocalSchemaCoordinator, -448 lines): Confirmed by reading its own class Javadoc (still present on dev before this PR) that it held no Flink-managed state — it was purely an in-process rendezvous point (WeakReference, ConcurrentHashMap, a daemon cleanup thread). So removing it is not itself a checkpoint-format change; the actual persistent-state surface was always BroadcastSchemaSinkOperator (and SchemaOperator on the source side), and those are the operators being rewritten here.
Control-plane/data-plane unification: SchemaEvolutionControlMessage (new, 161 lines) piggybacks schema commands onto ordinary SeaTunnelRow instances via row.getOptions() (SCHEMA_CHANGE_BROADCAST, SCHEMA_CHANGE_ID, etc.) rather than introducing a new Either<Control, Row>-style union type on the DataStream. This is a good design choice: the wire/network type flowing through Flink stays DataStream<SeaTunnelRow>, so there's no need to register a new top-level TypeSerializer for the main data channel — it avoids one whole class of serialization-compatibility risk that a naive "add a control-message type to the stream" design would have introduced.
SchemaRestorePlanGenerator (new, 182 lines): Builds a synthetic AlterTableColumnsEvent (a full drop+add column reconstruction, validated by round-tripping it through TableSchemaChangeEventDispatcher and asserting the rebuilt schema equals the target — SchemaRestorePlanGenerator.java:145-171) so a newly created sink writer (e.g., after rescale or TaskManager restart) can be brought from its initial schema straight to the latest checkpointed target schema in one step, without replaying the full DDL history. This only operates on state that was itself captured by the new protocol — it is not a migration path from the old coordinator's state (there isn't one — see 1.2).
Runtime path (source side): AbstractSourceExecuteProcessor.validateSchemaEvolutionIncrementalParallelism() (fails fast at job startup if incremental.parallelism != 1) → sourceStream.transform("schema-evolution", ..., SchemaOperator) → DDL detected → SchemaOperator buffers dependent rows, assigns a producer id/sequence, emits the control row → downstream BroadcastSchemaSinkOperator gates data rows behind the owning subtask's applied DDL, using Flink managed ListState for appliedSequenceState/latestSchemaEventState/pendingSchemaEventState/pendingRowState.
1.2 Compatibility Impact — Checkpoint/Savepoint State Format (the critical question for this PR)
I traced the actual ListStateDescriptor names and POJO types on both sides, before and after this PR, since that is what determines whether a checkpoint/savepoint taken under the old code can be restored under the new code:
BroadcastSchemaSinkOperator (sink side):
| Before | After | |
|---|---|---|
| State | one ListState<TableEpochEntry>, getListState, name "last-processed-epochs" |
four ListStates, all getUnionListState: "applied-schema-sequences" (SchemaSequenceEntry), "latest-applied-schema-events" (LatestSchemaEventEntry), "out-of-order-schema-events" (PendingSchemaEventEntry), "schema-gate-pending-rows" (PendingRowEntry) |
SchemaOperator (source side):
| Before | After | |
|---|---|---|
| State | "localSchemaState" (SchemaStateEntry), "lastProcessedEventTime" (Long), plus unchanged "schemaChangePending"/"bufferedRecords"/"firstSeenCheckpointId" |
"localSchemaState" replaced by "schemaEvolutionProtocolState" (SchemaEvolutionProtocolState); "lastProcessedEventTime" replaced by "lastProcessedEventTimeByTable" (TableEventTimeEntry); plus 3 brand-new fields (schemaChangeProducerId/schemaChangeSequence/lastEmittedSchemaChangeId) |
Every state descriptor that actually carried the "what schema/DDL progress has this job made" information was renamed and given a different POJO type on both the source and sink side. Flink resolves operator state by descriptor name at restore time; a checkpoint/savepoint containing "last-processed-epochs" or "localSchemaState" has no counterpart requested by the new operator code, so per Flink's standard restore contract this is unclaimed state — restoring such a checkpoint under this PR's code will either fail outright (allowNonRestoredState=false, the default) or, if a user explicitly forces --allowNonRestoredState, silently discard that progress (the job would start the new protocol with no memory of which DDLs were already applied). I did not find any adapter/migration code that reads the old descriptor names and translates them into the new POJOs — SchemaRestorePlanGenerator and the new initializeState methods only ever read the new-named state.
Compatibility classification: incompatible for cross-version checkpoint/savepoint restore, but not a "breaks a released version" issue. I checked whether the Flink-CDC-schema-evolution feature (the LocalSchemaCoordinator/BroadcastSchemaSinkOperator combination this PR replaces) was ever part of an official Apache release: its introducing commit (89b3e1ce1c2, "[Improve][Flink] supports multiple parallelisms and remove flink-specific logic from API #10107") is not an ancestor of the latest release tag 2.3.13 (git merge-base --is-ancestor 89b3e1ce1c2 2.3.13 → false), i.e. this whole feature has only ever existed on the unreleased dev line. So no user of a released SeaTunnel version has a job checkpointed under the old format that this PR would strand. This is pre-GA protocol churn, not a release-to-release regression.
That said, it is a real break for anyone currently running a dev-branch/SNAPSHOT build with schema-evolution-enabled Flink CDC jobs who tries to resume from a pre-PR checkpoint/savepoint after upgrading — and per this project's own contribution rules ("Any incompatible change MUST be explicitly documented in docs/en/introduction/concepts/incompatible-changes.md ... Include migration guidance"), that should be recorded. The PR's own checklist checks "[x] If necessary, please update incompatible-changes.md", but the diff does not touch that file at all — only docs/en(/zh)/introduction/configuration/schema-evolution.md were updated, and only to document the new incremental.parallelism = 1 startup constraint (correctly documented and correctly enforced — see 1.3), not the checkpoint-format break. See Issue 1.
1.3 Performance / Side-Effect Analysis
- The new
incremental.parallelism = 1restriction (AbstractSourceExecuteProcessor.validateSchemaEvolutionIncrementalParallelism,AbstractSourceExecuteProcessor.java:144-156) is a fail-fastIllegalArgumentExceptionat job startup, correctly gated to only fire when schema evolution is actually enabled on aSupportSchemaEvolutionsource in streaming mode — it doesn't affect jobs that don't use this feature. It's a deliberate new constraint (multi-reader schema evolution wasn't safely supported before either, per the PR description), consistently documented in bothdocs/enanddocs/zh. FlinkSourceReader'spollNext/lifecycle handling was reworked from a single racyinputStatusfield into aReaderLifecycleenum (ACTIVE/LOGICALLY_CLOSED/FINISHED) withsynchronizedtransition methods, plus explicit handling of a "stale no-more-element acknowledgement" race when a split reassignment reactivates a logically-closed reader (FlinkSourceReader.java:165-172). This looks like a genuine correctness fix for the Flink-1.13 keep-alive path bundled into this PR (likely surfaced while building/testing the schema-evolution recovery scenarios) — somewhat adjacent to the PR's stated scope, but directly load-bearing for the new recovery E2E tests, so I don't consider it unjustified scope creep.- Per-table DDL ownership (one sink subtask elected owner) plus row buffering ahead of the owner's applied DDL bounds memory to in-flight rows for the affected table(s) only, not the whole stream — reasonable for typical DDL frequency.
1.4 Error Handling and Logging
SchemaRestorePlanGenerator fails loudly (SchemaEvolutionException with a specific SchemaEvolutionErrorCode) rather than silently producing a wrong schema when the initial/target schema round-trip doesn't reconstruct exactly, or when table paths mismatch — appropriate defensive validation for a component reconstructing schema state after a restore. The PR description is explicit that connectors remain responsible for idempotent/convergent DDL application and for propagating failures, which is the correct division of responsibility (the translation layer can guarantee ordering and replay-at-least-once, not exactly-once DDL execution — that has to be the connector's job).
Issue 1 (Medium, blocking): docs/en/introduction/concepts/incompatible-changes.md was not updated to record that this PR changes the Flink schema-evolution checkpoint/savepoint state format (see 1.2 for the exact descriptor/type diff). The PR checklist claims this was done; it wasn't. Given no released version is affected, this doesn't need to block on "released users are broken," but it should still record: (a) that upgrading across this PR requires discarding/not-restoring any prior checkpoint or savepoint of a Flink CDC schema-evolution job, and (b) what the actual (fail-fast, not silent-corruption) failure mode looks like if someone tries anyway. This is a project-required doc for exactly this class of change.
Issue 2 (Low, non-blocking): The FlinkSourceReader keep-alive rework (1.3) is functionally sound but is a second, only loosely-related concern bundled into an already very large PR; a future PR of this size might be easier to review split by concern (schema protocol vs. reader keep-alive fix), though I recognize the two are entangled in the recovery E2E scenarios added here.
2. Code Quality Assessment
2.1 Coding Standards
New classes carry the required ASF license headers and class-level Javadoc explaining responsibility and constraints (e.g. SchemaRestorePlanGenerator's Javadoc explicitly documents why it reconstructs columns as adds-only rather than replaying full DDL history — a good "explain the why" comment per this project's standards). SchemaEvolutionControlMessage and SchemaEvolutionStreamUtils are clean, single-purpose utility classes.
2.2 Test Coverage and Test Stability
Substantial new/updated unit-test coverage: BroadcastSchemaSinkOperatorTest (+1069 lines), SchemaOperatorTest (+547), SchemaRestorePlanGeneratorTest (+158, new), SchemaEvolutionStreamUtilsTest (+77, new), FlinkSourceReaderTest (+181), TransformExecuteProcessorTest (+114), AbstractSourceExecuteProcessorTest (+66, covers the new incremental.parallelism guard), SchemaEvolutionRoutingTest (+59), SchemaOperator13Test (+85) — this is proportionate to the size of the rewrite and covers restore-from-state, rescale redistribution (getUnionListState behavior), and the new validation guard.
Two new E2E scenarios in MysqlCDCWithFlinkSchemaChangeIT are the most direct evidence for the new protocol's own checkpoint/restore correctness (not the old-to-new migration question, which isn't practically unit-testable):
testSchemaEvolutionRecoversAfterTaskManagerFailureBeforeNextCheckpoint— starts a second TaskManager, applies a DDL, then kills the primary TaskManager before the next 30s periodic checkpoint can capture the gate's applied sequence, and asserts the job recovers onto the second TaskManager with correct data/schema. Also exercises JDBC XA writer rollback since the recovery config enables exactly-once.testPendingSchemaEvolutionStateRestoresAfterRescale— applies a DDL, triggers a savepoint while the schema change is still pending in the operator's queue, cancels, and resubmits from that savepoint at a different parallelism, asserting the pending schema state survives the rescale.
Both use Awaitility-based polling (await().pollInterval(100ms).untilAsserted(...)) with a generous SCHEMA_EVOLUTION_ASSERT_TIMEOUT_MILLIS = 600_000 (10 min) — no hard Thread.sleep-based waits, good.
Stability rating: Risk present. The first test's entire premise depends on a wall-clock race against a fixed 30-second checkpoint interval: the comment at MysqlCDCWithFlinkSchemaChangeIT.java:~220 states "with a 30-second interval the next checkpoint cannot yet contain the gate's applied sequence" — this is an assumption about relative timing (start-second-TM + observe-2-TMs + stop-primary-TM + observe-1-TM must all complete within the 30s window) rather than something the test explicitly asserts. Under CI contention, if that sequence takes longer than the checkpoint interval, the test would silently start exercising a different code path (recovery after the checkpoint captured the DDL, rather than the intended before-checkpoint gap) without failing — the final assertions could still pass, but the test would no longer be testing what its name claims. This isn't a hard flake (no observed intermittent failures, generous timeout budget, all waits are polling-based), but it is a timing-precision risk worth being aware of, not a "High risk" (no arbitrary sleeps, no shared static state, no order dependence between test methods beyond the existing @Order/resetDatabaseToInitialState() pattern already used elsewhere in this suite).
2.3 Documentation Updates
docs/en(/zh)/introduction/configuration/schema-evolution.md correctly documents the new incremental.parallelism = 1 requirement. As covered in Issue 1, incompatible-changes.md was not updated despite the PR checklist claiming it was, and that's the one documentation gap I'd consider blocking given the magnitude of the internal protocol/state-format rewrite.
3. Architectural Soundness
3.1 Elegance of the Solution
Replacing a custom process-local singleton coordinator with a purely Flink-managed-state protocol is the right direction for a distributed system component that needs to survive TaskManager failure — it removes an entire class of "coordinator state lives outside Flink's fault-tolerance model" risk that the old LocalSchemaCoordinator (explicitly documented as non-persistent) had. Piggybacking control messages on SeaTunnelRow.getOptions() instead of introducing a new stream-level union type is a pragmatic choice that avoids a new serializer-compatibility surface.
3.2 Maintainability
The four-way state split in BroadcastSchemaSinkOperator (applied sequences / latest schema / out-of-order events / pending rows) is more state to reason about than the old single TableEpochEntry list, but each piece maps to a distinct, named concern, which should make future changes easier to scope than the old monolithic epoch entry would have.
3.3 Extensibility
The producer-id/sequence-based schemaChangeId scheme (SchemaEvolutionControlMessage.schemaChangeId/schemaChangeProducerId/schemaChangeSequence) gives the protocol a natural way to detect duplicate/out-of-order control messages, which should extend reasonably to future multi-writer or multi-owner scenarios if that's ever needed (currently constrained to one owner per table by the incremental.parallelism = 1 guard).
3.4 Historical-Version Compatibility
As detailed in 1.2: this is a hard break in the Flink schema-evolution checkpoint/savepoint state format relative to the pre-PR dev code, but since that feature has never been part of an official Apache SeaTunnel release, no released-version user's job is affected. The gap is that this isn't recorded in incompatible-changes.md as the project's own contribution guide requires for this class of change.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | incompatible-changes.md not updated despite the PR checklist claiming it was; the checkpoint/savepoint state-format break for Flink schema-evolution (renamed + retyped ListState descriptors on both SchemaOperator and BroadcastSchemaSinkOperator) isn't documented anywhere, though it's not a released-version regression |
docs/en/introduction/concepts/incompatible-changes.md (missing entry) |
Medium |
| 2 | FlinkSourceReader keep-alive lifecycle rework is a second, only loosely-related concern bundled into an already large PR |
FlinkSourceReader.java |
Low |
| 3 | testSchemaEvolutionRecoversAfterTaskManagerFailureBeforeNextCheckpoint depends on a wall-clock race against a fixed 30s checkpoint interval that isn't itself asserted, only assumed in a comment |
MysqlCDCWithFlinkSchemaChangeIT.java (new test, ~line 220) |
Low (test-precision, not correctness) |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers — must be fixed
- Issue 1: add an
incompatible-changes.mdentry documenting the Flink schema-evolution checkpoint/savepoint state-format change and the migration guidance (discard/don't-restore prior checkpoints for this feature when upgrading across this PR), matching what the PR checklist already claims was done.
- Issue 1: add an
- Recommended fixes — non-blocking
- Issue 2: consider whether the
FlinkSourceReaderkeep-alive fix belongs in a separate, focused PR next time — not asking for a split here given how entangled it is with the new recovery E2E tests. - Issue 3: consider adding an explicit assertion (e.g., inspecting checkpoint/DDL-application ordering via logs or metrics) that the failure genuinely lands before the next checkpoint, rather than relying solely on the 30s-interval timing assumption, to make the test self-verifying under CI contention.
- Issue 2: consider whether the
CI note: the "Build" check is still pending as of this review, and this PR is 2 commits ahead of / not behind dev (no rebase needed). Given the size of the change, please make sure the full CI run (not just a partial rerun) completes green, particularly the Flink E2E lanes exercising MysqlCDCWithFlinkSchemaChangeIT, before merge.
Overall: this is a well-designed, well-tested move from an ad hoc process-local coordinator to a properly Flink-checkpointed protocol — exactly the right direction for correctness under TaskManager failure. The core engineering is sound and the compatibility story for released versions is genuinely fine (this feature never shipped), but the missing incompatible-changes.md entry for a checkpoint-state-format break of this magnitude is a real, easily-fixed gap given the PR's own checklist already claims it was handled. Nice work on the depth of the new test coverage, especially the TaskManager-failure and rescale-savepoint E2E scenarios.
dybyte
left a comment
There was a problem hiding this comment.
I think this overlaps with some of the work already being done in #11912, especially around replacing LocalSchemaCoordinator and checkpoint-based schema coordination.
Could you clarify how you see the relationship between this issue and #11912? Is this intended as an alternative design, or as additional work on top of it?
It seems you focused on rewriting the SinkWriter layer. I replaced the entire Flink Coordinator, primarily addressing fault recovery issues by replacing the coordinator with a data plane protocol. I consider this additional work, and you can focus on the SinkWriter side. Your implementation essentially still utilizes the coordinator, while I completely removed it, using Flink's native mechanisms for coordination. In this branch, I didn't make any additional rewrites to the SinkWriter. |
Thanks for the clarification. Just to clarify one point about #11912: the current implementation is not limited to the SinkWriter layer, and it no longer uses LocalSchemaCoordinator. SchemaOperator also removes requestSchemaChange() and relies on Flink checkpoint completion to coordinate schema-change dispatch and the release of buffered rows. I agree that #11960 adds stronger recovery/rescaling mechanisms, such as explicit producer/sequence IDs, atomic protocol state, and replay handling. However, I think there is still an architectural overlap between the two PRs. #11912 keeps parallel sink writers for the same table and separates one-time external DDL application from writer-local schema refresh, while #11960 appears to partition data by table and let one table owner handle the schema change. So these seem less like independent SinkWriter/coordinator changes and more like two different coordination models for part of the same problem. Would it make sense to first agree on which parallel-writer model we want to keep, and then treat the additional recovery/rescaling guarantees in #11960 as follow-up hardening on top of that model? |
|
Thanks both for working through the relationship with #11912 in the open — that's exactly the kind of discussion that should happen before either lands, since merging both as-is would leave the project maintaining two different schema-evolution protocols for the same coordination problem. From my own read of this PR's diff (not a full comparative review of #11912, which I haven't traced code-level), I can confirm the framing dybyte gave is accurate for #11960's side: this PR does fully retire Given #11912 is "Related to #11785" and this PR closes #11958, and both are actively reworking the same That said, this doesn't change my earlier review: independent of how the #11912/#11960 overlap gets resolved, Issue 1 from my review (missing |
I agree that the two PRs should now be treated as alternative coordination models rather than independent changes. One point I would clarify is that I don't think the recovery/rescaling guarantees in #11960 are entirely orthogonal hardening that can simply be layered on top of either parallel-writer model. In #11960, deterministic table ownership, producer/sequence IDs, dependency tracking on data rows, pending controls/rows, and checkpointed protocol state are designed together as one consistency model. The ownership model is what removes the need for cross-writer coordination for a table, while the explicit protocol state makes that model recoverable and replayable after failure or rescaling. I agree that we should first reach consensus on which coordination model we want for Flink. But I think we should choose one of the architectures, once that is decided, we can then see which pieces from the other PR are still useful or can be reused. |
|
Agreed that's the right sequencing — settle on one coordination model first, then treat whichever pieces of the other PR still add value (this PR's producer/sequence IDs and replay handling, or #11912's writer-local refresh separation) as follow-up hardening on top of that choice, rather than reviewing two competing implementations in parallel. To be clear, this doesn't change where #11960 itself stands: Issue 1 from my review (the missing |
996c50b to
5e069a1
Compare
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for clarifying the relationship with #11912, @CloverDew and @dybyte. I re-reviewed the entire current diff and the source/transform/gate/writer/checkpoint paths. I agree these are alternative coordination models requiring a maintainer decision, rather than independent changes. This head still has the compatibility-documentation blocker, and I found an additional unaligned-recovery correctness blocker. I also need to update my August release statement: the old implementation is now present in released 3.0.0 and 3.1.0, so the impact is no longer limited to dev/SNAPSHOT users.
Reviewed head: 12b77ef0e7233d6a7a702b0a355379329f5e98bd; base: dev; local branch: seatunnel-review-11960-20261120; review date: 2026-11-20 (America/New_York). Merge base: d1e1d79b9e09bf61ad57878b9887c7d173471f39. Change size: 39 files changed, 4411 insertions(+), 1078 deletions(-).
What Problem Does This PR Solve?
User pain point: Process-local schema coordination cannot reliably coordinate independent Flink TaskManagers or reconstruct schema progress after recovery/rescaling.
Fix approach: Remove LocalSchemaCoordinator, carry schema controls and row dependencies through the data stream, route each table to one DDL owner, and checkpoint the protocol and pending rows in Flink state.
One-sentence summary and example: After a source adds a column, downstream rows wait until the table's writer sees the matching schema command; a restarted writer should recover its runtime schema before those rows resume.
1. Code Change Review
1.1 Core Logic Analysis
Before:
SchemaOperator -> process-local LocalSchemaCoordinator rendezvous
-> BroadcastSchemaSinkOperator -> writer DDL -> local acknowledgement
Persistent state: localSchemaState / lastProcessedEventTime / last-processed-epochs
After / complete runtime path:
Flink starter -> AbstractSourceExecuteProcessor
-> streaming + schema-enabled SupportSchemaEvolution source
-> validate incremental.parallelism == 1; enable reader flow control
-> FlinkSourceReader / FlinkRowCollector -> schema marker or data row
-> SchemaOperator queues DDL + following rows, waits two checkpoint completions
-> producer#sequence control + dependency-tagged rows
-> transforms map schema controls / preserve filtered no-op sequence markers
and copy dependencies onto replacement data rows
-> SchemaEvolutionStreamUtils: data keyBy(tableId), controls broadcast, union
-> BroadcastSchemaSinkOperator: sequence dedup / out-of-order controls / pending rows
-> table owner emits schema command, then dependent rows on a forward channel
-> common/Flink-2 SinkWriter -> SupportSchemaEvolutionSinkWriter.applySchemaChange
-> connector physical DDL or RestoreTableSchemaEvent runtime-schema refresh
-> writer/committer checkpoint lifecycle
Recovery -> source atomic producer/queue state, fresh completion fence
-> sink union state + table-owner redistribution + runtime-schema restore
-> in-flight controls/rows replay -> resume dependencies
The ordinary streaming schema-enabled path reaches the new protocol. SchemaEvolutionRouting avoids changing data partitioning for a schema-capable sink when its upstream protocol is disabled. The three starter variants preserve forward routing to their sink; transform output aliases retain the protocol flag. Non-schema jobs keep the previous stream construction.
Source protocol state now keeps producer identity, sequence, queued DDL/rows and dependency together in one redistributable entry; multiple active producers on a scale-down fail rather than being arbitrarily merged. The restored checkpoint fence is reset so old completion IDs do not authorize a newly restored XA transaction. The Flink-1.13 timer fails exactly-once work on a stalled second completion instead of treating elapsed time as commit proof; at-least-once fallback is explicitly separate. Sink buffer overflow and malformed/missing target-schema metadata fail instead of silently dropping a control. Writer exceptions preserve their original cause.
The deletion audit confirms the local coordinator/provider and acknowledgement calls are intentionally replaced by this protocol, with no remaining Java references. The flaw below concerns how sink progress is persisted, not the decision to remove the singleton.
Issue 1: A producer-sharded sequence can suppress a table owner's unprocessed control after an unaligned checkpoint
- Location:
seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/BroadcastSchemaSinkOperator.java:238-249; related restore at:206-214, dedup at:332-337, ownership at:580-610. - Problem description: The producer's applied sequence is saved only by
ownsUnionStateKey(producerId), while its table snapshot is saved only byisTableOwner(tableId). These can be different subtasks. A non-owner advances appliedSequences when consuming a control without recording the table snapshot. Under an unaligned checkpoint, gates need not have consumed the same broadcast prefix at snapshot time: one gate can have processed control P#1 while the table owner has it only in captured input-channel state. Flink explicitly allows barriers to overtake records in this mode (checkpoint model). - Concrete failure chain: Choose producer shard A and a different table owner B. A consumes P#1 and snapshots sequence 1; B snapshots before P#1 and has no latest table event. Restore unions A's sequence into every gate. When B replays its captured P#1,
appliedSequence >= sequencereturns before emitting the schema command; dependent rows are then considered ready although B's fresh writer has not received that schema. The reverse skew can also restore a table snapshot ahead of the sequence shard and replay a control as if it were new. The assumption that all gates have the same compact state is not valid at an unaligned snapshot cut. - Potential risk: Recovery can skip required DDL/runtime schema changes and deliver new-format rows to an old-schema writer, causing failure or incorrect writes. This is a source-derived execution counterexample, not a locally executed failure claim.
- Best improvement / root cause / location: Persist and restore the table owner's progress together with its schema/pending state; do not use another gate's broadcast progress as proof that this owner processed the control. Add a deterministic two-gate checkpoint/restore regression with different producer/table owners and an in-flight control, asserting the schema command precedes the row. Keep the unaligned case in CI. A smaller interim contract would have to reject the unsupported checkpoint mode explicitly and document that limitation; the complete solution should preserve the intended unaligned capability.
- Severity: High. Blocking: Yes. Raised by another reviewer: No. This is independent of @dybyte's architectural-overlap point.
1.2 Compatibility Impact
Partially incompatible: non-schema jobs retain their existing behavior, but schema-enabled jobs change table routing, incremental-reader constraints, graph structure and checkpoint/savepoint state contracts.
Issue 2: The cross-version schema-state break still lacks an incompatible-changes entry and migration contract
- Location:
SchemaOperator.java:557-591,BroadcastSchemaSinkOperator.java:176-199, and missing entries indocs/en/introduction/concepts/incompatible-changes.md/docs/zh/introduction/concepts/incompatible-changes.md. - Problem description: The released implementation requests
localSchemaStatewith SchemaStateEntry andlastProcessedEventTime; the sink requestslast-processed-epochswith TableEpochEntry. This head no longer reads those schema-progress states/types and requests atomic producer state and new union descriptors instead. Its “legacy” fallback concerns an earlier layout of the new protocol; it does not migrate the released coordinator-era state. The new graph also inserts filter/partition branches, so descriptor translation alone would not prove automatic operator mapping. - Updated release evidence: Freshly fetched official tags contain the old sink state at 3.0.0 commit 5056e3e and 3.1.0 commit 2d3983a. My August statement that this had never shipped is no longer applicable.
- Potential risk: Users cannot assume an existing schema-enabled job's checkpoint is upgrade-compatible. I also correct the earlier overly specific failure claim: merely changing a state descriptor name is not enough evidence that Flink must reject restore under the default
allowNonRestoredStatesetting; operator mapping and serializer restoration matter too. Neither successful new-protocol recovery nor forcing non-restored-state options proves migration safety. - Best improvement / alternatives: Update both incompatible-changes guides with affected jobs/releases, the incremental.parallelism/routing restriction, unsupported old-state restore boundaries, and a safe restart/resnapshot procedure with downstream duplicate/data-reconciliation precautions. If transparent upgrade is intended, retain/translate the old state and test real old-to-new savepoint/operator/serializer restoration. Do not tell users to discard source progress without explaining its data consequences.
- Severity: Medium. Blocking: Yes. Raised by another reviewer: No; this carries forward my prior Issue 1 with refreshed release evidence.
1.3 Performance / Side-Effect Analysis
One table is pinned to one writer even when sink parallelism is higher, so a single hot table loses parallel writer throughput. Only controls are broadcast, but every gate holds producer progress and out-of-order controls. Source polling pauses for two completions after split assignment and after a schema-emitting poll. Source and sink queues have record/estimated-byte bounds and fail on overflow; the source pending queue can include subsequent records from other tables too. Restore unions metadata/pending rows into all subtasks before owner filtering, so restoration memory/I/O grows with aggregate buffered state and parallelism. These are real capacity/latency tradeoffs to consider in the #11912 design choice.
1.4 Error Handling and Logging
Unsupported writers now fail rather than silently ignoring schema commands, and connector exceptions remain causes. Missing initial/target schemas and unreconstructable targets fail before entering checkpointed progress. The new test REST helper has a separate boundedness gap:
Issue 3: The savepoint deadline does not bound a blocking Flink REST request
- Location:
seatunnel-e2e/seatunnel-e2e-common/src/test/java/org/apache/seatunnel/e2e/common/container/flink/AbstractTestFlinkContainer.java:396-401; caller deadline at:332-365. - Problem description:
HttpClients.createDefault()supplies no explicit connect, connection-acquisition or socket timeout. The savepoint loop checks its 120-second deadline only between calls. If the fault-injected cluster accepts a connection but stops responding,client.executeor body consumption can block beyond that deadline; the finally cleanup/cancellation uses the same helper. Awaitility outside a blocking call does not supply a socket deadline. HttpClient's RequestConfig contract leaves those defaults undefined rather than imposing this test's deadline. - Potential risk: Recovery CI can hang and delay cleanup until an outer job timeout instead of reporting the actual failed readiness/savepoint operation.
- Best improvement / location: Give every request finite connect/acquisition/socket limits and bound savepoint polling by its remaining deadline; include request/job context. Verify with a controlled server that accepts a request but withholds the response, without adding external-network dependence.
- Severity: Medium. Blocking: Yes, for bounded fault-test execution. Raised by another reviewer: No.
2. Code Quality Assessment
2.1 Coding Standards
The control, stream-routing and restore-plan helpers separate responsibilities. Class/method comments explain ownership and checkpoint fences. The restore plan validates exact target-schema reconstruction through the real dispatcher. No unrelated connector registration, configuration entry or package dependency is removed. The changed test infrastructure keeps extra TaskManagers in teardown and reapplies connector extensions on newly created workers.
2.2 Test Coverage and Test Stability
Stability rating: Risk present. MysqlCDCWithFlinkSchemaChangeIT:191-282 still assumes standby startup/failure and pending-savepoint capture occur inside a 30-second checkpoint window. It polls real schema/data and RM state, but does not assert the checkpoint ID/cut establishing that named window. Under load it can pass while exercising a later cut. Replace that timing assumption with an explicit checkpoint/protocol barrier or assert the observed completed checkpoint IDs. The short sleep in REST savepoint polling follows a status query, so it is conditional polling, not an assertion-readiness sleep. Issue 3 separately requires finite I/O waits.
Test-to-risk mapping: SchemaOperator tests check two fresh completion fences, atomic producer/queue state across scale-down, sequence/dependency preservation, repeated timestamps, bounded buffers and exactly-once/at-least-once fallback. Gate tests check owner-only commands, row overtaking, duplicate/out-of-order controls, filtered controls, latest-schema restore and pending-row redistribution. Stream graph tests verify both broadcast and key partitioners. Restore-plan tests assert exact column order/types/metadata and duplicate rejection. Starter/transform tests cover protocol gating and replacement-row/no-op dependencies; reader tests cover logical close, stale acknowledgements and reactivation. MySQL recovery fixtures enable XA and compare complete schema/data, with a subsequent drop/update after recovery.
However, testReplicatedUnionStateIsSnapshottedAsSingleAggregateCopy:522-571 feeds every gate the same controls before snapshot, and the single-subtask restored-sequence test supplies a matching schema snapshot. Neither covers the mismatched subtask cuts in Issue 1. New-protocol synthetic state stores also do not test released-version serializer/graph migration in Issue 2. Existing assertions removed with the local coordinator are replaced by protocol assertions; I found no unrelated intentional weakening, but these missing guarantees must be covered.
No local build, compilation, UT, integration test, E2E, Docker or runtime job was run. git diff --check passed. All findings come from the exact-head diff, real source callers, test assertions and fetched release sources; CI availability is reported separately below.
2.3 Documentation Updates
Both language schema guides agree on one incremental reader, checkpoint progress and writer-local restore versus physical DDL replay. They do not replace the missing incompatible-changes/migration guidance. The unaffiliated #11912 design has not been fully comparatively reviewed in this pass; I am not claiming that it automatically solves these findings.
3. Architectural Soundness
3.1 Elegance of the Solution
Removing process-local rendezvous is a sound direction, but the current checkpoint sharding is not a complete recovery contract. The precise fix belongs in sink-gate state ownership/recovery, not in weakening connector DDL errors or dropping dependency tags. Keep one coherent coordination design chosen by maintainers; I agree with @dybyte's overlap concern and the author's later acknowledgement that the models are alternatives.
3.2 Maintainability
Atomic source state is an improvement. Sink state must offer the same invariant: persisted “applied” progress must prove the responsible table owner's schema state, not merely another subtask's receipt. Document and test the actual restore cut and failure behavior.
3.3 Extensibility
Producer IDs and sequence dependencies can support explicit replay, but do not by themselves establish multi-reader, parallel-per-table writer or cross-version compatibility. Keep the single incremental reader guard until a broader ordering model exists.
3.4 Historical-Version Compatibility
The fresh official release references above supersede the old dev-only assumption. Old-to-new migration needs an explicit supported or unsupported contract, with real state/graph evidence if restoration is promised.
4. Issue Summary
| Number | Issue | Location | Severity | Blocking |
|---|---|---|---|---|
| 1 | Sequence shard can suppress table-owner control after unaligned restore | BroadcastSchemaSinkOperator.java:238-249 | High | Yes |
| 2 | Released schema-state migration/incompatibility is undocumented | SchemaOperator.java:557; incompatible-changes guides | Medium | Yes |
| 3 | Unbounded REST I/O defeats savepoint/failure-test deadline | AbstractTestFlinkContainer.java:396-401 | Medium | Yes |
Complete-scan self-check: all 39 changed paths, removed coordinator/provider callers, three starters, shared/2.0 writers, transform/dependency flow, reader lifecycle, schema protocol state, tests/fixtures/assertion strength, bilingual changes, current release sources, peer discussion and current-head CI. This is source review, not live recovery acceptance.
5. Merge Recommendation
Conclusion: Not recommended to merge
Blockers — must be fixed: Correct and deterministically regress Issue 1; resolve the old-to-new state/migration contract and bilingual incompatible-changes entry in Issue 2; bound the REST test operations in Issue 3. The maintainers also need to choose the coordination model relative to #11912. Successful required current-head Flink CI and effective maintainer review remain separate gates.
Recommended fixes — non-blocking: Make the two E2E checkpoint windows self-verifying and add targeted reader flow-control tests for duplicate/aborted checkpoint notifications. Keep the acknowledged architectural tradeoffs visible rather than treating this as orthogonal writer hardening.
Overall assessment and alternatives: The problem is real and the data-plane direction is useful, but a successful synchronized-state test cannot establish safety at an unaligned cut. A focused state-ownership correction is preferable to swallowing DDL errors or allowing rows through. No other reviewer approval was present in the collected history; @dybyte's design concern remains unresolved by a source-only correctness review.
Current CI and repository snapshot: no Apache check reported on the head; no exact-head fork Build found. GitHub merge state: BLOCKED; review decision: REVIEW_REQUIRED. Daniel repository permissions are pull=true, push=false, triage=false; effective maintainer approval remains separate.
Separate synchronization fact: base dev, compare ahead, ahead 3 / behind 0. This is recorded as drift metadata, not a request to sync merely because the branch is behind.
SEZ9
left a comment
There was a problem hiding this comment.
Thanks for working on this. I reviewed the latest head 12b77ef0e723.
What this PR fixes
- User pain: Flink CDC schema evolution was coordinated through the JVM-static
LocalSchemaCoordinator(deleted here, 448 lines). A process-local coordinator cannot reliably coordinate source and sink subtasks on other TaskManagers or reconstruct schema progress after recovery or rescaling, so DDL-before-row ordering was not guaranteed on a real cluster. - Fix approach:
SchemaOperatornow stamps each DDL with a checkpointedproducerId#sequenceand tags later rows with the id they depend on.SchemaEvolutionStreamUtils.routeSchemaChangeskeys data rows by table id and broadcasts control rows intoBroadcastSchemaSinkOperator. The gate buffers rows until their control arrives, lets only the table-owning subtask forward the DDL toFlinkSinkWriter, and replays the latest schema as aRestoreTableSchemaEventafter restore.FlinkSourceReadergains a two-checkpoint pause, andincremental.parallelism != 1is rejected at startup. - One-line summary: The happy-path ordering holds in the code I traced, but I am not ready to approve this head. The dependency stamp adds permanent per-row cost and
keyBy(tableId)limits each table to one writer. Pending rows in union state inflate recovery memory and bypass the buffer caps on restore. The recovery paragraph in the docs overstates what the translation layer guarantees. Separately,incompatible-changes.mdis not among the changed files although the PR checklist ticks it, and rejectingincremental.parallelism > 1at startup is a user-visible behaviour change.
Runtime chain I rechecked
Job graph construction (client side)
AbstractSourceExecuteProcessor.execute() AbstractSourceExecuteProcessor.java:81
-> enableSourceKeepAliveIfNeeded() sets env 'schema-changes.source-flow-control'=true AbstractSourceExecuteProcessor.java:171-176
-> validateSchemaEvolutionIncrementalParallelism() checks only 'incremental.parallelism' AbstractSourceExecuteProcessor.java:118, 147-159
-> sourceStream.transform("schema-evolution", createSchemaOperator(...)) with no uid and no parallelism pin AbstractSourceExecuteProcessor.java:119-126, 194-197
(Flink 1.13: SchemaOperator13 with stall timeout derived from the checkpoint interval flink-13-starter SourceExecuteProcessor.java:59; SchemaOperator13.java:68-80, 130-143)
-> new DataStreamTableInfo(..., schemaEvolutionEnabled=true) AbstractSourceExecuteProcessor.java:131-135
TransformExecuteProcessor.execute() propagates the flag TransformExecuteProcessor.java:150-154
SinkExecuteProcessor -> SchemaEvolutionRouting.isRequired(isStreaming, stream, sink) SchemaEvolutionRouting.java:28-32
(starter-common SinkExecuteProcessor.java:55; flink-13-starter :211; flink-20-starter :54)
-> SchemaEvolutionStreamUtils.routeSchemaChanges(ds, parallelism, stream.getCatalogTables()).forward() SchemaEvolutionStreamUtils.java:45-63
data rows: filter(DataRowFilter).keyBy(row.getTableId()) SchemaEvolutionStreamUtils.java:49-52, 83-94
control rows: filter(SchemaRowFilter).broadcast() SchemaEvolutionStreamUtils.java:53-54
union -> BroadcastSchemaSinkOperator(initialSinkTables) at sink parallelism SchemaEvolutionStreamUtils.java:56-62
-> ds.sinkTo(new FlinkSink<>(...))
Source side (runtime)
FlinkSourceReader.addSplits(): any non-empty assignment sets pendingSchemaCheckpoints = 2 FlinkSourceReader.java:162-167
FlinkSourceReader.pollNext(): suspended while pendingSchemaCheckpoints > 0 FlinkSourceReader.java:122-125
-> sourceReader.pollNext(collector) -> FlinkRowCollector.collect(SchemaChangeEvent) sets schemaChangeThisPollNext FlinkRowCollector.java:78-87
-> a DDL in this poll re-arms the two-checkpoint pause FlinkSourceReader.java:128-134
FlinkSourceReader.snapshotState() records schemaSnapshotId FlinkSourceReader.java:146-148
FlinkSourceReader.notifyCheckpointComplete(): counts down, resumes at 0 FlinkSourceReader.java:224-236
SchemaOperator.processElement() SchemaOperator.java:157-183
-> '__SCHEMA_CHANGE_EVENT__' row -> handleSchemaChangeDetected() -> enqueueSchemaChange(); schemaChangePending = true SchemaOperator.java:185-217
-> while pending: enqueueDataRecord() (caps 100000 records / 64 MB, overflow fails the task) SchemaOperator.java:219-241
-> otherwise emitDataRecord() -> SchemaEvolutionControlMessage.requireSchemaChange(row, lastEmittedSchemaChangeId) SchemaOperator.java:772-775; SchemaEvolutionControlMessage.java:109-117
SchemaOperator.notifyCheckpointComplete(): first completion records firstSeenCheckpointId, the next one releases SchemaOperator.java:290-343
-> applyNextPendingSchemaChange(): id = producerId#(++sequence) SchemaOperator.java:434-459
-> sendSchemaChangeEventToDownstream() emits a row with 'schema_change_broadcast' + 'schema_change_id' SchemaOperator.java:759-770
-> drainDataUntilNextSchemaChange() releases buffered rows stamped with the new id SchemaOperator.java:461-482
Flink 1.13 only: SchemaOperator13.scheduleFallbackTimer() -> handleFallbackTimerOnTaskThread(); exactly-once throws, at-least-once releases SchemaOperator13.java:99-128; SchemaOperator.java:355-406
SchemaOperator.snapshotState(): one atomic SchemaEvolutionProtocolState entry, plus the legacy states written again SchemaOperator.java:485-548
SchemaOperator.initializeState(): restoreAtomicProtocolState() resets the fence to -1 SchemaOperator.java:551-607, 627-649
Transforms in between
TransformExecuteProcessor.mapRow(): control row -> transform.mapSchemaChangeEvent() -> transformedSchemaChangeRow() (null result marks 'schema_change_filtered'); data row -> copyRequiredSchemaChange() TransformExecuteProcessor.java:223-237; SchemaEvolutionControlMessage.java:95-132
ArrayFlatMap.flatMap(): same handling for flat-map transforms TransformExecuteProcessor.java:262-284
Sink gate (runtime)
BroadcastSchemaSinkOperator.processElement() BroadcastSchemaSinkOperator.java:270-292
control row -> handleBroadcastedSchemaChange() BroadcastSchemaSinkOperator.java:316-345
-> createRestorePlan() -> SchemaRestorePlanGenerator.generate(); result discarded, used as validation on every gate BroadcastSchemaSinkOperator.java:327-330, 491-494; SchemaRestorePlanGenerator.java:54-134
-> bufferOutOfOrderSchemaChange() -> stageContiguousSchemaChanges() BroadcastSchemaSinkOperator.java:347-413
-> owner only (isTableOwner(event.tablePath())): rememberLatestSchemaEvent() + emitApplySchemaEventToSink() BroadcastSchemaSinkOperator.java:402-405, 532-541, 569-590
-> completePendingSchemaChange() advances appliedSequences on every gate BroadcastSchemaSinkOperator.java:415-431
-> drainPendingRows() BroadcastSchemaSinkOperator.java:509-530
data row -> pass through if its required id is applied, else bufferPendingRow() (caps 100000 records / 64 MB) BroadcastSchemaSinkOperator.java:283-314
BroadcastSchemaSinkOperator.snapshotState(): sequences and out-of-order controls sharded by ownsUnionStateKey(), latest schemas by table owner, all pending rows BroadcastSchemaSinkOperator.java:235-267, 560-564
BroadcastSchemaSinkOperator.initializeState(): four union list states; sequences merged with Math::max; pending rows filtered by isTableOwner(row.getTableId()) BroadcastSchemaSinkOperator.java:175-232
-> first processElement() after restore -> replayRestoredSchemaEventsIfNeeded() emits RestoreTableSchemaEvent(changeAfter) per owned table, then staged controls, then pending rows BroadcastSchemaSinkOperator.java:450-479
Sink writer (forward channel from the gate)
FlinkSinkWriter.write() -> handleControlMessage() on 'schema_change_event' FlinkSinkWriter.java:104-134 (flink-20 copy: FlinkSinkWriter.java:101)
-> handleSchemaChangeEvent() -> SupportSchemaEvolutionSinkWriter.applySchemaChange(event); no LocalSchemaCoordinator acknowledgement follows FlinkSinkWriter.java:136-165
Findings
Issue 1: After the first DDL every data row is permanently stamped with a schema dependency and re-copied at the gate, and all rows of a table are pinned to one sink subtask
- Location:
seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/SchemaOperator.java:773 - Why it matters: Root cause:
SchemaOperator.emitDataRecordcallsrequireSchemaChange(row, lastEmittedSchemaChangeId)for every row.lastEmittedSchemaChangeIdis set inapplyNextPendingSchemaChange, restored from state, and never cleared.- So from the first DDL until the end of the job,
requireSchemaChangegives each row a freshHashMapcopy of its options plus a<uuid>#<seq>string that is serialized across the shuffle. - The gate allocates another
HashMapper stamped row inclearRequiredSchemaChangeto strip the id. Transforms in between add one more copy throughcopyRequiredSchemaChange. routeSchemaChangesadds two filter operators and akeyBy(tableId)exchange in front of every schema-evolution sink. The previous graph attached the gate directly, with nokeyBy.
Impact:
- This is steady-state allocation and serialization overhead on the hot path, even when the last DDL was days ago.
- Sink parallelism above 1 no longer spreads a table's rows. A single-table CDC job writes through one sink subtask whatever the configured parallelism. With a few tables, several can hash to the same subtask while other writers sit idle.
- Jobs whose rows were previously spread across parallel sink writers can lose throughput after upgrade.
Fix:
- Stop stamping rows once the dependency is known to be satisfied. This needs a condition that proves every gate has already applied the control. A completed checkpoint after the control was emitted is such a proof only with aligned barriers, so please state which condition you rely on.
- Where the operator is the sole owner of the row, mutate the options map in place instead of copying it at each hop.
- Document the one-writer-per-table behaviour in
schema-evolution.md(en and zh) so users can size sink parallelism accordingly. - Evidence:
seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/SchemaEvolutionControlMessage.java:148 Map<String, Object> options = new HashMap<>(row.getOptions());;seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/SchemaEvolutionStreamUtils.java:52 .keyBy(new TableIdKeySelector()); - Suggested fix:
lastEmittedSchemaChangeIdis never cleared, so after the first DDL every row for the rest of the job gets a new optionsHashMapplus the<uuid>#<seq>string here. The gate then makes a secondHashMapcopy inclearRequiredSchemaChange. That is per-row allocation and extra serialized bytes on the hot path long after the DDL has been applied everywhere.
Could the stamp be limited to the window where the dependency can actually be unsatisfied? The condition has to prove that every gate has applied the control. A completed checkpoint after the control was emitted only proves that with aligned barriers.
Related: keyBy(tableId) in routeSchemaChanges pins each table to a single sink subtask. Please call that out in the docs, since a single-table job now writes through one writer regardless of sink parallelism.
- Priority: P1 — should fix in this PR
- I traced this in the code.
- When it happens: Streaming job with MySQL-CDC
table-names = ["shop.products"],schema-changes.enabled = true, envparallelism = 5and a JDBC sink (the shape of the docs example). Every data row has tableIdshop.products, sokeyBysends all of them to one of the 5BroadcastSchemaHandlersubtasks and, via.forward(), to one sink writer; the other 4 writers receive no data rows. After the firstALTER TABLEis released, each later row gets a copied options map carryingrequired_schema_change_id=<uuid>#1, copied again at the gate, for the rest of the job.
Issue 2: Buffered data rows are checkpointed in union list state, so every sink gate loads every gate's pending rows on restore and bypasses the buffer caps
- Location:
seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/BroadcastSchemaSinkOperator.java:197 - Why it matters: - Root cause:
schema-gate-pending-rowsis registered withgetUnionListState. Each subtask snapshots its wholependingRowsqueue, up toMAX_PENDING_RECORDS(100,000 rows) orMAX_PENDING_BYTES(64 MB estimated). On restore, each subtask is handed the union of all subtasks' entries and only then filters withisTableOwner. - Memory impact: Flink keeps operator list state on the heap. With sink parallelism P, a recovering gate can hold up to P x 64 MB (estimated) of pending rows, most of which it does not own. That copy stays until the next
snapshotStatecallspendingRowState.clear(). Recovery of a backlogged job is when memory is tightest, and an OOM at that point would repeat on every restart from the same checkpoint. - Cap bypass: the restore loop adds owned rows to
pendingRowswithout theMAX_PENDING_RECORDS/MAX_PENDING_BYTEScheck thatbufferPendingRowenforces. After a rescale that concentrates more tables on one gate (for example a scale-down), that gate can start above the cap. The next row that needs buffering then throws the overflowSchemaEvolutionException, and restarting from the same checkpoint reproduces it. - Fix: keep union state for the compact control state only (sequences, latest schemas, out-of-order controls) and move pending rows out of it.
- Keyed state on the table id would follow the same key-group assignment that
isTableOwnermirrors, but the gate would then have to run as a keyed operator. - Plain list state returns each subtask's own rows when parallelism is unchanged, but needs an explicit answer for rescaling.
- Whichever is chosen, apply the same bound on the restore path, with a clear error instead of silently starting above the cap.
- Keyed state on the table id would follow the same key-group assignment that
- Evidence:
seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/BroadcastSchemaSinkOperator.java:199 "schema-gate-pending-rows", PendingRowEntry.class));;seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/BroadcastSchemaSinkOperator.java:216 for (PendingRowEntry entry : pendingRowState.get()) {;seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/BroadcastSchemaSinkOperator.java:265 pendingRowState.add(entry); - Suggested fix: Union state is a good fit for the small control state, but here it carries buffered data rows. On restore every gate receives every gate's pending rows (up to 64 MB estimated each) and only then filters by
isTableOwner, so heap use during recovery grows with sink parallelism.
The restore loop also adds rows without the MAX_PENDING_RECORDS/MAX_PENDING_BYTES check from bufferPendingRow. After a scale-down, a gate can start above the cap and fail on the next buffered row, and it will fail the same way on every restart from that checkpoint.
Could the pending rows live in non-union state, with the same bound applied on restore?
- Priority: P1 — should fix in this PR
- I traced this in the code.
- When it happens: Sink parallelism 2, two tables owned by different gates, each gate holding about 60,000 rows waiting for a schema control when a checkpoint or savepoint is taken (each under the 100,000 cap). Restore with sink parallelism 1: the single gate's loop at :216-221 loads all 120,000 rows into
pendingRowswith no cap check. If the awaited control has not yet been applied, the next dependent row hitspendingRows.size() >= MAX_PENDING_RECORDSinbufferPendingRowand throws 'Sink schema gate pending-row buffer overflow', and the same happens on each restart from that checkpoint. With parallelism unchanged, each of P gates still transiently holds all P gates' pending rows on heap until the next snapshot.
Issue 3: The recovery paragraph is misplaced and overstates the guarantee; the connector contract from the PR description is not written down anywhere
- Location:
docs/en/introduction/configuration/schema-evolution.md:481 - Why it matters: - Placement: the two new paragraphs are appended after the closing fence of the
### Mysql-CDC -> Jdbc-SqlServerexample, so they render as part of that example rather than as general Flink behaviour. - Overstated guarantee: the text says the sink restores its schema "without reapplying physical DDL". In the code,
replayRestoredSchemaEventsIfNeededbuilds aRestoreTableSchemaEventand sends it throughemitApplySchemaEventToSink.FlinkSinkWriterthen passes it toSupportSchemaEvolutionSinkWriter.applySchemaChangelike any other schema event. - Whether DDL is skipped therefore depends on each connector treating
RestoreTableSchemaEventas an in-memory refresh.AbstractJdbcSinkWriterdoes skip the dialect DDL for this event, but I did not check the other sinks. The sentence should be scoped to what the translation layer guarantees. - Missing contract: the PR description states that DDL is delivered at least once relative to checkpoints. It also says connectors must make
applySchemaChangesynchronous, propagate failures, and converge on repeated DDL. TheSupportSchemaEvolutionSinkWriterJavadoc only says "apply schema change to third party data receiver", andsink-connector-development.mddoes not mention any of this, so connector authors cannot find it. - Fix:
- Move the paragraphs into a dedicated Flink section near "Enable schema evolution" in both languages.
- Reword to at-least-once DDL delivery, with the restore event applied through
applySchemaChange. - Add the connector-side requirements to the sink developer docs and/or the
SupportSchemaEvolutionSinkWriterJavadoc.
- Evidence:
seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/BroadcastSchemaSinkOperator.java:464 new RestoreTableSchemaEvent(entry.event.getChangeAfter().copy());;seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/BroadcastSchemaSinkOperator.java:466 emitApplySchemaEventToSink(restoreEvent, entry.eventId); - Suggested fix: Two requests on this paragraph.
(1) It sits directly under the Mysql-CDC -> Jdbc-SqlServer example, so it reads as specific to that example. A dedicated Flink subsection near "Enable schema evolution" would be easier to find (same for zh).
(2) "without reapplying physical DDL" is stronger than what the translation layer guarantees. The gate emits a RestoreTableSchemaEvent that still goes through the writer's applySchemaChange, so the outcome depends on the connector. The JDBC writer skips DDL for it, but that is connector behaviour.
Could you reword it to the at-least-once contract from the PR description? Please also add the connector-side requirements (synchronous apply, propagate failures, converge on repeated DDL, handle the restore event without DDL) to the sink developer docs or the SupportSchemaEvolutionSinkWriter Javadoc.
- Priority: P2 — optional
- I traced this in the code.
- When it happens: Render
docs/en/introduction/configuration/schema-evolution.md: the paragraphs starting 'After recovery, the Flink sink restores its runtime schema…' and 'With Flink schema evolution enabled, source polling pauses…' appear directly beneath the SqlServer example under### Mysql-CDC -> Jdbc-SqlServer, not under a general Flink recovery or behaviour heading.
Review conclusion
Conclusion: final approval remains pending on the previous comments
2. Remaining follow-ups
- Issue 1: After the first DDL every data row is permanently stamped with a schema dependency and re-copied at the gate, and all rows of a table are pinned to one sink subtask
- Issue 2: Buffered data rows are checkpointed in union list state, so every sink gate loads every gate's pending rows on restore and bypasses the buffer caps
- Issue 3: The recovery paragraph is misplaced and overstates the guarantee; the connector contract from the PR description is not written down anywhere
Thanks for the updates so far. Happy to discuss the remaining points.
12b77ef to
d49b7e0
Compare
d49b7e0 to
ede4659
Compare
DanielLeens
left a comment
There was a problem hiding this comment.
Sorry for missing the protocol comment and interaction-only test problems in the previous round. These are carryover review omissions, not newly introduced production defects. Thanks for the substantial rework: I re-read the complete current diff and traced the table-keyed recovery path, and the three numbered blockers from my last review are addressed as explained below.
What problem does this PR solve?
The JVM-local coordinator cannot synchronize schema changes across separate Flink TaskManagers. This change replaces that acknowledgement path with ordered data-plane controls and table-keyed sink state. Example: after adding a column, a row that uses the new column waits for its table owner to apply the schema instead of trusting another process's local coordinator.
1. Code changes
1.1 Core logic
Complete runtime path:
CDC reader -> FlinkRowCollector schema marker -> SchemaOperator pending queue
-> two fresh checkpoint completion notifications -> producer#sequence control + dependent rows
-> map/flatMap transforms retain dependency and filtered no-op controls
-> SchemaTableRouter replicates each control to every configured table
-> keyBy(tableId) -> BroadcastSchemaSinkOperator keyed progress + pending rows
-> forward channel -> same sink subtask -> synchronous writer.applySchemaChange -> data write
Recovery/rescale -> source protocol tuple redistributed atomically; checkpoint fence restarts
-> table-keyed schema/progress/pending rows migrate together
-> RestoreTableSchemaEvent rebuilds writer runtime before table data
Flink 1.13 stalled checkpoint -> task-thread timer -> exactly-once fails, at-least-once may release
Key findings and correctness:
- The ordinary enabled streaming path reaches this protocol. Source capability and per-stream metadata now gate sink routing; unrelated sources no longer inherit another source's enabled flag. Map/flatMap replacement rows preserve dependencies, and filtered DDL retains a progress marker.
- Previous Issue 1 is closed in the current source design: applied sequence and pending rows belong to the table owner's keyed state. Progress from table A is not borrowed by table B. Controls are replicated to all known table keys because sequence numbers span tables. Each physical source table has one sink owner; cross-table merging to one physical target is explicitly unsupported.
- Source restore keeps producer/sequence/queue in one protocol tuple and refuses multiple active histories. It resets the checkpoint fence after restore. This is a correctness correction with deliberate throughput/upgrade costs, not merely a writer patch or a substitute for the alternative coordinator design in #11912.
- Previous Issue 2 is addressed as an explicit incompatibility, not an automatic state migration: both guides prohibit old coordinator/broadcast/union savepoints and allowNonRestoredState shortcuts, and prescribe a validated fresh snapshot cutover.
- Previous Issue 3 is closed: REST connect, connection-request and socket timeouts are each 10 seconds. The remaining test-quality and lifecycle documentation items below are carryovers I should have identified earlier.
Before:
LocalSchemaCoordinator.getInstance(jobId).requestSchemaChange(...);
// Sink acknowledgement reaches only its own JVM-local coordinator.After:
input.flatMap(new SchemaTableRouter(initialSinkTables))
.keyBy(new TableIdKeySelector())
.transform("BroadcastSchemaHandler", TypeInformation.of(SeaTunnelRow.class),
new BroadcastSchemaSinkOperator(initialSinkTables));
// Gate uses table-keyed ValueState and ListState; sink channel is forward().Current exact-head Build 44864251234 failed. unit-test (job 136724803195), Iceberg IT (136724802963) and JDBC part 7 (136724803615) stop downloading Maven wrapper 3.1.0 with HTTP 429, before tests. Retrigger those lanes after the rate limit clears; unrelated source/dependency changes are not a remedy. all-connectors-it-7 on Java 11/17 reaches SqlServerCDCIT and has four schema-evolution timeouts (expected 9 rows, got 0); the logs also contain a separate blank-url validation case, so that message alone is not established as the timeout root cause. Capture the failing test's task failure context before attributing it to this Flink protocol. MySQL CDC lanes were cancelled, so current-head native recovery success is not established. I have no evidence here that latest dev has fixed these specific failures; a blanket sync request would be unsupported.
1.2 Compatibility
Incompatible for existing Flink schema-evolution checkpoint/savepoint upgrades: old local coordinator and broadcast/union layouts are not migrated. Both incompatible-changes guides now state this and give a fresh-snapshot/separate-destination validation cutover. Incremental parallelism must be one; sink parallelism distributes tables, not a single table. Existing schema-changes.enabled default remains false. Internal row options/state/topology change; no public connector option is renamed.
1.3 Performance and side effects
Each control fans out to every configured table; each table has one Flink sink owner. Row dependency tagging copies option maps after DDL; the current implementation intentionally retains this dependency rather than guessing when it is safe to clear across unaligned cuts. Pending state is bounded per table, not per task; scale-down requires aggregate memory/backend sizing. The union-state P-fold restore issue from @SEZ9 is removed by keyed state, but per-table accumulated state still costs memory and checkpoint I/O. Exceptions fail the task; writer causes are preserved rather than logged and acknowledged as success.
1.4 Errors, logging, and findings
Issue 4: Document the protocol state and lifecycle boundaries
- Location:
seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/BroadcastSchemaSinkOperator.java:142. - Description and risk: The new keyed gate applyControl/isReady/drainRows methods and TableState sequence/control/pending counters have no method/field contract comments. SchemaOperator's selectProtocolState/restoreAtomicProtocolState and the source reader's pendingSchemaCheckpoints/schemaSnapshotId/lastSchemaCheckpointId also introduce nontrivial recovery state without local invariant documentation. Class-level summaries do not explain who owns these counters, which checkpoint cut they describe, or why every table sees every sequence. This is a carryover delivery omission.
- Best improvement: Add concise comments at those state fields and core methods: task-thread ownership, table/producer scope, contiguous sequence and FIFO rules, restore-before-first-row behavior, count/byte estimate limitations, and reset/release checkpoint conditions.
- Responsibility and trade-off: The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
- Severity: Medium; blocking: true.
- Previously raised by another reviewer: No, unless explicitly attributed above.
Issue 5: Give timer and stale-reader regressions observable outcomes
- Location:
seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-13/src/test/java/org/apache/seatunnel/translation/flink/schema/SchemaOperator13Test.java:42. - Description and risk: The timer registration test ends with only verify(registerTimer) counts/arguments. FlinkSourceReaderTest.testStaleNoMoreElementAcknowledgementDoesNotCloseReactivatedReader likewise ends with verify(resetNoMoreElementEvent/pollNext) on a mock that emits no data. Neither asserts the resulting schema/data or reader lifecycle outcome; these are pure interaction acceptance tests. They were reviewable in the previous version and I missed them.
- Best improvement: Retain precise timer assertions as complementary checks, but exercise a pending real control/data sequence through the captured callback and assert the defined exact-once failure or at-least-once output. For stale acknowledgement, emit an actual row through the reader and assert delivered contents, availability and continued activation. Use a supported subclass seam instead of reflective invocation.
- Responsibility and trade-off: The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
- Severity: Medium; blocking: true.
- Previously raised by another reviewer: No, unless explicitly attributed above.
Issue 6: Assert the checkpoint cut used by recovery scenarios
- Location:
seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mysql/MysqlCDCWithFlinkSchemaChangeIT.java:218. - Description and risk: The test assumes starting/registering a standby and stopping the primary will fit before the next 30-second checkpoint. A slow CI runner can cross that boundary and still pass while testing a different recovery cut. The savepoint test similarly waits only for a detection log before assuming the pending queue remains captured. This is a coverage/timing risk, not evidence of current production data loss.
- Best improvement: Observe the latest completed/in-progress checkpoint IDs or add a controlled checkpoint/DDL hook, and assert the captured savepoint/failure cut before proceeding. Keep the existing full schema/data comparisons and generous outer timeouts.
- Responsibility and trade-off: The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
- Severity: Medium; blocking: false.
- Previously raised by another reviewer: No, unless explicitly attributed above.
I read @SEZ9's detailed review and @dybyte's overlap discussion. The prior union-state amplification and owner-independent progress concerns are addressed by keyed ownership, and the connector/migration/performance restrictions are now in top-level bilingual guides. I agree with the direction of @TyrantLucifer's APPROVED/LGTM, but cannot yet share an unconditional merge conclusion because the carryover test-quality/documentation items remain. #11912 remains an alternative coordination architecture for maintainer selection, not an unrelated patch to stack blindly.
2. Code quality
2.1 Conventions
Reviewed all changed files for license, imports, naming, core-method and state-field comments. See the numbered findings for the required changes.
2.2 Test coverage and stability
Stability rating: Stable. At risk. The keyed-state fixture asserts exact output order, replay deduplication, cross-table isolation, filtered progress, pending restore and timestamps; the graph fixture asserts key-group partitioning. The restore-plan tests compare reconstructed schema and metadata. Source protocol tests poison independently redistributed legacy fields to check the new atomic tuple. They are static test inspection, not executed results. The new real-MySQL recovery tests compare table schema and all ordered data with XA enabled and TaskManager failover; the savepoint case scales 5 to 3. However, their claimed pending/external-DDL cut is inferred from a 30-second window, not asserted against checkpoint identity, and a pair of new tests only verify mock calls (Issue 5). The bounded REST polling sleep is condition polling, not a fixed sleep used as proof of readiness.
2.3 Documentation
The English and Chinese schema-evolution guides now match the keyed routing, per-table 100000/~64MiB pending limits, cross-table physical destination restriction, control fan-out, source checkpoint pauses, at-least-once DDL replay and runtime-only RestoreTableSchemaEvent contract. Developer guides require synchronous completion, failure propagation and connector-internal replica synchronization. Migration guidance is explicit; no automatic rollback/migration guarantee is implied.
3. Architecture
3.1 Change location
The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
3.2 Maintainability
Keep the behavior, lifecycle ownership, and failure contract together. The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
3.3 Extensibility
Prefer the existing component boundary and tests over unrelated shared abstractions.
3.4 Upgrade impact
Incompatible for existing Flink schema-evolution checkpoint/savepoint upgrades: old local coordinator and broadcast/union layouts are not migrated. Both incompatible-changes guides now state this and give a fresh-snapshot/separate-destination validation cutover. Incremental parallelism must be one; sink parallelism distributes tables, not a single table. Existing schema-changes.enabled default remains false. Internal row options/state/topology change; no public connector option is renamed.
4. Findings summary
Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.
| # | Finding | Location | Severity |
|---|---|---|---|
| 4 | Document the protocol state and lifecycle boundaries | seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/BroadcastSchemaSinkOperator.java:142 |
Medium |
| 5 | Give timer and stale-reader regressions observable outcomes | seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-13/src/test/java/org/apache/seatunnel/translation/flink/schema/SchemaOperator13Test.java:42 |
Medium |
| 6 | Assert the checkpoint cut used by recovery scenarios | seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mysql/MysqlCDCWithFlinkSchemaChangeIT.java:218 |
Medium |
5. Merge recommendation
Merge after fixes
Blocking items: Issues 4, 5. Current-head CI and write-capable maintainer review remain independent requirements.
Non-blocking suggestions: Issue 6: Assert the checkpoint cut used by recovery scenarios
Overall: the approach addresses a real path, but the listed blockers must be closed. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.
CI and repository state: Signal pull request update: SUCCESS; Build: FAILURE; Build: failure. GitHub reports BLOCKED / APPROVED.
Verification: Reviewed all changed files and the referenced call sites at b9f047a644a3ced8c53cf9423bdc439b602d4ceb against merge base c8e7a262897f341361094f158ffd4f60ae466b80. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.
Review time: 2026-11-21T08:11:14.417808-05:00
Local evidence: git fetch obtained head b9f047a644a3ced8c53cf9423bdc439b602d4ceb; git merge-base returned c8e7a262897f341361094f158ffd4f60ae466b80; git diff --stat reports 43 files changed, 3471 insertions(+), 1116 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.
DanielLeens
left a comment
There was a problem hiding this comment.
A CI status clarification on this unchanged head: the latest fork Build is now cancelled, rather than the failure state quoted in my full review. Cancellation is not a successful validation result, and Apache's recorded Build signal is still FAILURE. Please retrigger the existing Build for this branch/head when you are ready; this does not call for an unrelated dependency patch.
Conclusion: Merge after fixes. Blocking items: the already reported source/test-contract Issues 4 and 5 remain unresolved; CI becoming green alone would not clear them. Non-blocking: Issue 6 remains an additional checkpoint-cut assertion suggestion. This follow-up only corrects CI facts and introduces no new source finding.
Checked unchanged head b9f047a644a3ced8c53cf9423bdc439b602d4ceb against dev: compare diverged, ahead 4 / behind 1. This drift is recorded independently; it does not by itself request synchronization. This is a discussion/CI follow-up, not another full source review. No local build, test or runtime execution was performed. Daniel has READ repository permission; effective maintainer approval/dismissal remains a separate repository gate. Checked 2026-11-21T13:57:31.974195+00:00.
Head branch was pushed to by a user without write access
b9f047a to
ddd3a9d
Compare
ddd3a9d to
c4392df
Compare
c4392df to
29bb021
Compare
7f96eda to
3b47fcc
Compare
|
Thanks for the substantial rework on the table-keyed design. Staying strictly on the three earlier points, I can't tell from the thread whether any of them is settled on 1. Per-row cost after the first DDL (
2. Pending rows in union list state (
3. Docs (
A short note per point (fixed and where, or intentional and why) is enough for me to close these out. |
…, and fixed the data row allocation issue after job failure retries
3b47fcc to
01b99cf
Compare
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the extensive recovery and committer work. I re-read the complete current Apache SeaTunnel diff, all changed tests and the peer discussion. Retained Issues 4 and 5 still need the requested completion; retained Issue 6 remains non-blocking. The new shared CDC assigned-state change also introduces Issue 7 below. These are the complete findings for this head.
What problem does this PR solve?
User pain: A JVM-local schema coordinator cannot order DDL and dependent rows across independent Flink TaskManagers or reconstruct the protocol after failure/rescaling.
Fix: Replace it with producer/sequence controls, dependency-tagged rows, table-keyed sink progress and pending rows, source checkpoint flow control and recovered-commit classification.
In one sentence: A row using a newly added column waits behind its table's schema change, including after recovery, instead of relying on a process-local acknowledgement. For example, add a product attribute, fail a TaskManager, then restore both the schema transition and the rows that depend on it.
1. Code changes
1.1 Core logic
Complete runtime path:
Flink starter source -> per-source schema capability/config -> SchemaOperator (1.13 subclass has task-thread stall timer)
-> source DDL queued with following rows -> two fresh completion notifications -> producer#sequence control + dependent rows
-> map/flatMap propagate transformed/no-op controls and dependencies
-> SchemaTableRouter replicates each control to every configured table -> keyBy(tableId)
-> BroadcastSchemaSinkOperator table ValueState/ListState -> contiguous producer progress + FIFO pending rows
-> forward channel -> same sink subtask -> synchronous applySchemaChange -> ordinary writes
Restore/rescale -> atomic source protocol tuple; reset checkpoint fence; keyed table state moves together
-> per-table RestoreTableSchemaEvent before first data -> writer runtime schema rebuilt without physical DDL
Flink 1.15 -> RecoveryAwareSink/SinkV1Adapter -> original global topology/factory decorated
-> restored serialized state / upstream checkpoint lineage marks CommitWrapper -> FlinkGlobalCommitter.restoreCommit
-> fresh traffic remains strict commit; unresolved transactions fail, not acknowledge or busy-loop
Flink 1.20 -> checkpoint-tagged v1 envelope (v0 readable) -> restored boundary classifies recovery vs live requests
Shared CDC enumeration -> getNext creates all incremental splits -> splitAssigned flag snapshot
-> Flink readers keep assigned splits on restore; unassigned generated splits must also survive (Issue 7)
Key findings and correctness:
The ordinary enabled streaming path reaches the new protocol. Routing is per stream, not inferred from an unrelated source; map/flatMap replacement rows preserve dependencies, and filtered DDL still advances its sequence. Table-keyed state fixes the previous owner-independent progress and union-data amplification: table B cannot borrow table A's progress. The gate replays its saved runtime schema before processing a table after restore, stages contiguous controls, and drains rows before applying the next schema. Failures propagate through the writer with their cause.
Direct answers to @SEZ9's latest three questions: (1) requireSchemaChange still stamps every later row after the first DDL; clearRequiredSchemaChange strips the stamp at the sink gate, not permanently at the source. The copy/serialization cost remains intentional. A completed checkpoint is not a universal proof that every unaligned in-flight dependency can be dropped. One owner per physical source table is explicit in both guides, so a single hot table still uses one Flink sink subtask. (2) No pending data row is written to union list state now: pendingRows is keyed ListState, with per-table counters carried in keyed ValueState. Normal admitted snapshots already obey the same table limits and rescale does not concatenate different table keys. This is not an aggregate per-task heap cap. The serialized mock keyed-backend tests cover continuity, but not a real keyed-backend rescale/cap scenario; the native IT has the timing limitation in retained Issue 6. (3) The Flink section is now near Enable schema evolution, scopes replay as at-least-once and states the connector contract in both user and developer guides.
The new 1.15 wrapper delegates the original factory setup, operator ID, state, key context and lifecycle. It marks restored state before the global recovery callback, and classifies upstream replay using the restored checkpoint boundary even when transient flags disappeared in network serialization. A mixed end-of-input aggregate uses the idempotent recovery path; independent fresh aggregates retain strict commit. Identity-based weak tracking avoids conflating equal live and recovered values and avoids keeping every completed aggregate alive. Real original-topology harness tests complement serializer tests. The 1.20 envelope reads original v0 payloads, rejects malformed lengths/versions and tags new writer commits above the restored boundary. Pending aggregate retries now fail the task rather than being reported committed.
The shared CDC splitAssigned change is outside that schema-only graph restriction. It introduces the partial-assignment restore gap in Issue 7. Existing source compatibility serialVersionUID is explicit and unchanged; the new boolean defaults false for older serialized checkpoints, so the finding is lost pending work in newly written state, not an invented Java UID mismatch.
Before:
// Process-local acknowledgement cannot coordinate separate TaskManagers.
coordinator.requestSchemaChange(tableId, eventTime, SCHEMA_CHANGE_TIMEOUT_MS);
// IncrementalPhaseState did not persist splitAssigned.After:
input.flatMap(new SchemaTableRouter(initialSinkTables))
.keyBy(new TableIdKeySelector())
.transform("BroadcastSchemaHandler", TypeInformation.of(SeaTunnelRow.class),
new BroadcastSchemaSinkOperator(initialSinkTables));
// New CDC state, but remainingSplits is absent:
return new IncrementalPhaseState(startupOffset, resolvedStopOffset, splitAssigned);
this.splitAssigned = checkpointState != null && checkpointState.isSplitAssigned();Current CI fact changed: The previous wrapper-429 / SQLServer-timeout report belonged to an older head. Current Build 45104198922, attempt 2, is in progress at 01b99cf. The checked job snapshot has 86 successful, 9 skipped, one running MySQL CDC Java 17 lane and one cancelled LocalFile Java 17 lane; the Java 11 MySQL CDC lane is successful. I also read that lane's log: MysqlCDCWithFlinkSchemaChangeIT reports 16 cases, zero failures/errors/skips, and both named TaskManager-failure and pending-state-rescale methods have successful execution records. That is real current-head CI evidence; it does not make the intended checkpoint cut observable or cover the schema-disabled partial-assignment scenario. Cancelled/skipped is not accepted runtime coverage. The branch is ahead of fetched dev with behind_by=0, so a blanket sync suggestion is unsupported. Source/test blockers remain independently of this improved CI state.
1.2 Compatibility
Incompatible for existing Flink schema-evolution checkpoint/savepoint upgrades: the old local-coordinator and broadcast/union layouts are not migrated. Both migration guides reject allowNonRestoredState shortcuts and prescribe a validated fresh-snapshot cutover with rollback artifacts retained. Incremental parallelism is restricted to one only for enabled Flink schema evolution; single-table sink throughput is limited to one owner, with distinct physical destinations required across source tables. Public option names/defaults are stable. Flink 1.15 keeps committable bytes/operator identity; 1.20 writes an envelope v1 but reads v0. The new shared CDC assigned-state field must not lose pending partitions in otherwise supported non-schema jobs (Issue 7).
1.3 Performance and side effects
The design removes JVM-static coordination state, cleanup thread and cross-task assumptions. Per-row dependency copies/network bytes remain after DDL; keyed gate stripping sometimes avoids a second copy when the dependency is the only option. Control fan-out is O(configured tables), each source table has one sink owner, and hash collisions can leave other writers idle. Pending row/control limits are per table and estimates, so aggregate task/backend memory needs sizing on scale-down. Source flow control suspends availability instead of sleeping on the task thread. Unresolved commits fail for recovery instead of busy-looping or falsely acknowledging; weak identity bookkeeping avoids retaining completed global commits. No performance benchmark or external crash result is inferred from source inspection.
1.4 Errors, logging, and findings
Issue 7: Persist generated but unassigned incremental work before restoring the assigned flag
- Location:
seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/enumerator/IncrementalSplitAssigner.java:133. - Description and risk: New Issue 7, introduced by the shared CDC change in this head: getNext creates the entire incremental split set and sets splitAssigned=true after returning only its first split. snapshotState persists that flag plus offsets, but not remainingSplits. With schema-changes.enabled=false, a Flink CDC job can legitimately use incremental.parallelism=2: reader 0 receives the first of two table partitions, a checkpoint occurs before reader 1 requests its split, and failure restores reader 0's assigned split in reader state. The restored assigner has splitAssigned=true and an empty remainingSplits list, so getNext returns empty and noMoreSplits reports true; reader 1's never-assigned tables stop being captured. FlinkSource.restoreEnumerator/FlinkSourceEnumerator do not return all normally restored reader splits via addSplitsBack; that callback is not a replacement for persisting enumerator-owned pending work. The schema-only incremental.parallelism=1 validation does not protect ordinary CDC jobs.
- Best improvement: Persist remaining incremental splits or equivalent unassigned table/offset metadata together with the flag and distinguish fully distributed from merely generated state. Keep the no-duplicate behavior when readers really hold all assigned splits. Extend the existing assigner/enumerator test with two tables/two splits, checkpoint after only one getNext, restore while that reader keeps its split, and assert the other partition is assigned exactly once. Cover the schema-disabled Flink entry path; do not solve this by imposing an unrelated global parallelism restriction.
- Responsibility and trade-off: This is a long-term alternative Flink coordination model, not a local writer-only fix. Keep protocol correctness in translation/starter boundaries and preserve shared CDC behavior for other modes. Select the architecture against #11912 explicitly rather than merging overlapping assumptions.
- Severity: High; blocking: true.
- Previously raised by another reviewer: No, unless explicitly attributed above.
Issue 4: Document the protocol state and lifecycle boundaries
- Location:
seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/BroadcastSchemaSinkOperator.java:138. - Description and risk: Retained Issue 4 remains: keyed gate applyControl/isReady/drainRows and TableState counters have no local contract comments; SchemaOperator selectProtocolState/restoreAtomicProtocolState and source pendingSchemaCheckpoints/schemaSnapshotId/lastSchemaCheckpointId still lack their ownership/reset invariants. The newly added recovery classifier/tracker also needs a clear initialization/lineage/identity contract at its core methods and nontrivial state fields. Class summaries alone do not explain these boundaries.
- Best improvement: Add concise comments covering task-thread ownership, table/producer scope, contiguous sequence/FIFO ordering, replay-before-first-row, estimated limits, fresh checkpoint reset/release, and restored-only versus live committable classification. Include the new splitAssigned state semantics. This extends the already requested delivery contract to the new recovery code, not a request for a different architecture.
- Responsibility and trade-off: This is a long-term alternative Flink coordination model, not a local writer-only fix. Keep protocol correctness in translation/starter boundaries and preserve shared CDC behavior for other modes. Select the architecture against #11912 explicitly rather than merging overlapping assumptions.
- Severity: Medium; blocking: true.
- Previously raised by another reviewer: No, unless explicitly attributed above.
Issue 5: Give timer and stale-reader regressions observable outcomes
- Location:
seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-13/src/test/java/org/apache/seatunnel/translation/flink/schema/SchemaOperator13Test.java:42. - Description and risk: Retained Issue 5 is unchanged: the timer-registration test invokes a reflected protected method on an operator with no pending DDL/data and ends with registerTimer invocation counts. The stale no-more-element test verifies pollNext on a mock that emits no row. The common base handler test is useful, but does not prove the captured 1.13 callback reaches that behavior or that a reactivated reader delivers data.
- Best improvement: Use a supported subclass seam, feed a pending control/data sequence through the captured callback and assert the defined exactly-once failure or at-least-once output. Have the stale-reader case emit and assert an actual row plus availability/continued activation. Keep interaction assertions as complementary diagnostics.
- Responsibility and trade-off: This is a long-term alternative Flink coordination model, not a local writer-only fix. Keep protocol correctness in translation/starter boundaries and preserve shared CDC behavior for other modes. Select the architecture against #11912 explicitly rather than merging overlapping assumptions.
- Severity: Medium; blocking: true.
- Previously raised by another reviewer: No, unless explicitly attributed above.
Issue 6: Assert the checkpoint cut used by recovery scenarios
- Location:
seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mysql/MysqlCDCWithFlinkSchemaChangeIT.java:218. - Description and risk: Retained Issue 6: starting/registering a standby and stopping the primary is assumed to fit before the next 30-second checkpoint. Under slow scheduling the test can pass after another checkpoint captured applied schema progress, exercising a different cut. The savepoint case observes only a detection log before assuming the pending queue remains in its savepoint.
- Best improvement: Observe completed/in-progress checkpoint IDs or use a controlled checkpoint/DDL hook, and assert the saved failure/savepoint cut before proceeding. Retain exact schema/data comparisons and generous outer deadlines. This is a non-blocking coverage risk, not evidence of production data loss.
- Responsibility and trade-off: This is a long-term alternative Flink coordination model, not a local writer-only fix. Keep protocol correctness in translation/starter boundaries and preserve shared CDC behavior for other modes. Select the architecture against #11912 explicitly rather than merging overlapping assumptions.
- Severity: Medium; blocking: false.
- Previously raised by another reviewer: No, unless explicitly attributed above.
I read @SEZ9's detailed review and latest follow-up; the explicit point-by-point source answers are in 1.1. I agree that hot-table throughput and retained stamp costs need a deliberate maintainer decision, but would not clear dependencies using an unproved checkpoint shortcut. The union-data restore defect is replaced by keyed state, while native rescale/cap coverage remains limited. @dybyte and @CloverDew explicitly agree #11912 and this PR are alternative coordination models, not simply independent writer/coordinator patches. Maintainers should choose the ownership model before merging either architecture. @TyrantLucifer's historical LGTM is now DISMISSED, and latestOpinionatedReviews is empty / REVIEW_REQUIRED on this head; it is not a current approval. The code/test blockers below prevent approval regardless of the earlier favorable intent.
2. Code quality
2.1 Conventions
Reviewed all changed files for license, imports, naming, core-method and state-field comments. See the numbered findings for the required changes.
2.2 Test coverage and stability
Stability rating: At risk. Read all 23 changed Java test files, the XA recovery config/setup grants and the common Flink container changes. Gate tests compare exact control/data order, timestamps, duplicate behavior, table-isolated progress and serialized state. Atomic source tests poison independently redistributed legacy fields and assert the selected producer/queue and next sequence. The real Flink 1.15 topology harness is cloned as for shipping, restores actual operator state, compares committed transaction sets and checks fresh versus recovered traffic, partial end-of-input, unresolved failures and operator IDs with/without local committers. Its class is Isolated and resets the external test-owned ledger. The newer 1.20 tests validate envelope compatibility and callback classification; they do not establish external XA crash durability. Native MySQL tests compare schema and data after TaskManager failure/rescale and use JDBC XA. REST requests now have bounded connect/request timeouts, dynamic mapped host ports and explicit failure causes; additional TaskManagers are owned and stopped. LocalFile acceptance now checks actual committed binary equality and nonempty output per table, not just job exit. Retained Issue 5 still applies to the unchanged timer registration and stale-reader acceptance cases. Retained Issue 6 is a timing-dependent coverage risk; no high-risk new fixed-sleep success oracle was found. A 200 ms sleep inside bounded savepoint-condition polling is not a fixed sleep used as proof of success. No local runtime was executed.
2.3 Documentation
The six changed EN/ZH developer, schema-evolution and migration sections agree on ownership, control fan-out, per-table estimated limits, at-least-once DDL, synchronous connector failure propagation, runtime-only RestoreTableSchemaEvent and the fact that XA prepare is not commit. Physical DDL convergence and internal replica synchronization remain connector responsibilities; neither checkpoint completion count nor this translation layer universally proves external commit. The older SchemaOperator checkpoint-completion Javadoc still calls the XA fence guaranteed; correct that local explanation as part of retained Issue 4 so it matches the narrower documented contract. No blind reuse of an old savepoint or shared physical target is recommended.
3. Architecture
3.1 Change location
This is a long-term alternative Flink coordination model, not a local writer-only fix. Keep protocol correctness in translation/starter boundaries and preserve shared CDC behavior for other modes. Select the architecture against #11912 explicitly rather than merging overlapping assumptions.
3.2 Maintainability
Keep the behavior, lifecycle ownership, and failure contract together. This is a long-term alternative Flink coordination model, not a local writer-only fix. Keep protocol correctness in translation/starter boundaries and preserve shared CDC behavior for other modes. Select the architecture against #11912 explicitly rather than merging overlapping assumptions.
3.3 Extensibility
Prefer the existing component boundary and tests over unrelated shared abstractions.
3.4 Upgrade impact
Incompatible for existing Flink schema-evolution checkpoint/savepoint upgrades: the old local-coordinator and broadcast/union layouts are not migrated. Both migration guides reject allowNonRestoredState shortcuts and prescribe a validated fresh-snapshot cutover with rollback artifacts retained. Incremental parallelism is restricted to one only for enabled Flink schema evolution; single-table sink throughput is limited to one owner, with distinct physical destinations required across source tables. Public option names/defaults are stable. Flink 1.15 keeps committable bytes/operator identity; 1.20 writes an envelope v1 but reads v0. The new shared CDC assigned-state field must not lose pending partitions in otherwise supported non-schema jobs (Issue 7).
4. Findings summary
Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.
| # | Finding | Location | Severity |
|---|---|---|---|
| 7 | Persist generated but unassigned incremental work before restoring the assigned flag | seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/enumerator/IncrementalSplitAssigner.java:133 |
High |
| 4 | Document the protocol state and lifecycle boundaries | seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/schema/BroadcastSchemaSinkOperator.java:138 |
Medium |
| 5 | Give timer and stale-reader regressions observable outcomes | seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-13/src/test/java/org/apache/seatunnel/translation/flink/schema/SchemaOperator13Test.java:42 |
Medium |
| 6 | Assert the checkpoint cut used by recovery scenarios | seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mysql/MysqlCDCWithFlinkSchemaChangeIT.java:218 |
Medium |
5. Merge recommendation
Merge after fixes
Blocking items: Issues 7, 4, 5. Current-head CI and write-capable maintainer review remain independent requirements.
Non-blocking suggestions: Issue 6: Assert the checkpoint cut used by recovery scenarios
Overall: the approach addresses a real path, but the listed blockers must be closed. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.
CI and repository state: no check reported in the Apache rollup; Build: in_progress. GitHub reports BLOCKED / REVIEW_REQUIRED.
Verification: Reviewed all changed files and the referenced call sites at 01b99cf347660bdcb9d9b73e7e5b7d039b3e1b03 against merge base a76348f1f98953444fd030fbbc56209d8ad40d18. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.
Review time: 2026-11-23T09:02:20.970860-05:00
Local evidence: git fetch obtained head 01b99cf347660bdcb9d9b73e7e5b7d039b3e1b03; git merge-base returned a76348f1f98953444fd030fbbc56209d8ad40d18; git diff --stat reports 67 files changed, 5422 insertions(+), 1162 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.
|
I confirmed a CDC split recovery regression introduced by #11960. It affects the shared CDC enumerator, including jobs that run with Flink schema evolution disabled.
I verified two recovery cases against merge commit
The Flink test used synthetic CDC records. The Zeta test used the production enumerator, reader, and checkpoint classes with a mocked Hazelcast transport. Both tests deliberately controlled the timing, so they establish reachability. Production frequency is unknown. I also checked the I think this warrants a fix before the next release containing #11960. The regression tests should take a checkpoint at each of the two points above, restore it, and verify that each captured table has exactly one active incremental reader and that a new record from each table reaches the sink exactly once. Persisting only Split generation and assignment · Checkpoint contents · Enumerator-to-reader handoff |
Purpose of this pull request
Close: #11958
This PR replaces the process-local Flink schema coordinator and its coordinator protocol with a checkpointed data-plane schema-evolution protocol.
The new protocol keeps schema controls and dependent data consistently ordered without introducing a custom OperatorCoordinator:
The translation layer guarantees ordering, dependency gating, checkpoint state, and replay; Database DDL is delivered at least once relative to Flink checkpoints, Connectors remain responsible for making applySchemaChange synchronous and observable, propagating failures, and converging repeated DDL execution to the requested target schema.
Does this PR introduce any user-facing change?
Yes.
Previously, Flink CDC schema evolution relied on a process-local coordinator and did not provide sufficient distributed recovery evidence for the physical DDL/checkpoint failure window.
After this change:
How was this patch tested?
Please Refer: MysqlCDCWithFlinkSchemaChangeIT
Check list
New License Guide
incompatible-changes.mdto describe the incompatibility caused by this PR.