Repository navigation
[Fix][Connector-V2] Fix MySQL CDC snapshot split error with non-consecutive primary key IDs - #12463
Conversation
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
One or more issues must be addressed before approval.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 1
Open (4)
What changed in this PR
Improves CDC snapshot chunking for sparse numeric primary keys by preferring sampling-based splits.
Changes:
- Added sampling selection when distribution factors exceed 1.0.
- Added unit coverage for chunking helpers and sparse-ID scenarios.
| File | Description |
|---|---|
| seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/test/java/org/apache/seatunnel/connectors/cdc/base/source/enumerator/splitter/AbstractJdbcSourceChunkSplitterTest.java | Updated as part of this pull request. |
| seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/enumerator/splitter/AbstractJdbcSourceChunkSplitter.java | Updated as part of this pull request. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for working on this! I went through the full diff, traced the new decision logic against the real call chain, and also re-ran the actual fork CI logs. The approach (prefer sampling over arithmetic stepping when the PK distribution has gaps) is the right direction, and I can see you already addressed all four of Copilot's review comments in your latest commit (26fb2cb, "Fix Copilot review feedback"). However, I found a CI-confirmed test failure and a scoping gap in the fix itself that need to be resolved before this can merge — details below.
What Problem Does This PR Solve?
During MySQL CDC full-snapshot (startup.mode = "initial"), AbstractJdbcSourceChunkSplitter.splitTableIntoChunks() picks "evenly-sized" arithmetic chunking (splitEvenlySizedChunks) whenever distributionFactor = (MAX-MIN+1)/rowCount falls in [distributionFactorLower, distributionFactorUpper] (default [0.05, 100.0]). Arithmetic stepping assumes the gaps in the PK space are uniformly spread; when they are clustered (e.g. a large deleted-ID range), some chunks end up empty and others end up with far more than chunkSize rows, and the reader task for an overloaded chunk can blow the checkpoint timeout (CheckpointException: Checkpoint expired before completing, matching #10270). The PR's fix: when distributionFactor > 1.0 (gaps mathematically exist), prefer sampling-based boundary selection (efficientShardingThroughSampling) instead of pure arithmetic stepping, since sampling reflects the real data distribution.
Before/After Example
Table with PK id values 1..100 plus a second dense cluster 1,000,000..1,000,100 (201 total rows, chunkSize small enough that this is "evenly distributed" per the bounds). distributionFactor ≈ 1,000,100/201 ≈ 4975 — actually this would exceed the default upper bound of 100 and fall to the "uneven" branch already handled pre-PR. A more realistic example within bounds: 100,000 rows uniformly distributed 1..5,000,000 except with a dense hot cluster of 20,000 rows packed into ids 1..50,000 (distributionFactor ≈ 50, inside [0.05,100]). Before: splitEvenlySizedChunks steps by a fixed dynamicChunkSize ≈ distributionFactor * chunkSize, so the arithmetic window covering 1..50,000 captures far more than chunkSize rows in one chunk while windows covering the sparse tail get almost nothing — one reader task ends up scanning tens of thousands of extra rows and can exceed the checkpoint timeout. After (intended): sampling picks boundaries from real data points, so the dense cluster gets subdivided into multiple balanced chunks. After (actual, see Issue 1 below): for this table (shardCount = ceil(100000/8096) ≈ 13), the new branch is gated by sampleShardingThreshold (default 1000) < shardCount (13) → false, so it silently falls through to the exact same unchanged arithmetic path as before the PR. The fix does not fire for this table.
1. Code Change Review
1.1 Core Logic Analysis
seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/enumerator/splitter/AbstractJdbcSourceChunkSplitter.java
Before (dataIsEvenlyDistributed branch, simplified):
if (dataIsEvenlyDistributed) {
final int dynamicChunkSize = Math.max((int) (distributionFactor * chunkSize), 1);
return splitEvenlySizedChunks(tableId, min, max, approximateRowCnt, chunkSize, dynamicChunkSize);
}After (lines 175-225):
if (dataIsEvenlyDistributed) {
int shardCount = (int) Math.ceil((double) approximateRowCnt / chunkSize);
if (doubleCompare(distributionFactor, 1.0d) > 0
&& sampleShardingAllow
&& sampleShardingThreshold < shardCount) { // <-- gate, see Issue 1
...
Object[] sample = sampleDataFromColumn(jdbc, tableId, splitColumn, inverseSamplingRate);
if (sample.length >= shardCount) {
return efficientShardingThroughSampling(tableId, sample, approximateRowCnt, shardCount);
}
return splitUnevenlySizedChunks(jdbc, tableId, splitColumn, min, max, chunkSize);
}
final int dynamicChunkSize = Math.max((int) (distributionFactor * chunkSize), 1);
return splitEvenlySizedChunks(tableId, min, max, approximateRowCnt, chunkSize, dynamicChunkSize);
}Runtime path: SnapshotSplitAssigner.getNext() (SnapshotSplitAssigner.java:185) calls chunkSplitter.generateSplits(nextTable) exactly once per table, only for tables not yet in alreadyProcessedTables — and alreadyProcessedTables is part of the checkpointed SnapshotPhaseState (SnapshotSplitAssigner.java:247-250). So this is a normal-path change for any new table being split (not a boundary/recovery path), but it never re-runs for a table whose splits were already generated and persisted before a restart — good for restore compatibility (see 1.2).
Key findings:
- Issue 1 (High, CI-confirmed) — the new regression test throws
NullPointerExceptionin the actual fork CI on all 4 unit-test matrix jobs (JDK 8/11 × ubuntu/windows). See section 2.2 for full detail; this alone blocks merge. - Issue 2 (High) — the new sampling branch is gated by
sampleShardingThreshold < shardCount.sampleShardingThresholddefaults to1000(JdbcSourceOptions.SAMPLE_SHARDING_THRESHOLD,sample-sharding.threshold), andchunkSizedefaults to8096(SourceOptions.SNAPSHOT_SPLIT_SIZE). That means, under default configuration, the new sampling path only activates for tables with more than ~8.1 million rows (1000 * 8096). Issue #10270 does not describe a table anywhere near that size, and "large ranges of deleted rows" is a common pattern on tables well under 8M rows. For any such table withdistributionFactorin(1.0, 100.0]andapproximateRowCntbelow ~8.1M, control falls straight through to the unchangedsplitEvenlySizedChunksarithmetic path — i.e. the exact bug this PR claims to fix is still present for the majority of realistically-sized affected tables. This isn't a hypothetical: the PR's own new test (testSplitTableIntoChunksDecisionLogic) only exercises the sampling branch because it explicitly overridesgetSampleShardingThreshold()to return2— a value nobody would see in production.- Root cause context:
sampleShardingThresholdwas designed as a "large-N optimization" trigger for the pre-existing uneven-distribution branch (skip an expensive sampling scan on small tables where sampling doesn't pay for itself). Reusing the same knob, with the same default, to gate a correctness fix for a different problem (gap-clustering skew, independent of table size) conflates two different concerns and inherits a default that's wrong for this new use case. - Best improvement: Option A — introduce a separate, much lower threshold (or reuse
sampleShardingThresholdbut only as an anti-DoS ceiling on very small tables, e.g. skip sampling only whenshardCount <= 1) specifically for the gap-triggered sampling path, so it engages wheneverdistributionFactor > 1.0and there's more than one shard. Option B — if the existing threshold is kept for consistency, this must be called out explicitly in the PR description / doc as a known limitation ("only fixes tables large enough to need sample sharding already"), and the issue-linked bug report should be re-verified against the actual row count that triggered it. - Raised by another reviewer: No.
- Root cause context:
- Issue 3 (Medium, resolved — crediting Copilot) — Copilot's finding "Sampling bypasses threshold and adds an unbounded full-table scan" (
discussion_r4090951794) is now fixed by thesampleShardingThreshold < shardCountgate added in commit26fb2cb. I verifiedMySqlUtils.sampleDataFromColumn(connector-cdc-mysql/.../MySqlUtils.java:118-137) does runSELECT <col> FROM <table> WHERE MOD((<col> - MIN(<col>)),N)=0, which is not sargable and is effectively a full-table scan — so gating it behind a real threshold (rather than unconditionally ondistributionFactor > 1.0) is the correct call. +1 to Copilot's point, and confirmed fixed as of the latest commit. - Issue 4 (Low, resolved — crediting Copilot) — Copilot's "Flooring shard count leaves slightly oversized tables unsplit" (
discussion_r4090951770) is fixed by switching(int) (approximateRowCnt / chunkSize)to(int) Math.ceil(...)at both call sites (lines 183 and 227). Note this also changes the pre-existing "not evenly distributed" branch's shard-count calculation (line 227), which is a small, strictly-more-correct behavior change beyond the PR's stated scope — worth a one-line mention in the PR description, but not a concern on its own (monotonic fix, no new risk). - Issue 5 (Medium, mitigated but worth noting — Copilot's point) — Copilot's "Sparse-key sampling can undersplit tables" (
discussion_r4090951725) is now guarded by thesample.length >= shardCountcheck with a fallback tosplitUnevenlySizedChunks, so an under-populated sample no longer silently produces one giant chunk — it falls back instead. +1 to Copilot's underlying concern thatMOD((id-MIN),N)=0sampling is inherently unreliable for very sparse/clustered keys; the fallback bounds the damage but the sampling quality issue is structural to the sampling strategy itself (pre-existing in the "uneven" branch too, not newly introduced here), so I'd call this "mitigated," not "resolved."
1.2 Compatibility Impact
Fully compatible. No config option added/renamed/removed, no default value changed, no wire/serialization format touched. SnapshotPhaseState (which persists alreadyProcessedTables/remainingSplits) is untouched, and generateSplits() is only invoked for tables not yet processed (verified above), so jobs resuming from an existing checkpoint mid-snapshot are unaffected — only tables whose snapshot split generation hasn't happened yet will see the new logic. No entry needed in docs/en/introduction/concepts/incompatible-changes.md.
1.3 Performance / Side-Effect Analysis
When the new branch does fire (tables > ~8.1M rows by default, per Issue 2), it adds one extra full-table-scan-equivalent query (sampleDataFromColumn) during snapshot planning, before any data is read. This mirrors the cost already paid by the pre-existing "uneven distribution" sampling path, so it's not a new class of risk, just a wider trigger surface for an already-accepted cost/benefit tradeoff. No new retries, no new locks, no change to reader-side concurrency or resource cleanup.
1.4 Error Handling and Logging
sampleDataFromColumn declares throws Exception and is not swallowed; failures propagate normally. Log statements (info/warn) are appropriately leveled, include table/factor/sample-size context, and don't leak credentials. No issues here.
2. Code Quality Assessment
2.1 Coding Standards
The new branch has a clear explanatory comment (lines 176-182) describing the "why" (arithmetic assumes uniform gaps; sampling doesn't). Good. One Low item: seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/test/java/org/apache/seatunnel/connectors/cdc/base/source/enumerator/splitter/AbstractJdbcSourceChunkSplitterTest.java:164-338 uses Method.setAccessible(true) + reflection to invoke the private splitTableIntoChunks. It's not wrong per se (and it's what actually let the test attempt to exercise the real decision path, addressing Copilot's finding #4 in intent), but it's brittle against future renames/signature changes and obscures compile-time safety — as this very PR demonstrates (see Issue 1). A package-private test-only entry point, or promoting splitTableIntoChunks to package-private with a comment, would be more maintainable. Not a blocker.
Also Low: testSingleSplitWhenConcurrentReadDisabled and testEnableConcurrentReadOptionDefaultIsTrue (lines 426-451) test the pre-existing enableConcurrentRead short-circuit path, which this PR does not touch. This is out-of-scope test addition (harmless, adds coverage, but doesn't belong to "one PR solves one problem" per this repo's own CLAUDE.md PR Scope Rule). Consider splitting into a separate PR or dropping if unrelated to #10270.
2.2 Test Coverage and Test Stability — High risk
This is the primary blocker. I pulled the actual CI logs from the fork run (sun-9545sunoj/seatunnel run 35971339514, triggered by this PR's head 26fb2cb):
[ERROR] Tests run: 4, Failures: 0, Errors: 1, Skipped: 0 ... <<< FAILURE! - in AbstractJdbcSourceChunkSplitterTest
[ERROR] testSplitTableIntoChunksDecisionLogic Time elapsed: 0.011 s <<< ERROR!
java.lang.NullPointerException
at AbstractJdbcSourceChunkSplitterTest.testSplitTableIntoChunksDecisionLogic(AbstractJdbcSourceChunkSplitterTest.java:265)
This fails identically and deterministically on all four unit-test matrix jobs (JDK 8 ubuntu, JDK 11 ubuntu, JDK 8 windows, JDK 11 windows) — not an environmental flake.
Root cause: AbstractJdbcSourceChunkSplitterTest.java:265 calls splitMethod.invoke(splitterSuccess, null, tableId, null) — passing null for the Column splitColumn parameter. But production code (AbstractJdbcSourceChunkSplitter.java:137) does final String splitColumnName = splitColumn.name(); as the very first statement inside splitTableIntoChunks, before any of the test's overridden methods (queryMinMax, sampleDataFromColumn, etc.) are even reached. So the test throws NPE immediately and never actually reaches the sampling-vs-arithmetic decision it was written to verify — meaning Copilot's original finding #4 ("test bypasses split decision logic") is, in effect, still true: the intended regression coverage doesn't run.
The PR description states "Ran mvn spotless:apply and mvn -q -DskipTests verify" (note -DskipTests, so unit tests were never executed) and separately claims "All tests in AbstractJdbcSourceChunkSplitterTest passed locally" — this claim is directly contradicted by the CI evidence above.
Best improvement: construct a real Column via the existing pattern already used elsewhere in this module (Column.editor().name("id")....create(), see jdbc/source/JdbcSourceChunkSplitterTest.java:222-247 for the exact idiom) and pass that instead of null at line 265 (and the second invocation later in the same test). After that fix, please actually run mvn test -pl seatunnel-connectors-v2/connector-cdc/connector-cdc-base -am locally (not with -DskipTests) and confirm green before pushing.
Once that's fixed, the test's intent (verifying the sampling path is chosen vs. the fallback path) is sound and does cover the real decision path via the private method — I'd rate it "Stable" at that point, modulo the reflection-brittleness note in 2.1.
2.3 Documentation Updates
Not required — no user-facing config, default, or protocol changed. The PR description explicitly and correctly states "No" for user-facing changes.
3. Architectural Soundness
3.1 The fix is layered correctly: it only changes chunk-boundary selection within AbstractJdbcSourceChunkSplitter, reusing the existing sampleDataFromColumn/efficientShardingThroughSampling/splitUnevenlySizedChunks primitives rather than introducing new per-dialect code. Good reuse of existing infrastructure, no leakage of MySQL-specific logic into the shared base class.
3.2 The gating condition (Issue 2) is the one architectural concern: conflating "large-table sampling optimization" and "gap-skew correctness fix" under a single existing threshold with a large default is a design smell that undermines the PR's stated goal for the common case.
3.3 No SPI/registration surface touched (no new connector, no plugin-mapping/dist changes needed) — correctly scoped to the shared CDC base splitter only.
3.4 Section 11 (SupportMultiTableSinkWriter checklist) is not applicable — this PR only touches source-side snapshot splitting.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | New regression test throws NPE in CI (all 4 unit-test jobs); never exercises the intended decision path | AbstractJdbcSourceChunkSplitterTest.java:265 (root cause: AbstractJdbcSourceChunkSplitter.java:137) |
High (CI-confirmed) |
| 2 | Sampling fix gated behind sampleShardingThreshold (default 1000 shards ⇒ ~8.1M rows), so the fix doesn't fire for realistically-sized tables from #10270 |
AbstractJdbcSourceChunkSplitter.java:183-186 |
High |
| 3 | Full-table-scan-cost concern (Copilot) — resolved via threshold gate | AbstractJdbcSourceChunkSplitter.java:183-186 |
Medium (resolved) |
| 4 | Floored shard count under-splits (Copilot) — resolved via Math.ceil |
AbstractJdbcSourceChunkSplitter.java:183, 227 |
Medium (resolved) |
| 5 | Under-populated sample can still under-split for very sparse keys (Copilot) — mitigated via fallback, not eliminated | AbstractJdbcSourceChunkSplitter.java:208-220 |
Medium (mitigated) |
| 6 | Reflection-based private-method test is brittle | AbstractJdbcSourceChunkSplitterTest.java:194-197 |
Low |
| 7 | Unrelated test additions (enableConcurrentRead coverage) out of PR scope |
AbstractJdbcSourceChunkSplitterTest.java:426-451 |
Low |
5. Merge Recommendation
Not recommended for merge (yet).
Blockers:
- Issue 1 — fix the NPE in
testSplitTableIntoChunksDecisionLogic(pass a realColumn, notnull) and confirm CI is green on all matrix jobs, not just locally. - Issue 2 — either lower/separate the gating threshold so the fix actually engages for the table sizes implicated by #10270, or explicitly scope down the PR description to state this only helps very large tables, and re-confirm the linked issue's table size against that scope.
Recommended fixes (non-blocking): Issues 6 and 7 above.
Overall assessment: The direction (prefer sampling for gap-skewed keys) is sound and the author has already engaged constructively with Copilot's automated review, fixing 3 of its 4 findings correctly. But the fix as currently gated likely won't resolve the reported bug for typical table sizes, and the safety-net test meant to lock in this behavior is currently red in CI. Once the NPE is fixed and the threshold gating is revisited (or explicitly scoped), I'd be happy to re-review.
|
Thanks so much for the incredibly detailed and thorough review! I really appreciate you catching that scoping gap with the threshold and the NPE in the CI logs. I've just pushed a new commit that addresses all of your feedback:
I've verified the tests locally and the CI should hopefully be completely green on this run. Thanks again for the guidance—let me know if you spot anything else! |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the fast turnaround, and sorry for the delay getting back to this! I re-pulled the full diff at the current head, re-ran the actual fork CI logs (not just the commit messages), and re-verified every point from my last review one by one. Good news up front: both High-severity blockers from round 1 are genuinely fixed, not just claimed-fixed — I confirmed the regression test now passes in CI and traced the new gating condition end-to-end. I also owe you one correction on my own prior review (Issue 7 below) and a small apology for a style nit I should have caught the first time (Issue 8). Details follow.
What Problem Does This PR Solve?
During MySQL CDC full-snapshot (startup.mode = "initial"), AbstractJdbcSourceChunkSplitter.splitTableIntoChunks() picks "evenly-sized" arithmetic chunking whenever distributionFactor = (MAX-MIN+1)/rowCount falls in [distributionFactorLower, distributionFactorUpper] (default [0.05, 100.0]). Arithmetic stepping assumes PK gaps are uniformly spread; when gaps are clustered (e.g. a large deleted-ID range), some chunks end up empty and others end up with far more than chunkSize rows, and the reader task for an overloaded chunk can blow the checkpoint timeout (CheckpointException: Checkpoint expired before completing, matching #10270). This PR's fix: whenever distributionFactor > 1.0 (a gap mathematically exists) and there is more than one shard to produce, prefer sampling-based boundary selection over pure arithmetic stepping, since sampling reflects the real data distribution instead of assuming uniformity.
1. Code Change Review
1.1 Core Logic Analysis
seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/enumerator/splitter/AbstractJdbcSourceChunkSplitter.java
What changed since my last review (commit 26fb2cb → current head 16dbf2c), scoped to the PR's own two files:
Before (26fb2cb, my last-reviewed commit):
private List<ChunkRange> splitTableIntoChunks(
JdbcConnection jdbc, TableId tableId, Column splitColumn) throws Exception {
...
int shardCount = (int) Math.ceil((double) approximateRowCnt / chunkSize);
if (doubleCompare(distributionFactor, 1.0d) > 0
&& sampleShardingAllow
&& sampleShardingThreshold < shardCount) { // gated behind 1000-shard thresholdAfter (current head, AbstractJdbcSourceChunkSplitter.java:135-136, 183-186):
protected List<ChunkRange> splitTableIntoChunks(
JdbcConnection jdbc, TableId tableId, Column splitColumn) throws Exception {
...
int shardCount = (int) Math.ceil((double) approximateRowCnt / chunkSize);
if (doubleCompare(distributionFactor, 1.0d) > 0
&& sampleShardingAllow
&& shardCount > 1) { // gate now just "more than one shard"Two independent changes landed in this round:
splitTableIntoChunkswent fromprivatetoprotected(AbstractJdbcSourceChunkSplitter.java:135), so the test can call it directly instead of using reflection.- The sampling gate's condition changed from
sampleShardingThreshold < shardCounttoshardCount > 1(AbstractJdbcSourceChunkSplitter.java:186) — this is exactly "Option A" I proposed last round.
On the test side, AbstractJdbcSourceChunkSplitterTest.java (testSplitTableIntoChunksDecisionLogic, lines 164-340) now builds a real Column (AbstractJdbcSourceChunkSplitterTest.java:194-195, io.debezium.relational.Column.editor().name("id").create()) and calls splitterSuccess.splitTableIntoChunks(null, tableId, splitColumn) directly (line 265) instead of splitMethod.invoke(splitterSuccess, null, tableId, null). The overridden queryMinMax/isEvenlySplitColumn/splitUnevenlySizedChunks signatures were updated to match the real Column parameter type (lines 207, 212, 247, 283, 288, 323).
Runtime path (unchanged since last round, re-verified): SnapshotSplitAssigner.getNext() (SnapshotSplitAssigner.java:185) calls chunkSplitter.generateSplits(nextTable) exactly once per table, only for tables not yet in alreadyProcessedTables (added at line 187), and alreadyProcessedTables is part of the checkpointed SnapshotPhaseState (SnapshotSplitAssigner.java:247-250). So this remains a normal-path change for any table not yet split, and it never re-fires for a table whose splits were already persisted before a restart.
Key findings:
- Issue 1 (was High, now RESOLVED, CI-confirmed) — I pulled the actual fork CI logs for the current head (
sun-9545sunoj/seatunnelrun36177586378, jobunit-test (8, windows-latest)):Tests run: 4, Failures: 0, Errors: 0, Skipped: 0 ... in org.apache.seatunnel.connectors.cdc.base.source.enumerator.splitter.AbstractJdbcSourceChunkSplitterTest. The NPE is gone and the test genuinely exercises the decision logic now (verified by reading the full method body, not just the diff hunk — the test's overriddensampleDataFromColumn/splitEvenlySizedChunks/splitUnevenlySizedChunks/efficientShardingThroughSamplingall get correctly exercised via boolean flags,AbstractJdbcSourceChunkSplitterTest.java:197-199, 227, 251, 261, 267-271, 334-339). - Issue 2 (was High, now RESOLVED) — the gate is now
shardCount > 1instead ofsampleShardingThreshold < shardCount. WithchunkSizedefaulting to 8096 (SourceOptions.SNAPSHOT_SPLIT_SIZE), that means any table with more than ~8096 rows anddistributionFactorin(1.0, 100.0]now takes the sampling path — not just tables above ~8.1M rows as before. This is a real fix for the table sizes implicated by #10270; I traced it directly, it isn't just claimed in the PR description. - Issue 9 (NEW, Medium, non-blocking, see 1.3) — fixing Issue 2 has a side effect: it also reopens (in a bounded, intentional way) part of Copilot's original "unbounded full-table scan" concern, because the non-sargable
sampleDataFromColumnquery now runs for a much larger population of tables (any table >8096 rows with any PK gap, not just severely-skewed multi-million-row tables). See 1.3 for why I don't consider this a blocker. - Issue 6 (was Low, now RESOLVED) — the reflection-based private-method invocation is gone;
splitTableIntoChunksisprotectedand called directly. This is strictly more maintainable and removes the exact brittleness that caused Issue 1 in the first place. - Issue 7 (RETRACTED — my mistake, not yours) — in my last review I flagged
testSingleSplitWhenConcurrentReadDisabled/testEnableConcurrentReadOptionDefaultIsTrue(AbstractJdbcSourceChunkSplitterTest.java:429, 451) as "unrelated test additions... out of PR scope." I re-diffed against the actual pre-PR base (devat merge-base7067a098) and those two tests already exist there at lines 245/267, byte-for-byte — they predate this PR entirely and this PR never touches them. Your reply comment ("the enableConcurrentRead tests were pre-existing... I've left them as is") was correct and I was wrong to raise it as a scope concern. Sorry for the noise — no action needed on your side. - Issue 3/4/5 (Copilot's findings, status unchanged from last round) — Issue 3 (full-scan cost) is now partially reopened per Issue 9 above rather than fully "resolved." Issue 4 (
Math.ceilon shard count,AbstractJdbcSourceChunkSplitter.java:183, 227) remains fixed. Issue 5 (sparse-sample fallback tosplitUnevenlySizedChunkswhensample.length < shardCount,AbstractJdbcSourceChunkSplitter.java:208-220) is unchanged and still just "mitigated," not eliminated — this is pre-existing sampling-strategy behavior shared with the "uneven" branch, not something this PR needs to solve.
In-depth correctness analysis: For a table with approximateRowCnt > chunkSize (default 8096) and distributionFactor in (1.0, 100.0], the new branch always attempts sampling now. If sample.length >= shardCount, efficientShardingThroughSampling produces balanced boundaries from real data points — this is the fix working as intended, and it now actually engages for realistically-sized tables (not just >8.1M-row ones). If sampling under-returns (very sparse/clustered keys defeating the MOD(...)=0 sampler), it falls back to splitUnevenlySizedChunks, which queries exact boundaries — slower but correct. The only path where the pre-PR bug can still occur is distributionFactor outside (0.05, 100.0] entirely (already routed to the "uneven" branch pre-PR, unaffected by this diff) or shardCount <= 1 (a single-chunk table, where "balance" is moot anyway). I don't see a remaining scenario matching #10270 where the bug persists.
Runtime path (unchanged shape, re-verified):
SnapshotSplitAssigner.getNext() [SnapshotSplitAssigner.java:185]
-> chunkSplitter.generateSplits(nextTable) [only for tables not in alreadyProcessedTables]
-> splitTableIntoChunks(jdbc, tableId, splitColumn) [AbstractJdbcSourceChunkSplitter.java:135-225]
-> dataIsEvenlyDistributed && distributionFactor > 1.0 && shardCount > 1
-> sampleDataFromColumn(...) [MySqlUtils.java:118-140, non-sargable MOD() scan]
-> sample.length >= shardCount
-> efficientShardingThroughSampling(...) [balanced split from real data points]
else
-> splitUnevenlySizedChunks(...) [exact-boundary fallback]
-> alreadyProcessedTables.add(nextTable) [SnapshotSplitAssigner.java:187]
-> persisted in SnapshotPhaseState [SnapshotSplitAssigner.java:247-250]
1.2 Compatibility Impact
Fully compatible. No config option added, renamed, or removed; no default value changed (the widened trigger is a code-level gating change, not a config default); no wire/serialization format touched. SnapshotPhaseState (which persists alreadyProcessedTables/remainingSplits) is untouched, and generateSplits() is only invoked for tables not yet processed — jobs resuming from an existing checkpoint mid-snapshot are unaffected; only tables whose snapshot split generation hasn't happened yet see the new logic. splitTableIntoChunks going from private to protected is an internal visibility widening with no external callers (git grep confirms it's referenced only inside this class and its own test) — not an API break. No entry needed in docs/en/introduction/concepts/incompatible-changes.md.
1.3 Performance / Side-Effect Analysis
This is where the round-2 diff introduces a real, worth-naming trade-off. MySqlUtils.sampleDataFromColumn (MySqlUtils.java:118-140) runs:
SELECT id FROM tbl WHERE MOD((id - (SELECT MIN(id) FROM tbl)), N) = 0 ORDER BY idThis is not sargable (can't use an index range scan on the MOD(...) predicate) and is effectively a full-table scan plus a filesort. Before this round's fix, that cost was only paid for tables with shardCount > sampleShardingThreshold (default 1000 shards, i.e. ~8.1M+ rows) — Copilot's "unbounded full-table scan" concern was bounded by that threshold, and I credited that fix in my last review. Now that the gate is shardCount > 1, this query runs for any table over ~8096 rows with distributionFactor > 1.0 — which in practice is nearly every MySQL table using AUTO_INCREMENT that has ever had a single deleted or rolled-back-insert row, since that alone makes distributionFactor slightly greater than 1.0. That's a much larger population of snapshot jobs paying one extra full-scan-equivalent query during split planning than before this PR existed at all (not just before this round — before the whole PR).
I don't consider this a blocker, for three reasons: (a) it's a one-time cost during snapshot planning per table, not a recurring or per-row cost, and doesn't affect steady-state reader throughput or resource cleanup; (b) it's the direct, foreseeable consequence of the exact fix I recommended last round ("Option A: skip sampling only when shardCount <= 1"); and (c) the alternative (keeping the high threshold) is the bug this PR exists to fix. But it should be named explicitly rather than silently accepted — Issue 9 (Medium, non-blocking): consider a one-line callout in the PR description that this trades "unconditionally correct splitting" for "an extra full-table sampling query on any table with >1 shard and any PK gap," so future maintainers tuning sample-sharding.threshold understand it no longer bounds this code path. No code change requested.
1.4 Error Handling and Logging
Unchanged from last round and still fine: sampleDataFromColumn declares throws Exception, not swallowed; the log.warn for inverseSamplingRate > chunkSize (AbstractJdbcSourceChunkSplitter.java:189-193) and for insufficient sample size (AbstractJdbcSourceChunkSplitter.java:212-218) are correctly leveled with table/factor/sample-size context, and no credentials or row data are logged.
2. Code Quality Assessment
2.1 Coding Standards
The new branch's explanatory comment (AbstractJdbcSourceChunkSplitter.java:176-182) is clear about the "why." One finding on the test file:
Issue 8 (Low, non-blocking, partly a carryover I should have caught last round) — AbstractJdbcSourceChunkSplitterTest.java already imports Column (line 29), assertTrue/assertEquals/assertNull statically (lines 40-42), yet the new/modified test method uses fully-qualified names for all of them instead: io.debezium.relational.Column (lines 194-195, 207, 212, 247, 283, 288, 323 — new in this round, part of the NPE fix), and java.util.Collections.emptyList() / org.junit.jupiter.api.Assertions.assertTrue|assertFalse (lines 240, 252, 261, 266, 268, 270, 316, 328, 333, 335, 337 — present since 26fb2cb, i.e. I should have flagged this last round and didn't; sorry for missing it). It's harmless and compiles fine, just inconsistent with the rest of the same file, which uses the short names throughout. A one-pass cleanup to use the already-imported Column, the static assertTrue/assertFalse (add assertFalse to the static-import block), and Collections.emptyList() (already imported at the top of the file for other tests) would tidy this up. Not worth blocking on.
2.2 Test Coverage and Test Stability — Stable
testSplitTableIntoChunksDecisionLogic now genuinely exercises the real decision path (confirmed passing in fork CI, see Issue 1). I checked for the standard flaky-test patterns: no hard sleeps, no timing assumptions, no shared static state between the two sub-scenarios (samplingCalled/unevenlyCalled/evenlyCalled are local arrays reset between the two invocations at lines 273-275), no order dependence, no floating-point comparisons without delta, deterministic mocked return values throughout. I rate this Stable.
Separately: the currently-red fork CI run (36177586378) for this exact head has 5 failing jobs. I read the actual logs, not just the job names:
unit-test (8, windows-latest): real failure isTaskExecutionServiceTest.testStaleTaskDoneCleansOnlyOwnedGenerationResourcesinseatunnel-engine-server— this module has nothing to do withconnector-cdc-base, andAbstractJdbcSourceChunkSplitterTestin the same job run is green (4/4). Unrelated to this diff.updated-modules-integration-test-part-3 (8 & 11, ubuntu-latest): real failures areHudiSparkS3MultiTableIT/HudiSeatunnelS3MultiTableITtiming out after ~420s. Hudi/S3-container infra, unrelated to CDC chunk splitting.updated-modules-integration-test-part-6 (8 & 11, ubuntu-latest): real failure isOceanBaseCDCCompatibilityITunder Flink, root causejava.io.NotSerializableException: io.debezium.relational.TableIdwhen Flink tries to serialize the source coordinator provider. This is a pre-existing Flink-translation serialization gap forTableId, unrelated to this PR's chunk-boundary-selection logic (the diff never touchesTableIdserialization or the Flink coordinator path).
None of the 5 failures touch the file this PR changes or any code on its call path. These modules only run here because "updated modules" pulls in every CDC-family e2e module once connector-cdc-base changes, which is expected broader coverage, not new breakage from this diff.
2.3 Documentation Updates
Not required — no user-facing config, default, or protocol changed. The PR description correctly states "No" for user-facing changes.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix, now that the gate is scoped correctly. It reuses existing sampleDataFromColumn/efficientShardingThroughSampling/splitUnevenlySizedChunks primitives rather than introducing new logic, and the gating condition directly encodes the actual precondition for the bug (a gap exists and there's more than one shard to balance).
3.2 Maintainability
Improved this round: removing the reflection-based test invocation (Issue 6) in favor of a protected method is strictly better for long-term maintainability and was the direct cause of last round's CI failure, so it also closes that risk class.
3.3 Extensibility
No SPI/registration surface touched; correctly scoped to the shared CDC base splitter only, no MySQL-specific logic leaked into it.
3.4 Historical-Version Compatibility
No change to SnapshotPhaseState, serialization, or checkpoint/restore semantics (re-verified this round, see 1.2). Existing running jobs and checkpoints are unaffected.
4. Issue Summary
| # | Issue | Location | Severity | Raised by another reviewer |
|---|---|---|---|---|
| 1 | Regression test NPE, never exercised decision path — RESOLVED, CI-confirmed passing | AbstractJdbcSourceChunkSplitterTest.java:265 (fixed via real Column at 194-195) |
High → Resolved | No |
| 2 | Sampling fix gated behind sampleShardingThreshold (~8.1M rows), didn't fire for realistic tables — RESOLVED |
AbstractJdbcSourceChunkSplitter.java:186 |
High → Resolved | No |
| 3 | Full-table-scan cost concern — originally resolved via threshold, now partially reopened by the Issue 2 fix (see Issue 9) | AbstractJdbcSourceChunkSplitter.java:184-186 |
Medium → superseded by Issue 9 | Yes (@Copilot) |
| 4 | Floored shard count under-splits — RESOLVED via Math.ceil |
AbstractJdbcSourceChunkSplitter.java:183, 227 |
Medium → Resolved | Yes (@Copilot) |
| 5 | Under-populated sample can still under-split very sparse keys — mitigated via fallback, not eliminated (unchanged) | AbstractJdbcSourceChunkSplitter.java:208-220 |
Medium → Mitigated | Yes (@Copilot) |
| 6 | Reflection-based private-method test was brittle — RESOLVED via protected + direct call |
AbstractJdbcSourceChunkSplitter.java:135, AbstractJdbcSourceChunkSplitterTest.java:265, 332 |
Low → Resolved | No |
| 7 | "Unrelated test additions" — RETRACTED, these pre-date the PR entirely | AbstractJdbcSourceChunkSplitterTest.java:429, 451 |
N/A (my error) | No |
| 8 | FQN used instead of already-imported simple names in test method (mostly carryover I missed last round) | AbstractJdbcSourceChunkSplitterTest.java:194-195, 207, 212, 240, 247, 252, 261, 266-270, 283, 288, 316, 323, 328, 333-337 |
Low | No |
| 9 | Fixing Issue 2 widens the non-sargable full-table sampling scan to any table with shardCount > 1 and any PK gap, not just severely-skewed large tables |
AbstractJdbcSourceChunkSplitter.java:184-186, MySqlUtils.java:118-140 |
Medium (non-blocking, intentional trade-off) | No |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
-
Blockers — must be fixed:
- CI-only blocker (not a code defect): the current head's fork CI run (
36177586378) is red on 5 jobs. I traced every one of them to root cause and none touch this PR's diff or call path (TaskExecutionServiceTestinseatunnel-engine-server, Hudi S3 IT timeouts, and a pre-existing FlinkTableIdserialization gap in OceanBase CDC — see 2.2). No code change is needed for these; they need a rerun/rebase againstdevand green CI before this can actually be merged. I'm not asking for any further code changes here — this is the only remaining gate. - No code-correctness blockers remain. Both of my round-1 High-severity findings (Issue 1 NPE, Issue 2 threshold gating) are genuinely fixed and CI-verified, not just claimed-fixed.
- CI-only blocker (not a code defect): the current head's fork CI run (
-
Recommended fixes — non-blocking:
- Issue 8 (Low): tidy up the fully-qualified names in
testSplitTableIntoChunksDecisionLogicto use the already-importedColumn/assertTrue/assertFalse/Collections.emptyList()— cosmetic only. - Issue 9 (Medium): consider a one-line note in the PR description calling out that
sample-sharding.thresholdno longer bounds this new sampling path, so it's documented for whoever next tunes that option.
- Issue 8 (Low): tidy up the fully-qualified names in
Overall assessment: This is a clean, well-scoped re-review outcome — you addressed both real blockers from round 1 precisely as discussed (the exact Option A gating fix, and a proper Column instance instead of null), and I verified both against actual CI logs rather than taking the commit message at face value. The remaining items are a style nit I should have flagged earlier (my fault, not yours) and a deliberate, well-understood performance trade-off that is the natural cost of fixing Issue 2 correctly. I don't see a materially better alternative implementation: keeping sampleShardingThreshold as the gate (my "Option B" from last round, i.e. explicitly scoping the PR down to very large tables) would have been simpler but wouldn't actually fix #10270 for realistically-sized tables, so I think you made the right call taking Option A. Once CI is green on a rebase, I'd approve this without further code changes.
a99de36 to
39e612e
Compare
|
Thanks again for the incredibly detailed re-review and for taking the time to trace those CI flakes down to their root causes! I really appreciate you verifying everything end-to-end. I've just pushed an update to wrap up the final items:
Hope for a fully green CI run this time around! Let me know if everything looks good to merge. |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the fast turnaround again! I re-pulled the full diff at the current head, re-verified every finding from both of my previous rounds from scratch (not just the incremental delta), and pulled the fresh fork CI logs job-by-job. Good news: both the FQN cleanup (Issue 8) and the PR-description update (Issue 9) are done exactly as described, and there are no new code-side blockers in this round. I also worked through a concrete non-consecutive-PK example end-to-end to double check the split-boundary math, and found one real test-coverage gap in the process that I should have caught in round 2 — details below, with an apology, since the test structure that exposes it hasn't changed since I last reviewed it.
What Problem Does This PR Solve?
During MySQL CDC full-snapshot (startup.mode = "initial"), AbstractJdbcSourceChunkSplitter.splitTableIntoChunks() picks "evenly-sized" arithmetic chunking whenever distributionFactor = (MAX-MIN+1)/rowCount falls in [distributionFactorLower, distributionFactorUpper] (default [0.05, 100.0]). Arithmetic stepping assumes PK gaps are uniformly spread; when gaps are clustered (e.g. a large deleted-ID range), some chunks end up empty and others end up with far more than chunkSize rows, and the reader task for an overloaded chunk can blow the checkpoint timeout (CheckpointException: Checkpoint expired before completing, matching #10270). This PR's fix: whenever distributionFactor > 1.0 (a gap mathematically exists) and there is more than one shard to produce, prefer sampling-based boundary selection over pure arithmetic stepping, since sampling reflects the real data distribution instead of assuming uniformity, with a safety-net fallback to exact-query splitting if the sample itself turns out to be too sparse.
1. Code Change Review
1.1 Core Logic Analysis
Files with core changes: AbstractJdbcSourceChunkSplitter.java (production logic, untouched since my round-2 review) and AbstractJdbcSourceChunkSplitterTest.java (only file touched by the newest commit, 39e612e4f, "Fix FQN style nits in test").
I confirmed via gh api repos/apache/seatunnel/commits/39e612e4f47c16790dac39134b0e5d85b4d9b1c8 that the only change since my last review is 20 additions / 28 deletions, all inside the test file. The production file AbstractJdbcSourceChunkSplitter.java is byte-for-byte the same as what I fully reviewed last round, so the correctness/compatibility/performance conclusions from round 2 carry forward unchanged. I re-verified them from scratch anyway rather than assuming they still hold.
Current decision logic (AbstractJdbcSourceChunkSplitter.java:175-221):
if (dataIsEvenlyDistributed) {
int shardCount = (int) Math.ceil((double) approximateRowCnt / chunkSize);
if (doubleCompare(distributionFactor, 1.0d) > 0
&& sampleShardingAllow
&& shardCount > 1) {
int inverseSamplingRate = sourceConfig.getInverseSamplingRate();
if (inverseSamplingRate > chunkSize) {
inverseSamplingRate = chunkSize;
}
Object[] sample = sampleDataFromColumn(jdbc, tableId, splitColumn, inverseSamplingRate);
if (sample.length >= shardCount) {
return efficientShardingThroughSampling(tableId, sample, approximateRowCnt, shardCount);
}
return splitUnevenlySizedChunks(jdbc, tableId, splitColumn, min, max, chunkSize);
}
final int dynamicChunkSize = Math.max((int) (distributionFactor * chunkSize), 1);
return splitEvenlySizedChunks(tableId, min, max, approximateRowCnt, chunkSize, dynamicChunkSize);
}Test-side change this round (AbstractJdbcSourceChunkSplitterTest.java, commit 39e612e4f): the previously-flagged FQN usages are gone. Column.editor().name("id").create() (line 150), Collections.emptyList() (now via the java.util.Collections import added at line 101), and assertTrue/assertFalse (now via the static import added at line 106) are all used with their short names consistently, matching the rest of the file. This is exactly Issue 8 from my round-2 review, now resolved.
Concrete worked example (non-consecutive PK verification)
To independently verify the split-boundary math rather than taking the PR description at face value, I traced the exact arithmetic for a small table with PK values {1, 2, 5, 6, 100} (5 rows, min=1, max=100), using chunkSize=2 for tractable numbers (the real default is 8096, but the math scales identically):
distributionFactor = (100-1+1)/5 = 20.0→ inside[0.05, 100.0]→dataIsEvenlyDistributed = true.shardCount = ceil(5/2) = 3.- Gate check:
distributionFactor(20.0) > 1.0✓,sampleShardingAllow✓,shardCount(3) > 1✓ → sampling branch fires (this is exactly the scenario the old code mishandled:dynamicChunkSize = 20*2 = 40, so the old arithmetic stepping would produce ranges[1,41),[41,81),[81,∞)— the first range alone would swallow 4 of the 5 rows (1,2,5,6) into a single oversized chunk while the last is nearly empty, reproducing the #10270 symptom). inverseSamplingRate = min(1000, chunkSize=2) = 2.MySqlUtils.sampleDataFromColumnrunsSELECT id FROM tbl WHERE MOD((id - MIN(id)), 2) = 0 ORDER BY id, i.e.MOD((id-1), 2) = 0:- id=1:
(1-1) mod 2 = 0→ included - id=2:
(2-1) mod 2 = 1→ excluded - id=5:
(5-1) mod 2 = 0→ included - id=6:
(6-1) mod 2 = 1→ excluded - id=100:
(100-1) mod 2 = 1→ excluded - Sample =
[1, 5], length 2.
- id=1:
sample.length(2) < shardCount(3)→ the insufficient-sample guard (AbstractJdbcSourceChunkSplitter.java:208-220, added in round 1 in response to Copilot's finding) correctly fires and falls back tosplitUnevenlySizedChunks(jdbc, tableId, splitColumn, min=1, max=100, chunkSize=2), which queries the database directly for the real next-chunk boundary at each step (nextChunkEnd→queryNextChunkMax,AbstractJdbcSourceChunkSplitter.java:299-320) instead of guessing arithmetically. That method is unchanged by this PR and already covered by pre-existing tests, and it is boundary-exact by construction (it re-queries the actual data after every step), so for this sparse/clustered example it produces correct, non-overlapping, gap-free chunks covering all 5 rows.- To also exercise the case where sampling does engage (rather than falling back), I re-ran the same example with
chunkSize=1:shardCount = ceil(5/1) = 5,inverseSamplingRate = min(1000,1) = 1, soMOD((id-1),1)=0is trivially true for every row → sample =[1,2,5,6,100](length 5)>= shardCount(5)→efficientShardingThroughSamplingfires. WithapproxSamplePerShard = 5/5 = 1.0 <= 1, it walks the sample pairwise:(null,1),(1,2),(2,5),(5,6),(6,100),(100,null)— every boundary is a real observed PK value, so consecutive ranges tile the key space with no gap and no overlap between any two adjacent chunks, and every one of the 5 actual rows falls into exactly one range. (The leading(null,1)range is an artifact of the pre-existing, unchangedefficientShardingThroughSamplinghelper — it will simply scan zero rows since nothing is< 1— this is pre-existing behavior shared with the "uneven distribution" branch and not something introduced by this PR.)
So for this concrete non-consecutive-PK example, both branches this PR can take (sampling-succeeds and sampling-falls-back) produce correct, non-overlapping, complete chunk boundaries. I could not construct a case, within the intended precondition (distributionFactor > 1.0 && shardCount > 1), where the new code produces incorrect boundaries — the two possible outcomes are "real sampled boundaries" or "exact incremental DB-queried boundaries," and neither can silently drop or duplicate rows the way the old pure-arithmetic-stepping path could.
Runtime path (re-verified end to end, unchanged in shape from round 2):
SnapshotSplitAssigner.getNext() [SnapshotSplitAssigner.java:168-188]
-> chunkSplitter.generateSplits(nextTable) [only for tables not in alreadyProcessedTables, line 185]
-> splitTableIntoChunks(jdbc, tableId, splitColumn) [AbstractJdbcSourceChunkSplitter.java:135-269]
-> isEvenlySplitColumn && dataIsEvenlyDistributed
-> distributionFactor > 1.0 && sampleShardingAllow && shardCount > 1 (NEW gate, this PR)
-> sampleDataFromColumn(...) [MySqlUtils.java:118-140, non-sargable MOD() scan]
-> sample.length >= shardCount
-> efficientShardingThroughSampling(...) [real-data-point boundaries]
else
-> splitUnevenlySizedChunks(...) [exact incremental DB-queried boundaries]
-> else -> splitEvenlySizedChunks(...) [unchanged pure-arithmetic path, only for distributionFactor <= 1.0 now]
-> alreadyProcessedTables.add(nextTable) [SnapshotSplitAssigner.java:187]
-> persisted in SnapshotPhaseState [SnapshotSplitAssigner.java:247-250, snapshotState()]
I re-confirmed generateSplits() is only invoked for a table not already present in the checkpointed alreadyProcessedTables list, so this is a normal-path change for any table whose snapshot splits haven't been generated yet, and it never re-fires for a table whose splits were already persisted before a restart.
Key findings:
- The normal snapshot-planning path for any evenly-distributed, gap-containing (
distributionFactor > 1.0), multi-shard table reaches this new branch — it is not a boundary/recovery-only code path. - The fix is a precise, narrowly-scoped correctness fix (not a workaround): it replaces an assumption (gaps are uniform) with either real sampled data or an exact incremental query, both of which are boundary-correct by construction.
- Both of my round-1 blockers (NPE in the regression test; the fix not actually firing for realistically-sized tables because of the reused
sampleShardingThresholdgate) remain resolved, re-verified against the unchanged production file. - New finding this round (Issue 10 below): the regression test verifies which method gets invoked, not that the resulting chunk boundaries are actually correct/complete for a concrete non-consecutive-key dataset. My worked example above fills that gap for this review, but it isn't captured by an assertion in the test suite itself.
1.2 Compatibility Impact
Fully compatible. No config option added, renamed, or removed; no default value changed; no wire/serialization format touched. SnapshotPhaseState (which persists alreadyProcessedTables/remainingSplits) is untouched, and generateSplits() is only invoked for tables not yet processed — jobs resuming from an existing checkpoint mid-snapshot are unaffected; only tables whose snapshot split generation hasn't happened yet see the new logic. splitTableIntoChunks going from private to protected (needed so the test can call it directly instead of via reflection) is an internal visibility widening with no external callers outside this class and its own test — not an API break. No entry needed in docs/en/introduction/concepts/incompatible-changes.md.
1.3 Performance / Side-Effect Analysis
Unchanged from round 2, re-confirmed: MySqlUtils.sampleDataFromColumn (MySqlUtils.java:118-140) runs a MOD(...)-filtered scan that is not sargable, effectively a full-table-scan-equivalent query. Under the current gate (shardCount > 1 rather than the old sampleShardingThreshold < shardCount), this now runs for any table over ~8096 rows (default chunk size) with distributionFactor > 1.0 — in practice most AUTO_INCREMENT MySQL tables that have ever had a deleted row. This is a one-time cost during snapshot planning per table, not a recurring/per-row cost, and it's the direct, foreseeable, and necessary consequence of actually fixing the bug for realistically-sized tables (the alternative — keeping the high threshold — is the exact bug this PR exists to fix). The PR description now explicitly documents this trade-off (the "Note on Performance Trade-off" section), which resolves what was Issue 9 in my last review. No new retries, no new locks, no change to reader-side concurrency or resource cleanup.
1.4 Error Handling and Logging
Unchanged and still fine: sampleDataFromColumn declares throws Exception, not swallowed; log.warn calls for inverseSamplingRate > chunkSize (AbstractJdbcSourceChunkSplitter.java:188-193) and for an insufficient sample (:212-218) are correctly leveled with table/factor/sample-size context; no credentials or row data are logged.
Issue 10 (Medium, NEW — genuine gap I should have caught in round 2, see apology below):
- Location:
AbstractJdbcSourceChunkSplitterTest.java:120-286(testSplitTableIntoChunksDecisionLogic) - Problem description: This test sits in the "decision logic" unit-test layer for
splitTableIntoChunks. It correctly verifies which strategy method gets invoked (sampleDataFromColumn→efficientShardingThroughSamplingvs. thesplitUnevenlySizedChunksfallback) by overriding all three strategy methods to returnCollections.emptyList()and recording boolean flags. What it does not do is assert on the actualList<ChunkRange>thatefficientShardingThroughSampling/splitUnevenlySizedChunkswould produce for a concrete non-consecutive-key dataset — i.e. it can't catch a regression in the real boundary math (e.g., an off-by-one inefficientShardingThroughSampling's indexing, or a bug that makes the fallback under- or over-cover the key range), only a regression in the routing decision itself. - Potential risk: If a future change accidentally breaks
efficientShardingThroughSampling's boundary computation (the actual mechanism that prevents #10270 from recurring) while leaving the routing condition intact, this test suite would stay green. The boundary-correctness safety net currently relies entirely on the separate, pre-existingtestEfficientShardingThroughSamplingtest, which was not written with a genuinely sparse/clustered-gap dataset in mind (I checked it — it uses a small dense/near-consecutive sample set) and predates this PR. - Best improvement: Option A — add one additional assertion-based test that runs
splitTableIntoChunksend-to-end against a table double seeded with a concrete non-consecutive key set (e.g. the{1,2,5,6,100}example above, or a larger deleted-range scenario matching #10270) and asserts on the actual returnedChunkRangelist: boundaries are non-overlapping, contiguous (no gaps), and every known row falls into exactly one chunk. Option B (lighter-weight) — extendtestEfficientShardingThroughSamplingwith a case using a genuinely clustered/sparse sample array (not just consecutive-ish values) to independently validate the boundary math the new gate now relies on more heavily. I don't consider this a hard merge blocker since the underlying boundary methods are pre-existing, but it's the difference between "this PR's test suite proves the fix is wired up" and "this PR's test suite proves the fix actually produces correct output," and given this is a data-correctness-critical path (silent row loss/duplication risk), I'd like to see it closed before or shortly after merge. - Severity: Medium
- Raised by another reviewer: No.
Issue 11 (Low, NEW, cosmetic):
- Location: PR description ("How was this patch tested?" section)
- Problem description: The PR description states the added test is named
testSplitEvenlySizedChunksWithNonConsecutiveIds, but the method actually added istestSplitTableIntoChunksDecisionLogic(AbstractJdbcSourceChunkSplitterTest.java:120). Harmless, just a stale reference from an earlier draft. - Potential risk: None functionally; purely a documentation-accuracy nit for anyone cross-referencing the PR description against the diff later.
- Best improvement: Update the PR description to reference the actual method name.
- Severity: Low
- Raised by another reviewer: No.
A sincere apology for Issue 10: I rated this exact test "Stable" in my round-2 review and treated the decision-logic coverage as sufficient to close out Copilot's original "test bypasses split decision logic" finding. That was correct as far as it went (the test genuinely does exercise the real decision path now, which was the round-1 problem), but I should have also checked at that time whether the test asserts on the output of the chosen strategy, not just which strategy gets chosen — and I didn't do that until working through the concrete PK example for this round. This is a carryover I should have caught earlier, not a new problem introduced by the FQN-cleanup commit; the test structure is unchanged since round 2.
2. Code Quality Assessment
2.1 Coding Standards
Issue 8 (FQN usage inconsistent with the file's existing style) is resolved — verified above. The new branch's explanatory comment (AbstractJdbcSourceChunkSplitter.java:176-182) remains clear about the "why." No other coding-standard issues found.
2.2 Test Coverage and Test Stability
Coverage: see Issue 10 above — the routing/gating logic is well covered; the actual boundary-output correctness for a genuinely sparse/clustered key set is not independently asserted by a new test, though it is exercised manually in this review via the worked example.
Stability rating: Stable. I re-checked testSplitTableIntoChunksDecisionLogic for the standard flaky-test anti-patterns: no hard sleeps, no timing assumptions, no shared static state leaking between the two sub-scenarios (samplingCalled/unevenlyCalled/evenlyCalled are local arrays reset between the two invocations, AbstractJdbcSourceChunkSplitterTest.java:223-225), no execution-order dependence, no floating-point comparisons without delta, fully deterministic mocked return values throughout. This conclusion is unchanged from round 2 since the test's control flow wasn't touched by the FQN-only commit.
CI diagnosis (current head 39e612e4f, fork run 36268024049): the "Build" check is failing on 5 jobs. I pulled the actual logs (not just job names) for every one of them:
| Job | Real failing test | Root cause | Related to this PR's diff? |
|---|---|---|---|
unit-test (8, ubuntu-latest) |
org.apache.seatunnel.engine.server.event.JobStateEventTest#testNotEndJobStateEvent |
org.awaitility.core.ConditionTimeoutException waiting on an event-state counter |
No — seatunnel-engine-server module, unrelated to connector-cdc-base. The PR's own test (AbstractJdbcSourceChunkSplitterTest) passes 4/4 in this exact job. |
unit-test (11, windows-latest) |
org.apache.seatunnel.connectors.seatunnel.paypal.source.PayPalClientTest#closeWakesRetryWait |
AssertionFailedError: expected <true> but was <false> — a known Windows loopback-HTTP timing flake in connector-http-paypal |
No — different connector module entirely, unrelated to CDC chunk splitting. A fix PR (#12444, "Release PayPalClientTest's arrival latch before the response body write") exists but is still open, not merged as of this review. |
updated-modules-integration-test-part-6 (8, ubuntu-latest) and (11, ubuntu-latest) |
org.apache.seatunnel.connectors.seatunnel.cdc.oceanbase.OceanBaseCDCCompatibilityIT (4/5 errors, both jobs) |
java.io.NotSerializableException: io.debezium.relational.TableId inside Coordinator Provider for node Source: OceanBase-CDC-Source is not serializable — a deterministic (not timing-based) Flink-translation serialization gap for OceanBase CDC |
No — this is the shared Debezium-runtime TableId serialization issue, unrelated to AbstractJdbcSourceChunkSplitter. Two fix PRs exist (#12489 "Use shared Debezium runtime for OceanBase CDC", #12477 "Stop bundling debezium-core in the OceanBase CDC jar") but neither is merged to dev as of this review. |
updated-modules-integration-test-part-2 (11, ubuntu-latest) |
org.apache.seatunnel.connectors.seatunnel.cdc.postgres.PostgresCDCIT#testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes |
org.awaitility.core.ConditionTimeoutException: expected <1> but was <0> within 3 minutes — a container-timing flake |
No — different connector (Postgres, not MySQL) and a different scenario (startup-mode/offset resumption, not snapshot chunk splitting). The e2e fixture tables here are far below chunkSize (8096 default), so shardCount would be 1 and this PR's new gate (shardCount > 1) would never even engage for this test's data. |
Important correction to my own round-2 guidance: last round I said a rebase onto latest dev was the lowest-cost next step, and the author did exactly that. It cleared the previous round's failures (a different TaskExecutionServiceTest flake and Hudi S3 IT timeouts), which is good evidence the rebase itself worked as intended. However, the OceanBase NotSerializableException failure is deterministic, not a flake — it will reproduce on every single run against the current dev HEAD regardless of how many times this PR is rebased or CI is retried, because the actual fix (#12489/#12477) hasn't landed in dev yet. I want to be upfront about that so we don't burn more CI cycles expecting a rerun to help with that specific job. The PayPalClientTest and JobStateEventTest failures, by contrast, are genuinely timing-sensitive and may or may not clear on a plain retry.
2.3 Documentation Updates
Not required — no user-facing config, default, or protocol changed. The PR description now also documents the sampling-threshold performance trade-off (Issue 9 from round 2, resolved). Issue 11 above is a minor stale test-name reference, not a functional documentation gap.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix. Reuses existing sampleDataFromColumn/efficientShardingThroughSampling/splitUnevenlySizedChunks primitives; the gating condition directly encodes the actual precondition for the bug (a gap exists and there's more than one shard to balance), with a safety-net fallback when sampling itself is defeated by very sparse keys.
3.2 Maintainability
Good — splitTableIntoChunks being protected (instead of reflection-based test access) is strictly better for long-term maintainability, and this round's FQN cleanup brings the new test method in line with the rest of the file's style.
3.3 Extensibility
No SPI/registration surface touched; correctly scoped to the shared CDC base splitter only, no MySQL-specific logic leaked into it.
3.4 Historical-Version Compatibility
No change to SnapshotPhaseState, serialization, or checkpoint/restore semantics (re-verified this round). Existing running jobs and checkpoints are unaffected.
4. Issue Summary
| # | Issue | Location | Severity | Raised by another reviewer |
|---|---|---|---|---|
| 1 | Regression test NPE, never exercised decision path — RESOLVED | AbstractJdbcSourceChunkSplitterTest.java (fixed via real Column) |
High → Resolved | No |
| 2 | Sampling fix gated behind sampleShardingThreshold (~8.1M rows), didn't fire for realistic tables — RESOLVED |
AbstractJdbcSourceChunkSplitter.java:186 |
High → Resolved | No |
| 3 | Full-table-scan cost concern — resolved via threshold, superseded by the wider trigger surface | AbstractJdbcSourceChunkSplitter.java:184-186 |
Medium → Superseded by Issue 9 (documented trade-off) | Yes (@Copilot) |
| 4 | Floored shard count under-splits — RESOLVED via Math.ceil |
AbstractJdbcSourceChunkSplitter.java:183, 227 |
Medium → Resolved | Yes (@Copilot) |
| 5 | Under-populated sample can still under-split very sparse keys — mitigated via fallback, not eliminated | AbstractJdbcSourceChunkSplitter.java:208-220 |
Medium → Mitigated | Yes (@Copilot) |
| 6 | Reflection-based private-method test was brittle — RESOLVED via protected + direct call |
AbstractJdbcSourceChunkSplitter.java:135 |
Low → Resolved | No |
| 7 | "Unrelated test additions" — RETRACTED, pre-dated the PR entirely (my error) | AbstractJdbcSourceChunkSplitterTest.java |
N/A (my error) | No |
| 8 | FQN used instead of already-imported simple names in test method — RESOLVED this round | AbstractJdbcSourceChunkSplitterTest.java |
Low → Resolved | No |
| 9 | Widened full-table sampling scan trade-off not documented — RESOLVED, now called out in PR description | AbstractJdbcSourceChunkSplitter.java:184-186 |
Medium → Resolved | No |
| 10 | New regression test verifies routing, not actual chunk-boundary output, for a concrete non-consecutive-key dataset | AbstractJdbcSourceChunkSplitterTest.java:120-286 |
Medium (NEW, carryover omission — see apology) | No |
| 11 | PR description references a test method name that doesn't match the actual added method | PR description | Low (NEW, cosmetic) | No |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
-
Blockers — must be fixed:
- CI (not a code defect, but currently blocking the merge gate): the current head's fork CI run (
36268024049) is red on 5 jobs. All 5 are traced to root cause above and none touch this PR's diff or call path. Two of them (PayPalClientTest,JobStateEventTest) are timing-sensitive flakes that may clear on a retry; the other two (OceanBaseCDCCompatibilityIT×2) are a deterministic pre-existing bug indevwith open-but-unmerged fixes (#12489, #12477) — a retry or another rebase will not clear those specific jobs until one of those fixes lands. I'd suggest looping in a maintainer who can either help land the OceanBase fix or make a judgment call on merging despite that specific known-unrelated failing job. - No code-correctness blockers remain. All High-severity findings from round 1 (Issue 1 NPE, Issue 2 threshold gating) are resolved and re-verified against the unchanged production file this round.
- CI (not a code defect, but currently blocking the merge gate): the current head's fork CI run (
-
Recommended fixes — non-blocking:
- Issue 10 (Medium): add an assertion-based test that validates actual chunk-boundary output (non-overlapping, gap-free, full coverage) for a concrete non-consecutive-key dataset, not just which strategy method gets invoked. I'd like to see this closed given this is a data-correctness-critical path, but I'm not blocking merge on it since the underlying boundary-computation methods are pre-existing and unchanged by this PR.
- Issue 11 (Low): fix the stale test-method-name reference in the PR description.
Overall assessment: The code itself is in good shape — this is a precise, well-scoped fix, both round-1 blockers are genuinely resolved (not just claimed), and I independently re-derived the split-boundary math for a concrete {1,2,5,6,100}-style example and couldn't find a scenario where the new gate produces incorrect (overlapping/gapped) chunks. The only thing keeping this from a clean "ready to merge" today is CI, and — importantly — not all of the current CI failures are equally actionable: the PayPal/JobState ones are ordinary flakes, but the OceanBase one is a real, deterministic, already-tracked upstream bug that no amount of rebasing or retrying on this PR's side will fix by itself. I don't see a materially better alternative implementation than the current approach (sampling with an exact-query fallback) for the code itself. Once CI is green — most likely after #12489/#12477 land and a re-sync — I'd be happy to approve without further code changes.
7159d22 to
b66fb9f
Compare
|
Thanks for sticking with this PR through these thorough reviews! I genuinely appreciate the detailed tracing, and you were completely right to call out the gap in boundary-output assertions. I’ve just pushed a final update addressing the remaining non-blocking items:
The branch has also been rebased against the latest apache:dev. I completely understand the known deterministic flakes (OceanBase TableId serialization) are a blocker on the CI side until their respective upstream fixes merge. Thank you again for your patience and for making this patch much more robust! Let me know if you are happy to |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the update — re-reviewed the latest head (b66fb9fd) from scratch. Good news up front: the boundary-output test-coverage gap I raised in round 3 (Issue 10) is now genuinely closed, not just claimed-closed — I hand-traced both new scenarios against the real, unmocked production algorithm myself before checking the test's assertions, and independently pulled the fork CI logs rather than trusting the job names. There are no remaining code-side blockers. Details below, including exactly which of my prior issues are resolved, and a fresh, honest read of the current CI state.
What Problem Does This PR Solve?
During MySQL CDC full-snapshot (startup.mode = "initial"), AbstractJdbcSourceChunkSplitter.splitTableIntoChunks() picks "evenly-sized" arithmetic chunking whenever distributionFactor = (MAX-MIN+1)/rowCount falls in [distributionFactorLower, distributionFactorUpper] (default [0.05, 100.0]). Arithmetic stepping assumes primary-key gaps are uniformly spread; when gaps are clustered (e.g. a large deleted-ID range), some chunks end up empty and others end up with far more than chunkSize rows, and the reader task for an overloaded chunk can blow the checkpoint timeout (CheckpointException: Checkpoint expired before completing, matching #10270). This PR's fix: whenever distributionFactor > 1.0 (a gap mathematically exists) and there is more than one shard to produce, prefer sampling-based boundary selection over pure arithmetic stepping, with a safety-net fallback to exact incremental-query splitting if the sample itself turns out to be too sparse.
1. Code Change Review
1.1 Core Logic Analysis
Production code: AbstractJdbcSourceChunkSplitter.java is byte-for-byte unchanged since my round-2 review (16dbf2c7) — I diffed 16dbf2c7..b66fb9fd on that file and got an empty diff. So the correctness, compatibility, and performance conclusions from rounds 2-3 all carry forward unchanged; I re-verified them from scratch rather than assuming.
Test code — what actually changed this round: the only file touched by b66fb9fd is AbstractJdbcSourceChunkSplitterTest.java, adding one new method, testSplitTableIntoChunksBoundaryCorrectnessWithSparseKeys (lines 340-484). This is a direct, well-targeted response to Issue 10: it exercises splitTableIntoChunks end-to-end (mocking only the DB-access seams: queryMinMax, isEvenlySplitColumn, queryApproximateRowCnt, sampleDataFromColumn, queryNextChunkMax) against a concrete PK set {1, 2, 5, 6, 100} — the same non-consecutive-key example I worked through by hand in round 3 — and asserts on the actual ChunkRange list returned, not just on which strategy method got called.
I re-derived both scenarios by hand against the real, unmocked algorithm before trusting the test's own assertions:
- Fallback scenario (
chunkSize=2):distributionFactor=20.0,shardCount=3, gate fires, mocked sample{1,5}(length 2)< shardCount(3)→ falls back tosplitUnevenlySizedChunks. WalkingnextChunkEnd/queryNextChunkMaxagainst the test's own mock produces(null,2),(2,6),(6,null)— exactly the threeassertEqualsin the test. - Sampling-success scenario (
chunkSize=1):shardCount=5, mocked sample{1,2,5,6,100}(length 5)>= shardCount(5)→efficientShardingThroughSampling.approxSamplePerShard=1.0<=1takes the pairwise branch, producing(null,1),(1,2),(2,5),(5,6),(6,100),(100,null)— exactly the sixassertEqualsin the test.
Both traces match the test's hard-coded expectations exactly. Because only the DB-access seams are mocked, this test genuinely exercises the real splitTableIntoChunks, splitUnevenlySizedChunks, nextChunkEnd, and efficientShardingThroughSampling code — it isn't a mirror/tautological test. It has real failure power: an off-by-one in the sampling index math, a broken loop-termination condition in the unevenly-sized fallback, or a regression in the sample.length >= shardCount gate would flip these specific assertions red. That is precisely the gap I described as missing in round 3, and it's now filled with real coverage rather than a routing-only check.
I also confirmed this in the actual fork CI (not just locally): the current head's unit-test (8, ubuntu-latest) job log shows AbstractJdbcSourceChunkSplitterTest: Tests run: 5, Failures: 0, Errors: 0, Skipped: 0 — up from 4 in round 3, the 5th being this new test, and it's green.
Runtime path (unchanged in shape, re-verified once more since the production file didn't move): SnapshotSplitAssigner.getNext() → chunkSplitter.generateSplits(nextTable) (only for tables not yet in the checkpointed alreadyProcessedTables) → splitTableIntoChunks → the new gate (distributionFactor > 1.0 && sampleShardingAllow && shardCount > 1) → sampling-success or exact-query fallback, exactly as described in my last two reviews.
1.2 Compatibility Impact
Fully compatible, unchanged conclusion. No config option added, renamed, or removed; no default value changed; no wire/serialization format touched. SnapshotPhaseState (which persists alreadyProcessedTables/remainingSplits) is untouched, and generateSplits() is only invoked for tables not yet processed, so jobs resuming from an existing checkpoint mid-snapshot for a non-consecutive-PK table are unaffected — only tables whose snapshot split generation hasn't happened yet see the new logic, and there is no chunk-boundary misalignment risk against an old checkpoint because the new logic never re-runs against already-persisted splits. This round's diff is test-only, so there is nothing new to re-verify on the compatibility front.
1.3 Performance / Side-Effect Analysis
Unchanged from round 3: the wider sampling-scan trigger surface introduced in round 1's Option-A fix (any table >~8096 rows with any PK gap, not just severely-skewed multi-million-row tables) is a deliberate, already-documented trade-off (the PR description's "Note on Performance Trade-off" section, unchanged and still present). Test-only changes this round don't add any new runtime cost.
1.4 Error Handling and Logging
Unchanged and still fine — no changes to production code this round.
2. Code Quality Assessment
2.1 Coding Standards
No new coding-standard issues. The new test method is internally consistent with the rest of the file (uses the already-cleaned-up short names from Issue 8's fix — Column, Collections.emptyList() isn't needed here, assertEquals — no reintroduced FQNs).
2.2 Test Coverage and Test Stability — Stable
Coverage: Issue 10 is closed — see 1.1 above. Between testSplitTableIntoChunksDecisionLogic (routing/gating, from round 1) and the new testSplitTableIntoChunksBoundaryCorrectnessWithSparseKeys (actual boundary output for a genuinely sparse/clustered key set, both the sampling-success and fallback branches), this data-correctness-critical path now has both "the right strategy gets chosen" and "the chosen strategy produces correct, non-overlapping, complete boundaries" independently asserted.
Stability: checked the new test for the standard flaky-test anti-patterns — no sleeps, no timing assumptions, two fully independent splitter instances/anonymous subclasses for the two scenarios (no shared mutable state), fully deterministic mocked return values, no floating-point comparisons without context. I rate it Stable.
Fresh CI diagnosis for the current head (fork run 36307864565, checked live, not from a cached job list):
| Job | Result | Notes |
|---|---|---|
unit-test (8/11 × ubuntu/windows) |
Green, all 4 | Includes this PR's own test, 5/5 passing. Neither of round 3's two flaky failures (JobStateEventTest, PayPalClientTest) recurred this run. |
updated-modules-integration-test-part-6 (8 & 11, ubuntu) |
Red, both | Pulled the raw log: identical java.io.NotSerializableException: io.debezium.relational.TableId in the Flink OceanBase CDC coordinator-provider path, byte-for-byte the same deterministic bug identified in round 3. I checked: the tracked fixes (#12489, #12477) are both still OPEN, not merged to dev — this was certain to fail again regardless of this PR's content, exactly as predicted last round. Not this PR's responsibility. |
updated-modules-integration-test-part-2 (Postgres) |
Green this run | Round 3's PostgresCDCIT timing flake did not recur. |
updated-modules-integration-test-part-4 ×2, kafka-connector-it |
Still running as of this review | Unrelated modules/scenarios by content (Kafka connector IT, an unrelated "updated modules" batch with no call-path connection to connector-cdc-base), but I want to be upfront that I did not observe their final conclusion — worth a final glance before merge rather than assuming green. |
So: no new CI breakage caused by this round's commit, the two previously-flaky failures cleared on their own (consistent with them being flakes, not regressions), and the one deterministic failure is exactly the same already-tracked, unrelated bug as before, for the same reason (its fix hasn't landed yet).
2.3 Documentation Updates
Not required — no user-facing config, default, or protocol changed.
Issue 11 (Low, carried forward, still open): the PR description's "How was this patch tested?" section still references testSplitEvenlySizedChunksWithNonConsecutiveIds, which matches neither actual test method (testSplitTableIntoChunksDecisionLogic or the new testSplitTableIntoChunksBoundaryCorrectnessWithSparseKeys). Purely cosmetic, not blocking — would be nice to tidy up whenever convenient.
3. Architectural Soundness
Unchanged from round 3 — no production code moved this round. The fix remains a precise, narrowly-scoped correctness fix reusing existing primitives (sampleDataFromColumn/efficientShardingThroughSampling/splitUnevenlySizedChunks), correctly scoped to the shared CDC base splitter with no MySQL-specific leakage, and with no change to checkpoint/restore semantics for existing running jobs.
4. Issue Summary
| # | Issue | Location | Severity | Status |
|---|---|---|---|---|
| 1 | Regression test NPE, never exercised decision path | AbstractJdbcSourceChunkSplitterTest.java |
High | Resolved (round 2, CI-confirmed) |
| 2 | Sampling fix gated behind sampleShardingThreshold (~8.1M rows), didn't fire for realistic tables |
AbstractJdbcSourceChunkSplitter.java:186 |
High | Resolved (round 2, gate changed to shardCount > 1) |
| 3 | Full-table-scan cost concern (Copilot) | AbstractJdbcSourceChunkSplitter.java:184-186 |
Medium | Resolved, superseded by documented trade-off (Issue 9) |
| 4 | Floored shard count under-splits (Copilot) | AbstractJdbcSourceChunkSplitter.java:183, 227 |
Medium | Resolved via Math.ceil (round 1) |
| 5 | Under-populated sample can still under-split very sparse keys (Copilot) | AbstractJdbcSourceChunkSplitter.java:208-220 |
Medium | Mitigated, not eliminated (pre-existing sampling-strategy behavior shared with the "uneven" branch; not this PR's obligation to fully solve) |
| 6 | Reflection-based private-method test was brittle | AbstractJdbcSourceChunkSplitterTest.java |
Low | Resolved (round 2, protected + direct call) |
| 7 | "Unrelated test additions" | AbstractJdbcSourceChunkSplitterTest.java |
N/A | Retracted (round 2, my own error — pre-dated the PR) |
| 8 | FQN used instead of already-imported simple names | AbstractJdbcSourceChunkSplitterTest.java |
Low | Resolved (round 3) |
| 9 | Widened full-table sampling scan trade-off not documented | PR description | Medium | Resolved (round 3, "Note on Performance Trade-off" added) |
| 10 | Regression test verified routing only, not actual chunk-boundary output, for a concrete non-consecutive-key dataset | AbstractJdbcSourceChunkSplitterTest.java:340-484 |
Medium | Resolved this round — new testSplitTableIntoChunksBoundaryCorrectnessWithSparseKeys, independently hand-verified against the real algorithm, genuinely exercises boundary output for both branches |
| 11 | PR description references a test method name that doesn't match any actual test | PR description | Low | Still open, cosmetic, non-blocking |
No new code-side issues found in this round's commit.
5. Merge Recommendation
Conclusion: Approve
- No code-correctness blockers remain. All three rounds of findings are now resolved, retracted, or explicitly downgraded to non-blocking (mitigated/documented trade-off), and I independently verified the newest fix (Issue 10) by hand-tracing the algorithm myself rather than trusting the test or the PR description.
- CI status, checked live for the current head: all
unit-testjobs (including this PR's own, now 5/5) are green, and both of round 3's flaky failures cleared on this run without any code change — consistent with them being ordinary flakes. The one job that failed again (OceanBaseCDCCompatibilityITviaupdated-modules-integration-test-part-6) failed for the exact same deterministic, already-tracked, unrelated reason as before (TableIdNotSerializableException in the Flink OceanBase CDC path), and its fixes (#12489, #12477) are still open/unmerged — this will keep failing regardless of how many more times this PR is rebased or retried, through no fault of this PR. Three unrelated jobs (kafka-connector-it,updated-modules-integration-test-part-4×2) were still in progress when I finished this review; I'd recommend a quick final glance at those before the actual merge, but nothing in their scope plausibly touches this diff's call path. - Non-blocking cleanup: Issue 11 (stale test-method-name reference in the PR description) — purely cosmetic, feel free to leave it or fix it in a follow-up, either is fine.
Overall assessment: this has been a genuinely productive back-and-forth — every substantive concern raised across four rounds (two of them mine, two from Copilot) has been addressed with a real fix rather than a workaround, and the newest commit closes the one meaningful gap I found in my own round-3 review (routing-only coverage) with a properly assertion-based test that I verified independently produces the exact chunk boundaries the real algorithm would produce. I don't see a materially better alternative implementation for the fix itself. Thank you for sticking with this through the review process — nice work, and I'd be glad to see this merged once the unrelated OceanBase CI item is resolved upstream or a maintainer makes the call to merge past that known-unrelated job.
…cutive primary key IDs
…ld for sampling, verify sample size
… sampling threshold for gap-skewed tables
b66fb9f to
4c80ec6
Compare
|
Thanks again! Quick update regarding the CI build failures: I noticed that the upstream fix for the deterministic OceanBase CDC TableId serialization failure (#12477 #12477) has just merged into dev. I’ve rebased this branch onto the latest upstream/dev to pull in that fix, which should resolve the failures in updated-modules-integration-test-part-6 (connector-cdc-oceanbase-e2e). I also verified spotless:apply and confirmed all 5 unit tests in AbstractJdbcSourceChunkSplitterTest pass locally. Additionally, I've updated the PR description with the exact test method names to wrap up the cosmetic nit (Issue 11). Looking forward to the clean CI run! |
|
Thanks for the update, and nice catch pulling in #12477! I re-checked the latest fork CI run at your rebased head ( Good news: the previous deterministic OceanBase CDC failure in However, CI is not fully green yet: a new, unrelated failure showed up in This is a transient Maven Central 502 while resolving No further rebase or code change needed on your side for this — I'd just re-run the failed |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks @sun-9545sunoj for keeping this branch current and for rerunning the CI jobs. Since my last approval, the head moved only through a merge of dev (7e81f88); your last real commit is still 4c80ec6. I re-read the PR at the new head from scratch, and my approval stands. The good news is that CI is now fully green on this head. Details below.
What Problem Does This PR Solve?
- User pain point: during a MySQL CDC full snapshot (
startup.mode = "initial"),AbstractJdbcSourceChunkSplitter.splitTableIntoChunks()picks arithmetic "evenly-sized" chunking wheneverdistributionFactor = (MAX-MIN+1)/rowCountis within[distributionFactorLower, distributionFactorUpper]. When primary-key gaps are clustered (for example a large deleted-ID range), some chunks end up empty and others far larger thanchunkSize, and a reader for an overloaded chunk can exceed the checkpoint timeout (the #10270 symptom). - Fix approach: when
distributionFactor > 1.0(a gap provably exists) and more than one shard is needed, prefer sampling-based boundaries over arithmetic stepping, and fall back to exact incremental-query splitting if the sample is too sparse. - One-sentence summary: snapshot chunk boundaries now follow the real key distribution instead of assuming gaps are uniform.
1. Code Change Review
1.1 Core Logic Analysis
Is the author code unchanged? Yes. The three-dot diff against current dev (0278a6a747) is still exactly two files (+392 / -4): AbstractJdbcSourceChunkSplitter.java and AbstractJdbcSourceChunkSplitterTest.java. Both are byte-identical (same git blob) to the version I approved at 4c80ec6. Dev has not touched connector-cdc-base since your last commit, so the merge brought nothing into this code path (the only CDC change in the delta is an unrelated Postgres test, PostgresRelationSchemaChangeResolverTest).
I re-read the production change once more:
// before
if (dataIsEvenlyDistributed) {
final int dynamicChunkSize = Math.max((int) (distributionFactor * chunkSize), 1);
return splitEvenlySizedChunks(tableId, min, max, approximateRowCnt, chunkSize, dynamicChunkSize);
}
// after (abridged; new gate in front of the arithmetic path)
int shardCount = (int) Math.ceil((double) approximateRowCnt / chunkSize);
if (doubleCompare(distributionFactor, 1.0d) > 0 && sampleShardingAllow && shardCount > 1) {
Object[] sample = sampleDataFromColumn(jdbc, tableId, splitColumn, inverseSamplingRate);
if (sample.length >= shardCount) {
return efficientShardingThroughSampling(tableId, sample, approximateRowCnt, shardCount);
}
return splitUnevenlySizedChunks(jdbc, tableId, splitColumn, min, max, chunkSize);
}Runtime path (the normal path for any gap-skewed table, not only a recovery path):
SnapshotSplitAssigner.getNext()
-> chunkSplitter.generateSplits(table) (only for tables not yet in alreadyProcessedTables)
-> splitTableIntoChunks(jdbc, tableId, splitColumn)
-> queryMinMax / queryApproximateRowCnt -> distributionFactor
-> distributionFactor in [lower, upper] ?
yes + factor > 1.0 + shardCount > 1 -> sampleDataFromColumn
sample.length >= shardCount -> efficientShardingThroughSampling (data-driven boundaries)
else -> splitUnevenlySizedChunks (exact incremental queries)
yes + factor <= 1.0 or one shard -> splitEvenlySizedChunks (unchanged)
no -> existing sampling / uneven branch (only the ceil and sample-size guard are new)
1.2 Compatibility Impact
Fully compatible. No option added, renamed or removed, no default changed, and no serialization format touched. SnapshotPhaseState (alreadyProcessedTables / remainingSplits) is not modified, and generateSplits() runs only for tables whose splits have not been persisted yet, so a job resuming from an existing checkpoint does not see its boundaries recomputed.
1.3 Performance / Side-Effect Analysis
Unchanged from my earlier reviews: the sampling scan is now reachable for any table with more than one shard and a key gap, which is a deliberate and documented trade-off (the "Performance Trade-off" note in the PR description). No new threads, retained state or resources.
1.4 Error Handling and Logging
No blocking issues found. The insufficient-sample case logs a warn with the table, sample size and required size, and then falls back to exact splitting instead of under-splitting.
2. Code Quality Assessment
2.1 Coding Standards
The change is small and the new branch carries comments explaining why it exists. Fine.
2.2 Test Coverage and Test Stability
testSplitTableIntoChunksDecisionLogic pins the routing and testSplitTableIntoChunksBoundaryCorrectnessWithSparseKeys asserts the exact ChunkRange boundaries for the key set {1, 2, 5, 6, 100} on both the sampling and fallback branches; either would turn red on an off-by-one in the boundary math or a broken sample.length >= shardCount gate. Stability: Stable (fully mocked DB seams, no sleeps, no shared mutable state).
2.3 Documentation Updates
Not required: no user-facing option, default or protocol changed.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise, narrowly scoped fix that reuses the existing sampling and uneven-split primitives in the shared CDC base splitter, with no MySQL-specific leakage.
3.2 Maintainability
Clear and well commented.
3.3 Extensibility
Fine. The same gate benefits every CDC connector that extends this splitter.
3.4 Historical-Version Compatibility
No change to checkpoint or restore semantics for already running jobs.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| - | No open issues at this head. All earlier items (1 to 11) are resolved, retracted or accepted as documented trade-offs | - | - |
Other reviewers: the only other reviewer is the Copilot bot, and its inline findings (full-scan cost, floored shard count, under-populated sample) were addressed in earlier rounds and re-verified above.
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers - must be fixed: none.
- Recommended fixes - non-blocking: none.
CI and sync status (checked live for head 7e81f88):
- The fork
Buildrun for this exact head (run 37302067614) completedsuccesswith 42 jobs green and 33 skipped. This includes all fourunit-testjobs (JDK 8 and 11, Linux and Windows), bothmysql-cdc-connector-itjobs, and bothupdated-modules-integration-test-part-6jobs. The earlier red items I raised (the OceanBaseTableIdserialization failure and the transient Maven Central 502 inmysql-cdc-connector-it (11)) are gone, and the apache-sideBuildcheck isSUCCESS. - The branch is diverged (
ahead_by=7,behind_by=46against dev) but has no merge conflicts (GitHub reports it mergeable, and a trial merge with current dev has no conflict markers), so syncing is not required.
So, for me: CI was the only remaining item from my last round, it is now green, and there is no code-side blocker. A GitHub review approval from someone with write access is the remaining merge gate, since my account cannot satisfy the write-review rule. Thank you for sticking with this through so many rounds, nice work!
davidzollo
left a comment
There was a problem hiding this comment.
LGTM +1. Thank you for your contribution!
…cutive primary key IDs (apache#12463)



Purpose of this pull request
Fixes #10270
During the CDC full snapshot stage (
startup.mode = "initial"), if the table's primary key IDs are highly non-consecutive (e.g., large ranges of deleted rows resulting in sparse clusters of data), the job can fail withCheckpointException: Checkpoint expired before completing.Root Cause:
In
AbstractJdbcSourceChunkSplitter.splitTableIntoChunks(), thedistributionFactoris calculated as(MAX - MIN + 1) / rowCount. If this factor falls within[0.05, 100.0], the data is deemed "evenly distributed" andsplitEvenlySizedChunks()is invoked. However, this method uses pure arithmetic stepping (min + step,min + 2*step). When IDs are clustered with large gaps, some arithmetic chunks end up empty while others hold a disproportionately large number of rows, causing the reader task for those overloaded chunks to exceed the checkpoint timeout.Fix:
When
distributionFactor > 1.0(which mathematically guarantees gaps exist in the ID space) and there is>1shard, the chunk splitter now prefersefficientShardingThroughSampling(). Sampling uses actual data points to determine chunk boundaries, ensuring splits remain balanced regardless of gap distribution. It gracefully falls back to exact incremental-query splitting (splitUnevenlySizedChunks) if sampling is disabled (sampleShardingAllow = false) or returns insufficient data.Does this PR introduce any user-facing change?
No. Configuration options remain unchanged. This strictly improves the internal chunk-splitting robustness for sparse tables.
How was this patch tested?
Added
testSplitTableIntoChunksDecisionLogicinAbstractJdbcSourceChunkSplitterTestto verify the routing logic:distributionFactor > 1.0).distributionFactor <= 1.0) or when sampling is explicitly disabled.Added
testSplitTableIntoChunksBoundaryCorrectnessWithSparseKeysto verify that both the sampling path and the fallback path produce correct, gap-free, non-overlapping boundaries for a concrete sparse dataset.Ran
mvn spotless:applyandmvn -q -DskipTests verify.All tests in
AbstractJdbcSourceChunkSplitterTestpassed locally.Check list
If any new Jar binary package adding in your PR, please add License Notice according New License Guide
https://github.com/apache/seatunnel/blob/dev/docs/en/developer/new-license.md
If necessary, please update the documentation to describe the new feature.
https://github.com/apache/seatunnel/tree/dev/docs
If necessary, please update incompatible-changes.md to describe the incompatibility caused by this PR.
If you are contributing the connector code, please check that the following files are updated:
plugin-mapping.propertieshttps://github.com/apache/seatunnel/blob/dev/plugin-mapping.properties
and add new connector information in it.
seatunnel-disthttps://github.com/apache/seatunnel/blob/dev/seatunnel-dist/pom.xml
label-scope-confhttps://github.com/apache/seatunnel/blob/dev/.github/workflows/labeler/label-scope-conf.yml
seatunnel-e2ehttps://github.com/apache/seatunnel/tree/dev/seatunnel-e2e/seatunnel-connector-v2-e2e/
plugin_confighttps://github.com/apache/seatunnel/blob/dev/config/plugin_config
connector-cdc-base, not adding a new connector. Existing E2E tests for MySQL CDC natively cover snapshot splitting.)Note on Performance Trade-off
As a result of this fix,
sample-sharding.thresholdno longer bounds the sampling path for gap-skewed tables (tables withdistributionFactor > 1.0). To ensure perfectly balanced splits regardless of total row count, these tables will now always incur an extra full-table sampling query during chunk splitting as long as there is>1shard.