Repository navigation
[Fix][Connector-V2][CDC] Do not use a nullable column as the snapshot split column - #12597
davidzollo merged 8 commits into
Conversation
DanielLeens
left a comment
There was a problem hiding this comment.
Thank you @CodeWithPravinMaske for this contribution, and especially for the very clear reproduction (1000 of 1100 rows) and the root-cause note about Debezium promoting the first UNIQUE KEY to a primary key. This is a well-scoped fix. I re-derived everything from the source at the PR head; no blocking issue found, details below.
What Problem Does This PR Solve?
Pain point: For a table without a primary key, the JDBC CDC sources pick the snapshot split column from a unique key, even when that column is nullable. Snapshot chunks are range predicates (col <= ?, col >= ? AND col <= ?, col >= ?). NULL never satisfies a range predicate and there is no IS NULL chunk, so every row whose split column is NULL is silently skipped as soon as the table has more than one chunk.
Fix approach: Treat a nullable column as not usable for chunking. Nullability is read from DatabaseMetaData#getColumns (not from the parsed Debezium column, which is wrong for MySQL), and nullable candidates are skipped in getSplitColumn. If nothing usable remains, the existing single-split fallback reads the whole table.
Example: table t(id int NOT NULL, code int NULL, UNIQUE KEY(code)), no PK, snapshot.split.size = 5. Before: code is chosen, rows with code IS NULL are never read. After: code is skipped, one full-table split is used, all rows are read.
1. Code Change Review
1.1 Core Logic Analysis
Real call chain at the PR head:
AbstractJdbcSourceChunkSplitter.generateSplits(tableId) (AbstractJdbcSourceChunkSplitter.java:~75-100)
-> getSplitColumn(jdbc, dialect, tableId) (:401)
1) configured snapshotSplitColumn (:419-452) -> NEW: dialect.isColumnNullable(...) check at :438
2) primary key first column (:455-466) -> unchanged (PK columns are NOT NULL in all supported DBs)
3) unique keys loop (:470-495) -> NEW: dialect.isColumnNullable(...) skip at :479
-> splitColumn == null ?
exactly_once = true -> UnsupportedOperationException (message reworded, :86-90)
exactly_once = false -> single split createSnapshotSplit(... null, null, null) (existing fallback)
else -> splitTableIntoChunks (range chunks)
JdbcDataSourceDialect.isColumnNullable(...) (JdbcDataSourceDialect.java:139-154)
-> metaData.getColumns(catalog, schema, table, column) ; exact match on TABLE_NAME / COLUMN_NAME ; IS_NULLABLE == "NO" => not nullable
-> metadata does not describe the column => fall back to Column#isOptional()
The normal user path reaches this logic: any CDC job on a table that has no PK (or whose configured split column is a unique key) goes through getSplitColumn. It is a main-path snapshot fix, not just an edge path. The class is shared by MySQL, PostgreSQL, Oracle, SQL Server and DB2 CDC splitters (all extend AbstractJdbcSourceChunkSplitter); the static getSplitColumn(Table) helpers in MySqlUtils and OracleUtils have no callers, so there is no second selection path that bypasses the fix.
Correctness points I verified:
- Exact matching on
TABLE_NAME/COLUMN_NAMEis the right call becausegetColumnstreats these arguments as LIKE patterns (_and%would otherwise over-match). - Reading
IS_NULLABLEfrom metadata (instead of the parsed column) is justified; the parsed column is exactly what is wrong for MySQL here. - The ordering is preserved: a non-nullable unique key still wins over a nullable one (
splitColumnPrefersNotNullUniqueKeyOverNullableOne). "NO".equalsIgnoreCase(...)treats empty/unknown ("") as nullable, which is the safe direction (worst case: a single split, never lost rows).
1.2 Compatibility Impact
Partially incompatible (documented, intentional).
- Config options, defaults, serialization and checkpoint/savepoint formats are untouched; no new state is written. Splits already persisted in a restored enumerator state are not re-generated.
- Behavior change 1: tables whose only key is a nullable unique key go from N parallel snapshot splits to one split (data now complete, snapshot slower).
- Behavior change 2: with
exactly_once = truesuch a table now fails at startup (new job or a table that has no restored split state) instead of running and losing rows. This is a loud failure replacing a silent data loss, which I consider the right trade-off; it is documented inincompatible-changes.mden and zh, with migration guidance. - The same
snapshotSplitColumnpointing to a nullable column is now ignored with a WARN (falls through to PK / unique key / single split), also documented.
1.3 Performance / Side-Effect Analysis
- Extra cost: one
DatabaseMetaData#getColumnscall per candidate column, only during split generation (once per table, per unique key). Negligible; no hot path, no new threads, locks, retries or unbounded structures. - Trade-off to be aware of: a nullable-unique-key table with no actual NULLs (very common, e.g. an optional business code that is in practice always filled) loses snapshot parallelism and is read by a single reader. For very large tables this can be a real slowdown. This is documented, so it is not a blocker; see Issue 2.
1.4 Error Handling and Logging
No blocking issues found.
Issue 1: The production isColumnNullable implementation is never exercised by a unit test
- Location:
JdbcSourceChunkSplitterTest.java(test dialect overrideisColumnNullablereturningcolumn.isOptional()), production code atJdbcDataSourceDialect.java:139-154 - Problem: The three new unit tests prove the splitter's decision logic, but the dialect used in the tests overrides the new method with
column.isOptional(), so the metadata query, the exact-name matching and the fallback branch are only covered indirectly by the MySQL E2E (one database, one driver). - Potential risk: A regression in the matching loop (for example case handling for Oracle upper-case names, or a driver returning a different
TABLE_NAMEform) would not be caught by unit tests, and it is the part that actually differs per database. - Best improvement: add a small unit test for the default method using a mocked
Connection/DatabaseMetaData/ResultSet(cases:IS_NULLABLE=NO,YES, no matching row falls back toColumn#isOptional, pattern-like name not matching another table's column). - Severity: Medium
- Raised by another reviewer: No
Issue 2: Parallelism is lost even when the nullable column contains no NULL
- Location:
AbstractJdbcSourceChunkSplitter.java:479-487 - Problem: Nullability is judged from the schema only, so a nullable unique column that happens to hold no NULLs also disables chunking.
- Potential risk: snapshot throughput regression for large tables on upgrade (documented, but users have to change DDL or set
snapshotSplitColumnto a NOT NULL column). - Best improvement (optional, can be a follow-up): keep the current safe behavior, and make sure the WARN text tells the user how to regain parallelism (declare NOT NULL or configure a non-nullable
snapshotSplitColumn). A data-dependent probe (... WHERE col IS NULL LIMIT 1) or an extraIS NULLchunk would be the long-term improvement, but it has snapshot-vs-binlog consistency implications and I would not ask for it in this PR. - Severity: Low
- Raised by another reviewer: No
Issue 3: WARN message does not mention the remedy
- Location:
AbstractJdbcSourceChunkSplitter.java:438-444and:479-487 - Problem: Messages explain why the column is skipped but not how to restore parallel reading.
- Risk: operators seeing a slower snapshot need to open the docs to find out.
- Best improvement: append a short hint such as "declare a NOT NULL unique column or set a non-nullable snapshotSplitColumn to enable parallel snapshot reading".
- Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
Good. The new default method has a Javadoc that explains the why (the parsed column is unreliable for MySQL), and the key branches carry comments. Imports are explicit, no wildcard, no new dependencies, log via Lombok is consistent with the file.
2.2 Test Coverage and Test Stability
- Unit: three new tests in
JdbcSourceChunkSplitterTest(nullable unique key skipped, NOT NULL key preferred, configured nullable split column ignored). They fail without the fix (the author documentedexpected: <null> but was: <nullable_int>), and the fixture columns were made explicitly NOT NULL, which models real PK columns and does not weaken existing assertions. See Issue 1 for the missing coverage of the real metadata lookup. - E2E:
testMysqlCdcSnapshotWithNullableUniqueKeyinAbstractMysqlCDCITBase(so it runs inMysqlCDCITandMysql8_4CDCIT), 30 rows, 10 NULL codes,snapshot.split.size = 5, compares row ids viaawait().atMost(60000). It is a polling assertion on result equality (no fixedThread.sleep), the data set is static, and the DDL is isolated in its ownnullable_unique_keytemplate with its own tables. Stability rating: Stable. A small remark: the job runs in STREAMING mode and the future is never cancelled, which matches the pattern of neighbouring tests in this class, so I do not consider it a problem. - Other databases (PostgreSQL, Oracle, SQL Server, DB2) rely on standard JDBC metadata and have no dedicated test; acceptable for a base-class fix, but see Issue 1.
2.3 Documentation Updates
incompatible-changes.md is updated in both docs/en and docs/zh, the content is consistent with the code (message text, exactly_once behavior, snapshotSplitColumn / primaryKeys migration advice). No other option or default changes, so no connector option docs need updating.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix. It is placed at the single shared choke point (getSplitColumn), not in each connector, and it reuses the existing single-split fallback rather than inventing a new code path.
3.2 Maintainability
Good. One default method on the dialect interface plus two small guards; dialects can override isColumnNullable if a driver needs special handling.
3.3 Extensibility
A future IS NULL chunk (to keep parallelism for nullable keys) can reuse the same helper without changing the guard logic.
3.4 Historical-Version Compatibility
No change to checkpoint/state formats or option names. The only differences are the documented behavior changes in 1.2. Restored jobs keep their persisted splits.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | Real isColumnNullable metadata lookup has no unit test |
JdbcDataSourceDialect.java:139-154 / JdbcSourceChunkSplitterTest | Medium |
| 2 | Parallelism lost even when nullable column has no NULLs | AbstractJdbcSourceChunkSplitter.java:479-487 | Low |
| 3 | WARN text lacks remedy hint | AbstractJdbcSourceChunkSplitter.java:438-444, 479-487 | Low |
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers - must be fixed: none from the code side. The only open item is CI (see below).
- Recommended fixes - non-blocking: Issue 1 (unit test for the real metadata lookup), Issues 2 and 3 (warning hint).
Overall assessment: the root cause is correctly identified and fixed at the right place, with documented compatibility trade-offs and a stable E2E that reproduces the loss. Approving from the code-review side.
Better alternative: none needed for this PR; an IS NULL chunk is a possible follow-up if retaining parallelism for nullable keys matters.
CI / sync status: the apache-side Build check is only a pointer to the fork run; that run (attempt 2) was cancelled at the "Build website" job and the integration jobs were skipped, so there is currently no real test result on this head. This is not a code failure. Please re-run the failed/cancelled jobs in your fork Actions (for example the "Run" workflow) so the unit and connector-cdc-mysql-e2e jobs actually execute and report green. The branch is 14 commits behind dev with no conflicts; syncing is not required for this review.
…d hint the remedy in warnings
|
Thanks a lot for the detailed review, @DanielLeens!
This commit also triggers a fresh CI run, since the previous attempt was cancelled at the website job. |
…c-nullable-unique-key-split # Conflicts: # docs/en/introduction/concepts/incompatible-changes.md # docs/zh/introduction/concepts/incompatible-changes.md
…c-nullable-unique-key-split # Conflicts: # docs/en/introduction/concepts/incompatible-changes.md # docs/zh/introduction/concepts/incompatible-changes.md
…c-nullable-unique-key-split # Conflicts: # docs/en/introduction/concepts/incompatible-changes.md # docs/zh/introduction/concepts/incompatible-changes.md
|
CI note: the remaining red jobs are unrelated to this PR: |
SEZ9
left a comment
There was a problem hiding this comment.
Thanks for working on this. I reviewed the latest head dd24a4a3834c.
What this PR fixes
- User pain: For a table with no primary key, the JDBC CDC splitter uses the first unique-key column as the snapshot split column even when it is nullable; the chunk range predicates (
col <= ?,col >= ? AND col <= ?,col >= ?) never match NULL and there is noIS NULLchunk, so every NULL row is silently dropped once the table has more than one chunk (reproduced on MySQL 8.0: 1000 of 1100 rows arrive, no error). - Fix approach: Add
JdbcDataSourceDialect#isColumnNullable(default impl atJdbcDataSourceDialect.java:139-154readsIS_NULLABLEviaDatabaseMetaData#getColumnswith exact TABLE_NAME/COLUMN_NAME match, falling back tocolumn.isOptional()), and inAbstractJdbcSourceChunkSplitter#getSplitColumnskip a nullable unique-key column (:484if (dialect.isColumnNullable(jdbc, tableId, firstColumn))→ WARN +continue) and ignore a nullable configuredsnapshotSplitColumn(:442) with a WARN, so the existing null-split fallback at:89-101reads the table as one split; exactly-once error text updated at:93; unit tests, a MySQL E2E (nullable_unique_keytemplate) and incompatible-changes docs (en/zh) added. - One-line summary: The core idea is right and the unique-key and
snapshotSplitColumnpaths are now safe for all JDBC CDC dialects, but the guard is not applied to the primary-key branch (AbstractJdbcSourceChunkSplitter.java:465-472callsisEvenlySplitColumn(firstColumn)with no nullability check), so a nullable column injected viatable-names-config.primaryKeysstill drops NULL rows despite the migration guide recommending exactly that option; a metadata miss silently falls back to the unreliableColumn#isOptional()with no log; and the new E2E comparesidonly (AbstractMysqlCDCITBase.java:378-386) because NULL codes arrive at the sink as0, so the row loss is fixed while a value-corruption bug on the same table is knowingly left in place.
Runtime chain I rechecked
SnapshotSplitAssigner.getNext() SnapshotSplitAssigner.java:185
-> AbstractJdbcSourceChunkSplitter.generateSplits(tableId) AbstractJdbcSourceChunkSplitter.java:68
-> dialect.openJdbcConnection(sourceConfig) AbstractJdbcSourceChunkSplitter.java:79
-> getSplitColumn(jdbc, dialect, tableId) AbstractJdbcSourceChunkSplitter.java:83
-> dialect.getPrimaryKey(jdbc, tableId) AbstractJdbcSourceChunkSplitter.java:421
-> [configured snapshotSplitColumn] dialect.isColumnNullable(jdbc, tableId, column) AbstractJdbcSourceChunkSplitter.java:442 (CHANGED: WARN + fall through)
-> JdbcDataSourceDialect.isColumnNullable() JdbcDataSourceDialect.java:139
-> jdbcConnection.connection().getMetaData().getColumns(catalog, schema, table, column) JdbcDataSourceDialect.java:141-144
-> exact TABLE_NAME/COLUMN_NAME match -> IS_NULLABLE != "NO" JdbcDataSourceDialect.java:147-149
-> else column.isOptional() JdbcDataSourceDialect.java:153
-> [primary key branch] isEvenlySplitColumn(firstColumn) AbstractJdbcSourceChunkSplitter.java:465-472 (NOT guarded by isColumnNullable)
-> [unique keys] dialect.getUniqueKeys(jdbc, tableId) AbstractJdbcSourceChunkSplitter.java:477
-> per key: dialect.isColumnNullable(jdbc, tableId, firstColumn) AbstractJdbcSourceChunkSplitter.java:484 (CHANGED: WARN + continue)
-> isEvenlySplitColumn / columnComparable / sqlTypePriority AbstractJdbcSourceChunkSplitter.java:493-497
-> return null when no safe column AbstractJdbcSourceChunkSplitter.java:507-508
-> splitColumn == null: isExactlyOnce() -> UnsupportedOperationException (message CHANGED) AbstractJdbcSourceChunkSplitter.java:89-94
-> else createSnapshotSplit(jdbc, tableId, 0, null, null, null) single full-table split AbstractJdbcSourceChunkSplitter.java:96
-> splitColumn != null: splitTableIntoChunks(jdbc, tableId, splitColumn) -> range chunks AbstractJdbcSourceChunkSplitter.java:105
Findings
Issue 1: Nullability guard covers unique keys and snapshotSplitColumn but not the primary-key branch, so a nullable column injected via table-names-config.primaryKeys still becomes the split column and NULL rows are still dropped — contradicting the incompatible-changes text and the migration guide
- Location:
seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/enumerator/splitter/AbstractJdbcSourceChunkSplitter.java:484 - Why it matters: - The new
dialect.isColumnNullable(...)check is applied only in the configured-split-column path (AbstractJdbcSourceChunkSplitter.java:442) and in the unique-key loop (:484). The primary-key branch directly below (:465-472, unchanged) still takestable.columnWithName(primaryKey.get().getColumnNames().get(0))and returns it afterisEvenlySplitColumnwith no nullability check. - In all five dialects
getPrimaryKeyreadstableMap.get(tableId).getTableSchema().getPrimaryKey()(MySqlDialect.java:130,PostgresDialect.java:221,OracleDialect.java:127,SqlServerDialect.java:158,Db2Dialect.java:164). That catalog PK is whatCatalogTableUtils.mergeCatalogTableConfigbuilds fromtable-names-config.primaryKeys; when the named column is nullable it only logsPrimary key({}) is nullable for catalog table {}(CatalogTableUtils.java:93) and flips the catalog column to non-nullable — the database still reportsIS_NULLABLE=YES. - Consequence: a user with a PK-less table who follows the MySQL-CDC doc and the new Migration Guide (
incompatible-changes.md:13) and setsprimaryKeysto the nullable unique column gets exactly the same silent NULL-row loss this PR sets out to fix, while the heading at:8-10claims nullable columns are "no longer used as the snapshot split column". - Suggested fix: apply
dialect.isColumnNullable(jdbc, tableId, firstColumn)in the PK branch too (skip with WARN, or fail fast when the PK came from user config andexactly_onceis enabled), and state in the docs that aprimaryKeyscolumn must be NOT NULL in the database. - Evidence:
seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/enumerator/splitter/AbstractJdbcSourceChunkSplitter.java:442 if (dialect.isColumnNullable(jdbc, tableId, column)) {;docs/en/introduction/concepts/incompatible-changes.md:13 - **Migration Guide**: Declare a NOT NULL unique column, or configuretable-names-config.primaryKeys/snapshotSplitColumnwith a non-nullable column, to keep parallel snapshot reading.;seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/enumerator/splitter/AbstractJdbcSourceChunkSplitter.java:93 "Exactly once is enabled, but not found primary key or non-nullable unique key for table %s", - Suggested fix: This guard (and the one at L442) covers unique keys and
snapshotSplitColumn, but the primary-key branch right above (L465-472) still returns the first PK column unchecked. All dialects resolvegetPrimaryKeyfrom the catalog table, andCatalogTableUtils.mergeCatalogTableConfigletstable-names-config.primaryKeysname a nullable column (it only WARNs and flips the catalog column to non-nullable; the DB metadata still saysIS_NULLABLE=YES). So the data-loss case this PR fixes remains for users who followed the MySQL-CDC doc's advice to declare a unique non-primary column viaprimaryKeys— and the incompatible-changes entry says we "no longer split on a nullable column" while recommending exactly that option. Please applydialect.isColumnNullable(jdbc, tableId, firstColumn)in the PK branch as well (skip with WARN, or fail fast when the PK was user-configured andexactly_onceis on), and note in the docs that the configured key column must be NOT NULL. - Severity: Medium
Issue 2: The incompatible-changes heading and Migration Guide overstate the fix: a nullable column configured via table-names-config.primaryKeys is still used as the split column, because the primary-key branch of getSplitColumn has no nullability guard and all dialects return the catalog-table PK
- Location:
docs/en/introduction/concepts/incompatible-changes.md:13 - Why it matters: - Root cause: the two new guards are only on the
snapshotSplitColumnbranch (AbstractJdbcSourceChunkSplitter.java:442) and the unique-key loop (:484). The primary-key branch at:465-472is untouched. In every shipped dialect (MySqlDialect.java:130,PostgresDialect.java:221,OracleDialect.java:127,SqlServerDialect.java:158,Db2Dialect.java:164)getPrimaryKeyreturnstableMap.get(tableId).getTableSchema().getPrimaryKey(), i.e. the catalog table into whichCatalogTableUtils.mergeCatalogTableConfiginjects the user-configuredprimaryKeys, forcing the column to non-nullable with only a WARN (CatalogTableUtils.java:93). - The heading at
docs/en/introduction/concepts/incompatible-changes.md:8-10says nullable columns are "no longer used as the snapshot split column" for all JDBC CDC sources, and the Migration Guide at:13recommendstable-names-config.primaryKeysas a way to keep parallel reading. Both statements are only true for the unique-key andsnapshotSplitColumnpaths; a nullableprimaryKeyscolumn still splits the snapshot and still drops NULL rows. - Fix: either add the same guard to the PK branch (preferred, see F1), or narrow the heading and guide to say the check covers unique keys and
snapshotSplitColumnonly and that aprimaryKeyscolumn must genuinely be NOT NULL in the database. The zh copy atdocs/zh/introduction/concepts/incompatible-changes.md:12needs the same change. - Evidence:
docs/en/introduction/concepts/incompatible-changes.md:13 - **Migration Guide**: Declare a NOT NULL unique column, or configuretable-names-config.primaryKeys/snapshotSplitColumnwith a non-nullable column, to keep parallel snapshot reading.;seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/enumerator/splitter/AbstractJdbcSourceChunkSplitter.java:484 if (dialect.isColumnNullable(jdbc, tableId, firstColumn)) {;docs/en/introduction/concepts/incompatible-changes.md:11 - **Description**: ... A nullable column (from a unique key or fromsnapshotSplitColumn) is now skipped; if no non-nullable key column remains, the table is read as a single split. - Suggested fix: The guide points users to
table-names-config.primaryKeys, but that path is not covered by the new check:getSplitColumnonly callsdialect.isColumnNullableon thesnapshotSplitColumnbranch (:442) and in the unique-key loop (:484); the primary-key branch at:465-472is unchanged, and every dialect'sgetPrimaryKeyreturns the catalog-table PK thatCatalogTableUtils.mergeCatalogTableConfigbuilds fromprimaryKeys(forcing the column to non-nullable with just a WARN atCatalogTableUtils.java:93). So a nullableprimaryKeyscolumn still splits the snapshot and still drops NULL rows. I'd either add the same guard to the PK branch, or narrow this heading/guide to say the check covers unique keys andsnapshotSplitColumnonly and that aprimaryKeyscolumn must genuinely be NOT NULL in the database (same fix indocs/zh/.../incompatible-changes.md:12). - Severity: Medium
Issue 3: isColumnNullable silently falls back to the parsed Column#isOptional() — the value the Javadoc says is unreliable — whenever the exact TABLE_NAME/COLUMN_NAME match misses (identifier case, catalog/schema mismatch), re-opening the data-loss hole with no log
- Location:
seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/dialect/JdbcDataSourceDialect.java:153 - Why it matters: - Root cause:
JdbcDataSourceDialect.java:147-148comparetableId.table()/column.name()with case-sensitiveequalsagainst the metadata strings, and:153returnscolumn.isOptional()when nothing matched. On MySQL withlower_case_table_names=1(default on Windows/macOS, common in Docker images configured that way) a table configured asdb.MyTableis stored and returned bygetColumnsasmytable; on Oracle an unquoted identifier comes back upper-cased. In those cases the LIKE lookup finds the row but the exact comparison rejects it, and the method returnscolumn.isOptional(). - The Javadoc at
:130-131itself states that for a MySQL PK-less table the parsed column of a nullable unique key is reported as not optional, so the fallback returnsfalsein precisely the scenario this PR fixes, and the nullable column is used as the split column again. Nothing is logged, so the regression is invisible. - Also, the JDBC spec allows an empty
IS_NULLABLEstring for "unknown";:149treats anything butNOas nullable, which is at least safe, but should probably route through the same fallback for clarity. - Suggested fix:
- (a) compare case-insensitively when
!metaData.supportsMixedCaseIdentifiers()(or based onstoresLowerCaseIdentifiers()/storesUpperCaseIdentifiers()), - (b) also match
TABLE_SCHEM/TABLE_CATagainst the non-null parts oftableId, and - (c) emit a WARN with table and column whenever the fallback to
column.isOptional()is taken. - Evidence:
seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/dialect/JdbcDataSourceDialect.java:148 && column.name().equals(rs.getString("COLUMN_NAME"))) {;seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/dialect/JdbcDataSourceDialect.java:149 return !"NO".equalsIgnoreCase(rs.getString("IS_NULLABLE"));;seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/dialect/JdbcDataSourceDialect.java:153 return column.isOptional(); - Suggested fix: The exact-match guard against the LIKE pattern is right, but the case-sensitive
equalsonTABLE_NAME/COLUMN_NAMEmeans that on MySQL withlower_case_table_names=1(table configured asMyTable, metadata returnsmytable) or on Oracle with unquoted identifiers, we fall through tocolumn.isOptional()— which the Javadoc above says is exactly the value we cannot trust, and which isfalsefor a Debezium-promoted unique key. The data loss then comes back silently. Could we (a) match case-insensitively when!metaData.supportsMixedCaseIdentifiers()(or based onstoresLowerCaseIdentifiers()/storesUpperCaseIdentifiers()), (b) also checkTABLE_SCHEM/TABLE_CATagainst the non-null part oftableId, and (c) log a WARN with table/column whenever this fallback is taken? An emptyIS_NULLABLE(unknown per JDBC spec) should probably also go through the fallback rather than being treated as YES. - Severity: Medium
Issue 4: Rows with NULL in the nullable unique key are now read but arrive at the sink with code = 0; the new E2E deliberately compares only id to hide this, so the fix trades silent row loss for silent value corruption on MySQL
- Location:
seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mysql/AbstractMysqlCDCITBase.java:378 - Why it matters: - The test comment added at
AbstractMysqlCDCITBase.java:378-379states that "the NULL codes are emitted as 0 by the MySQL schema parsing, which is a separate issue from the skipped rows", and the assertion at:380-386runsselect id from ... order by idon source and sink and compares only that. The source DDL (nullable_unique_key.sql:29) declarescode int DEFAULT NULLand the inserts include 10 rows with NULLcode. - Root cause is the same one the PR description identifies: Debezium's
MySqlAntlrDdlParserpromotes the first UNIQUE KEY of a PK-less table to the primary key and marks the column NOT NULL, so the schema used to build rows treatscodeas non-optional and NULL values are coerced to the type default0. This PR works around that for the split column choice but leaves the row-value path untouched. - Consequence: after this fix all 1100 rows reach the sink, but 10 of them carry
code = 0instead of NULL in a column that is supposed to be unique — a user-visible correctness bug on the exact table shape this change targets, now with a test that is written to avoid noticing it. - Suggested action: at minimum compare
id, nameso row content is verified and reference a follow-up issue for the NULL→0 coercion; ideally fixMySqlSchemato clear the promoted PK / restoreoptional=truewhen the catalog reports no primary key, which would also makeColumn#isOptional()trustworthy forisColumnNullable. - Evidence:
seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mysql/AbstractMysqlCDCITBase.java:380 String idQuery = "select id from " + MYSQL_DATABASE + ".%s order by id";;seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/resources/ddl/nullable_unique_key.sql:29codeint DEFAULT NULL,;docs/en/introduction/concepts/incompatible-changes.md:11 - **Impact**: Such tables are now read completely, but with one snapshot split instead of several. - Suggested fix: This comment documents a real correctness problem rather than a test limitation: after this fix the 10 NULL-code rows reach the sink with
code = 0, because the Debezium parser still treats the promoted UNIQUE KEY as a NOT NULL primary key (MySqlSchemaonly overrides PK names when the catalog has one). We go from silently dropping rows to silently rewriting a unique column to 0. Could you at least compareid, namehere so the row content is verified, and link a follow-up issue for the NULL→0 coercion? IdeallyMySqlSchemashould clear the promoted PK / restoreoptional=truewhen the catalog reports no primary key, which would also makeColumn#isOptional()trustworthy. - Severity: Medium
Issue 5: JdbcDataSourceDialect#isColumnNullable Javadoc does not state the SPI contract for dialect implementors: when it is called, that it issues a DatabaseMetaData.getColumns round trip per candidate key, and that catalog-backed dialects may override it
- Location:
seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/dialect/JdbcDataSourceDialect.java:139 - Why it matters: - The new default method at
JdbcDataSourceDialect.java:139is a public SPI extension on the dialect interface. The Javadoc at:127-138explains the MySQL motivation and the return value well, but not the contract: it is invoked fromAbstractJdbcSourceChunkSplitter.getSplitColumnonce for the configuredsnapshotSplitColumn(:442) and once per unique key (:484) during split generation, and each call runs agetColumnsmetadata query (:141-144). - All five shipped dialects already hold a
tableMapofCatalogTables (the same mapgetPrimaryKeyreads at e.g.MySqlDialect.java:130), so implementors could answer from the catalog column's nullability without a round trip; the Javadoc should say that overriding is expected/allowed and what the default costs. - Suggested wording: add an
@implSpec/@implNotedescribing when the method is called, that the default performs oneDatabaseMetaData#getColumnslookup per call, and that dialects with a catalog schema cache may override it. - Evidence:
seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/dialect/JdbcDataSourceDialect.java:139 default boolean isColumnNullable(JdbcConnection jdbcConnection, TableId tableId, Column column);seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/dialect/JdbcDataSourceDialect.java:141 DatabaseMetaData metaData = jdbcConnection.connection().getMetaData(); - Suggested fix: Nice, clear Javadoc on the why. Since this is a new SPI method on the dialect interface, could you also add the when/cost for implementors: it is called by
AbstractJdbcSourceChunkSplitter.getSplitColumnfor the configuredsnapshotSplitColumnand for every unique key of every table during split generation, and the default issues aDatabaseMetaData#getColumnsquery on each call. A one-liner that dialects which already hold aCatalogTablemap (all five shipped ones do) may override it from the catalog column's nullability would make the contract explicit. - Severity: Low
Issue 6: One DatabaseMetaData.getColumns round trip per candidate key per table during split generation, although only MySQL needs it; on Oracle this is a slow dictionary query multiplied by table × unique-key count
- Location:
seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/dialect/JdbcDataSourceDialect.java:143 - Why it matters: -
isColumnNullableissuesmetaData.getColumns(...)(JdbcDataSourceDialect.java:143-144) and is called from the splitter for the configured split column (AbstractJdbcSourceChunkSplitter.java:442) and for every unique key in the loop (:484), insidegenerateSplits, which runs sequentially in the enumerator for each captured table. - For PostgreSQL, Oracle, SQL Server and DB2 the Debezium
Tableis built byJdbcConnection#readSchemafrom JDBC metadata, soColumn#isOptional()already reflectsIS_NULLABLEand the extra query is redundant; only MySQL's DDL-parsed schema has the unique-key promotion problem the Javadoc describes. - Oracle's
getColumnsis a notoriously slow dictionary query (ALL_TAB_COLUMNSjoins), so a multi-table job with several unique indexes per table pays table × unique-key round trips at every job start and every restart from a checkpoint without saved splits. - Suggested fix: keep the interface default as
column.isOptional()and move the metadata lookup intoMySqlDialect, or fetchgetColumns(catalog, schema, table, null)once per table ingetSplitColumnand reuse the result for all candidate columns. - Evidence:
seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/dialect/JdbcDataSourceDialect.java:144 tableId.catalog(), tableId.schema(), tableId.table(), column.name())) {;seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/enumerator/splitter/AbstractJdbcSourceChunkSplitter.java:484 if (dialect.isColumnNullable(jdbc, tableId, firstColumn)) { - Suggested fix: This
getColumnscall runs once per candidate key per table from the splitter loop. For PostgreSQL/Oracle/SQL Server/DB2 the DebeziumTablealready comes fromJdbcConnection#readSchema, socolumn.isOptional()is the metadata value and the query is redundant — only MySQL's DDL-parsed schema has the promotion problem. On OraclegetColumnsis a slow dictionary query, so multi-table jobs with several unique indexes will pay for it at every start. Consider keeping the default ascolumn.isOptional()and putting this metadata lookup inMySqlDialect, or fetchinggetColumns(..., table, null)once per table and reusing it for all candidates. - Severity: Low
Review conclusion
Conclusion: final approval remains pending on the previous comments
2. Remaining follow-ups
- Issue 1: Nullability guard covers unique keys and
snapshotSplitColumnbut not the primary-key branch, so a nullable column injected viatable-names-config.primaryKeysstill becomes the split column and NULL rows are still dropped — contradicting the incompatible-changes text and the migration guide - Issue 2: The incompatible-changes heading and Migration Guide overstate the fix: a nullable column configured via
table-names-config.primaryKeysis still used as the split column, because the primary-key branch ofgetSplitColumnhas no nullability guard and all dialects return the catalog-table PK - Issue 3:
isColumnNullablesilently falls back to the parsedColumn#isOptional()— the value the Javadoc says is unreliable — whenever the exactTABLE_NAME/COLUMN_NAMEmatch misses (identifier case, catalog/schema mismatch), re-opening the data-loss hole with no log - Issue 4: Rows with NULL in the nullable unique key are now read but arrive at the sink with
code = 0; the new E2E deliberately compares onlyidto hide this, so the fix trades silent row loss for silent value corruption on MySQL - Issue 5:
JdbcDataSourceDialect#isColumnNullableJavadoc does not state the SPI contract for dialect implementors: when it is called, that it issues aDatabaseMetaData.getColumnsround trip per candidate key, and that catalog-backed dialects may override it - Issue 6: One
DatabaseMetaData.getColumnsround trip per candidate key per table during split generation, although only MySQL needs it; on Oracle this is a slow dictionary query multiplied by table × unique-key count
Thanks for the updates so far. Happy to discuss the remaining points.
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks @CodeWithPravinMaske for the quick follow-up (the metadata unit tests and the remedy hint in the WARN texts are exactly what I asked for), and sorry for the extra round. I re-reviewed the latest head dd24a4a383 from scratch and also read @SEZ9's review. Sorry for missing one thing in my previous round, and that is on me: I wrote that primary key columns are NOT NULL in every supported database, which overlooked that a primary key can also be user-declared through table-names-config.primaryKeys (see Issue 1). This is a carryover from the earlier head, not something your latest commits introduced. Because it affects the accuracy of the new incompatible-changes.md entry, I am withdrawing my earlier approval and changing this review to "changes requested"; I think the fix is small.
What Problem Does This PR Solve?
- User pain point: for a table without a primary key, the JDBC CDC sources pick the snapshot split column from a unique key even when it is nullable. Snapshot chunks are range predicates, NULL never matches a range and there is no
IS NULLchunk, so every row with NULL in that column is silently skipped once the table has more than one chunk (#12598). - Fix approach: new
JdbcDataSourceDialect#isColumnNullable(readsIS_NULLABLEfromDatabaseMetaData#getColumns, exact name match, falls back toColumn#isOptional()), used inAbstractJdbcSourceChunkSplitter#getSplitColumnto skip a nullable unique key and to ignore a nullable configuredsnapshotSplitColumn; the existing single-split fallback then reads the table completely. - One-sentence summary: a nullable unique key can no longer silently drop rows from the snapshot.
1. Code Change Review
1.1 Core Logic Analysis
AbstractJdbcSourceChunkSplitter.generateSplits(tableId)
-> getSplitColumn(jdbc, dialect, tableId) [AbstractJdbcSourceChunkSplitter.java:~405]
1) configured snapshotSplitColumn: isColumnNullable(...) -> WARN + fall through [:442] (NEW)
2) primary key first column: isEvenlySplitColumn only [:465] (unchanged, no nullability check)
3) unique keys: isColumnNullable(...) -> WARN + continue [:484] (NEW)
-> splitColumn == null: exactly_once -> UnsupportedOperationException (message reworded) / else single full-table split
-> else splitTableIntoChunks(...) range chunks
JdbcDataSourceDialect.isColumnNullable [JdbcDataSourceDialect.java:139-154]
-> getColumns(catalog, schema, table, column); exact TABLE_NAME + COLUMN_NAME match; IS_NULLABLE == "NO" -> not nullable
-> no matching row -> column.isOptional()
Key findings:
- The normal path reaches the change: every CDC snapshot of a table without a primary key (or with a configured split column) goes through
getSplitColumn. The fix sits at the shared choke point for MySQL, PostgreSQL, Oracle, SQL Server and DB2. - The unique-key and
snapshotSplitColumnbranches are now safe, a NOT NULL unique key still wins over a nullable one, and an empty or unknownIS_NULLABLEis treated as nullable, which is the safe direction. - The primary-key branch is the one path that is not covered (Issue 1).
getPrimaryKeyin every dialect returns the catalog table's key, whichCatalogTableUtils.mergeCatalogTableConfigbuilds fromtable-names-config.primaryKeysand for which a nullable column only produces a WARN (CatalogTableUtils.java:93). - Precise fix for the case it targets; the one blind spot is the user-declared key.
1.2 Compatibility Impact
Partially incompatible, intentional and documented. Options, defaults, serialization and checkpoint formats are unchanged; persisted splits in a restored enumerator state are not regenerated. Tables whose only key is a nullable unique key go from several snapshot splits to one, and with exactly_once = true they now fail at startup with a clear message instead of running and losing rows. That trade-off (loud failure instead of silent loss) is the right one. The documentation of it needs one correction (Issue 1).
1.3 Performance / Side-Effect Analysis
One DatabaseMetaData#getColumns call per candidate key and once for the configured split column, only during split generation. No hot path, no new threads, locks or retries. A nullable unique key with no actual NULLs also loses parallelism; this is documented and I keep it as a known, accepted trade-off (previous Issue 2).
1.4 Error Handling and Logging
The WARN texts now include the remedy, and the exactly-once message names the non-nullable requirement. Formal issues for this head:
Issue 1: A nullable column declared through table-names-config.primaryKeys is still used as the split column, and the new incompatible-changes.md entry says otherwise
- Location:
AbstractJdbcSourceChunkSplitter.java:465-472(primary key branch, no nullability check);docs/en/introduction/concepts/incompatible-changes.md(new entry heading and Description) and the zh counterpart;docs/en/connectors/source/MySQL-CDC.md:485 - Problem: the entry says JDBC CDC sources "no longer split the snapshot on a nullable column", but a column named in
table-names-config.primaryKeysgoes through the primary key branch, which was not touched. The MySQL-CDC page recommends exactly this for "a unique non-primary column" and does not mention NOT NULL, andCatalogTableUtilsonly logs a WARN when that column is nullable. A user following that recipe with a nullable unique column still gets multi-chunk snapshots that skip the NULL rows, silently, and withexactly_once = truethe new startup error does not trigger either. Note that the Migration Guide sentence itself correctly says "non-nullable column"; it is the heading and Description that overstate. - Potential risk: the same silent row loss as #12598 remains for the documented primaryKeys recipe, and the upgrade note gives operators false assurance.
- Best improvement: Option A (consistent behavior): apply
dialect.isColumnNullable(...)to the primary key branch as well and skip it with the same WARN. Be aware this changes behavior for existing jobs that declared a nullable (but NULL-free) column viaprimaryKeyswithexactly_once = true: they would start failing at startup after upgrade, so it needs to be listed in the incompatible-changes entry. Option B (minimal, no behavior change): narrow the heading and Description to "unique keys andsnapshotSplitColumn", state that aprimaryKeyscolumn must be NOT NULL in the database, add that sentence toMySQL-CDC.md(and zh), and log a WARN in the primary key branch when the column is nullable per the metadata so the risk is visible. I lean towards B for this PR and Option A as a follow-up if the maintainers want strictness, but either is fine as long as the docs match the code. - Severity: Medium (documentation contract; blocker until the text is accurate)
- Raised by another reviewer: Yes, +1 to @SEZ9's Issues 1 and 2 (same root cause); the compatibility angle of Option A is my addition.
Issue 2: isColumnNullable falls back to the parsed Column#isOptional() silently when the exact-name match misses
- Location:
JdbcDataSourceDialect.java:147-153 - Problem: the exact
equalsonTABLE_NAME/COLUMN_NAMEis right to filter LIKE over-matches, but if the driver returns a differently cased name thantableId/ the parsed column carry, the method silently returnscolumn.isOptional(), which the Javadoc itself says is unreliable for MySQL. I could not construct a concrete reproduction:tableIdand the column come from the same database's metadata, so the names normally agree. This is therefore hardening rather than a proven bug (a partial overlap with @SEZ9's Issue 3, where I would not go as far as calling it a confirmed regression). - Best improvement: when no exact match is found, log one WARN naming table and column before falling back (so the unreliable path is visible), and optionally accept a case-insensitive match only when no exact match exists. An empty
IS_NULLABLEalready counts as nullable, which is fine. - Severity: Low
- Raised by another reviewer: Partly, @SEZ9 (Issue 3).
Issue 3: The E2E compares ids only
- Location:
AbstractMysqlCDCITBase.java:378-386 - Problem: comparing
idproves that no rows are skipped, which is the point of this PR. The NULL-to-0 conversion that the comment mentions is a pre-existing, separate bug (the PR description says it also happens on binlog events ondevand links #12599), so I do not agree with calling this PR a trade of row loss for value corruption; per the PR description the same coercion already applies to binlog events ondev, so it is not introduced here. Thenamecolumn is not affected by that bug, so comparingid, namewould also verify row content at no cost. - Severity: Low (optional)
- Raised by another reviewer: Partly, @SEZ9 (Issue 4); I would keep it non-blocking because #12599 tracks the root cause.
Issue 4: Javadoc on the new SPI method does not state when it is called and what it costs
- Location:
JdbcDataSourceDialect.java:127-139 - Problem: the Javadoc explains why, but not that it is called for the configured split column and for every unique key during split generation, with one metadata round trip per call, and that dialects may override it. On the cost question (@SEZ9's Issue 6): as @SEZ9 notes, PostgreSQL, SQL Server, Oracle and DB2 build their
Tablefrom JDBC metadata, soisOptional()should already be accurate there and only MySQL strictly needs the lookup (I did not verify each dialect's schema reader independently); the query is however comparable to the existinggetPrimaryKey/getConstraintKeysmetadata calls in the same method and runs once per table, so I would not ask to restructure it in this PR. A one-line note in the Javadoc is enough. - Severity: Low
- Raised by another reviewer: Yes, +1 to @SEZ9 (Issue 5); partial overlap with Issue 6 as described.
2. Code Quality Assessment
2.1 Coding Standards
Good: the guard is small, the comments explain why, no wildcard imports and no new dependency.
2.2 Test Coverage and Test Stability
- Unit tests (
JdbcSourceChunkSplitterTest) now cover the splitter decisions (nullable unique key skipped, NOT NULL key preferred, configured nullable column ignored) and the real defaultisColumnNullableagainst mockedDatabaseMetaData:IS_NULLABLEYES and NO overriding the parsed column, fallback without a metadata row, and LIKE-pattern over-match rejection. The earlier gap (previous Issue 1) is closed. Fixture key columns were made explicitly NOT NULL to model real key columns; I checked that the existing assertions are unchanged, so no test was weakened. - E2E
testMysqlCdcSnapshotWithNullableUniqueKey: pollingawait()on result equality, static data, its own template and tables, runs in both MySQL CDC suites. Stability rating: Stable. - CI on the head: the apache-side
Buildcheck points to the contributor's fork run. There,mysql-cdc-connector-it,oracle-cdc-connector-it, all unit-test legs, code style, license header and the updated-modules shards passed; the only red jobs areelasticsearch-connector-iton JDK 11 and 17 (iterable lengths differ, expected: <11> ...). This PR touches no Elasticsearch code. The failure reproduces on currentdev(the ElasticsearchIT slice tests left un-polled by #12642) and a fix is open as #12711, so this is an inference from the logs and that PR, not something I re-ran. A sync alone will not clear it until #12711 is indev.
2.3 Documentation Updates
en and zh incompatible-changes.md are updated and consistent with each other; only the scope statement needs correcting (Issue 1). If Option B is chosen, docs/en and docs/zh MySQL-CDC.md should get the NOT NULL note too.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix at the single shared choke point, reusing the existing single-split fallback.
3.2 Maintainability
Good: one default SPI method plus two small guards.
3.3 Extensibility
A future IS NULL chunk could reuse the same helper without changing the guard logic.
3.4 Historical-Version Compatibility
No change to checkpoint or state formats or to option names; the behavior change is the documented one.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | primaryKeys-declared nullable column still used for splitting; docs overstate the fix |
AbstractJdbcSourceChunkSplitter.java:465-472, incompatible-changes.md (en/zh), MySQL-CDC.md:485 | Medium (blocker) |
| 2 | Silent fallback to Column#isOptional() on name-match miss |
JdbcDataSourceDialect.java:147-153 | Low |
| 3 | E2E compares ids only | AbstractMysqlCDCITBase.java:378-386 | Low |
| 4 | SPI Javadoc lacks when/cost | JdbcDataSourceDialect.java:127-139 | Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers - must be fixed
- Issue 1: make the documentation match the behavior (Option B at minimum), or guard the primary key branch (Option A) and document the resulting startup failure.
- Recommended fixes - non-blocking
- Issues 2, 3 and 4. They do not block merge because they concern diagnosability, test depth and Javadoc, not the correctness of the skip logic.
Overall assessment: the root cause is correctly identified and fixed in the right place, the tests are now solid, and the compatibility trade-off is sensible. Once the documentation scope is corrected (or the primary key branch is guarded) I do not expect further source-level concerns. Better alternative: none for this PR; an IS NULL chunk is a possible long-term follow-up. I also noted @SEZ9's review is still pending, so the final approval stays with them and the maintainers.
CI / sync: the branch is 17 commits behind dev with no conflicts, and the only red job is the unrelated ElasticsearchIT failure described above; no code change is needed for it. Thanks again for the careful work and the quick turnaround so far!
…lit column and harden the nullability lookup
|
Thanks @DanielLeens and @SEZ9 for the careful re-review. Updated: Primary key configured in
Fallback when the name match misses (Daniel #2, SEZ9 #3). E2E compares ids only (Daniel #3, SEZ9 #4). It now compares Javadoc (Daniel #4, SEZ9 #5). It now says when the method is called (for each candidate split column during split generation), that the default runs one Metadata cost (SEZ9 #6). I kept the lookup in the default method. It is one query per candidate column, only at split generation, next to the existing
|
…eat and the merge order with apache#12597
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks @CodeWithPravinMaske for the fast and thorough follow-up. I re-reviewed the new head 83d6fdf5fd from scratch (full diff, call chain, tests, docs), and I also re-read @SEZ9's review and your reply. All four items from my previous round, and the substantive points from @SEZ9, are addressed in code, tests and docs. I found no source-level blocker on this head. I do have one small documentation carryover that I should have caught earlier, plus two low-severity suggestions.
Sorry for missing this in the last review, that is on me: the "unique non-primary column via table-names-config.primaryKeys" recipe exists not only in MySQL-CDC.md but also in the Oracle and PostgreSQL CDC pages (Issue 1 below). It is a carryover from the earlier heads, not something your latest commit introduced. Also, when I suggested guarding the primary key branch (my earlier Option A) I did not point out that it adds a metadata query on the common real-primary-key path (Issue 2); that is a consequence of my suggestion, not a mistake on your side.
What Problem Does This PR Solve?
- User pain point: for a table without a primary key, the JDBC CDC sources (MySQL, PostgreSQL, Oracle, SQL Server, DB2) pick the snapshot split column from a unique key even when it is nullable. Snapshot chunks are range predicates, NULL never matches a range and there is no
IS NULLchunk, so every row with NULL in that column is silently skipped once the table has more than one chunk (#12598). - Fix approach: new default method
JdbcDataSourceDialect#isColumnNullablereadsIS_NULLABLEfromDatabaseMetaData#getColumns(the parsed Debezium column is wrong for MySQL).AbstractJdbcSourceChunkSplitter#getSplitColumnnow skips a nullable column in all three sources of a split column: configuredsnapshotSplitColumn, the primary key (new in this head, coverstable-names-config.primaryKeys) and unique keys. If nothing usable remains, the existing single-split fallback reads the whole table. - One-sentence summary: a nullable key column can no longer silently drop rows from the CDC snapshot.
1. Code Change Review
1.1 Core Logic Analysis
Complete runtime path at this head:
CDC job start -> SnapshotSplitAssigner.getNext()
-> AbstractJdbcSourceChunkSplitter.generateSplits(tableId) [AbstractJdbcSourceChunkSplitter.java:~68-105]
-> getSplitColumn(jdbc, dialect, tableId) [:~405]
1) configured snapshotSplitColumn: isColumnNullable -> WARN, fall through [:~442]
2) primary key first column: isColumnNullable -> WARN, fall through (NEW) [:~465-475]
else isEvenlySplitColumn -> columnComparable / priority-1 early return
3) unique keys loop: isColumnNullable -> WARN + continue [:~484-495]
-> returns null if nothing safe
-> splitColumn == null:
exactly_once -> UnsupportedOperationException (message now "non-nullable primary key or unique key") [:~90-94]
otherwise -> createSnapshotSplit(...) single full-table split
-> splitColumn != null -> splitTableIntoChunks(...) range chunks
-> JdbcDataSourceDialect.isColumnNullable [JdbcDataSourceDialect.java:~146-175]
-> getColumns(catalog, schema, table, column)
-> exact TABLE_NAME + COLUMN_NAME match -> IS_NULLABLE != "NO"
-> else first case-insensitive match (NEW)
-> else WARN + Column#isOptional() (WARN is NEW)
Before / after of the key change (primary key branch):
// before
if (isEvenlySplitColumn(firstColumn)) { ... }
// after
if (dialect.isColumnNullable(jdbc, tableId, firstColumn)) {
log.warn("Skip primary key {} ... column {} is nullable. " + NULLABLE_SPLIT_COLUMN_HINT, ...);
} else if (isEvenlySplitColumn(firstColumn)) { ... }Key findings:
- The normal path reaches the change: every CDC snapshot goes through
getSplitColumn, so the fix sits at the single shared choke point for all five JDBC CDC dialects. - The previous gap is closed: a nullable column injected through
table-names-config.primaryKeys(whichCatalogTableUtils.mergeCatalogTableConfigturns into the catalog PK, and for which a nullable column only logs a WARN) is now skipped, and the docs say so. This resolves my previous Issue 1 and @SEZ9's Issues 1 and 2. - Name matching is now safe in both directions: exact match wins, a case-insensitive match is only used if no exact row exists, and a total miss logs a WARN naming table and column. This resolves my previous Issue 2 and @SEZ9's Issue 3 (I did not ask for the schema/catalog match in (b); I agree it is not needed given
getColumnsis already called with catalog and schema). - Real primary keys are NOT NULL, so the behavior for real PK tables is unchanged apart from the extra metadata lookup (Issue 2).
- This is a precise fix, not a workaround.
1.2 Compatibility Impact
Partially incompatible, intentional and documented (incompatible-changes.md en/zh, both updated consistently). Option names, defaults, split/checkpoint serialization are unchanged; splits already persisted in a restored enumerator state are not regenerated. Behavior changes for upgraders: (a) a table whose only usable key is nullable now gets one snapshot split instead of several; (b) with exactly_once = true, such a table, or a nullable column configured in primaryKeys, now fails at startup with a clear message instead of running and losing rows. (b) also applies to an existing job whose configured primaryKeys column is nullable in the database but holds no NULLs; the entry states this explicitly. I think trading silent loss for a loud failure is the right call, but it is a visible upgrade-time behavior change, so I would like a maintainer to explicitly sign off on it. I did not verify an upgrade from a released tag, this is based on the code and the docs entry.
1.3 Performance / Side-Effect Analysis
- One extra
DatabaseMetaData#getColumnsround trip per candidate column, only during split generation, never in the read path. No new threads, locks, retries or state. - With the primary key guard this lookup now also happens for every table that has a real primary key (see Issue 2).
- A nullable key with no actual NULLs loses snapshot parallelism (single split). Documented and accepted as the safe direction.
1.4 Error Handling and Logging
WARN texts carry the remedy hint (primaryKeys or snapshotSplitColumn in table-names-config), the exactly-once message names the non-nullable requirement, and the metadata miss is now visible. No exceptions are swallowed; SQLException from the metadata call propagates as before for the other metadata calls in the same method.
Issue 1: The "unique non-primary column via primaryKeys" recipe in the Oracle and PostgreSQL CDC pages does not mention the new NOT NULL requirement
- Location:
docs/en/connectors/source/Oracle-CDC.md:430-432,docs/en/connectors/source/PostgreSQL-CDC.md:300-302, and the zh counterpartsdocs/zh/connectors/source/Oracle-CDC.md,docs/zh/connectors/source/PostgreSQL-CDC.md - Problem description: the guard lives in the shared
connector-cdc-basesplitter, so it applies to Oracle, PostgreSQL, SQL Server and DB2 too. This PR adds the sentence "The column must be NOT NULL in the database ..." only toMySQL-CDC.md(en/zh). The Oracle and PostgreSQL pages carry the identical recipe ("declare it viatable-names-config.primaryKeysand setexactly_once = true") without that note. (I also sawprimaryKeysexamples in DB2-CDC.md and Opengauss-CDC.md; I did not check whether they describe the same recipe.) - Potential risk: a user following the Oracle/PostgreSQL recipe with a nullable unique column hits a startup failure (
exactly_once = true) that is only explained in the MySQL page and inincompatible-changes.md. - Best improvement: copy the one-sentence NOT NULL note to the Oracle and PostgreSQL pages (en and zh) where the same recipe appears; no code change needed.
- Severity: Medium (documentation completeness; I would like to see it in this PR since it is a three-line change, but it does not affect correctness of the fix)
- Raised by another reviewer: No (carryover omitted from my previous review).
Issue 2: The metadata query now also runs for tables with a real primary key
- Location:
AbstractJdbcSourceChunkSplitter.java:~465-475andJdbcDataSourceDialect.java:~146-175 - Problem description: before this head, a table with a real PK needed no extra query in
getSplitColumn. Now each such table pays onegetColumnscall at split generation, although real PK columns are NOT NULL by definition and only a user-configuredprimaryKeyscolumn can be nullable. On OraclegetColumnsis a comparatively slow dictionary query, and a job with thousands of captured tables repeats it at every start. Related to @SEZ9's earlier cost point (their Issue 6), but this head widens it from "per unique key" to "per table". - Potential risk: slower job start on very wide table lists; I did not measure it, and
getSplitColumnalready issues other per-table queries (unique keys, min/max, count), so I expect it to be modest. Not a correctness risk. - Best improvement: keep as is and accept the cost, or (Option A) fetch
getColumns(catalog, schema, table, null)once per table ingetSplitColumnand reuse it for the configured column, the PK and all unique keys; (Option B) let dialects with a cheaper source overrideisColumnNullable, which your Javadoc already allows. I would not block the PR on this. - Severity: Low
- Raised by another reviewer: Partly (@SEZ9's Issue 6 on query cost; I agreed it did not need restructuring for the unique-key case, and I am keeping it non-blocking here).
Issue 3: Logger created inline in a default interface method
- Location:
JdbcDataSourceDialect.java:~170-175(LoggerFactory.getLogger(JdbcDataSourceDialect.class).warn(...)) - Problem description: Lombok
@Slf4jis not available on an interface, so the inline lookup is understandable, but it does a logger lookup on every miss. A smallLogger LOG = LoggerFactory.getLogger(...)constant, or logging the miss in the callerAbstractJdbcSourceChunkSplitter(which has@Slf4jand already hastableIdand the column), is a cleaner pattern. - Potential risk: none functionally; style only.
- Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
Good: comments explain why (NULL never matches a range predicate, primaryKeys may name a nullable column, LIKE-pattern over-match), the SPI Javadoc now states when the method is called, its cost and that dialects may override it, no wildcard imports and no new dependency.
2.2 Test Coverage and Test Stability
- New unit tests:
splitColumnSkipsNullableConfiguredPrimaryKey(turns red if the PK guard is removed: it would returnnullable_intinstead of null),splitColumnPrefersNotNullUniqueKeyOverNullablePrimaryKey,isColumnNullableMatchesNameIgnoringCaseWithoutExactRow(red without the case-insensitive match). I checked the existing assertions inJdbcSourceChunkSplitterTestare unchanged, so nothing was weakened. The configured-primary-key path is covered at unit level only; the MySQL E2E exercises the unique-key path, which is acceptable. - E2E
testMysqlCdcSnapshotWithNullableUniqueKeynow comparesid, name, which also verifies row content; it polls withawait()on static data and runs in both MySQL CDC suites. Stability rating: Stable. - CI of the current head: the apache-side
Buildcheck is only a pointer; the real run is in the contributor's fork (run 38211912002 on83d6fdf5fd), which is still in progress at the time of this review (34 jobs green so far, several IT jobs pending). One job is red:updated-modules-integration-test-part-2 (11), caused by a single error,PostgresCDCIT.testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes(expected: <1> but was: <0>atPostgresCDCIT.java:625-628, a committed-offset check, not a snapshot split assertion). The other PostgresCDCIT cases in that job, including thecustom_primary_keyones that exercise the new PK branch, passed. This is the known flaky committed-offset test also mentioned in your reply (#12261); my conclusion is an inference from the logs, I did not re-run it. The earlierelasticsearch-connector-itfailure is addressed ondevby #12711 (already merged), and the Elasticsearch job on this head is still running. A sync withdevis not required for those; once the fork run finishes, a rerun of only the failed job should clear the Postgres flake.
2.3 Documentation Updates
incompatible-changes.md (en/zh) and MySQL-CDC.md (en/zh) are updated and consistent with the code. Only the Oracle/PostgreSQL pages are missing the note (Issue 1).
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix at the single shared choke point, reusing the existing single-split fallback.
3.2 Maintainability
Good: one default SPI method and three small symmetric guards.
3.3 Extensibility
A future IS NULL chunk could reuse the same helper without touching the guard logic; the root NULL-to-0 coercion in MySQL (#12599 / #12608) stays correctly separate.
3.4 Historical-Version Compatibility
No change to option names, defaults, checkpoint or split state formats; the only behavior change is the documented one (see 1.2).
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | Oracle/PostgreSQL CDC docs (en/zh) lack the NOT NULL note for the primaryKeys recipe |
Oracle-CDC.md:430, PostgreSQL-CDC.md:300 | Medium (non-blocking) |
| 2 | Metadata query now also runs for real-PK tables | AbstractJdbcSourceChunkSplitter.java:~465, JdbcDataSourceDialect.java:~146 | Low |
| 3 | Inline logger lookup in default interface method | JdbcDataSourceDialect.java:~170 | Low |
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers - must be fixed
- None on the source side. All issues from my previous round are closed.
- Recommended fixes - non-blocking
- Issue 1 (add the NOT NULL sentence to the Oracle and PostgreSQL pages, en and zh), Issues 2 and 3. They concern documentation completeness, a small startup cost and style, not the correctness of the skip logic.
Regarding other reviewers: @SEZ9's review is still COMMENTED with final approval pending; I checked each of their six points against this head and they are all either fixed or deliberately kept (the per-candidate metadata query, which I consider acceptable). I am replacing my earlier CHANGES_REQUESTED conclusion: the source blocker from my previous round is closed on my side. Because I only have read-only review rights here, the old entry may still show in GitHub's summary and a maintainer with write access may need to do the final approve or dismiss step. Remaining gate: the fork CI run on this head must finish green (the Postgres committed-offset check is the only red job so far and looks like the known flake), then final maintainer approval, including the explicit sign-off on the exactly_once startup-failure behavior noted in 1.2.
Better alternative: none for this PR. Thanks again for the careful work and the quick turnaround!
…ys in the Oracle and PostgreSQL CDC docs
|
Thanks @DanielLeens for the re-review!
|
…c-nullable-unique-key-split
|
Thanks @DanielLeens for the re-review!
|
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks @CodeWithPravinMaske for the quick follow-up, and for the clear answers to my last round. I re-reviewed the new head 4a0cc3d2e2 from scratch (full diff against dev, call chain, tests, docs, CI). (1) The NOT NULL sentence is now in the Oracle and PostgreSQL CDC pages (en and zh), so my Issue 1 is closed. (2) Keeping one getColumns call per table in getSplitColumn is reasonable, given the other per-table metadata and min/max queries in the same method and the documented override point; I agree it does not need to change in this PR. (3) Your reasoning on the inline logger (no private field on an interface, and a constant would widen the SPI) is fair, so I withdraw that style point. The head moved from 83d6fdf5fd only by the docs commit 14f57ff277 plus a merge of dev (4a0cc3d2e2); I re-checked that the merge did not touch the PR's own files. I also noticed the same reply comment was posted twice; that is harmless.
What Problem Does This PR Solve?
- User pain point: for a table without a primary key, the JDBC CDC sources pick the snapshot split column from a unique key even when it is nullable. Chunk predicates are range queries, NULL never matches them and there is no
IS NULLchunk, so rows with NULL in that column are silently skipped once the table has more than one chunk (#12598). - Fix approach: new default
JdbcDataSourceDialect#isColumnNullablereadsIS_NULLABLEfromDatabaseMetaData#getColumns;AbstractJdbcSourceChunkSplitter#getSplitColumnskips a nullable column in all three sources (configuredsnapshotSplitColumn, first primary-key column, unique keys) and the existing single-split fallback reads the table completely. - Summary: a nullable key column can no longer silently drop rows from the CDC snapshot.
1. Code Change Review
SnapshotSplitAssigner.getNext()
-> AbstractJdbcSourceChunkSplitter.generateSplits(tableId)
-> getSplitColumn(jdbc, dialect, tableId)
1) configured snapshotSplitColumn -> isColumnNullable -> WARN, fall through
2) primary key first column -> isColumnNullable -> WARN, fall through
3) unique keys loop -> isColumnNullable -> WARN + continue
-> null when nothing safe remains
-> null: exactly_once -> UnsupportedOperationException (message now says "non-nullable")
otherwise -> createSnapshotSplit(...) single full-table split
-> else splitTableIntoChunks(...)
JdbcDataSourceDialect.isColumnNullable: exact name match -> case-insensitive match -> WARN + Column#isOptional()
- The normal path reaches the change: every JDBC CDC snapshot goes through
getSplitColumn, so this is the single shared choke point for MySQL, PostgreSQL, Oracle, SQL Server and DB2. - Real primary keys are NOT NULL, so tables with a real PK keep their split column; only user-configured nullable keys and nullable unique keys change behavior.
- The
getColumnsname/pattern handling is safe: LIKE-pattern over-matches are filtered by exact name, a case-insensitive match is used only when no exact row exists, and a total miss is logged before falling back. No exception is swallowed. - Compatibility: no option names, defaults, or split/checkpoint serialization change. The only behavior change is the documented one in
incompatible-changes.md(en/zh): such tables get one snapshot split, and withexactly_once = truethey fail at startup with a clear message instead of losing rows. This is intentional and written down; I did not verify an upgrade from a released tag, this is based on the code and the docs entry. A maintainer may still want to explicitly acknowledge theexactly_oncestartup-failure behavior. - Performance: one extra metadata query per candidate column, only at split generation, never in the read path; no new threads, locks or state.
2. Tests and CI
- Unit tests in
JdbcSourceChunkSplitterTestcover the nullable unique key, preferring a NOT NULL unique key over a nullable one, a nullable configured split column, a nullable configured primary key, and the metadata lookup (YES/NO, fallback, LIKE over-match, case-insensitive match). They would turn red if the corresponding guard were removed. I compared the existing assertions withdevand none were weakened. - E2E
testMysqlCdcSnapshotWithNullableUniqueKey(runs in both MySQL CDC suites) now comparesid, nameon static data; the NULL-to-0 value issue is separate (#12599 / #12608). - CI on the current head: the fork run
38283116775for4a0cc3d2e2completed withsuccess(75 jobs, none failed or cancelled), and the apache-sideBuild,labelerandNotify test workflowchecks are all green. The earlier redPostgresCDCITcommitted-offset job and the Elasticsearch failure no longer appear on this head. - The branch is 0 commits behind
dev(ahead 8).
3. Summary
| # | Issue | Severity | Status |
|---|---|---|---|
| 1 | Oracle/PostgreSQL docs missing the NOT NULL note | Medium | Fixed in 14f57ff277 |
| 2 | Extra metadata query for real-PK tables | Low | Accepted, non-blocking |
| 3 | Inline logger in default interface method | Low | Accepted, non-blocking |
Conclusion: Ready to merge
- Blockers - must be fixed
- None. My earlier
CHANGES_REQUESTEDwas cleared on the previous head; the only item left was CI, which is now green on this head, so I am approving.
- None. My earlier
- Recommended follow-up (optional, separate PR)
- If startup time on very large table lists becomes a concern, fetch the columns once per table, as you offered.
Thanks again for the careful work and the quick turnaround!
|
@CodeWithPravinMaske thanks for the update. Guarding the primary-key branch in A few items from the earlier review aren't mentioned in your update:
Happy to do a final pass once those are in — or let me know if you think any of them shouldn't be. |
|
Thanks @SEZ9! All of these are in the current head ( |
|
Thanks for the detailed rundown, @CodeWithPravinMaske. I'd like to confirm each point against the code in
Once I can verify these in the diff and the E2E comment is in, I'm happy to approve. |
davidzollo
left a comment
There was a problem hiding this comment.
Thank you @CodeWithPravinMaske for this contribution, and for making sure a nullable column is never used as the snapshot split key, which closes a subtle correctness gap in CDC snapshot splitting. Thanks also for responding so promptly to the review feedback.
CI is green on the current head and the code-side review has no remaining blockers, so I am approving. Really appreciate the time and care you put into this PR - contributions like this make SeaTunnel better for everyone. Looking forward to more from you!
|
Please ignore the following message if you have joined in the Slack~ To facilitate focused communication among contributors, we’ve created a brand-new dedicated #contributors channel in official Slack workspace. This channel is designed for technical discussions, feature design brainstorming, roadmap sync and direct communication with project core Contributors. Everyone who contributes code, docs, test cases or community ideas is warmly invited to join, share thoughts and collaborate together under The Apache Way. Welcome to join 😄 |
Closes #12598
Purpose of this pull request
For a table without a primary key, the JDBC CDC sources take the snapshot split column from a unique key, even when that column is nullable. The snapshot chunks are range queries (
col <= ?,col >= ? AND col <= ?,col >= ?), NULL never matches a range, and there is noIS NULLchunk, so every row with NULL in the split column is silently skipped once the table has more than one chunk.Reproduced on MySQL 8.0 (
dev): table without a primary key, nullableUNIQUE KEY (code), 1000 rows with a code plus 100 rows withcode IS NULL,snapshot.split.size = 100→ 1000 of 1100 rows reach the sink, no error.For MySQL, the nullability on the parsed schema cannot be trusted here: Debezium 1.9.8 promotes the first
UNIQUE KEYof a table without a primary key to a primary key and marks its columns NOT NULL (MySqlAntlrDdlParser#parsePrimaryIndexColumnNames).Changes
JdbcDataSourceDialect#isColumnNullable: new default method that readsIS_NULLABLEfromDatabaseMetaData#getColumns(exact table/column match, then a case-insensitive match), falling back to the parsed column with a WARN when the metadata does not describe it. Standard JDBC, so it works for all JDBC CDC dialects.AbstractJdbcSourceChunkSplitter#getSplitColumn: skips a nullable column as the split column, whether it is the first column of a unique key, a configuredsnapshotSplitColumn, or a primary key configured intable-names-config.primaryKeys(real primary keys are NOT NULL, so they are unaffected), with a WARN log. If no non-nullable key column remains, the existing single-split fallback reads the whole table.... not found non-nullable primary key or unique key ....The change is in
connector-cdc-base, so it covers MySQL, PostgreSQL, Oracle, SQL Server and DB2 CDC.Does this PR introduce any user-facing change?
Yes, a bug fix with a behavior change, documented in
incompatible-changes.md(en/zh):exactly_once = true, such a table now fails at startup with a clear message instead of running and losing rows. This also applies to a job whose configuredtable-names-config.primaryKeyscolumn is nullable in the database. Declaring a NOT NULL key (or a non-nullablesnapshotSplitColumn/primaryKeys) keeps parallel snapshot reading.How was this patch tested?
JdbcSourceChunkSplitterTest, extended): a nullable unique key is skipped (single split), a non-null unique key is preferred over a nullable one, a nullable configured split column is ignored, a nullable configured primary key is skipped (and a NOT NULL unique key is used instead), and the metadata lookup is tested forIS_NULLABLEYES/NO, the fallback, the LIKE-pattern over-match and a case-insensitive name match. The fixture key columns are now explicitly NOT NULL, as primary key columns are in real databases. Without the fix the three new tests fail (expected: <null> but was: <nullable_int>).AbstractMysqlCDCITBase#testMysqlCdcSnapshotWithNullableUniqueKey, runs inMysqlCDCITandMysql8_4CDCIT): 30-row table without a primary key, nullable unique key with 10 NULL rows,snapshot.split.size = 5; asserts every source row (id,name) reaches the sink.MysqlCDCITpassed on all 5 PR containers locally; with the fix reverted it fails on all 5 withexpected: <30> but was: <20>(the 10 NULL rows are missing).Skip unique key uk_code of table shop.no_pk_orders as snapshot split column: column code is nullable.Related, not in this PR: the same Debezium promotion makes MySQL-CDC emit
0instead ofNULLfor that column (also on binlog events ondev). Reported separately in #12599; the E2E above compares row ids only for that reason.Check list
New License Guide — N/A, no new jar.
incompatible-changes.mdto describe the incompatibility caused by this PR. — Done (en/zh).