Skip to content

[Fix][Connector-V2][CDC] Do not use a nullable column as the snapshot split column - #12597

Merged
davidzollo merged 8 commits into
apache:devfrom
CodeWithPravinMaske:fix/cdc-nullable-unique-key-split
Oct 14, 2026
Merged

davidzollo merged 8 commits into
apache:devfrom
CodeWithPravinMaske:fix/cdc-nullable-unique-key-split

Conversation

@CodeWithPravinMaske

@CodeWithPravinMaske CodeWithPravinMaske commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

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 no IS NULL chunk, 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, nullable UNIQUE KEY (code), 1000 rows with a code plus 100 rows with code 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 KEY of 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 reads IS_NULLABLE from DatabaseMetaData#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 configured snapshotSplitColumn, or a primary key configured in table-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.
  • The exactly-once error now says ... 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):

  • Tables whose only key is a nullable unique key are now read completely, as a single snapshot split instead of several.
  • With 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 configured table-names-config.primaryKeys column is nullable in the database. Declaring a NOT NULL key (or a non-nullable snapshotSplitColumn / primaryKeys) keeps parallel snapshot reading.

How was this patch tested?

  • Unit tests (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 for IS_NULLABLE YES/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>).
  • E2E (AbstractMysqlCDCITBase#testMysqlCdcSnapshotWithNullableUniqueKey, runs in MysqlCDCIT and Mysql8_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. MysqlCDCIT passed on all 5 PR containers locally; with the fix reverted it fails on all 5 with expected: <30> but was: <20> (the 10 NULL rows are missing).
  • Manual, real MySQL 8.0: the 1100-row reproduction above now delivers all 1100 rows; the log shows 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 0 instead of NULL for that column (also on binlog events on dev). Reported separately in #12599; the E2E above compares row ids only for that reason.

Check list

  • If any new Jar binary package adding in your PR, please add License Notice according
    New License Guide — N/A, no new jar.
  • If necessary, please update the documentation to describe the new feature. — N/A, bug fix.
  • If necessary, please update incompatible-changes.md to describe the incompatibility caused by this PR. — Done (en/zh).
  • If you are contributing the connector code, please check that the following files are updated: — N/A, fix to existing connectors.

@CodeWithPravinMaske CodeWithPravinMaske changed the title [Bug][Connector-V2][CDC] Snapshot silently skips rows when a table without a primary key is split by a nullable unique key [Fix][Connector-V2][CDC] Do not use a nullable column as the snapshot split column Oct 1, 2026

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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_NAME is the right call because getColumns treats these arguments as LIKE patterns (_ and % would otherwise over-match).
  • Reading IS_NULLABLE from 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 = true such 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 in incompatible-changes.md en and zh, with migration guidance.
  • The same snapshotSplitColumn pointing 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#getColumns call 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 override isColumnNullable returning column.isOptional()), production code at JdbcDataSourceDialect.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_NAME form) 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 to Column#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 snapshotSplitColumn to 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 extra IS NULL chunk 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-444 and :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 documented expected: <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: testMysqlCdcSnapshotWithNullableUniqueKey in AbstractMysqlCDCITBase (so it runs in MysqlCDCIT and Mysql8_4CDCIT), 30 rows, 10 NULL codes, snapshot.split.size = 5, compares row ids via await().atMost(60000). It is a polling assertion on result equality (no fixed Thread.sleep), the data set is static, and the DDL is isolated in its own nullable_unique_key template 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

  1. Blockers - must be fixed: none from the code side. The only open item is CI (see below).
  2. 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.

@CodeWithPravinMaske

Copy link
Copy Markdown
Contributor Author

Thanks a lot for the detailed review, @DanielLeens!

  • Issue 1: added unit tests for the default JdbcDataSourceDialect#isColumnNullable with a mocked DatabaseMetaData: IS_NULLABLE=YES / NO, the fallback to Column#isOptional() when no row matches, and a row matched only by the LIKE pattern (noXpk for no_pk) that must be ignored. With the exact-name check removed, the pattern test fails.
  • Issue 3: the WARN messages now say how to restore parallel snapshot reading (declare a NOT NULL unique column or configure a non-nullable snapshotSplitColumn).
  • Issue 2: agreed, I kept the schema-based check in this PR since a data-dependent probe or an IS NULL chunk has snapshot/binlog consistency implications. Happy to look at an IS NULL chunk as a follow-up.

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
@CodeWithPravinMaske

Copy link
Copy Markdown
Contributor Author

CI note: the remaining red jobs are unrelated to this PR: elasticsearch-connector-it fails the same way on #12608 since dev brought in #12642 (ElasticsearchIT slice tests read 0/10 of 11 rows); PostgresCDCIT.testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes is the known flaky committed-offset check (#12261), not snapshot splitting; and FlussSourceIT timed out. The splitter unit tests and MySQL/Oracle CDC E2E tests pass.

@SEZ9 SEZ9 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 no IS NULL chunk, 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 at JdbcDataSourceDialect.java:139-154 reads IS_NULLABLE via DatabaseMetaData#getColumns with exact TABLE_NAME/COLUMN_NAME match, falling back to column.isOptional()), and in AbstractJdbcSourceChunkSplitter#getSplitColumn skip a nullable unique-key column (:484 if (dialect.isColumnNullable(jdbc, tableId, firstColumn)) → WARN + continue) and ignore a nullable configured snapshotSplitColumn (:442) with a WARN, so the existing null-split fallback at :89-101 reads the table as one split; exactly-once error text updated at :93; unit tests, a MySQL E2E (nullable_unique_key template) and incompatible-changes docs (en/zh) added.
  • One-line summary: The core idea is right and the unique-key and snapshotSplitColumn paths are now safe for all JDBC CDC dialects, but the guard is not applied to the primary-key branch (AbstractJdbcSourceChunkSplitter.java:465-472 calls isEvenlySplitColumn(firstColumn) with no nullability check), so a nullable column injected via table-names-config.primaryKeys still drops NULL rows despite the migration guide recommending exactly that option; a metadata miss silently falls back to the unreliable Column#isOptional() with no log; and the new E2E compares id only (AbstractMysqlCDCITBase.java:378-386) because NULL codes arrive at the sink as 0, 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 takes table.columnWithName(primaryKey.get().getColumnNames().get(0)) and returns it after isEvenlySplitColumn with no nullability check.
  • In all five dialects getPrimaryKey reads tableMap.get(tableId).getTableSchema().getPrimaryKey() (MySqlDialect.java:130, PostgresDialect.java:221, OracleDialect.java:127, SqlServerDialect.java:158, Db2Dialect.java:164). That catalog PK is what CatalogTableUtils.mergeCatalogTableConfig builds from table-names-config.primaryKeys; when the named column is nullable it only logs Primary key({}) is nullable for catalog table {} (CatalogTableUtils.java:93) and flips the catalog column to non-nullable — the database still reports IS_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 sets primaryKeys to the nullable unique column gets exactly the same silent NULL-row loss this PR sets out to fix, while the heading at :8-10 claims 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 and exactly_once is enabled), and state in the docs that a primaryKeys column 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 configure table-names-config.primaryKeys/snapshotSplitColumn with 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 resolve getPrimaryKey from the catalog table, and CatalogTableUtils.mergeCatalogTableConfig lets table-names-config.primaryKeys name a nullable column (it only WARNs and flips the catalog column to non-nullable; the DB metadata still says IS_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 via primaryKeys — and the incompatible-changes entry says we "no longer split on a nullable column" while recommending exactly that option. Please apply dialect.isColumnNullable(jdbc, tableId, firstColumn) in the PK branch as well (skip with WARN, or fail fast when the PK was user-configured and exactly_once is 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 snapshotSplitColumn branch (AbstractJdbcSourceChunkSplitter.java:442) and the unique-key loop (:484). The primary-key branch at :465-472 is untouched. In every shipped dialect (MySqlDialect.java:130, PostgresDialect.java:221, OracleDialect.java:127, SqlServerDialect.java:158, Db2Dialect.java:164) getPrimaryKey returns tableMap.get(tableId).getTableSchema().getPrimaryKey(), i.e. the catalog table into which CatalogTableUtils.mergeCatalogTableConfig injects the user-configured primaryKeys, forcing the column to non-nullable with only a WARN (CatalogTableUtils.java:93).
  • The heading at docs/en/introduction/concepts/incompatible-changes.md:8-10 says nullable columns are "no longer used as the snapshot split column" for all JDBC CDC sources, and the Migration Guide at :13 recommends table-names-config.primaryKeys as a way to keep parallel reading. Both statements are only true for the unique-key and snapshotSplitColumn paths; a nullable primaryKeys column 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 snapshotSplitColumn only and that a primaryKeys column must genuinely be NOT NULL in the database. The zh copy at docs/zh/introduction/concepts/incompatible-changes.md:12 needs the same change.
  • Evidence: docs/en/introduction/concepts/incompatible-changes.md:13 - **Migration Guide**: Declare a NOT NULL unique column, or configure table-names-config.primaryKeys/snapshotSplitColumn with 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 from snapshotSplitColumn) 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: getSplitColumn only calls dialect.isColumnNullable on the snapshotSplitColumn branch (:442) and in the unique-key loop (:484); the primary-key branch at :465-472 is unchanged, and every dialect's getPrimaryKey returns the catalog-table PK that CatalogTableUtils.mergeCatalogTableConfig builds from primaryKeys (forcing the column to non-nullable with just a WARN at CatalogTableUtils.java:93). So a nullable primaryKeys column 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 and snapshotSplitColumn only and that a primaryKeys column must genuinely be NOT NULL in the database (same fix in docs/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-148 compare tableId.table() / column.name() with case-sensitive equals against the metadata strings, and :153 returns column.isOptional() when nothing matched. On MySQL with lower_case_table_names=1 (default on Windows/macOS, common in Docker images configured that way) a table configured as db.MyTable is stored and returned by getColumns as mytable; 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 returns column.isOptional().
  • The Javadoc at :130-131 itself states that for a MySQL PK-less table the parsed column of a nullable unique key is reported as not optional, so the fallback returns false in 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_NULLABLE string for "unknown"; :149 treats anything but NO as 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 on storesLowerCaseIdentifiers()/storesUpperCaseIdentifiers()),
  • (b) also match TABLE_SCHEM/TABLE_CAT against the non-null parts of tableId, 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 equals on TABLE_NAME/COLUMN_NAME means that on MySQL with lower_case_table_names=1 (table configured as MyTable, metadata returns mytable) or on Oracle with unquoted identifiers, we fall through to column.isOptional() — which the Javadoc above says is exactly the value we cannot trust, and which is false for a Debezium-promoted unique key. The data loss then comes back silently. Could we (a) match case-insensitively when !metaData.supportsMixedCaseIdentifiers() (or based on storesLowerCaseIdentifiers()/storesUpperCaseIdentifiers()), (b) also check TABLE_SCHEM/TABLE_CAT against the non-null part of tableId, and (c) log a WARN with table/column whenever this fallback is taken? An empty IS_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-379 states 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-386 runs select id from ... order by id on source and sink and compares only that. The source DDL (nullable_unique_key.sql:29) declares code int DEFAULT NULL and the inserts include 10 rows with NULL code.
  • Root cause is the same one the PR description identifies: Debezium's MySqlAntlrDdlParser promotes 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 treats code as non-optional and NULL values are coerced to the type default 0. 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 = 0 instead 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, name so row content is verified and reference a follow-up issue for the NULL→0 coercion; ideally fix MySqlSchema to clear the promoted PK / restore optional=true when the catalog reports no primary key, which would also make Column#isOptional() trustworthy for isColumnNullable.
  • 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:29 code int 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 (MySqlSchema only 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 compare id, name here so the row content is verified, and link a follow-up issue for the NULL→0 coercion? Ideally MySqlSchema should clear the promoted PK / restore optional=true when the catalog reports no primary key, which would also make Column#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:139 is a public SPI extension on the dialect interface. The Javadoc at :127-138 explains the MySQL motivation and the return value well, but not the contract: it is invoked from AbstractJdbcSourceChunkSplitter.getSplitColumn once for the configured snapshotSplitColumn (:442) and once per unique key (:484) during split generation, and each call runs a getColumns metadata query (:141-144).
  • All five shipped dialects already hold a tableMap of CatalogTables (the same map getPrimaryKey reads 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/@implNote describing when the method is called, that the default performs one DatabaseMetaData#getColumns lookup 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.getSplitColumn for the configured snapshotSplitColumn and for every unique key of every table during split generation, and the default issues a DatabaseMetaData#getColumns query on each call. A one-liner that dialects which already hold a CatalogTable map (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: - isColumnNullable issues metaData.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), inside generateSplits, which runs sequentially in the enumerator for each captured table.
  • For PostgreSQL, Oracle, SQL Server and DB2 the Debezium Table is built by JdbcConnection#readSchema from JDBC metadata, so Column#isOptional() already reflects IS_NULLABLE and the extra query is redundant; only MySQL's DDL-parsed schema has the unique-key promotion problem the Javadoc describes.
  • Oracle's getColumns is a notoriously slow dictionary query (ALL_TAB_COLUMNS joins), 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 into MySqlDialect, or fetch getColumns(catalog, schema, table, null) once per table in getSplitColumn and 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 getColumns call runs once per candidate key per table from the splitter loop. For PostgreSQL/Oracle/SQL Server/DB2 the Debezium Table already comes from JdbcConnection#readSchema, so column.isOptional() is the metadata value and the query is redundant — only MySQL's DDL-parsed schema has the promotion problem. On Oracle getColumns is a slow dictionary query, so multi-table jobs with several unique indexes will pay for it at every start. Consider keeping the default as column.isOptional() and putting this metadata lookup in MySqlDialect, or fetching getColumns(..., 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 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
  • 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
  • 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
  • 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
  • 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
  • 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

Thanks for the updates so far. Happy to discuss the remaining points.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @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 NULL chunk, 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 (reads IS_NULLABLE from DatabaseMetaData#getColumns, exact name match, falls back to Column#isOptional()), used in AbstractJdbcSourceChunkSplitter#getSplitColumn to skip a nullable unique key and to ignore a nullable configured snapshotSplitColumn; 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 snapshotSplitColumn branches are now safe, a NOT NULL unique key still wins over a nullable one, and an empty or unknown IS_NULLABLE is treated as nullable, which is the safe direction.
  • The primary-key branch is the one path that is not covered (Issue 1). getPrimaryKey in every dialect returns the catalog table's key, which CatalogTableUtils.mergeCatalogTableConfig builds from table-names-config.primaryKeys and 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.primaryKeys goes 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, and CatalogTableUtils only 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 with exactly_once = true the 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 via primaryKeys with exactly_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 and snapshotSplitColumn", state that a primaryKeys column must be NOT NULL in the database, add that sentence to MySQL-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 equals on TABLE_NAME / COLUMN_NAME is right to filter LIKE over-matches, but if the driver returns a differently cased name than tableId / the parsed column carry, the method silently returns column.isOptional(), which the Javadoc itself says is unreliable for MySQL. I could not construct a concrete reproduction: tableId and 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_NULLABLE already 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 id proves 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 on dev and 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 on dev, so it is not introduced here. The name column is not affected by that bug, so comparing id, name would 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 Table from JDBC metadata, so isOptional() 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 existing getPrimaryKey / getConstraintKeys metadata 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 default isColumnNullable against mocked DatabaseMetaData: IS_NULLABLE YES 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: polling await() 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 Build check 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 are elasticsearch-connector-it on JDK 11 and 17 (iterable lengths differ, expected: <11> ...). This PR touches no Elasticsearch code. The failure reproduces on current dev (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 in dev.

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

  1. 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.
  2. 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!

@github-actions github-actions Bot removed the reviewed label Oct 10, 2026
…lit column and harden the nullability lookup
@CodeWithPravinMaske

Copy link
Copy Markdown
Contributor Author

Thanks @DanielLeens and @SEZ9 for the careful re-review. Updated:

Primary key configured in table-names-config.primaryKeys (Daniel #1, SEZ9 #1/#2). I went with guarding the primary key branch too (Daniel's Option A), so the docs and the code say the same thing.

  • getSplitColumn now runs the same isColumnNullable check on the first primary key column. It skips the column with a WARN, then the unique keys are tried, then the single-split fallback is used. Real primary keys are NOT NULL in the database, so only a user-configured nullable key is affected.
  • This also closes the exactly-once concern Daniel raised on [Fix][Connector-V2][MySQL-CDC] Keep NULL in nullable unique key columns of tables without a primary key #12608: with this PR, a NULL can never be in the split key.
  • The behavior change Daniel pointed out (a job with exactly_once = true and a nullable configured primaryKeys column now fails at startup, even if the column holds no NULLs) is written in incompatible-changes.md (en/zh). The exactly-once error now says not found non-nullable primary key or unique key.
  • The MySQL-CDC docs (en/zh) now say that a column declared via table-names-config.primaryKeys must be NOT NULL in the database.
  • New tests: splitColumnSkipsNullableConfiguredPrimaryKey and splitColumnPrefersNotNullUniqueKeyOverNullablePrimaryKey. Both fail without the guard.

Fallback when the name match misses (Daniel #2, SEZ9 #3). isColumnNullable keeps the exact match first, then accepts a case-insensitive match, and logs a WARN naming the table and column before falling back to the parsed column. An empty IS_NULLABLE still counts as nullable, the safe direction. New test: isColumnNullableMatchesNameIgnoringCaseWithoutExactRow (it fails without the case-insensitive match).

E2E compares ids only (Daniel #3, SEZ9 #4). It now compares id, name. On the NULL -> 0 value itself: that is the pre-existing bug tracked in #12599 and fixed in #12608 (it also happens on binlog events on dev), so it's kept separate from this PR. The test comment links #12599.

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 DatabaseMetaData#getColumns query per call, and that a dialect may override it.

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 getPrimaryKey / getUniqueKeys metadata calls of the same method. As Daniel noted, it doesn't need restructuring in this PR, and a dialect with a cheaper source can override it.

JdbcSourceChunkSplitterTest (13) and AbstractJdbcSourceChunkSplitterTest (3) pass. CI: the ElasticsearchIT failures come from dev (#12711).

CodeWithPravinMaske added a commit to CodeWithPravinMaske/seatunnel that referenced this pull request Oct 12, 2026

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @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 NULL chunk, 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#isColumnNullable reads IS_NULLABLE from DatabaseMetaData#getColumns (the parsed Debezium column is wrong for MySQL). AbstractJdbcSourceChunkSplitter#getSplitColumn now skips a nullable column in all three sources of a split column: configured snapshotSplitColumn, the primary key (new in this head, covers table-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 (which CatalogTableUtils.mergeCatalogTableConfig turns 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 getColumns is 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#getColumns round 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 counterparts docs/zh/connectors/source/Oracle-CDC.md, docs/zh/connectors/source/PostgreSQL-CDC.md
  • Problem description: the guard lives in the shared connector-cdc-base splitter, 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 to MySQL-CDC.md (en/zh). The Oracle and PostgreSQL pages carry the identical recipe ("declare it via table-names-config.primaryKeys and set exactly_once = true") without that note. (I also saw primaryKeys examples 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 in incompatible-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-475 and JdbcDataSourceDialect.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 one getColumns call at split generation, although real PK columns are NOT NULL by definition and only a user-configured primaryKeys column can be nullable. On Oracle getColumns is 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 getSplitColumn already 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 in getSplitColumn and reuse it for the configured column, the PK and all unique keys; (Option B) let dialects with a cheaper source override isColumnNullable, 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 @Slf4j is not available on an interface, so the inline lookup is understandable, but it does a logger lookup on every miss. A small Logger LOG = LoggerFactory.getLogger(...) constant, or logging the miss in the caller AbstractJdbcSourceChunkSplitter (which has @Slf4j and already has tableId and 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 return nullable_int instead of null), splitColumnPrefersNotNullUniqueKeyOverNullablePrimaryKey, isColumnNullableMatchesNameIgnoringCaseWithoutExactRow (red without the case-insensitive match). I checked the existing assertions in JdbcSourceChunkSplitterTest are 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 testMysqlCdcSnapshotWithNullableUniqueKey now compares id, name, which also verifies row content; it polls with await() on static data and runs in both MySQL CDC suites. Stability rating: Stable.
  • CI of the current head: the apache-side Build check is only a pointer; the real run is in the contributor's fork (run 38211912002 on 83d6fdf5fd), 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> at PostgresCDCIT.java:625-628, a committed-offset check, not a snapshot split assertion). The other PostgresCDCIT cases in that job, including the custom_primary_key ones 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 earlier elasticsearch-connector-it failure is addressed on dev by #12711 (already merged), and the Elasticsearch job on this head is still running. A sync with dev is 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

  1. Blockers - must be fixed
    • None on the source side. All issues from my previous round are closed.
  2. 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!

@CodeWithPravinMaske

Copy link
Copy Markdown
Contributor Author

Thanks @DanielLeens for the re-review!

  1. Oracle / PostgreSQL docs: added the same NOT NULL sentence to the "unique non-primary column via table-names-config.primaryKeys" recipe in Oracle-CDC.md and PostgreSQL-CDC.md (en and zh). DB2, SQL Server and openGauss don't have that recipe.
  2. Metadata query for real-PK tables: I'd keep it as is for now. It's one getColumns call per table at split generation, next to the per-table metadata and min/max queries that getSplitColumn already runs, and a dialect with a cheaper source can override isColumnNullable. Happy to fetch the columns once per table in a follow-up if startup time on very large table lists becomes a concern.
  3. Inline logger: an interface can't hold a private logger field, and a Logger constant would become a public field of the dialect SPI. So I left the lookup inline. It only runs on the rare metadata-miss path, right before falling back to the parsed column.

@CodeWithPravinMaske

Copy link
Copy Markdown
Contributor Author

Thanks @DanielLeens for the re-review!

  1. Oracle / PostgreSQL docs: added the same NOT NULL sentence to the "unique non-primary column via table-names-config.primaryKeys" recipe in Oracle-CDC.md and PostgreSQL-CDC.md (en and zh). DB2, SQL Server and openGauss don't have that recipe.
  2. Metadata query for real-PK tables: I'd keep it as is for now. It's one getColumns call per table at split generation, next to the per-table metadata and min/max queries that getSplitColumn already runs, and a dialect with a cheaper source can override isColumnNullable. Happy to fetch the columns once per table in a follow-up if startup time on very large table lists becomes a concern.
  3. Inline logger: an interface can't hold a private logger field, and a Logger constant would become a public field of the dialect SPI. So I left the lookup inline. It only runs on the rare metadata-miss path, right before falling back to the parsed column.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @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 NULL chunk, so rows with NULL in that column are silently skipped once the table has more than one chunk (#12598).
  • Fix approach: new default JdbcDataSourceDialect#isColumnNullable reads IS_NULLABLE from DatabaseMetaData#getColumns; AbstractJdbcSourceChunkSplitter#getSplitColumn skips a nullable column in all three sources (configured snapshotSplitColumn, 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 getColumns name/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 with exactly_once = true they 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 the exactly_once startup-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 JdbcSourceChunkSplitterTest cover 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 with dev and none were weakened.
  • E2E testMysqlCdcSnapshotWithNullableUniqueKey (runs in both MySQL CDC suites) now compares id, name on static data; the NULL-to-0 value issue is separate (#12599 / #12608).
  • CI on the current head: the fork run 38283116775 for 4a0cc3d2e2 completed with success (75 jobs, none failed or cancelled), and the apache-side Build, labeler and Notify test workflow checks are all green. The earlier red PostgresCDCIT committed-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

  1. Blockers - must be fixed
    • None. My earlier CHANGES_REQUESTED was cleared on the previous head; the only item left was CI, which is now green on this head, so I am approving.
  2. 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!

@SEZ9

SEZ9 commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator

@CodeWithPravinMaske thanks for the update. Guarding the primary-key branch in getSplitColumn with the same isColumnNullable check (skip with WARN → try unique keys → single-split fallback) is the direction I was hoping for, and it should bring the code in line with what incompatible-changes.md and the MySQL-CDC docs say about table-names-config.primaryKeys. I haven't looked at the updated diff yet, so I'll confirm the first two points from my review once the changes are pushed. Your comment also got cut off at spl — could you paste the full name of the second new test so I know what it covers?

A few items from the earlier review aren't mentioned in your update:

  1. isColumnNullable fallback — when the exact TABLE_NAME/COLUMN_NAME match in DatabaseMetaData.getColumns misses (identifier case, catalog/schema mismatch), it still silently falls back to Column#isOptional(), which the Javadoc itself calls unreliable. Please either skip the candidate key with a WARN in that case, or at least log that the metadata lookup missed and the parsed value is being used.
  2. NULL unique-key values arriving as code = 0 — the E2E compares only id, so the sink-side value for rows with a NULL unique key isn't verified. Please extend the assertion to compare code as well (expecting NULL); if it does come through as 0, that should be fixed in this PR rather than masked by the test.
  3. SPI Javadoc on isColumnNullable — please document when the method is called, that the default issues one getColumns round trip per candidate key, and that catalog-backed dialects may override it.
  4. Per-key metadata round trip — one getColumns call per candidate key per table during split generation adds up on Oracle. Caching per table (one getColumns call for all columns) or letting dialects that already hold the catalog table short-circuit would address this cheaply.

Happy to do a final pass once those are in — or let me know if you think any of them shouldn't be.

@CodeWithPravinMaske

Copy link
Copy Markdown
Contributor Author

Thanks @SEZ9! All of these are in the current head (4a0cc3d2e): the second test is splitColumnPrefersNotNullUniqueKeyOverNullablePrimaryKey; isColumnNullable now tries a case-insensitive match and logs a WARN naming the table and column before falling back to the parsed column; the Javadoc documents when it's called, the one getColumns query per call, and that dialects may override it; the E2E compares id, name. Comparing code isn't possible here: NULL arriving as 0 is #12599, fixed in #12608, which merges after this PR. I kept the per-table metadata lookup as discussed with @DanielLeens. CI is green on the current head.

@SEZ9

SEZ9 commented Oct 14, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the detailed rundown, @CodeWithPravinMaske. I'd like to confirm each point against the code in 4a0cc3d2e rather than infer it from the description, so a few pointers would help:

  • F3 / F5 (isColumnNullable fallback + Javadoc): could you point me to the case-insensitive retry and the WARN log that names the table and column before the fallback, and to the updated Javadoc describing when the method is called, the one getColumns query per call, and that dialects may override it? Once I can see those in the diff I can close both.
  • F6 (per-key metadata round trip): keeping the per-table lookup is fine with me as long as the Javadoc note about catalog-backed dialects overriding it is in place; please point me to it.
  • F4 (E2E assertion): comparing id, name is reasonable while the NULL-arriving-as-0 issue is being handled separately. Please add a short comment next to the E2E assertion explaining why code is excluded and referencing the follow-up, so it isn't read as hiding a regression, and point me to the changed assertion.
  • F1 / F2 (primary-key branch guard + docs): does the primary-key branch of getSplitColumn now run the nullability check too, so a nullable column injected via table-names-config.primaryKeys is skipped (or rejected with a clear error) instead of becoming the split column? If yes, please point me to that guard and the splitColumnPrefersNotNullUniqueKeyOverNullablePrimaryKey test, and the incompatible-changes entry and migration guide are accurate. If the PK branch is still unguarded, either add the guard or narrow the docs to what is actually fixed.

Once I can verify these in the diff and the E2E comment is in, I'm happy to approve.

@davidzollo davidzollo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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!

@davidzollo
davidzollo added this pull request to the merge queue Oct 14, 2026
@davidzollo

Copy link
Copy Markdown
Contributor

Please ignore the following message if you have joined in the Slack~

To facilitate focused communication among contributors, we’ve created a brand-new dedicated #contributors channel in official Slack workspace.
Slack workspace link: https://s.apache.org/seatunnel-slack

This channel is designed for technical discussions, feature design brainstorming, roadmap sync and direct communication with project core Contributors. Everyone who contributes code, docs, test cases or community ideas is warmly invited to join, share thoughts and collaborate together under The Apache Way. Welcome to join 😄

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug][Connector-V2][CDC] Snapshot silently skips rows when a table without a primary key is split by a nullable unique key

4 participants