Skip to content

[Feature][Connector-V2] Support per-table primary key mapping via multi_table_config.primary_keys for JDBC sink - #12015

Open
luozihen wants to merge 35 commits into
apache:devfrom
luozihen:dev
Open

luozihen wants to merge 35 commits into
apache:devfrom
luozihen:dev

Conversation

@luozihen

@luozihen luozihen commented Aug 31, 2026 •

Copy link
Copy Markdown

Purpose of this pull request

Close #11878.

Add a new JDBC sink option multi_table_config.primary_keys to support per-table
primary key mapping in multi-table generated-SQL scenarios.

When the upstream table name matches one of the configured patterns, the mapped key
columns are used; otherwise it falls back to the existing primary_keys / catalog
metadata logic. Inside this new option, ${primary_key} / ${unique_key} can be
mixed with static columns. The legacy top-level primary_keys contract is kept
unchanged.

This PR also fixes the config-parsing issue that blocked the feature. SeaTunnel rebuilds
configs with ConfigFactory.parseMap(...), which treats map keys as Typesafe Config path
expressions; regex keys such as ^t_nova_.*$ contain . and $, so they failed with
ConfigException$BadPath. The rebuild in ConfigShadeUtils.processConfig therefore now uses a
JSON round-trip (ConfigFactory.parseString(..., ConfigSyntax.JSON)), which keeps plugin option
keys literal.

The fix is deliberately scoped to avoid a cross-cutting API change: ReadonlyConfig#toConfig()
is left byte-for-byte identical to dev, so dotted-key semantics are unchanged for all existing
callers. The only shared code touched is MultiTableFailureHelper#mergeOptions(), which now
merges the two option maps directly instead of round-tripping through HOCON withFallback, with
a Javadoc note stating that the merge is shallow/top-level.

Review status (F1-F8)

F1 (ReadonlyConfig#toConfig dotted-key round-trip):
Done. ReadonlyConfig#toConfig() is unchanged and identical to dev, so dotted-key path
semantics for existing callers are untouched. The parsing fix is scoped to
ConfigShadeUtils.processConfig() (JSON round-trip, so regex option keys such as ^t_nova_.*$
are not read as HOCON paths) and to MultiTableFailureHelper#mergeOptions() (direct shallow map
merge instead of Config#withFallback, with the merge contract documented on the method).
Regression test: ReadableConfigTest#testToConfigPreservesDottedKeyExpansion;
MultiTableFailureHelperTest#testMergeOptionsPreservesSpecialCharacterKeys covers the merge.
Neither parsing change is specific to the new option, and both are documented as such:
ConfigShadeUtils.processConfig runs for every job (it is the shade rebuild); the change only makes
the rebuild keep keys literal instead of interpreting them as HOCON paths. ConfigFactory.parseMap
stores dotted keys literally as well (an env map with "job.mode" keeps a literal key in both
cases), so the shape of every other option is unchanged and only inputs that previously failed with
ConfigException.BadPath behave differently. MultiTableFailureHelper#mergeOptions is shared too:
its merge changed from a HOCON deep merge to a shallow top-level merge, where the primary side's
value replaces the fallback side's on a key collision. All of its callers - MultipleTableJobConfigParser,
AbstractSinkExecuteProcessor and its Flink 1.13 variant, the Spark 2 / Spark common
SinkExecuteProcessors (five production call sites), plus the two helpers in the same class - merge
sink plugin options against job-env options (disjoint namespaces) or a single-key internal map, so no
caller can hit a nested-object collision; the new contract is documented on the method.
One entry point is still open and is out of scope here: when a job is submitted through the REST
submit-job API with the (default) JSON body, the body is turned into a map and parsed by
ConfigBuilder.of(Map) before the shade rebuild, so ConfigFactory.parseMap(...) still rejects
regex keys such as ^t_nova_.*$ with ConfigException.BadPath. This is documented as a known
limitation in docs/en|zh/connectors/sink/Jdbc.md (config files and the HOCON REST body work) and
will be fixed separately; see the Follow-up section.

F2 / F5 (declaration-order semantics):
Done. JdbcSinkFactory#toCompiledPatternMap copies the configured patterns into an explicit
LinkedHashMap<Pattern, List<String>>, so "the first pattern in declaration order wins" is
guaranteed by the code instead of relying on the map implementation that Jackson happens to
produce. JdbcSinkFactoryTest#testResolveMultiTablePrimaryKeysFromHoconFirstMatchWins declares
overlapping patterns in a real HOCON string in non-alphabetical order (^table2$, ^table1$,
then a catch-all ^table.*$) and asserts that the first declared match wins. That test does not use
a hand-built map: it parses the HOCON string with ConfigFactory.parseString, wraps the sink block
with ReadonlyConfig.fromConfig(...) and calls JdbcSinkFactory#resolveMultiTablePrimaryKeys, which
reads the option and builds the ordered map in toCompiledPatternMap - the same HOCON string -> ReadonlyConfig -> option -> toCompiledPatternMap chain the runtime uses (the E2E below covers the
remaining engine-level steps: shade rebuild, placeholder pass, createSink). The English and Chinese
connectors/sink/Jdbc.md docs state the same rule.

F3 (identifier validation for the resolved key columns):
Done. JdbcSinkFactory#validatePrimaryKeyColumns rejects blank names and names containing a
comma before they are joined into PRIMARY_KEYS, raising JDBC-12
(INVALID_MULTI_TABLE_CONFIG). Those are the only unsafe inputs, because the resolved names are
interpolated through the dialect's quoteIdentifier when SQL is generated
(JdbcDialect#getDeleteStatement, MysqlDialect#quoteIdentifier,
MysqlCreateTableSqlBuilder#buildPrimaryKeySql); a comma would collide with the delimiter of the
comma-joined primary_keys value and a blank name would produce an empty list element. Test:
JdbcSinkFactoryTest#testFactoryContextWithMultiTableConfigInvalidColumnFails.
Embedded quote characters are deliberately not rejected: the dialect quoting only wraps the name
(MysqlDialect#quoteIdentifier returns a backtick-wrapped name without escaping, and
CatalogUtils#quoteIdentifier behaves the same), so a name containing the dialect quote character
would already be unusable in the generated SQL. Such a name cannot come from the ${primary_key} /
${unique_key} expansion (those are upstream catalog column names) and would have to be typed by the
user, so it surfaces as a database error rather than as a silently wrong key. A dialect-specific
quote-character rule is left as a deliberate follow-up instead of half-implementing it here.

F4 (connector-level ${primary_key} / ${unique_key} vs engine-level TablePlaceholder):
The engine pass runs first (TableSinkFactoryContext#replacePlaceholderAndCreate ->
TablePlaceholderProcessor#replaceTablePlaceholder), but it only rewrites top-level String
values and single-element String lists and never descends into nested objects, so the
multi_table_config map reaches the connector untouched. The connector then expands
${primary_key} / ${unique_key} per matched table in
JdbcSinkFactory#expandPrimaryKeyPlaceholder. When a matched table uses such a placeholder but
the upstream catalog table has no primary key (or no unique key), the job fails fast with
JDBC-12; it does not silently fall back and does not leave the literal placeholder in
PRIMARY_KEYS. Documented in docs/{en,zh}/introduction/configuration/sink-options-placeholders.md
and pinned by JdbcSinkFactoryTest#testPlaceholderOrderBetweenEngineAndConnectorPasses, which
asserts that the engine pass expands a top-level primary_keys = ["${primary_key}"], leaves the
nested multi_table_config.primary_keys map untouched, and that the connector expands it
afterwards. The fail-fast path is covered by
JdbcSinkFactoryTest#testResolveMultiTablePrimaryKeysMissingPrimaryKeyFails.

F5: see F2.

F6 (regex validation -> JDBC-12):
Done. Every configured pattern is compiled up front in toCompiledPatternMap ->
compilePattern, which maps PatternSyntaxException to JdbcConnectorException carrying
JDBC-12. Tests: JdbcSinkFactoryTest#testResolveMultiTablePrimaryKeysInvalidRegexFails and
JdbcSinkFactoryTest#testCompilePatternInvalidFails. Compiled patterns are memoized in a
bounded, access-ordered LRU cache (MAX_CACHED_PATTERNS = 256, wrapped in
Collections.synchronizedMap), so each distinct pattern is compiled once per JVM. 256 sits
comfortably above the number of distinct patterns a busy deployment configures (a handful to a
few dozen), and exceeding it only evicts an older entry that is recompiled on next use.

F7 (tests):
Done, no longer deferred. Both halves are in this PR.

The toConfig() regression test already exists and is part of this PR's diff:
ReadableConfigTest#testToConfigPreservesDottedKeyExpansion (seatunnel-api, line 383) asserts
that a dotted map key such as a.b still expands through the dotted path.

The engine-level E2E for the new option is
JdbcMysqlMultipleTablesIT#testMysqlJdbcMultipleTableE2e. It uses two dedicated source tables
(source.mtc_table1 / source.mtc_table2) whose key columns are NOT NULL, points
jdbc_mysql_source_and_sink_with_multi_table_config.conf at them, and lets the sink create the
target tables (schema_save_mode = "CREATE_SCHEMA_WHEN_NOT_EXIST"). It then asserts the resolved
primary keys read from information_schema.STATISTICS (sink.mtc_table1 -> c_int, c_integer;
sink.mtc_table2 -> c_mediumint) plus the table row counts. It runs on the Zeta, Flink and
Spark containers in CI.

The dedicated fixture (rather than the shared source.table1 / source.table2, which the other
test methods depend on) is required because of the pre-existing MySQL DDL gap described in the
Follow-up section: a column that is explicitly declared NULL cannot be part of a PRIMARY KEY.

F8 (option key naming):
Done. The key is fully snake_case - multi_table_config - in JdbcSinkOptions, the English and
Chinese docs, the E2E config and all tests; no mixed multi-table_config spelling remains in the
PR.

Additional fix from the previous review round (not part of F1-F8):
The patterns were previously matched against the resolved sink table name, so combining
multi_table_config.primary_keys with table / tablePrefix / tableSuffix silently defeated
the mapping and the sink fell back to catalog metadata. JdbcSinkFactory#createSink now keeps the
upstream CatalogTable and matches on that, which is what the docs already described. Regression
test: JdbcSinkFactoryTest#testFactoryContextWithMultiTableConfigMatchesUpstreamTableName.

Does this PR introduce any user-facing change?

Yes. Adds a new optional JDBC sink option multi_table_config.

Semantics:

  • Each key is a Java regular expression matched against the upstream table name with
    full-match semantics (tableName.matches(pattern)).
  • Each value is a list of key columns. ${primary_key} and ${unique_key} are
    supported only inside this option and can be mixed with static columns.
  • Precedence: matched mapping wins; otherwise falls back to the existing logic
    (top-level primary_keys -> catalog primary key -> first unique key -> plain INSERT).
  • If a table matches multiple patterns, the first pattern in declaration order wins.
  • If a matched table uses ${primary_key} / ${unique_key} but the upstream table has
    no primary/unique key, the job fails with a clear error.

No existing option is renamed, removed, or changed in default behavior.

Example configurations

Example 1

env {
  job.mode = "STREAMING"
  parallelism = 1
  checkpoint.interval = 10000
}

source {
  MySQL-CDC {
    plugin_output = "sharding00_source"
    url = "jdbc:mysql://<host>:3306/st_source"
    username = "<username>"
    password = "<password>"
    database-names = ["st_source"]
    table-pattern = "st_source\\.t_(nova_(fo_serial|order)_(000|048)|tyuen_txn_(cp|qr)_(000|048))"
    startup.mode = "initial"
    server-id = "5400-5408"
  }
}

transform {
  Sql {
    plugin_input = "sharding00_source"
    plugin_output = "sharding00_transform"
    query = "SELECT *, 'idc' AS DATA_SOURCE FROM dual"
  }

  DefineSinkType {
    plugin_input = "sharding00_transform"
    plugin_output = "sharding00_typed"
    columns = [
      { column = "DATA_SOURCE", type = "VARCHAR(32)" }
    ]
  }
}

sink {
  Jdbc {
    plugin_input = "sharding00_typed"
    url = "jdbc:mysql://<host>:3306/st_target?rewriteBatchedStatements=true&autoReconnect=true"
    driver = "com.mysql.cj.jdbc.Driver"
    username = "<username>"
    password = "<password>"
    generate_sink_sql = true
    database = "st_target"

    multi_table_config {
      primary_keys {
        "^t_nova_.*$"      = ["${primary_key}", "DATA_SOURCE"]
        "^t_tyuen_txn_.*$" = ["id_txn_ctrl", "DATA_SOURCE"]
      }
    }

    schema_save_mode = "CREATE_SCHEMA_WHEN_NOT_EXIST"
    data_save_mode = "APPEND_DATA"
  }
}

Example 2

env {
  job.mode = "STREAMING"
  parallelism = 1
  checkpoint.interval = 10000
}

source {
  MySQL-CDC {
    plugin_output = "gote_source"
    url = "jdbc:mysql://<host>:3306/st_source"
    username = "<username>"
    password = "<password>"
    database-names = ["st_source"]
    table-pattern = "st_source\\.t_(nova_merchant_info|tyuen_txn_ext|nova_merge_settle_serial)"
    startup.mode = "initial"
    server-id = "5500-5508"
  }
}

transform {
  Sql {
    plugin_input = "gote_source"
    plugin_output = "gote_transform"
    query = "SELECT *, 'idc' AS DATA_SOURCE FROM dual"

    table_transform = [
      {
        table_path = "st_source.t_nova_merchant_info"
        query = "SELECT * FROM dual"
      }
    ]
  }

  DefineSinkType {
    plugin_input = "gote_transform"
    plugin_output = "gote_typed"
    columns = [
      { column = "DATA_SOURCE", type = "VARCHAR(32)" }
    ]
    table_match_regex = "st_source\\.t_(tyuen_txn_ext|nova_merge_settle_serial)"
  }
}

sink {
  Jdbc {
    plugin_input = "gote_typed"
    url = "jdbc:mysql://<host>:3306/st_target?rewriteBatchedStatements=true&autoReconnect=true"
    driver = "com.mysql.cj.jdbc.Driver"
    username = "<username>"
    password = "<password>"
    generate_sink_sql = true
    database = "st_target"

    primary_keys = ["merchant_id"]

    multi_table_config {
      primary_keys {
        "t_tyuen_txn_ext.*"          = ["id_txn_ctrl", "DATA_SOURCE"]
        "t_nova_merge_settle_serial" = ["${primary_key}", "DATA_SOURCE"]
      }
    }

    schema_save_mode = "CREATE_SCHEMA_WHEN_NOT_EXIST"
    data_save_mode = "APPEND_DATA"
  }
}

Table DDL

The source tables are created manually on the upstream side; the target tables are created by
generate_sink_sql = true. multi_table_config.primary_keys decides which key columns are used
when writing to the target tables, which shows up as the key columns of the generated
upsert / delete statements.

To keep the transform-derived DATA_SOURCE column (a length-less STRING) from being created as
LONGTEXT by the MySQL dialect - which cannot be part of a primary key - the example
configurations use DefineSinkType to declare it as VARCHAR(32). The source table DDL is listed
below, followed by the target table DDL as created by the sink.

Demo 1 source tables

CREATE TABLE t_nova_fo_serial_000 (
  serial_id   BIGINT       NOT NULL,
  order_no    VARCHAR(64),
  amount      DECIMAL(18,2),
  status      VARCHAR(16),
  created_at  DATETIME,
  PRIMARY KEY (serial_id)
);

CREATE TABLE t_nova_order_000 (
  id          BIGINT       NOT NULL,
  order_no    VARCHAR(64),
  amount      DECIMAL(18,2),
  created_at  DATETIME,
  PRIMARY KEY (id)
);

CREATE TABLE t_tyuen_txn_cp_000 (
  id          BIGINT       NOT NULL,
  id_txn_ctrl VARCHAR(64)  NOT NULL,
  amount      DECIMAL(18,2),
  channel     VARCHAR(16),
  created_at  DATETIME,
  PRIMARY KEY (id),
  UNIQUE KEY uk_id_txn_ctrl (id_txn_ctrl)
);

CREATE TABLE t_tyuen_txn_qr_000 (
  id          BIGINT       NOT NULL,
  id_txn_ctrl VARCHAR(64)  NOT NULL,
  qr_code     VARCHAR(128),
  amount      DECIMAL(18,2),
  created_at  DATETIME,
  PRIMARY KEY (id),
  UNIQUE KEY uk_id_txn_ctrl (id_txn_ctrl)
);

Demo 1 target tables (created by the sink)

CREATE TABLE t_nova_fo_serial_000 (
  serial_id   BIGINT       NOT NULL,
  DATA_SOURCE VARCHAR(32)  NOT NULL,
  order_no    VARCHAR(64),
  amount      DECIMAL(18,2),
  status      VARCHAR(16),
  created_at  DATETIME,
  PRIMARY KEY (serial_id, DATA_SOURCE)
);

CREATE TABLE t_nova_order_000 (
  id          BIGINT       NOT NULL,
  DATA_SOURCE VARCHAR(32)  NOT NULL,
  order_no    VARCHAR(64),
  amount      DECIMAL(18,2),
  created_at  DATETIME,
  PRIMARY KEY (id, DATA_SOURCE)
);

CREATE TABLE t_tyuen_txn_cp_000 (
  id          BIGINT       NOT NULL,
  id_txn_ctrl VARCHAR(64)  NOT NULL,
  DATA_SOURCE VARCHAR(32)  NOT NULL,
  amount      DECIMAL(18,2),
  channel     VARCHAR(16),
  created_at  DATETIME,
  PRIMARY KEY (id_txn_ctrl, DATA_SOURCE)
);

CREATE TABLE t_tyuen_txn_qr_000 (
  id          BIGINT       NOT NULL,
  id_txn_ctrl VARCHAR(64)  NOT NULL,
  DATA_SOURCE VARCHAR(32)  NOT NULL,
  qr_code     VARCHAR(128),
  amount      DECIMAL(18,2),
  created_at  DATETIME,
  PRIMARY KEY (id_txn_ctrl, DATA_SOURCE)
);

Demo 2 source tables

CREATE TABLE t_nova_merchant_info (
  id            BIGINT       NOT NULL,
  merchant_id   VARCHAR(64)  NOT NULL,
  merchant_name VARCHAR(128),
  mcc           VARCHAR(16),
  created_at    DATETIME,
  PRIMARY KEY (id),
  UNIQUE KEY uk_merchant_id (merchant_id)
);

CREATE TABLE t_tyuen_txn_ext (
  id          BIGINT       NOT NULL,
  id_txn_ctrl VARCHAR(64)  NOT NULL,
  txn_amount  DECIMAL(18,2),
  ext_info    VARCHAR(255),
  created_at  DATETIME,
  PRIMARY KEY (id),
  UNIQUE KEY uk_id_txn_ctrl (id_txn_ctrl)
);

CREATE TABLE t_nova_merge_settle_serial (
  id          BIGINT       NOT NULL,
  settle_no   VARCHAR(64),
  amount      DECIMAL(18,2),
  settle_date DATE,
  created_at  DATETIME,
  PRIMARY KEY (id)
);

Demo 2 target tables (created by the sink)

CREATE TABLE t_nova_merchant_info (
  id            BIGINT       NOT NULL,
  merchant_id   VARCHAR(64)  NOT NULL,
  merchant_name VARCHAR(128),
  mcc           VARCHAR(16),
  created_at    DATETIME,
  PRIMARY KEY (merchant_id)
);

CREATE TABLE t_tyuen_txn_ext (
  id          BIGINT       NOT NULL,
  id_txn_ctrl VARCHAR(64)  NOT NULL,
  DATA_SOURCE VARCHAR(32)  NOT NULL,
  txn_amount  DECIMAL(18,2),
  ext_info    VARCHAR(255),
  created_at  DATETIME,
  PRIMARY KEY (id_txn_ctrl, DATA_SOURCE)
);

CREATE TABLE t_nova_merge_settle_serial (
  id          BIGINT       NOT NULL,
  DATA_SOURCE VARCHAR(32)  NOT NULL,
  settle_no   VARCHAR(64),
  amount      DECIMAL(18,2),
  settle_date DATE,
  created_at  DATETIME,
  PRIMARY KEY (id, DATA_SOURCE)
);

Generated SQL

Below are the upsert / delete statements that the MySQL JDBC sink actually generated after
running the two demos above. Each target table uses the different key columns assigned to it by
multi_table_config.primary_keys.

-- Example 1
INSERT INTO `st_target`.`t_nova_fo_serial_000`
  (`serial_id`, `order_no`, `amount`, `status`, `created_at`, `DATA_SOURCE`)
VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE ...;
DELETE FROM `st_target`.`t_nova_fo_serial_000`
  WHERE `serial_id` = ? AND `DATA_SOURCE` = ?;

INSERT INTO `st_target`.`t_tyuen_txn_cp_000`
  (`id`, `id_txn_ctrl`, `amount`, `channel`, `created_at`, `DATA_SOURCE`)
VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE ...;
DELETE FROM `st_target`.`t_tyuen_txn_cp_000`
  WHERE `id_txn_ctrl` = ? AND `DATA_SOURCE` = ?;

-- Example 2
INSERT INTO `st_target`.`t_nova_merchant_info`
  (`id`, `merchant_id`, `merchant_name`, `mcc`, `created_at`)
VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE ...;
DELETE FROM `st_target`.`t_nova_merchant_info`
  WHERE `merchant_id` = ?;

INSERT INTO `st_target`.`t_tyuen_txn_ext`
  (`id`, `id_txn_ctrl`, `txn_amount`, `ext_info`, `created_at`, `DATA_SOURCE`)
VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE ...;
DELETE FROM `st_target`.`t_tyuen_txn_ext`
  WHERE `id_txn_ctrl` = ? AND `DATA_SOURCE` = ?;

INSERT INTO `st_target`.`t_nova_merge_settle_serial`
  (`id`, `settle_no`, `amount`, `settle_date`, `created_at`, `DATA_SOURCE`)
VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE ...;
DELETE FROM `st_target`.`t_nova_merge_settle_serial`
  WHERE `id` = ? AND `DATA_SOURCE` = ?;

How was this patch tested?

Added unit tests:

  • JdbcSinkFactoryTest: mapping hit, fallback to legacy primary_keys, missing upstream
    primary key error, first-match-wins, string value handling, invalid regex, blank/comma column
    rejection, compiled-pattern caching, matching against the upstream table name when the sink
    table name is remapped, and the full factory-context path.
  • JdbcSinkFactoryTest#testResolveMultiTablePrimaryKeysFromHoconFirstMatchWins: parses a real
    HOCON config string whose patterns overlap in non-alphabetical declaration order (^table2$,
    ^table1$, then a catch-all ^table.*$) and asserts that the first declared match wins.
  • JdbcSinkFactoryTest#testFactoryContextWithMultiTableConfigMatchesUpstreamTableName: runs the
    whole createSink path with a static table remap and asserts the pattern still resolves
    against the upstream table name.
  • JdbcSinkFactoryTest#testPlaceholderOrderBetweenEngineAndConnectorPasses: pins the order
    between the engine-level TablePlaceholder pass and the connector-level expansion (the nested
    multi_table_config.primary_keys map reaches the sink untouched and is expanded there).
  • ConfigShadeTest#testDecryptPreservesSpecialCharacterKeys: special-character config keys are
    preserved after decryptConfig.
  • ReadableConfigTest#testToConfigPreservesDottedKeyExpansion: dotted-key expansion is preserved
    for existing ReadonlyConfig#toConfig callers.
  • MultiTableFailureHelperTest#testMergeOptionsPreservesSpecialCharacterKeys: overlapping scalar
    option keys keep the primary-side value under the direct map merge.
  • ConfigShadeTest#testDecryptPreservesOrdinaryConfigShapes: an unquoted dotted key, a quoted
    dotted key inside a nested map and numeric values come back unchanged from decryptConfig.
  • JdbcSinkFactoryTest#testLegacyPrimaryKeysStillRebuildCatalogPrimaryKey: the legacy top-level
    primary_keys branch still rebuilds the catalog primary key after the refactor.

Engine-level E2E coverage (exercised by CI on the Zeta, Flink and Spark containers):

  • JdbcMysqlMultipleTablesIT#testMysqlJdbcMultipleTableE2e drops the dedicated target tables and
    runs
    seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/resources/jdbc_mysql_source_and_sink_with_multi_table_config.conf.
    The job reads two dedicated source tables (source.mtc_table1 / source.mtc_table2) whose key
    columns are NOT NULL, so the sink can create the target tables itself
    (schema_save_mode = "CREATE_SCHEMA_WHEN_NOT_EXIST") and the resolved key columns end up in the
    generated create-table DDL. The NOT NULL key columns are required because of the pre-existing
    MySQL DDL gap described in the Follow-up section, and the shared
    source.table1 / source.table2 fixture used by the other test methods is left untouched.
  • The test then asserts the primary keys read back from information_schema.STATISTICS
    (sink.mtc_table1 -> c_int, c_integer, sink.mtc_table2 -> c_mediumint) plus the table row
    counts, which fails if the per-table mapping or the declaration order is lost.
  • The same config also pins precedence: the fallback primary_keys = ["id"] must not be used, and
    a catch-all pattern declared last must not win.

Manually verified with MySQL-CDC -> JDBC using the two demo configurations above
(generate_sink_sql = true), and confirmed the auto-created target tables (with
DefineSinkType setting DATA_SOURCE to VARCHAR(32)) together with the generated
upsert / delete statements match the expected per-table primary key mapping.

Also run ./mvnw spotless:apply and
./mvnw -pl :connector-jdbc-e2e-part-1 -am -DskipTests -Dskip.ui=true package to compile the
E2E module locally.

Follow-up

  • Pre-existing MySQL DDL gap found while writing the E2E: MysqlCreateTableSqlBuilder (and the
    OceanBase MySQL-mode twin) emit an explicit NULL for nullable columns even when those columns
    are part of a PRIMARY KEY, which MySQL rejects with ER_PRIMARY_CANT_HAVE_NULL (1171,
    All parts of a PRIMARY KEY must be NOT NULL). It affects the existing top-level primary_keys
    option as well, so it is not specific to multi_table_config. Tracked in
    [Bug][Connector-V2][JDBC] MySQL sink auto-create fails when a configured primary key column is nullable #12415 and deliberately left out of this PR to keep the diff scoped; a follow-up
    PR will emit NOT NULL for key columns plus a unit test in MysqlCreateTableSqlBuilderTest.
  • Optional follow-up: fail fast with JDBC-12 when a static primary key column does not exist in
    the upstream schema. Not done here because the check has to account for field_ide case
    conversion, so it deserves its own change.
  • REST JSON submission path: ConfigBuilder.of(Map) (used by RestUtil.buildConfig /
    RestUtil.buildConfigList) still parses the JSON body with ConfigFactory.parseMap(...), which
    rejects regex keys such as ^t_nova_.*$ with ConfigException.BadPath. Documented as a known
    limitation in the JDBC sink docs; the fix (rebuild the map with literal keys when a key is not a
    valid path) will be tracked in a separate issue so this PR stays scoped.

Check list

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

What Problem Does This PR Solve?

  • User pain point: multi-table JDBC sink jobs (e.g. MySQL-CDC -> JDBC with generate_sink_sql = true) currently have only one global primary_keys option, so there is no way to give different tables different key columns (or mix ${primary_key}/${unique_key} with a shared static column such as DATA_SOURCE) in a single sharding/merge job.
  • Fix approach: adds a new multi-table_config.primary_keys option to JdbcSinkFactory that maps a table-name regex to a key-column list (with ${primary_key}/${unique_key} expansion), taking precedence over the existing primary_keys / catalog-metadata fallback. Along the way, it also fixes a real config-reconstruction bug: ConfigFactory.parseMap(...) treats every map key as a HOCON path expression, so a regex key such as ^t_nova_.*$ (which contains . and $) throws ConfigException$BadPath. The PR replaces ConfigFactory.parseMap(...) with a Jackson JSON round-trip in two places: ReadonlyConfig#toConfig() and ConfigShadeUtils#processConfig.
  • One-sentence summary: a well-motivated, mostly well-tested JDBC feature, but it ships a semantics change to a widely-shared config-reconstruction API (ReadonlyConfig#toConfig()) whose blast radius goes far beyond the JDBC connector, and it introduces some avoidable code duplication in JdbcSinkFactory.

1. Code Change Review

1.1 Core Logic Analysis

Runtime path — is the config-parsing bug real, and is the fix on the necessary path?

I traced the actual failure path instead of taking the PR description at face value:

  • ConfigShadeUtils.processConfig (seatunnel-core/seatunnel-core-starter/.../ConfigShadeUtils.java:161-215) runs unconditionally for every job at submission time (it is the sensitive-field encrypt/decrypt step, invoked regardless of connector type). Before the fix it ended with ConfigFactory.parseMap(configMap), where configMap already came from JsonUtils.toMap(JsonUtils.parseObject(...)) — i.e. it is itself the result of a JSON parse. Reconstructing that same, already-JSON-safe map via parseMap is exactly where a job containing a multi-table_config.primary_keys block with regex keys would blow up with ConfigException$BadPath, before the JDBC connector ever runs. So this half of the fix is real, necessary, and — because configMap's values are guaranteed JSON-serializable already — low risk: JsonUtils.toJsonString(configMap) followed by ConfigFactory.parseString(json, JSON) is a lossless, purely textual re-encoding of data that was already JSON. Good, surgical fix.
  • ReadonlyConfig#fromConfig(Config) (seatunnel-api/.../ReadonlyConfig.java:56-65) was already implemented via a JSON render + Jackson read (unchanged by this PR), so per-table ReadonlyConfig objects built from the post-decrypt Config already preserve the regex keys correctly. JdbcSinkFactory.resolveMultiTablePrimaryKeys() reads MULTI_TABLE_CONFIG directly off this ReadonlyConfig via config.get(Option) (a plain map lookup, not toConfig()), so the actual feature path does not appear to require the ReadonlyConfig#toConfig() change at all.

Finding — Issue 1: The ReadonlyConfig#toConfig() change (seatunnel-api/.../ReadonlyConfig.java:78-86) swaps ConfigFactory.parseMap(confData) for a Jackson JSON round-trip. This method is @Deprecated but still very actively used — I counted ~20 call sites outside this PR's diff, including the connector prepare() fallback path in FactoryUtil.java:127 and :235 (source.prepare(options.toConfig()) / sink.prepare(config.toConfig()), used by every legacy/fallback SeaTunnelSource/SeaTunnelSink), plus MultiTableFailureHelper, ConfigBuilder, MetalakeConfigUtils, and connector code in Hive, Clickhouse, HDFS, Neo4j, AmazonSQS, AmazonDynamoDB, OpenMLDB, HTTP, IoTDB, GraphQL, and JsonPathTransformConfig.

  • The semantic difference that matters: ConfigFactory.parseMap() treats every map key (at every nesting level) as a HOCON path expression and auto-expands dotted keys into nested structure (e.g. {"a.b": 1} becomes {a: {b: 1}}). The new JSON-based toConfig() keeps such keys literal/flat ({"a.b": 1} stays a single flat key). Any existing caller that (a) builds a Map/ReadonlyConfig with a deliberately dotted key relying on that auto-expansion, and (b) later reads it back through .toConfig() with a dotted-path lookup (config.getString("a.b"), config.getConfig("a")...), would silently stop finding the value after this change — no exception, just a missing/empty config, which is worse than a loud failure.
  • I searched the repo for this pattern (property-bag-style options with dotted keys, e.g. Kafka-style sasl.jaas.config, feeding into .toConfig()) and did not find a currently-broken caller — the connectors that do call .toConfig() (Hive, Clickhouse, HDFS, etc.) appear to use flat, non-dotted option keys. So I cannot point at a concrete regression today, but I also could not exhaustively audit ~20 call sites across unrelated connector modules within this review, and a silent, non-throwing behavior change on a @Deprecated-but-still-load-bearing shared API is exactly the kind of change that tends to surface as a hard-to-reproduce field bug months later.
  • Recommendation: since the actual JDBC feature does not appear to need this method changed (per the trace above), consider narrowing the fix to only ConfigShadeUtils.processConfig (which is provably necessary and provably safe), and leaving ReadonlyConfig#toConfig() untouched — or, if there is a concrete call path that does need it (please point it out if I missed one), add an explicit regression test that proves no other caller relies on the old dot-expansion behavior, and call that out in the PR description as an intentional, audited behavior change to a shared API.
  • Location: seatunnel-api/src/main/java/org/apache/seatunnel/api/configuration/ReadonlyConfig.java:78-86.

JdbcSinkFactory changes

  • resolveMultiTablePrimaryKeys / matchesPattern / toPrimaryKeyList / expandPrimaryKeyPlaceholder / getPrimaryKeyColumns / getUniqueKeyColumns (JdbcSinkFactory.java:222-297) are straightforward and correct for the described semantics: full-match regex (tableName.matches(pattern)), first-match-wins by declaration order (relies on Map iteration order — traced back through fromConfig's Jackson TypeReference<Map<String,Object>> read, which defaults to LinkedHashMap and therefore preserves declaration order; consistent with the documented "first pattern in declaration order wins"), and a clear JdbcConnectorException when ${primary_key}/${unique_key} is used but the upstream table has no such key.
  • I verified there is no double-processing conflict with the existing generic placeholder framework: TablePlaceholderProcessor.replaceTablePlaceholder (seatunnel-api/.../TablePlaceholderProcessor.java:161-206) only rewrites top-level config values that are String or a single-element String List; a top-level Map value (like multi-table_config) falls through both branches untouched. So the framework's own ${primary_key} substitution never touches values nested inside multi-table_config.primary_keys, and expandPrimaryKeyPlaceholder is the sole, correct place that expands those placeholders. Good — this interaction is easy to get wrong and it was handled correctly (whether by design or by a fortunate structural side effect).
  • Finding — Issue 2 (code duplication): the pre-existing primary-key-resolution logic (catalog PK -> first unique key -> plain INSERT) is now duplicated verbatim into the else branch of the new if (multiTablePrimaryKeys.isPresent()) (JdbcSinkFactory.java:159-201 is essentially a copy of the pre-PR block). This is ~35 lines of copy-pasted logic instead of extracting the pre-existing block into a private helper and calling it from the else branch. It works, but it is an avoidable maintainability regression — a future bug fix to the fallback-resolution logic now has two places to be applied.
    • Location: seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:118-201.

1.2 Compatibility Impact

  • Fully compatible for the new multi-table_config option itself: it is purely additive, optional, and only takes effect when a table name matches a configured pattern; unmatched tables fall back to the pre-existing primary_keys / catalog-metadata logic unchanged. No existing option is renamed, removed, or has its default changed.
  • Partially incompatible / needs verification: the ReadonlyConfig#toConfig() semantics change described in Issue 1 above is a behavior change to a shared, widely-used API with a real (if currently unproven in-repo) potential to silently drop dotted-key config values for callers outside the JDBC connector. This should be either scoped down or explicitly verified/documented before merge.
  • ConfigShadeUtils.processConfig's change is safe/compatible as analyzed above (input is already JSON-normalized).

1.3 Performance / Side-Effect Analysis

  • All changed code runs once per job/sink-instantiation at submission time (createSink(), config decrypt/encrypt), not in the per-record hot path. The extra Jackson serialize+parse round-trip in toConfig()/processConfig is negligible relative to job-submission overhead.
  • No new threads, connections, or unbounded collections are introduced. resolveMultiTablePrimaryKeys iterates a small, user-configured map once per table.

1.4 Error Handling and Logging

Issue Location Problem Risk Fix Severity Raised by another reviewer
1 seatunnel-api/.../ReadonlyConfig.java:78-86 toConfig() (a @Deprecated but heavily used shared API, ~20 call sites outside this diff) changes Map->Config reconstruction from ConfigFactory.parseMap (which auto-expands dotted keys into nested paths) to a literal JSON round-trip. No test proves other callers don't rely on the old dot-expansion behavior; a broken caller would fail silently (missing config value, not an exception). Medium — no concrete broken caller found in-repo during this review, but the audit wasn't exhaustive across ~20 unrelated call sites/connectors, and the failure mode is silent Scope the fix to only ConfigShadeUtils.processConfig (provably necessary and safe) and leave toConfig() untouched, since the traced feature path doesn't appear to need it; or add explicit regression coverage + call this out as an intentional audited change in the PR description Medium No
2 seatunnel-connectors-v2/.../JdbcSinkFactory.java:118-201 Pre-existing PK-fallback-resolution logic duplicated verbatim into the new else branch instead of extracted into a shared private method Low — maintainability only, not a correctness bug Extract the pre-existing block (lines ~159-201) into a private method and call it from both branches Medium No

Error messages themselves (INVALID_MULTI_TABLE_CONFIG, "table X matched pattern Y ... but the upstream table has no primary key") are clear, include table/pattern context, and don't leak sensitive data — good.

2. Code Quality Assessment

2.1 Coding Standards

  • New public/package-visible method resolveMultiTablePrimaryKeys and the new private helpers (matchesPattern, toPrimaryKeyList, expandPrimaryKeyPlaceholder, getPrimaryKeyColumns, getUniqueKeyColumns) have no Javadoc explaining the matching semantics (full-match regex, first-match-wins) or the placeholder-expansion contract. Given this logic implements a non-trivial, user-facing precedence rule, a short Javadoc on resolveMultiTablePrimaryKeys (at minimum) would help future maintainers avoid re-deriving the semantics from the docs. Medium severity per project convention (non-trivial new methods should have doc comments), non-blocking.
  • The new MULTI_TABLE_CONFIG Option (JdbcSinkOptions.java:112-121) does have a description — good.
  • Naming and style otherwise follow existing conventions in the file (Google/AOSP format via Spotless, no wildcard imports).

2.2 Test Coverage and Test Stability

  • New unit tests: JdbcSinkFactoryTest (mapped hit, unmatched/fallback, missing-PK error, first-match-wins, string-value parsing, full factory-context path), ConfigShadeTest#testDecryptPreservesSpecialCharacterKeys, ReadableConfigTest#testToConfigPreservesSpecialCharacterKeys. These directly exercise the claimed bug (regex keys with ./$) and the claimed fix, and cover the main success/fallback/error paths reasonably well.
  • Stability rating: Stable. All new tests are pure, deterministic unit tests — no sleeps, no timing assumptions, no external I/O, no shared mutable static state, no thread races. I did not find any flaky-test anti-patterns (no Thread.sleep, no wall-clock assertions, no unordered-collection assertions without normalization).
  • Gap: there is no test proving ReadonlyConfig#toConfig()'s new behavior is compatible with a dotted-key map for a caller outside the JDBC path (see Issue 1) — the two new tests for toConfig()/processConfig only test the "regex key is preserved" happy path, not "does anything that relied on the old path-expansion still work."

2.3 Documentation Updates

  • docs/en/connectors/sink/Jdbc.md and docs/zh/connectors/sink/Jdbc.md are both updated with a matching new multi-table_config section (table row + full example), and both docs/en / docs/zh sink-options-placeholders.md are updated to mention the mixed static/placeholder support inside multi-table_config. English and Chinese docs are consistent with each other and with the code (option key multi-table_config, sub-key primary_keys, placeholder syntax). Good, this satisfies the project's docs/en + docs/zh requirement.
  • Minor nit (non-blocking): the docs describe the option as being for "multi-table generated-SQL jobs," but the implementation applies unconditionally to any createSink() call regardless of generate_sink_sql/single-vs-multi-table — a single-table job whose table name happens to match a configured pattern would also have its primary key overridden. This is very likely intended (the underlying PK resolution logic is shared for both scenarios), but the docs could be slightly clearer that the matching applies to the sink's resolved table name in general, not only in an explicit "multi-table" topology.

3. Architectural Soundness

3.1 Elegance of the Solution

The regex-to-key-list mapping design itself (declaration-order first-match, placeholder expansion scoped to this option only) is a precise, well-scoped solution to the stated problem, and the interaction with the existing generic placeholder framework was checked and is safe (see 1.1). The underlying config-parsing bug fix, however, is applied at a broader scope than the traced necessary path requires (see Issue 1) — a more surgical fix (scoped to ConfigShadeUtils only, or to a JDBC-local helper) would be more consistent with a minimal-blast-radius change to a 3-year production system.

3.2 Maintainability

Mostly good, aside from the code duplication noted in Issue 2.

3.3 Extensibility

The multi-table_config option shape ({ primary_keys: { "<regex>": [...] } }) leaves room for adding sibling keys under multi-table_config in the future (e.g. per-table field mappings) without another breaking change, since it's read as a generic Map<String,Object>.

3.4 Historical-Version Compatibility

No existing option is renamed/removed, and the new option is opt-in with a fallback to the exact pre-existing logic when unmatched/absent. The one open question is the ReadonlyConfig#toConfig() semantics change (Issue 1), which is not a config-option compatibility break but is a shared-API behavior change that could affect historical jobs relying on the old dot-expansion quirk, if any exist.

4. Issue Summary

Number Issue Location Severity
1 ReadonlyConfig#toConfig() semantics changed (dotted-key auto-expansion removed) for a shared API used by ~20 call sites outside this PR's scope; feature's own path doesn't appear to need this change seatunnel-api/src/main/java/org/apache/seatunnel/api/configuration/ReadonlyConfig.java:78-86 Medium
2 Pre-existing PK-fallback logic duplicated instead of extracted into a shared helper seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:118-201 Medium
3 New non-trivial methods (resolveMultiTablePrimaryKeys and helpers) lack Javadoc seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:222-297 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed
    • None that I would call a hard functional blocker today — I could not find a concrete, currently-broken caller of ReadonlyConfig#toConfig() in this repo. However, given this is a 3-year production system and the change is a silent (non-throwing) behavior change to a widely shared, actively-used API, I'd strongly encourage narrowing Issue 1's fix to only the provably-necessary ConfigShadeUtils.processConfig path before merge, or getting explicit maintainer sign-off that the broader toConfig() change has been audited.
  2. Recommended fixes — non-blocking
    • Extract the duplicated PK-fallback-resolution block into a shared private method (Issue 2).
    • Add short Javadoc to resolveMultiTablePrimaryKeys and its helpers describing the matching/placeholder semantics (Issue 3).
    • Optional doc clarification that the mapping applies to any createSink() call whose resolved table name matches, not only strictly "multi-table" topologies.

Overall this is a solid first contribution: the core feature logic is correct and well-tested, the interaction with the existing placeholder-replacement framework was checked and doesn't conflict, and both English and Chinese docs were updated consistently. The main thing I'd want a maintainer with full-repo context to weigh in on is whether widening the ReadonlyConfig#toConfig() fix (rather than keeping it scoped to ConfigShadeUtils, which is where the actual necessary fix lives) is an accepted tradeoff — I have read-only review rights here (Comment only), so a write-capable maintainer will need to make the final call on approval/merge regardless.

CI is currently still running (Build check in progress on the fork at the time of this review) — please make sure it's green before merge.

Welcome to the Apache SeaTunnel community — thanks for digging into a real, tricky config-parsing bug in addition to the feature itself, and for the thorough PR description with worked examples and generated SQL output. Looking forward to getting this in.

@davidzollo davidzollo added the First-time contributor First-time contributor label Aug 31, 2026
@luozihen

luozihen commented Sep 1, 2026

Copy link
Copy Markdown
Author

@DanielLeens
Hi, I accidentally merged the upstream dev branch into my dev branch before opening this PR (commit hash: [2acb55a]). This caused the CI tests to fail because of the upstream code, while my own changes are fully tested and working.

Since this merge commit has already been pushed, I'd like to ask for your preferred way to fix this:

Safe way (Revert): I can run git revert -m 1 [hash] and push normally. This will add a revert commit to cancel the upstream changes and pass the CI, but it leaves a revert commit in history.

Clean way (Rebase): I can drop that merge commit via interactive rebase and force push, but it will rewrite the remote history.

I'm leaning towards option 1 to avoid force-push issues. Please let me know your preference. Sorry for the noise!

@DanielLeens

Copy link
Copy Markdown
Contributor

@luozihen thanks for flagging this proactively instead of just leaving CI red — that's exactly the right instinct, and this kind of accidental merge-into-feature-branch mistake is extremely common, so no need to apologize for the noise!

My preference here is actually option 2 (rebase), not option 1 (revert) — and I'd suggest an even simpler variant than a manual interactive rebase:

git fetch origin dev
git rebase origin/dev
# resolve any real conflicts if your own commits touch lines dev has since changed
git push --force-with-lease

A plain (non-interactive) git rebase origin/dev will automatically drop the merge commit for you — rebase replays only the commits that are yours (not already reachable from origin/dev), and a merge commit whose "left" parent is already on origin/dev contributes no new patch of its own, so it gets skipped rather than replayed. You shouldn't need to hand-pick which commit to drop.

Why rebase over revert in this specific case:

  • A revert commit cancels out the upstream changes in your branch's history, but it doesn't remove the merge commit itself — your branch still carries an extra merge commit and a revert commit, both of which are irrelevant to this PR's actual diff. That's more history noise, not less, and it can make the "Files changed" tab harder to read while this PR is under review.
  • Force-pushing here is safe: this is your own PR branch, nobody else has based work on top of it, and Apache SeaTunnel squash-merges PRs on landing anyway, so the interim commit history won't survive into dev either way. There's no shared-history risk that the usual "don't force-push" caution is meant to protect against.
  • A clean rebase means CI runs against exactly your feature diff on top of current dev, with nothing from a stale merge snapshot mixed in — which also makes it easier for me to confirm the green run actually reflects your changes when I re-review.

Go ahead with the rebase + force-push, and ping me once CI is green again — I'll take another look. Thanks again for the careful contribution and for keeping the PR history clean, that's a great habit to build early!

@DanielLeens

Copy link
Copy Markdown
Contributor

Hi @luozihen — thanks for flagging this, but good news: you don't actually need to revert or rebase to fix CI here. I traced the failure before answering, and the merge commit isn't the cause.

The real failure is a genuine, 100% reproducible bug in the new unit test added by this PR itself:

ConfigShadeTest.testDecryptPreservesSpecialCharacterKeys (seatunnel-core/seatunnel-core-starter/src/test/java/org/apache/seatunnel/core/starter/utils/ConfigShadeTest.java:407-416) fails in the unit-test job on all 4 JDK/OS legs (8/11 x ubuntu/windows) with:

org.apache.seatunnel.shade.com.typesafe.config.ConfigException$Parse: String: 2: Expecting close brace } or a comma, got '=' ...

Root cause is a HOCON syntax bug in the literal string passed to ConfigFactory.parseString(...):

"sink { Jdbc { url = \"jdbc:mysql://localhost:3306/db\" "
        + "username = \"u\" password = \"p\" "
        + "multi-table_config { ... } } }"

In HOCON, sibling key-value pairs on the same line need a comma (or a newline) between them. Since url = "...", username = "u", and password = "p" sit on one logical line separated only by whitespace, the parser treats the quoted URL string and the following bareword username as one concatenated value, then chokes on the unexpected = right after it — which matches the "got '='" message exactly. This is a static parse error, not timing/environment dependent, so it fails on every run regardless of the merge commit.

Fix: add commas (or put each field on its own line) between url/username/password/multi-table_config in that HOCON literal, e.g.:

"sink { Jdbc { url = \"jdbc:mysql://localhost:3306/db\", "
        + "username = \"u\", password = \"p\", "
        + "multi-table_config { ... } } }"

Separately, the other failure in this run (rocketmq-connector-it) is an unrelated Testcontainers/Docker networking flake inside the RocketMQ broker container (RemotingSendRequestException: send request to ... failed) — unrelated to your diff, safe to ignore/rerun.

On the git-history question: this repo squash-merges PRs at merge time, so the intermediate commit history (merge commit included) won't carry into the final merged commit either way — you don't need to revert or force-push-rebase purely for CI's sake. If you'd still like a tidier branch, git revert -m 1 (your option 1) is the safer choice since the merge commit is already pushed publicly. Push the test fix above on top of that, and CI should go green.

@DanielLeens

Copy link
Copy Markdown
Contributor

@luozihen Thanks for flagging this, and no worries about the noise.

Before answering the revert-vs-rebase question I dug into the actual CI failure, because fixing the merge commit alone will not fix CI here.

The real root cause is not the upstream dev merge — it's a HOCON syntax bug in your own new test, ConfigShadeTest#testDecryptPreservesSpecialCharacterKeys (seatunnel-core/seatunnel-core-starter/src/test/java/org/apache/seatunnel/core/starter/utils/ConfigShadeTest.java:407-416 at your current head). I compared this method between your pre-merge commit (88c2358193b9) and the merge commit (2acb55a048d0) and it is byte-for-byte identical in both — so the apache:dev merge did not introduce this failure, it was already broken before you merged.

The failing job is unit-test (all four JDK/OS matrix lanes), failing in module seatunnel-core-starter:

[ERROR] Tests run: 13, Failures: 0, Errors: 1, Skipped: 0 <<< FAILURE! - in org.apache.seatunnel.core.starter.utils.ConfigShadeTest
[ERROR] testDecryptPreservesSpecialCharacterKeys  Time elapsed: 0.004 s  <<< ERROR!
org.apache.seatunnel.shade.com.typesafe.config.ConfigException$Parse: String: 2: Expecting close brace } or a comma, got '='
	at ConfigShadeTest.testDecryptPreservesSpecialCharacterKeys(ConfigShadeTest.java:442)

The raw HOCON literal the test builds its input from is:

"source { FakeSource { plugin_output = \"fake\" } }\n"
        + "sink { Jdbc { url = \"jdbc:mysql://localhost:3306/db\" "
        + "username = \"u\" password = \"p\" "
        + "multi-table_config { primary_keys { "
        + "\"^t_nova_.*$\" = [\"${primary_key}\", \"DATA_SOURCE\"] "
        + "\"^t_tyuen_txn_.*$\" = [\"id_txn_ctrl\", \"DATA_SOURCE\"] "
        + "} } } }"

In HOCON, fields inside an object must be separated by a comma or a newline. url = "..." username = "u" on one physical line with only a space between them is not valid — the parser tries to concatenate the quoted url value with the following unquoted token username, then errors out on the = that comes right after it (hence "Expecting close brace } or a comma, got '='"). The same missing-separator problem repeats for username/password, password/multi-table_config, and the two primary_keys entries ("^t_nova_.*$" = [...] next to "^t_tyuen_txn_.*$" = [...]).

Fix: add commas (or real newlines) between every field, e.g.:

Config input =
        ConfigFactory.parseString(
                "source { FakeSource { plugin_output = \"fake\" } }\n"
                        + "sink { Jdbc { url = \"jdbc:mysql://localhost:3306/db\", "
                        + "username = \"u\", password = \"p\", "
                        + "multi-table_config { primary_keys { "
                        + "\"^t_nova_.*$\" = [\"${primary_key}\", \"DATA_SOURCE\"], "
                        + "\"^t_tyuen_txn_.*$\" = [\"id_txn_ctrl\", \"DATA_SOURCE\"] "
                        + "} } } }");

(or switch to a Java text block / genuinely multi-line literal so real newlines do the separating for you — that tends to be less error-prone than tracking commas across a long chain of concatenated strings).

On your actual question, once that test is fixed:

  • Recommendation: rebase (your option 2), not revert. This is your own PR source branch, not a shared/protected branch, so an interactive rebase to drop the accidental merge commit followed by a force-push is completely normal and safe here — that's exactly what rebasing your own feature branch is for. git revert -m 1 <merge-sha> also "works," but reverting a merge commit has a well-known follow-up trap: if you ever merge apache:dev into this branch again later, git can silently treat the commits from the first merge as already-integrated-then-reverted, and you'd have to revert your own revert first to bring them back. Rebasing avoids that trap and gives reviewers a clean, linear diff.
  • Practically, it won't affect the permanent project history either way: Apache SeaTunnel merges PRs with squash-merge, so everything on this branch collapses into a single commit on dev regardless of whether the branch itself contains a merge commit, a revert commit, or a clean rebase.

So: rebase onto the latest apache:dev, fix the missing commas in testDecryptPreservesSpecialCharacterKeys, force-push to your own branch, and CI should go green. Let me know if anything else comes up.

@luozihen

luozihen commented Sep 1, 2026 •

Copy link
Copy Markdown
Author

@DanielLeens
Thank you very much for your patience and thoroughness in diagnosing the exact cause of the CI failure – I truly appreciate it. This was indeed my oversight: I verified the changes using my usual testing approach but did not actually run this specific unit test locally, which led to the issue. I have now revised the HOCON block in the configuration literal and verified that the test passes locally. I have pushed the updated code and am now waiting for the CI to finish. Again, I apologise for the inconvenience and am very grateful for your detailed guidance.

Separately, I have rebased my branch as suggested. Going forward, I will avoid merging from the upstream repository into my feature branch, as that can introduce unnecessary noise and distract from the actual changes in this PR.

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

Hi @luozihen — thanks for the update, and glad the missing-comma HOCON bug in testDecryptPreservesSpecialCharacterKeys turned out to be a quick, local fix once you spotted it. Rebasing to drop the accidental merge commit was the right call too, that keeps the diff clean for review. I re-checked: CI on the new head is currently still queued/in-progress on your fork, so please ping again once it finishes and I'll take a final look at the green run.

Since the head has moved (2acb55a0 -> 53f84008), here is a complete re-review against the current head, not just a diff against my last review.

What Problem Does This PR Solve?

  • User pain point: multi-table JDBC sink jobs (e.g. MySQL-CDC -> JDBC with generate_sink_sql = true) only have one global primary_keys option, so there's no way to give different tables different key columns (or mix ${primary_key}/${unique_key} with a shared static column such as DATA_SOURCE) in a single sharding/merge job.
  • Fix approach: adds a multi-table_config.primary_keys option to JdbcSinkFactory that maps a table-name regex to a key-column list (with ${primary_key}/${unique_key} expansion), taking precedence over the existing primary_keys / catalog-metadata fallback. It also fixes a real config-reconstruction bug: ConfigFactory.parseMap(...) treats every map key as a HOCON path expression, so a regex key such as ^t_nova_.*$ (containing . and $) throws ConfigException$BadPath. The PR replaces ConfigFactory.parseMap(...) with a Jackson JSON round-trip in ReadonlyConfig#toConfig() and ConfigShadeUtils#processConfig.
  • One-sentence summary: same well-motivated, mostly well-tested JDBC feature as before; the code itself is unchanged since my last review other than the CI-blocking unit-test HOCON syntax fix, so my previous findings on the shared-API change and code duplication still apply and have not yet been addressed.

1. Code Change Review

1.1 Core Logic Analysis

I diffed 2acb55a0 (my last-reviewed commit) against the current head 53f84008 directly (git diff 2acb55a0 53f84008 --stat). The only file with a real content change is seatunnel-core/seatunnel-core-starter/src/test/java/.../ConfigShadeTest.java (the comma fix in the new testDecryptPreservesSpecialCharacterKeys HOCON literal, resolving the parse failure discussed on the thread). Everything else in that raw diff is unrelated upstream dev content (BigQuery/Hive/Stripe connectors, SQL functions, etc.) that came in through the merge commit and is not part of this PR's actual diff (gh pr diff correctly excludes it via merge-base). So the functional code of this feature is byte-for-byte identical to what I reviewed at 2acb55a0.

I re-verified the core logic directly in the current checkout, all consistent with before:

  • JdbcSinkFactory.resolveMultiTablePrimaryKeys() / matchesPattern() / toPrimaryKeyList() / expandPrimaryKeyPlaceholder() / getPrimaryKeyColumns() / getUniqueKeyColumns() (JdbcSinkFactory.java:222-297, unchanged) — full-match regex (tableName.matches(pattern)), first-match-wins via LinkedHashMap iteration order (traced through fromConfig's Jackson TypeReference<Map<String,Object>>, which preserves declaration order), clear JdbcConnectorException when a placeholder is used but the upstream key is missing. Correct.
  • No double-processing with TablePlaceholderProcessor.replaceTablePlaceholder (seatunnel-api/.../TablePlaceholderProcessor.java:161-206), which only rewrites top-level String/single-element String List values and leaves a top-level Map (like multi-table_config) untouched — still verified safe.

Carryover Issue 1 (from my 2acb55a0 review, still open at 53f84008): ReadonlyConfig#toConfig() (seatunnel-api/src/main/java/org/apache/seatunnel/api/configuration/ReadonlyConfig.java:78-86, confirmed unchanged in the current checkout) still swaps ConfigFactory.parseMap(confData) for a Jackson JSON round-trip. This @Deprecated-but-still-load-bearing method has ~20 call sites outside this diff (e.g. FactoryUtil.java legacy source.prepare()/sink.prepare() fallback, MultiTableFailureHelper, connectors like Hive/Clickhouse/HDFS/Neo4j/AmazonSQS/AmazonDynamoDB/OpenMLDB/HTTP/IoTDB/GraphQL). parseMap() auto-expands dotted map keys into nested HOCON paths ({"a.b":1} -> {a:{b:1}}); the new JSON-based toConfig() keeps such keys literal/flat. Any caller building a dotted-key map that's later read back via a dotted-path lookup on the resulting Config would silently get a missing value instead of an exception — a hard-to-trace regression class. I still haven't found a concrete broken caller in-repo (the trace shows the JDBC feature itself only needs the ConfigShadeUtils.processConfig half of the fix, which is provably necessary and safe since its input is already JSON-normalized), but this remains unaddressed since last review.

Carryover Issue 2 (still open): the pre-existing PK-fallback-resolution logic (catalog PK -> first unique key -> plain INSERT) is still duplicated verbatim into the else branch of if (multiTablePrimaryKeys.isPresent()) (JdbcSinkFactory.java:159-201), instead of being extracted into a shared private helper called from both branches.

Carryover Issue 3 (still open): resolveMultiTablePrimaryKeys and its private helpers still have no Javadoc describing the matching/placeholder-expansion contract (verified via grep for /** in the current file — none precede these methods).

1.2 Compatibility Impact

  • Fully compatible for the new multi-table_config option: purely additive, optional, only takes effect when a table name matches a configured pattern; unmatched tables fall back to the pre-existing logic unchanged.
  • Partially incompatible / unverified, unchanged from last review: the ReadonlyConfig#toConfig() semantics change (Issue 1) is a behavior change to a shared API with a real, if currently unproven in-repo, potential to silently drop dotted-key config values for callers outside the JDBC connector.

1.3 Performance / Side-Effect Analysis

Unchanged from last review: all changed code runs once per job/sink-instantiation at submission time, not in the per-record hot path. No new threads, connections, or unbounded collections.

1.4 Error Handling and Logging

Unchanged from last review: error messages (INVALID_MULTI_TABLE_CONFIG, missing-PK/unique-key messages) are clear, include table/pattern context, and don't leak sensitive data.

Issue Location Problem Risk Fix Severity Raised by another reviewer
1 seatunnel-api/src/main/java/org/apache/seatunnel/api/configuration/ReadonlyConfig.java:78-86 toConfig() (shared, ~20 call sites) changes Map->Config reconstruction semantics (dotted-key auto-expansion removed); no regression test proves other callers are unaffected Medium — no concrete broken caller found in-repo, audit not exhaustive, failure mode is silent Scope the fix to ConfigShadeUtils.processConfig only (provably necessary and safe) and leave toConfig() untouched; or add explicit regression coverage + call out as an audited change in the PR description Medium No
2 seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:118-201 Pre-existing PK-fallback logic duplicated verbatim into the new else branch Low — maintainability only Extract into a shared private method used by both branches Medium No
3 seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:222-297 New non-trivial methods lack Javadoc Low Add short Javadoc describing matching/placeholder semantics Low No

2. Code Quality Assessment

2.1 Coding Standards

Unchanged from last review: naming/style follow existing conventions (Google/AOSP via Spotless, no wildcard imports). The new MULTI_TABLE_CONFIG Option has a description. Missing Javadoc on new helper methods per Issue 3 above.

2.2 Test Coverage and Test Stability

  • New unit tests are unchanged in structure from last review: JdbcSinkFactoryTest (mapped hit, unmatched/fallback, missing-PK error, first-match-wins, string-value parsing, full factory-context path), ReadableConfigTest#testToConfigPreservesSpecialCharacterKeys, and ConfigShadeTest#testDecryptPreservesSpecialCharacterKeys (now fixed — the HOCON literal in this test previously had missing commas between sibling fields on the same line, which is exactly what broke CI; the current head adds the required commas, e.g. url = "...", username = "u", password = "p", multi-table_config { ... }, and I traced this to be syntactically valid HOCON that will parse successfully).
  • Stability rating: Stable. All new/modified tests are pure, deterministic unit tests — no sleeps, no timing assumptions, no external I/O, no unordered-collection assertions without normalization.
  • Gap unchanged from last review: no test proves ReadonlyConfig#toConfig()'s new behavior is compatible with a dotted-key map for a caller outside the JDBC path (Issue 1).

2.3 Documentation Updates

Unchanged from last review: docs/en and docs/zh for Jdbc.md and sink-options-placeholders.md are both updated consistently and match the code (option key multi-table_config, sub-key primary_keys, placeholder syntax).

3. Architectural Soundness

3.1 Elegance of the Solution

Unchanged: the regex-to-key-list mapping design is precise and well-scoped. The underlying config-parsing bug fix is still applied at a broader scope than the traced necessary path requires (Issue 1) — inconsistent with a minimal-blast-radius change to a 3-year production system.

3.2 Maintainability

Unchanged, aside from the duplication noted in Issue 2.

3.3 Extensibility

Unchanged: the multi-table_config shape ({ primary_keys: { "<regex>": [...] } }) leaves room for future sibling keys without another breaking change.

3.4 Historical-Version Compatibility

Unchanged: no existing option is renamed/removed, new option is opt-in with exact fallback to pre-existing logic. Open question remains the ReadonlyConfig#toConfig() semantics change (Issue 1).

4. Issue Summary

Number Issue Location Severity
1 ReadonlyConfig#toConfig() semantics changed (dotted-key auto-expansion removed) for a shared API used by ~20 call sites outside this PR's scope; feature's own path doesn't appear to need this change (carried over from 2acb55a0 review, still unaddressed) seatunnel-api/src/main/java/org/apache/seatunnel/api/configuration/ReadonlyConfig.java:78-86 Medium
2 Pre-existing PK-fallback logic duplicated instead of extracted into a shared helper (carried over, still unaddressed) seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:118-201 Medium
3 New non-trivial methods lack Javadoc (carried over, still unaddressed) seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:222-297 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed
    • Get CI green on the current head (the HOCON test-syntax fix looks correct from my read of the diff, but I want to see the actual run finish rather than assume it).
    • No hard functional blocker in the feature logic itself, same as last time — but I'd still like Issue 1 either scoped down to ConfigShadeUtils.processConfig only, or explicitly justified/tested, before merge, since it's a silent behavior change to a widely-used shared API.
  2. Recommended fixes — non-blocking
    • Extract the duplicated PK-fallback block into a shared private method (Issue 2).
    • Add short Javadoc to resolveMultiTablePrimaryKeys and its helpers (Issue 3).

Nothing new to flag on the feature logic itself since my last pass — the code is identical to what I reviewed at 2acb55a0, and the only change on this head is the CI-fixing test correction, which looks right. I have read-only review rights here (Comment only), so a write-capable maintainer will need to make the final call on approval/merge, particularly on whether the ReadonlyConfig#toConfig() scope is an accepted tradeoff.

Thanks again for staying engaged through the CI back-and-forth, and for the clean rebase — looking forward to a green run.

@luozihen

luozihen commented Sep 3, 2026

Copy link
Copy Markdown
Author

@DanielLeens
Thanks for the thorough re-review and for laying out the three issues so clearly.

I've addressed all of them in the latest push:

  1. Scoped down the shared-API change (Issue 1) — reverted ReadonlyConfig#toConfig() back to
    ConfigFactory.parseMap(confData), so the existing dotted-key expansion semantics are left
    untouched. The JDBC feature no longer depends on changing toConfig(); instead,
    MultiTableFailureHelper.mergeOptions() now merges the underlying option maps directly
    (primary takes precedence), which avoids re-parsing the regex keys as HOCON paths.

  2. Extracted the duplicated PK-fallback logic (Issue 2) — moved it into
    applyPrimaryKeys / applyFallbackPrimaryKeys, called from both branches.

  3. Added Javadoc (Issue 3) — documented the matching and placeholder-expansion contract for
    resolveMultiTablePrimaryKeys and its private helpers.

I also updated the tests to match: removed the now-obsolete
ReadableConfigTest#testToConfigPreservesSpecialCharacterKeys, and added a
MultiTableFailureHelperTest case verifying that mergeOptions preserves the special-character
keys.

The changes are committed and CI is running on the new head. I'll ping here again once it finishes.

Regarding the previous CI run, I noticed an error that I wasn't able to interpret on my own:

Error during callback
com.github.dockerjava.api.exception.InternalServerErrorException: Status 500:
{"message":"Get \"https://registry-1.docker.io/v2/\": net/http: request canceled while waiting
for connection (Client.Timeout exceeded while awaiting headers)"}

It looks like it timed out pulling an image from Docker Hub, so it may be a transient network
issue rather than a problem with the changes. I'm not confident about that conclusion though, so
if this (or anything similar) shows up again in the new run, I'd really appreciate a pointer on
how to interpret and troubleshoot it.
Thanks again for your patience and guidance throughout this.

@luozihen

luozihen commented Sep 4, 2026

Copy link
Copy Markdown
Author

@DanielLeens Quick follow-up: the latest CI run has finished, and it failed on a different set of errors — all
in the Doris connector integration tests:

DorisCDCSinkIT » ... org.testcontainers.containers.ContainerLaunchException ...
DorisErrorIT.testDoris:91 » ContainerLaunch Container startup failed
DorisIT » ... org.testcontainers.containers.ContainerLaunchException ...

These are ContainerLaunchException / Container startup failed from Testcontainers, which looks
like the Docker container couldn't be started in the CI environment — similar in nature to the
earlier Docker Hub pull timeout. They're in the Doris connector ITs and don't appear related to this
PR, whose changes are in the JDBC connector and config modules.
I'm still not entirely sure how to interpret these, so if you could let me know whether this is
likely a transient CI/Docker environment issue or something I should address on my side, I'd really
appreciate it.
Thanks again for your patience.

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

What Problem Does This PR Solve?

  • User pain point: multi-table JDBC sink jobs (e.g. MySQL-CDC -> JDBC with generate_sink_sql = true) only have one global primary_keys option, so there is no way to give different tables different key columns (or mix ${primary_key}/${unique_key} with a shared static column such as DATA_SOURCE) in a single sharding/merge job.
  • Fix approach: adds a multi-table_config.primary_keys option to JdbcSinkFactory that maps a table-name regex to a key-column list (with ${primary_key}/${unique_key} expansion), taking precedence over the existing primary_keys / catalog-metadata fallback. It also carries a real config-reconstruction bug fix in ConfigShadeUtils#processConfig so a regex key such as ^t_nova_.*$ (containing . and $) survives the encrypt/decrypt round trip instead of throwing ConfigException$BadPath.
  • One-sentence summary: this is a re-review at a new head (53f84008 -> 1730aeef); all three issues from my previous two passes have been addressed with clean, well-scoped fixes, and my fresh trace of the current code found only one small new maintainability nit, no functional blockers.

1. Code Change Review

1.1 Core Logic Analysis

Verifying the three previously-open issues are actually resolved (not just claimed)

I diffed the current head against the commit my last review covered and re-read every touched file end to end rather than trusting the PR author's summary comment.

  • Former Issue 1 (shared ReadonlyConfig#toConfig() semantics change) — confirmed resolved. seatunnel-api/src/main/java/org/apache/seatunnel/api/configuration/ReadonlyConfig.java no longer appears anywhere in git diff <merge-base>...HEAD — it is byte-for-byte back to the pre-PR version, so the ~20 external call sites I flagged before (FactoryUtil.java legacy prepare() fallback, Hive/Clickhouse/HDFS/Neo4j/etc.) are no longer at risk. The actual JDBC feature's own need (surviving encrypt/decrypt with regex keys) is now met solely by ConfigShadeUtils#processConfig (seatunnel-core/seatunnel-core-starter/.../ConfigShadeUtils.java:213-217), which was already the provably-necessary, provably-safe half of the original fix: it swaps ConfigFactory.parseMap(configMap) for ConfigFactory.parseString(JsonUtils.toJsonString(configMap), ConfigParseOptions.defaults().setSyntax(ConfigSyntax.JSON)), and configMap is itself already the result of a JSON parse (JsonUtils.toMap(JsonUtils.parseObject(jsonString)) two lines above), so this is a lossless textual re-encoding, not a semantics change.
    • The one place that previously depended on the now-reverted toConfig() behavior, MultiTableFailureHelper#mergeOptions (seatunnel-api/.../MultiTableFailureHelper.java:55-66), was reworked to merge the underlying Map<String,Object> directly instead of round-tripping through Config: merged.putAll(fallback.getSourceMap()); merged.putAll(primary.getSourceMap()); return ReadonlyConfig.fromMap(merged);. getSourceMap() and fromMap() are pre-existing ReadonlyConfig APIs (unchanged by this PR — verified via git diff), so this trades a Config#withFallback() deep-merge for a shallow, top-level-key putAll merge. I checked both call sites of mergeOptions (withMultiTableFailurePolicy and withFailedTables, same file, lines 68-91): in both cases primary is a synthetic single-key map (MULTI_TABLE_FAILURE_POLICY or MULTI_TABLE_INITIAL_FAILED_TABLES) that never overlaps with any nested key inside the real options/envOptions map, so the shallow-vs-deep-merge distinction is a no-op for every current caller. The new MultiTableFailureHelperTest#testMergeOptionsPreservesSpecialCharacterKeys (seatunnel-api/src/test/.../MultiTableFailureHelperTest.java:34-65) directly exercises the regex-key-survival property this rework needed to preserve. Good, targeted fix.
  • Former Issue 2 (duplicated PK-fallback logic) — confirmed resolved. The pre-existing catalog-PK/unique-key/plain-INSERT fallback block is now extracted into applyFallbackPrimaryKeys (JdbcSinkFactory.java:204-233), and the new multi-table-match branch calls the shared applyPrimaryKeys helper (JdbcSinkFactory.java:163-191) that both resolveMultiTablePrimaryKeys and applyFallbackPrimaryKeys's explicit-primary_keys case route through. createSink() itself (JdbcSinkFactory.java:122-127) is now a clean two-branch dispatch with no duplicated body.
  • Former Issue 3 (missing Javadoc) — confirmed resolved. resolveMultiTablePrimaryKeys, matchesPattern, toPrimaryKeyList, expandPrimaryKeyPlaceholder, getPrimaryKeyColumns, and getUniqueKeyColumns (JdbcSinkFactory.java:234-390) all now carry Javadoc describing the matching semantics (full-match regex, first-match-wins, ${primary_key}/${unique_key} contract) or return-value contract. This matches project convention for non-trivial new methods.

New finding from this pass — Issue 1 (new, Low): while verifying the Issue-2 extraction, I noticed applyFallbackPrimaryKeys (JdbcSinkFactory.java:204-233) re-implements the exact same "catalog primary key, else first unique key" lookup that getPrimaryKeyColumns/getUniqueKeyColumns (JdbcSinkFactory.java:363-390) already provide — the two helpers were added earlier in this same diff for the ${primary_key}/${unique_key} placeholder-expansion path. Concretely, applyFallbackPrimaryKeys re-derives catalogTable.getTableSchema().getPrimaryKey() and re-filters getConstraintKeys() for a UNIQUE_KEY constraint inline, instead of calling getPrimaryKeyColumns(catalogTable) / getUniqueKeyColumns(catalogTable) and joining the result. This is a small residual duplication introduced by the very refactor that fixed the original Issue 2 — not a correctness bug (both code paths currently compute identical results, verified by reading both side by side), purely a maintainability nit: a future change to "how we pick the catalog fallback key" now has two places to update instead of one.

  • Location: seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkFactory.java:204-233 (duplicate) vs. :363-390 (existing helpers it could delegate to).

Runtime path (touches seatunnel-api: MultiTableFailureHelper, and the core-starter config-decrypt step)

  1. Job submission: ConfigShadeUtils.processConfig (seatunnel-core-starter/.../ConfigShadeUtils.java:151-224) runs once per job, decrypting sensitive fields in the raw JSON-rendered config map (including any multi-table_config.primary_keys block) and reconstructing a Config via the JSON-syntax parse path fixed here.
  2. Per-table dispatch: for each table in a multi-table sink, FactoryUtil/engine code builds a TableSinkFactoryContext and calls JdbcSinkFactory.createSink(context) (JdbcSinkFactory.java:88-161).
  3. Inside createSink, resolveMultiTablePrimaryKeys(config, catalogTable) (JdbcSinkFactory.java:242-263) reads MULTI_TABLE_CONFIG off the per-table ReadonlyConfig (a plain map lookup, no toConfig() involved) and either matches a regex pattern (first-match-wins via LinkedHashMap-preserving iteration order from ReadonlyConfig.fromMap/fromConfig's Jackson read) or falls through to applyFallbackPrimaryKeys.
  4. Either branch calls applyPrimaryKeys (or its inline equivalent) to write PRIMARY_KEYS back into the sink config map and rebuild the CatalogTable with a PrimaryKey.of(...) reflecting the resolved columns; config = ReadonlyConfig.fromMap(new HashMap<>(map)) then feeds JdbcSinkConfig.of(config) and the eventual JdbcSink construction, which is what generated UPSERT/UPDATE/DELETE statements key off.
  5. Separately, MultiTableFailureHelper.withMultiTableFailurePolicy/withFailedTables (unrelated call sites, engine/translation layer) merge environment-level failure-policy options into per-connector options via the reworked mergeOptions — this path does not intersect with the JDBC multi-table_config values above (different config keys), so there is no interaction risk between the two changes in this PR.
  6. I re-verified there is still no double-processing with the generic placeholder framework: TablePlaceholderProcessor.replaceTablePlaceholder (seatunnel-api/.../TablePlaceholderProcessor.java:161-206, unchanged) only rewrites top-level String/single-element-String-List values, so it never touches the nested Map under multi-table_config, leaving expandPrimaryKeyPlaceholder as the sole place that expands ${primary_key}/${unique_key} inside this option.

1.2 Compatibility Impact

Fully compatible. The new multi-table_config option is purely additive and opt-in; unmatched or absent configuration falls back to the exact pre-existing primary_keys/catalog-metadata resolution logic (now in applyFallbackPrimaryKeys, byte-equivalent to the pre-PR inline code). The ReadonlyConfig#toConfig() behavior-change risk I flagged in both previous reviews is fully eliminated now that the method is untouched. ConfigShadeUtils#processConfig's JSON-syntax parse is a lossless re-encoding of already-JSON-normalized data, and MultiTableFailureHelper#mergeOptions's shallow-merge rework is behaviorally identical to the old deep merge for every current caller (verified above). No existing option is renamed, removed, or has its default changed; no protocol/serialization/checkpoint format is touched.

1.3 Performance / Side-Effect Analysis

  • All changed code executes once per job submission / per-table sink instantiation (createSink(), config decrypt), not in the per-record hot path — negligible overhead relative to job-submission cost.
  • mergeOptions's shallow HashMap copy is strictly cheaper than the old Config#withFallback() deep merge it replaces.
  • No new threads, connections, unbounded collections, or retry loops introduced.

1.4 Error Handling and Logging

Issue Location Problem Risk Fix Severity Raised by another reviewer
1 seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkFactory.java:204-233 applyFallbackPrimaryKeys re-implements the catalog-PK/unique-key lookup that getPrimaryKeyColumns/getUniqueKeyColumns (lines 363-390) already provide, instead of delegating to them Low — maintainability only; both paths currently compute identical results Have applyFallbackPrimaryKeys call getPrimaryKeyColumns(catalogTable) and, if empty, getUniqueKeyColumns(catalogTable), joining the result, instead of re-deriving the lookup inline Low No

Error messages (INVALID_MULTI_TABLE_CONFIG, "table X matched pattern Y ... but the upstream table has no primary/unique key") remain clear, include table/pattern context, and do not leak sensitive data.

2. Code Quality Assessment

2.1 Coding Standards

All new non-trivial methods now have Javadoc (former Issue 3, confirmed fixed above). The new MULTI_TABLE_CONFIG Option (JdbcSinkOptions.java:112-121) has a description. Naming/style follow existing conventions (Google/AOSP via Spotless, no wildcard imports). No missing-comment items found in this pass.

2.2 Test Coverage and Test Stability

  • JdbcSinkFactoryTest gained direct unit tests for resolveMultiTablePrimaryKeys (mapped hit, unmatched/fallback, missing-key error, first-match-wins, string-value parsing) plus an end-to-end testFactoryContextWithMultiTableConfigValid through the real createSinkViaFactoryContext entry path.
  • MultiTableFailureHelperTest#testMergeOptionsPreservesSpecialCharacterKeys directly covers the reworked shallow-merge behavior for regex keys.
  • ConfigShadeTest#testDecryptPreservesSpecialCharacterKeys covers the ConfigShadeUtils fix; the previously CI-breaking missing-comma HOCON syntax bug in this test's literal is fixed in the current head (verified: every sibling field in the object literal is now comma-separated).
  • Stability rating: Stable. All new/modified tests are pure, deterministic unit tests operating on in-memory maps — no Thread.sleep, no wall-clock assertions, no external I/O, no unordered-collection comparisons without normalization, no shared mutable static state.

2.3 Documentation Updates

docs/en/connectors/sink/Jdbc.md and docs/zh/connectors/sink/Jdbc.md both add a matching multi-table_config option-table row and a full ### multi-table_config [object] section with two worked examples (pure mapping, and mixed with top-level primary_keys). docs/en/introduction/configuration/sink-options-placeholders.md and its docs/zh counterpart both add a clarifying paragraph distinguishing the generic placeholder framework's single-element-list restriction from the JDBC-specific multi-table_config.primary_keys mixing support — this is accurate per my trace of TablePlaceholderProcessor vs. expandPrimaryKeyPlaceholder above. English and Chinese docs are consistent with each other and with the code (option key multi-table_config, sub-key primary_keys, placeholder syntax).

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix. With the ReadonlyConfig#toConfig() scope-down, both halves of this PR are now minimal-blast-radius: the config-decrypt fix is confined to ConfigShadeUtils, and the JDBC feature logic is confined to JdbcSinkFactory/JdbcSinkOptions. The regex-to-key-list design (declaration-order first-match, placeholder expansion scoped to this option only) is well-suited to the stated problem and was verified not to conflict with the existing generic placeholder framework.

3.2 Maintainability

Good, aside from the small residual duplication noted in Issue 1 above.

3.3 Extensibility

Unchanged from my prior assessment: the multi-table_config shape ({ primary_keys: { "<regex>": [...] } }) leaves room for future sibling keys under multi-table_config without another breaking change, since it is read as a generic Map<String,Object>.

3.4 Historical-Version Compatibility

No existing option is renamed/removed; the new option is opt-in with an exact fallback to the pre-existing logic when unmatched/absent. The shared-API risk that was the main open question in my last two reviews (ReadonlyConfig#toConfig()) is fully closed now that the method is untouched.

4. Issue Summary

Number Issue Location Severity
1 applyFallbackPrimaryKeys duplicates the catalog-PK/unique-key lookup already provided by getPrimaryKeyColumns/getUniqueKeyColumns instead of delegating to them seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:204-233 (vs. :363-390) Low

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers — must be fixed
    • None. All three issues from my previous two review passes (shared ReadonlyConfig#toConfig() behavior change, duplicated PK-fallback logic, missing Javadoc) are verified resolved in the current head, and this fresh independent pass found no new functional, compatibility, or data-safety issues.
  2. Recommended fixes — non-blocking
    • Have applyFallbackPrimaryKeys delegate to the existing getPrimaryKeyColumns/getUniqueKeyColumns helpers instead of re-deriving the same lookup inline (Issue 1 above).

On CI: the apache-side Build check is currently red, but I dereferenced it to the actual fork run (luozihen/seatunnel run 33743266792) and both failing jobs are doris-connector-it (JDK 8 and 11), not any module touched by this PR's diff (JDBC connector, seatunnel-api config, seatunnel-core-starter). I pulled the actual job logs and the failures are Testcontainers/Docker networking symptoms around the Doris FE/BE containers — Connection reset, Temporary failure in name resolution on the doris_e2e hostname, and Can't find tablet id ... maybe already dropped — not assertion failures on JDBC/PK-mapping behavior. This matches the author's own report on the PR thread and is consistent with a transient container-networking flake rather than a regression caused by this diff; I'd recommend a rerun of just the doris-connector-it job rather than any code change. mergeStateStatus shows BLOCKED/mergeable: MERGEABLE — that reflects branch protection requiring an approving review (reviewDecision: REVIEW_REQUIRED), not a merge conflict; no sync-with-dev action is needed on that front.

Overall this turned into a genuinely productive back-and-forth: the author correctly diagnosed and fixed a real HOCON test-syntax bug I flagged, and then addressed all three substantive review findings with clean, well-scoped fixes rather than papering over them — the shared-API change was properly scoped down instead of left broad, the duplication was properly extracted, and the documentation (English and Chinese) is thorough and matches the implementation. I do not see a materially better alternative implementation for the core feature; the regex-map design is a reasonable, minimal-footprint choice for this kind of per-table override. I have read-only review rights here (Comment only), so a write-capable maintainer will need to make the final call on approval/merge once the unrelated Doris IT flake clears on rerun.

Thanks for the thorough engagement through several rounds of CI back-and-forth, and for taking the shared-API scoping concern seriously rather than just chasing green CI — that is exactly the kind of care a 3-year production system needs from new contributors. Welcome again to the Apache SeaTunnel community.

@luozihen

luozihen commented Sep 7, 2026

Copy link
Copy Markdown
Author

@DanielLeens
Hi, could you please advise on how to rerun only the failed tests? The CI has been consistently red, and I'm wondering what I should do next. Any guidance would be appreciated. Thanks!

@DanielLeens

Copy link
Copy Markdown
Contributor

@luozihen Good question — and yes, this is still the same unrelated Doris-connector flake I called out in my last review, not a new failure. I re-checked the fork run just now (luozihen/seatunnel run 33743266792, head 1730aeef): the only two non-passing jobs are doris-connector-it (8, ubuntu-latest) and doris-connector-it (11, ubuntu-latest), both Testcontainers/Docker networking symptoms against the Doris FE/BE containers, plus kudu-connector-it which was cancelled (a downstream side-effect of the matrix, not a real failure) and a batch of updated-modules-integration-test-* jobs that were skipped. Nothing in the JDBC/config modules this PR touches is failing.

Since this PR's CI runs inside your own fork, you have direct rerun access without needing me or another maintainer:

  • UI: open the run page on luozihen/seatunnel (Actions tab -> this run -> "Re-run jobs" -> "Re-run failed jobs", top-right).
  • CLI (with your own GitHub auth, not mine): gh run rerun 33743266792 --repo luozihen/seatunnel --failed

That reruns only the failed/skipped legs, not the whole matrix, so it should be quick. To be clear: CI hasn't actually re-executed since your last push (the HOCON fix + rebase) — GitHub is just still displaying that same red run from 2026-09-03. A rerun is exactly the right next step here, no further code change needed on your side. If it comes back green (or fails again with the same Doris/Testcontainers signature), ping this thread and I'll do a fresh confirmation pass.

@luozihen

luozihen commented Sep 8, 2026

Copy link
Copy Markdown
Author

@DanielLeens Thank you for your guidance. The CI checks have now turned green. Could you please advise on the next steps? This is my first time submitting a PR, so I’m not entirely familiar with the full process. Apologies for any inconvenience, and thank you for your time.

@SEZ9

SEZ9 commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator

@luozihen Great news, thanks for rerunning — glad the Doris flake cleared and the run is green now. No need to apologise, you're doing everything right for a first PR.

Next steps from here:

  1. I'll do the fresh confirmation pass I promised on 1730aeef, going back through the points from my earlier review. To make that quick and avoid me guessing, could you post a short checklist in this thread of which of those items your last push (the HOCON fix + rebase) addressed, and which are still open or you'd like to push back on? Specifically:

    • F1 — the ReadonlyConfig.toConfig() JSON round-trip and its effect on dotted-key path semantics for all callers.
    • F2 / F5 — the "first pattern in declaration order wins" guarantee vs. the Map<String, Object> option type, and keeping the doc statement in docs/en/connectors/sink/Jdbc.md consistent with whatever ordering the code actually guarantees.
    • F3 — identifier validation for the resolved key columns before they're comma-joined into PRIMARY_KEYS and reach generated SQL.
    • F4 — how the connector-level ${primary_key}/${unique_key} expansion interacts with the engine-level TablePlaceholder replacement.
    • F6 — explicit compile-time validation of user-supplied regex patterns mapped to the new JDBC-12 error code.
    • F7 — a regression test for the previous toConfig() dotted-key expansion and an engine-level IT/E2E for the new option.
    • F8 — the multi-table_config key naming (hyphen + underscore mix).
  2. Once I've confirmed those, if anything is still open I'll leave targeted comments; if it's all covered I'll approve and we'll get a second maintainer look before merge, which is standard here.

You don't need to take any further action on CI. Just the checklist above and I'll take it from there.

@DanielLeens

Copy link
Copy Markdown
Contributor

@luozihen Congratulations on getting CI all the way to green, and welcome to the Apache SeaTunnel community — this has been a genuinely solid first contribution, and the way you dug into the HOCON/CI issues yourself along the way was great to see.

Where things stand right now, for your reference: I approved this PR on my side after the last round of fixes, and the latest run on 1730aeef is fully green (Build, labeler, and the notify workflow all completed successfully).

On next steps, here is roughly how it works in an Apache project like this one:

  1. My approval alone isn't enough to merge. Apache SeaTunnel requires review/approval from a project committer with merge rights before a PR can go in — my account here doesn't hold that permission, so a second maintainer still needs to look this over. That's normal and not a sign anything is wrong with your PR.
  2. @SEZ9 is doing exactly that second pass — they've already asked for a short checklist confirming which items from the earlier review round your last push addressed. Please answer that when you have a moment; it'll let them wrap their confirmation quickly.
  3. Timeline: since SeaTunnel is a volunteer-driven Apache project, maintainer availability varies — it can take anywhere from a few days to a couple of weeks to get a second reviewer's attention, especially for a larger feature PR like this one. There's nothing further you need to do to speed this up beyond answering open review questions promptly; no need to re-ping unless it's been quiet for a while.
  4. Once a maintainer with merge rights approves, they (or another committer) will merge it — normally as a squash merge onto dev.

Thanks again for your patience through the CI back-and-forth, and for the clear, cooperative communication throughout review — that makes this a lot smoother for everyone. Nicely done for a first PR.

@luozihen

luozihen commented Sep 8, 2026

Copy link
Copy Markdown
Author

@SEZ9
Thanks for the update, and for the clean checklist — that makes it much easier to confirm.

Here's the status against F1–F8 on the latest head:

Addressed:

  • F1 — I reverted ReadonlyConfig#toConfig() back to ConfigFactory.parseMap(confData), so
    the dotted-key path-expansion semantics are unchanged. The fix is now scoped to
    MultiTableFailureHelper.mergeOptions(), which merges the option maps directly instead of
    going through toConfig().
  • F4 — ${primary_key} / ${unique_key} expansion happens only in the connector
    (expandPrimaryKeyPlaceholder). The engine-level
    TablePlaceholderProcessor.replaceTablePlaceholder only rewrites top-level String /
    single-element-String-List values, so it leaves the nested multi-table_config map untouched —
    no double processing.

Addressed, but please confirm if you'd like it stricter:

  • F2 / F5 — I kept the order-based "first match wins" behavior and documented it. This is backed by
    the code path: ReadonlyConfig.fromConfig uses Jackson's TypeReference<Map<String, Object>>,
    which deserializes to a LinkedHashMap, preserving declaration order; I did not add a separate
    order-preservation test, so if you'd prefer I pin it down with a test or an explicit LinkedHashMap
    type, I can do that.

Still open — happy to address as follow-ups:

  • F3 — I haven't added explicit identifier validation for the resolved key columns; they are
    still comma-joined into PRIMARY_KEYS and rely on the existing list conversion.
  • F6 — regex patterns are currently validated lazily at match time (thrown as JDBC-12), not
    up-front during config validation.
  • F7 — I haven't added a regression test for the restored toConfig() dotted-key behavior, nor
    an engine-level IT/E2E for the new option (only unit tests so far).
  • F8 — the key is multi-table_config to match the name we settled on in the issue. If the
    project convention prefers a different form, I'm fine renaming it.

Happy to take the open ones on, or wait for your targeted comments and fix them accordingly.
Thanks again!

@SEZ9

SEZ9 commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator

@luozihen Thanks for the detailed status — here's my response point by point.

F1 / F4 — direction looks right; closure pending verification. Reverting ReadonlyConfig#toConfig() to ConfigFactory.parseMap(confData) and scoping the change to MultiTableFailureHelper.mergeOptions() is exactly what I was hoping for, and your explanation of why TablePlaceholderProcessor.replaceTablePlaceholder leaves the nested map untouched is consistent with the intent. I'll confirm both against the actual changes on the latest head before marking them resolved.

F2 / F5 — yes, please make it stricter. Relying on Jackson happening to produce a LinkedHashMap is an implementation detail rather than a contract, and since the docs promise "first pattern in declaration order wins", I'd like that pinned down in code:

  • Make the ordering explicit where the option is read/iterated (e.g. copy into a LinkedHashMap, or type it so order is guaranteed by construction).
  • Add a unit test declaring several patterns that match the same table and asserting the first-declared one wins.

F3 — please handle in this PR. Since the resolved key columns are comma-joined into PRIMARY_KEYS and end up in generated SQL, please validate each resolved column as a plain identifier (at minimum reject empty names) before joining, with a small unit test for a rejected value.

F6 — please also do this in this PR. Lazy failure at match time means a bad regex only surfaces once data flows for a matching table. Please compile every pattern during config validation and raise JDBC-12 up front, with a unit test for an invalid pattern.

F7 — two pieces:

  • The regression test for the restored toConfig() dotted-key expansion directly protects the F1 revert, so please add it in this PR.
  • The engine-level IT/E2E for the new option can be a follow-up; please note that in the PR description.

F8 — please rename. The existing JDBC sink options are snake_case, so the mixed hyphen/underscore in multi-table_config will stand out to users. A fully snake_case name would fit the convention; please update the docs and tests to match. I understand the current name came from the issue discussion, but I'd rather keep the option surface consistent.

Summary for this PR: F2/F5 explicit ordering + test, F3 identifier validation + test, F6 eager regex validation + test, F7 toConfig() regression test, F8 rename. F1/F4 to be confirmed against the diff; F7's IT/E2E can be a follow-up. Ping me once pushed and I'll take another pass.

@SEZ9

SEZ9 commented Oct 22, 2026

Copy link
Copy Markdown
Collaborator

Thanks @luozihen, both fixes sound right.

  1. Key column validation: having toPrimaryKeyList() reject non-string / null list elements and empty results with a JDBC-12 error that names the pattern, while keeping validatePrimaryKeyColumns() as the final guard, is the shape I was hoping for. Good that the new JdbcSinkFactoryTest cases cover both resolveMultiTablePrimaryKeys() and the createSink path.

  2. REST JSON body: moving ConfigBuilder.of(Map) onto the same rebuildWithLiteralKeys helper as the config-file and shade paths closes the gap, and testOfMapPreservesLiteralRegexOptionKeys covering the map → of(Map) → ConfigShadeUtils.decryptConfig sequence is a solid regression test. My preference is to keep the REST commit in this PR so the literal-key behaviour is fixed in one place for all three entry points; the separate REST PR can be put on hold or closed once this lands.

Remaining asks before I can approve:

  • Please post the CI result for d9bb157 once it finishes.
  • Could you confirm whether the earlier points are covered on this head or still pending: declaration-order guarantees for the pattern map (and the matching docs wording), the interaction with the engine-level TablePlaceholder replacement, a regression test for the old toConfig() dotted-key expansion plus an engine-level IT/E2E for the new option, and the multi-table_config key naming.

@hutiefang76

Copy link
Copy Markdown
Collaborator

@luozihen, there is real overlap at ConfigBuilder.of(Map), variable backfill and the decrypt re-parse, but the two current implementations have different key semantics.

Your JSON rebuild keeps every map key literal. #12443 quotes only invalid path expressions and preserves the existing handling of valid ones. For example, {"a->b":"v"} still becomes nested a.b in #12443, whereas the JSON rebuild keeps one a->b key. Surrounding whitespace and quotes in valid keys differ too; ordinary dotted keys such as job.mode stay literal in both.

#12443 also covers ReadonlyConfig.toConfig(), the config-adapter conversion and both variable-map conversions, which remain outside the three rebuild sites changed here. Its REST submit-path tests are separate from the JDBC mapping coverage.

I propose keeping one shared config fix in #12443 and rebasing the JDBC feature onto it, while keeping the primary-key validation changes in this PR. That avoids merging competing conversions. The intended key contract and merge order need to be agreed before either version lands; the two patches cannot simply be treated as identical fixes.

@luozihen

Copy link
Copy Markdown
Author

@nzw921rx @DanielLeens @SEZ9
CI is red. After checking the logs, I confirmed that it failed in two places:

Issue 1 should be caused by merging code, and issue 2 should be intermittent.

For issue 2, I can recompile. For issue 1, how can I handle it?

@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 @luozihen for the fast fixes, and thanks @nzw921rx, @SEZ9 and @hutiefang76 for the follow-up. The head moved from 82fc5e61a (the head I approved) to d9bb1574f with three new commits: 6cacc034a (reject empty or non-string key columns), 0c43f10dd (ConfigBuilder.of(Map) keeps keys literal) and a dev merge. I diffed the 18 PR-owned files between the two heads (the rest of the 680-file raw diff is the dev merge) and re-read the changed code and the REST call chain. This is a static review; I did not build or run tests. The two extra optionRule() entries and the two extra tests in JdbcSinkFactory/JdbcSinkFactoryTest come from dev, not from this PR.

I am withdrawing my earlier Approve. Sorry for approving a head whose REST entry point I had only treated as "a documented limitation": the new commit 0c43f10dd turns that limitation into a behavior change for existing REST users, and I only found the consequence now (Issue 1). Everything else is in good shape.

What Problem Does This PR Solve?

  • User pain point: a multi-table JDBC sink cannot declare a different primary key per upstream table; users need regex-keyed multi_table_config.primary_keys.
  • Fix approach: JdbcSinkFactory resolves the key columns per table (first matching regex wins, ${primary_key} / ${unique_key} expanded), validates the shape in optionRule(), and the core config rebuilds keep option keys literal so regex keys survive ConfigFactory.parseMap.
  • One-sentence summary: per-table primary keys for the JDBC sink, plus the config-loading changes needed to carry regex keys.

1. Code Change Review

1.1 Core Logic Analysis

Status of the open points

Point Status Evidence at d9bb1574f
@nzw921rx / my last comment: empty resolved key list, null / non-string elements Fixed JdbcSinkFactory.toPrimaryKeyList(value, pattern) (JdbcSinkFactory.java:392-433) rejects non-string elements, non-list/non-string values and any value that yields no column with JDBC-12 naming the pattern; toCompiledPatternMap (:345) calls it for every entry at sink creation, so the failure happens before JdbcSink.createWriter(). validatePrimaryKeyColumns (:283) stays as the final guard for [""]. Tests: testMultiTableConfigWithEmptyKeyListFails, ...BlankStringValueFails, ...BlankKeyFails, ...NullKeyFails, ...NonStringKeyFails, ...NonListNonStringValueFails, ...NullValueFails, ...CommaSeparatedStringValue, testFactoryContextWithEmptyKeyListFailsBeforeWriterIsCreated.
@nzw921rx: REST JSON body rejects regex keys Implemented, but with a compatibility side effect Issue 1 below.
@SEZ9 earlier asks (declaration order, placeholder order, toConfig() regression test, E2E, key naming) Unchanged and still covered None of those files changed since the head I verified on 10-21.

Runtime path of the new REST change:

POST submit-job (JSON body) -> RestUtil.buildConfig (RestUtil.java:75-76) -> ConfigBuilder.of(Map) (ConfigBuilder.java:112-115)
   before: ConfigFactory.parseMap(map)        keys are path expressions: "a.b" becomes {a:{b}}
   now:    rebuildWithLiteralKeys(map) (:283) JSON render + JSON parse: "a.b" stays one literal key
 -> JobInfoService.submitJob (JobInfoService.java:472-476) -> ConfigShadeUtils.decryptConfig(config)
      -> config.getConfig("env") + TypesafeConfigUtils.getConfig(env, "shade.identifier" | "shade.properties", ...)  (ConfigShadeUtils.java:109-125)
 -> submitJobInternal

Issue 1 (new in 0c43f10dd, High): ConfigBuilder.of(Map) no longer expands dotted keys, so REST JSON submissions and /encrypt-config that use dotted env keys lose their shade settings

  • Location: seatunnel-core/seatunnel-core-starter/.../ConfigBuilder.java:112-115 and :283; consumers ConfigShadeUtils.java:109-125 / :127-143 (identifier and properties), getSensitiveOptions (shade.options), TypesafeConfigUtils.getConfig (it calls config.hasPath(configKey)), JobInfoService.java:472-476, EncryptConfigService.java:36-37; test ConfigBuilderTest.java:118-155.
  • Problem: ConfigFactory.parseMap treats every map key as a path expression, so a REST JSON body {"env": {"shade.identifier": "my-shade", "shade.options": ["password"]}} used to become env { shade { identifier = ..., options = [...] } }. The repository itself pins this behavior: ReadableConfigTest#testToConfigPreservesDottedKeyExpansion (ReadableConfigTest.java:383-390) puts a literal "a.b" into a map and expects config.getInt("a.b") to work after parseMap. After this commit the same body becomes env { "shade.identifier" = ... } with one literal key, and hasPath("shade.identifier") looks for shade then identifier, so it is false. ConfigShadeUtils.decryptConfig then falls back to DEFAULT_SHADE (ConfigShadeUtils.java:68) and an empty shade.options/shade.properties. The dotted form is exactly what the documented encrypted output looks like (docs/en/introduction/configuration/config-encryption-decryption.md prints "shade.identifier" : "base64" inside env), so users re-submitting such a JSON body through the REST API are the affected group. The new test confirms the shape change rather than refuting it: it asserts that env unwraps to the literal {"job.mode": "BATCH"} (ConfigBuilderTest.java:153) and describes this as the shape "they had before this change", which is not what parseMap produced before.
  • Potential risk: for a REST JSON job with a custom shade, the encrypted option values are no longer decrypted (or are decoded with the wrong shade) and the job fails with credential errors or, worse, runs with a wrong value; /encrypt-config silently encrypts with the default shade or skips shade.options. Anything else that reads dotted keys through the Config API on the REST JSON path changes the same way, while code that goes through ReadonlyConfig (it accepts both shapes, ReadonlyConfig.java getValue) keeps working, which makes the breakage selective and hard to spot. I traced this by reading the source; I did not run it, so please confirm with a test as described below.
  • Best improvement: keep the previous behavior for every key that is a valid path expression and only protect the keys that parseMap cannot take. Two safe options:
    • Minimal: drop 0c43f10dd from this PR and leave the REST JSON body as the documented limitation tracked in #12434 (the docs text on 82fc5e61a already says so). The JDBC feature and the file and HOCON paths stay complete.
    • Root cause: in of(Map) (and the shared helper), quote or escape only the keys that are not valid path expressions (for example the regex keys) and let parseMap expand the rest, then add a test that runs a REST-shaped map with env."shade.identifier", env."job.mode" and a regex key through RestUtil.buildConfig and ConfigShadeUtils.decryptConfig and asserts both the shade lookup and the regex key survive. This is the same direction @hutiefang76 describes for #12443, so it should be agreed with that PR first.
  • Severity: High
  • Raised by another reviewer: Partly. @hutiefang76 pointed out that the literal rebuild and #12443 have different key semantics and asked for one agreed contract; the shade consequence is new here.

Issue 2 (Low): the new test comment contradicts the pre-change behavior

  • Location: ConfigBuilderTest.java:118-155 (the comment "Dotted option keys keep the literal shape they had before this change").
  • Problem: see Issue 1; whichever option you pick, the comment and the job.mode assertion should describe the real before/after shape.
  • Severity: Low
  • Raised by another reviewer: No

1.2 Compatibility Impact

Partially incompatible, because of Issue 1 only: the REST JSON submit and encrypt endpoints change how dotted keys are represented in the Config. The JDBC part is additive: multi_table_config is a new optional key, nothing existing is renamed, and a sink without it takes the unchanged fallback path (applyFallbackPrimaryKeys). The file and HOCON paths are unaffected because their maps are already expanded before the literal rebuild.

1.3 Performance / Side-Effect Analysis

No concern. Patterns are compiled and validated once per sink creation (COMPILED_PATTERN_CACHE), the cost is proportional to the number of configured patterns, and no hot-path code changed.

1.4 Error Handling and Logging

Good. Every malformed shape is rejected with JDBC-12 and a message that names the pattern; no exception is swallowed.

2. Code Quality Assessment

2.1 Coding Standards

Javadoc on the changed helpers explains the failure mode being prevented. No concern.

2.2 Test Coverage and Test Stability

The new JDBC validation tests would go red on the previous toPrimaryKeyList (it stringified null and accepted an empty list), by reading the diff, and cover [], "", [""], [null], [123], non-list values, null and the positive comma-separated case. Gap: nothing tests the REST path with a dotted env shade key (Issue 1). Stability rating: Stable for the JDBC tests (deterministic, no containers); the E2E JdbcMysqlMultipleTablesIT is unchanged since my last check. No existing test was weakened.

CI for head d9bb1574f (the apache-side Build check is still in progress; the real run is https://github.com/luozihen/seatunnel/actions/runs/39710874854, completed with failure). To answer @luozihen's question:

  • Unit tests: all four unit-test lanes (JDK 11/17, ubuntu/windows) fail with the same single error, LLMBooleanOutputTest.readsLegacyFactoryWrapperWithValidationDisabled:248 InvalidClass in seatunnel-transforms-v2. The Open udf failed text is a logged message, not the failing assertion. This PR does not touch that module, and the fix is on dev: cc54bb43 ([Fix][Transform-V2] Restore archived LLM wrapper deserialization, #12938), which this head does not contain (the branch is 3 commits behind dev). Syncing dev and re-running is the right step; this is not an intermittent flake.
  • Dead links: https://raw.githubusercontent.com/intersystems-community/iris-driver-distribution/main/JDBC/JDK18/intersystems-jdbc-3.8.4.jar is an existing link in the Jdbc docs on dev (the en sink and source pages and the zh source page), not in this PR's diff, and the job is not a merge gate, so nothing to do here.
  • transform-v2-it-part-2 (17) failed in TestPythonTransformIT (a parameter resolution error before the test body); it is a transform E2E unrelated to this diff and should pass on re-run.

2.3 Documentation Updates

docs/en/connectors/sink/Jdbc.md and the zh page now claim that regex keys work for the JSON REST body. If Issue 1 is resolved by dropping the REST commit, that sentence must go back to the limitation wording from 82fc5e61a.

3. Architectural Soundness

The connector part is well contained: all JDBC behavior sits in JdbcSinkFactory, validation is early and uniform, and the legacy primary_keys branch is untouched. The REST change is a shared-entry-point change in seatunnel-core that overlaps with #12443 (same method, different key contract), which is why it deserves its own agreement and its own tests rather than riding along with a connector feature.

4. Issue Summary

Number Issue Location Severity
1 ConfigBuilder.of(Map) keeps all keys literal, so dotted env keys such as shade.identifier are no longer found on REST JSON submit and /encrypt-config ConfigBuilder.java:112-115, :283; ConfigShadeUtils.java:109-143 High
2 Test comment describes the wrong "before" shape ConfigBuilderTest.java:118-155 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

1. Blockers - must be fixed

  • Issue 1: either remove 0c43f10dd (and restore the limitation wording in the two Jdbc docs) and keep the REST body in #12434 / #12443, or make of(Map) expand valid path keys as before and only protect the invalid ones, with the REST-shaped test described above. Please also agree the key contract with @hutiefang76 so that #12443 and this PR do not land competing conversions.
  • CI: sync with the latest dev (it carries #12938) and re-run; the unit-test failures are unrelated to this diff, and Build must be green before merge.

2. Recommended fixes - non-blocking

  • Issue 2. The two optional Low items from my previous review (an unreachable defensive branch and a test nit) are still optional.

Overall assessment: the per-table primary key feature and the empty/non-string validation are done well and well tested. The only thing standing between this PR and merge is the REST key semantics, which is a small change either way. Thank you again for the patience through these rounds!

@luozihen

Copy link
Copy Markdown
Author

Hi @hutiefang76 — thanks for the careful comparison. You are right that these are two different key contracts rather than two copies of the same fix, so it is worth agreeing on the contract and the ownership before either lands.

I ran the semantics against the shaded HOCON in this repo, because the thread mixes upstream typesafe-config behaviour with this fork's:

input key ConfigFactory.parseMap literal rebuild in this PR
job.mode, shade.identifier literal key kept, hasPath(...) is true identical
a->b expanded to nested a -> b one a->b key
" x " (quote characters in the key text) normalized to x kept as " x "
^t_.*$ ConfigException$BadPath kept as a literal key

The first row matters for the thread: this repo patches the shaded parser (#8975), so plain dotted keys are not expanded by parseMap here, and env.hasPath("shade.identifier") is true both before and after this change. I could not reproduce the REST shade consequence, but I agree it is exactly the kind of thing that should be pinned rather than argued, so I will add the REST-shaped test Daniel asked for (map -> RestUtil.buildConfig -> ConfigShadeUtils.decryptConfig, with a regex key, job.mode, shade.identifier and a->b).

The remaining deltas are the ones you named, and they are the contract question. Items I would like us to agree on:

  1. Key contract for the shared conversion: all keys literal (current [Feature][Connector-V2] Support per-table primary key mapping via multi_table_config.primary_keys for JDBC sink #12015), or quote only the keys that fail path parsing ([Fix][Core] Preserve literal config keys across REST and file loading #12443). I lean to the second: it keeps a->b and the quoting behaviour byte-compatible with today and only rescues keys that cannot be represented now.
  2. Ownership: only one PR should change ConfigBuilder.of(Map), backfillUserVariables and ConfigShadeUtils.processConfig; the other drops its overlapping commit and rebases.
  3. Scope: should ReadonlyConfig.toConfig(), the config-adapter path and the variable-map conversions (currently only in [Fix][Core] Preserve literal config keys across REST and file loading #12443) follow the same contract, or stay out of the shared change?
  4. Merge order: whichever lands second removes its duplicate. 0c43f10 here is a single, self-contained commit and easy to drop.
  5. Tests that pin the contract: the REST-shaped case above, asserting which keys stay literal and which still expand.

Concretely, two ways to proceed:

Which of the two would you prefer? Once we agree on the contract and the owner, I will make the change the same day.

@SEZ9

SEZ9 commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator

@luozihen thanks for digging through the CI logs.

Issue 1 (dead link): I cannot tell from the thread whether that URL comes from the base branch or from the JDBC sink doc this PR touches. Could you check whether the link appears in your diff? If it is only in the base branch, a rebase onto the latest main should tell us, and a docs-only fix in a separate PR would be the right place for it; I would not block this PR on it. If it is in your diff, please update or remove the link here.

Issue 2 (ZetaSQLEngine - Open udf failed in unit-test): re-triggering is fine; I do not expect a code change from you for it unless it reproduces consistently.

On the ReadonlyConfig.toConfig() key-contract thread, a few concrete asks to close it out:

  1. I lean the same way you do: quote only the keys that fail path parsing, so existing keys keep their current behaviour and only keys that cannot be represented today are rescued.
  2. Only one PR should carry the shared conversion change. If it lands elsewhere, please drop 0c43f10dd from this PR and rebase once that is merged; if it lands here, keep it as the single self-contained commit it is now.
  3. Please add the REST-shaped test you described (map -> RestUtil.buildConfig -> ConfigShadeUtils.decryptConfig with a regex key, job.mode, shade.identifier and a->b), asserting which keys stay literal and which still expand. Since that exercises the REST path rather than ReadonlyConfig.toConfig() directly, please also add a direct toConfig() test for the dotted-key behaviour so both paths are pinned.

The JDBC-specific items from the earlier review (declaration-order guarantee for the map-typed option and its docs, identifier validation on the resolved key columns, the ${primary_key}/${unique_key} vs. TablePlaceholder interaction, regex compile-time validation mapped to JDBC-12, and the multi-table_config naming) are independent of the shared conversion, so feel free to push those regardless of which PR carries the config change.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks @luozihen for the thorough follow-up, and thanks @SEZ9 and @hutiefang76 for helping converge on the key contract. The head is still d9bb1574f0dfee9f6673533dff2616522a76e6c4, the one my latest review covers, so that review stands; this is a clarification, not a new full review. Static read only, nothing was executed locally.

1. The first row of the semantics table does not match the shaded parser source on this head. The table says job.mode / shade.identifier are kept as literal keys by ConfigFactory.parseMap. I traced the code path in this repo and it points the other way:

  • ConfigImpl.fromPathMap (seatunnel-config-shade/.../impl/ConfigImpl.java:189-193) calls PropertiesParser.fromPathMap.
  • PropertiesParser.fromPathMap (PropertiesParser.java, the map overload) builds Path.newPath(key) for every entry, and Path.newPath is PathParser.parsePath (Path.java:233-235), which splits on ..
  • Nested map values are converted with FromMapMode.KEYS_ARE_PATHS (PropertiesParser.java:175-177), so a key inside env such as shade.identifier is also split into shade -> identifier. This is also why the regex key ^t_nova_.*$ fails with BadPath in the first place.
  • The existing ReadableConfigTest#testToConfigPreservesDottedKeyExpansion (ReadableConfigTest.java:383-390) pins the same thing for toConfig().

I could not find a patch to this path in seatunnel-config-shade (I searched for #8975 and found nothing), so unless you can point me at the exact class that changes this, I read the expansion as the current behavior. That is why I flagged Issue 1: with the literal rebuild in 0c43f10dd, an env body carrying shade.identifier would no longer be found by hasPath("shade.identifier") in ConfigShadeUtils.

This is a factual question we can settle by test rather than by argument, and you already offered the right one. Please add the REST-shaped test exactly as you described (map -> RestUtil.buildConfig -> ConfigShadeUtils.decryptConfig) with env containing shade.identifier, job.mode, a.b and a regex key, and assert which keys still expand and which stay literal. If it is green on the literal rebuild, I will withdraw Issue 1 and say so; if it is red, it tells you which of the two options below to take.

2. Which option to take. Both are fine from my side. I agree with @SEZ9 and your own lean: keep existing keys behaving exactly as today and only rescue keys that cannot be parsed as a path today (quote-only-invalid). Only one PR should change ConfigBuilder.of(Map) / ConfigShadeUtils.processConfig; please agree the owner with @hutiefang76 and drop the duplicate commit in the other PR. If the owner is #12443, drop 0c43f10dd here and restore the limitation wording in the two Jdbc docs; the JDBC feature and validation stay in this PR.

3. CI, to correct one point in the thread. The unit-test failure is not the Open udf failed log line (that is logged output). All four unit-test lanes fail on LLMBooleanOutputTest.readsLegacyFactoryWrapperWithValidationDisabled in seatunnel-transforms-v2, which this PR does not touch; the fix is #12938 (cc54bb43), and this head does not contain it (verified: it is not an ancestor of the head). So re-triggering alone will not turn it green; syncing the latest dev and re-running will. The dead link (the InterSystems IRIS driver URL) is on dev already and not in your diff, so I agree with @SEZ9 not to block on it.

Next step: sync dev, add the REST-shaped test, settle the owner of the shared conversion, then push; I will do a fresh pass on the new head. My earlier change request is still the visible state on this PR; Daniel has no write-level review controls, so once the blockers are cleared a maintainer with write access needs to do the final approve or dismiss.

@SEZ9

SEZ9 commented Oct 24, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the follow-up. The head is still d9bb1574f0dfee9f6673533dff2616522a76e6c4, so my latest review stands; this is a clarification on PR12015-F1 (and the related test gap in PR12015-F7), not a new review.

On the semantics table (F1). The first row says job.mode / shade.identifier are kept as literal keys when the config is built from a map. My reading of the shaded config parser points the other way: keys supplied via a map are parsed as paths and split on ., including keys inside nested maps such as env. That is the same mechanism that makes a regex key like ^t_nova_.*$ fail with BadPath. I could not find a change in this PR that alters that parsing, so unless you can point me at the exact class that does, I have to treat expansion as the current behavior, which means the literal rebuild in 0c43f10dd could stop an env-supplied shade.identifier from being resolved the way it is today.

This is easiest to settle with a test rather than discussion, and you already proposed the right one:

  1. Please add the REST-shaped test you described (map -> RestUtil.buildConfig -> ConfigShadeUtils.decryptConfig) with env containing shade.identifier, job.mode, a.b and one regex key, asserting which keys expand and which stay literal on the literal rebuild. If it is green I will withdraw F1 and say so here; if it is red, it tells us which direction to take.
  2. Either way, please correct or confirm the first row of the semantics table so the doc and the test agree.
  3. If the test is red, I'd lean toward the narrow option: keep every key that parses as a path today behaving exactly as it does now, and only rescue keys that fail path parsing. That keeps the change contained to the JDBC sink use case instead of altering toConfig() for every caller.

Once the test and the table update are pushed, I'll re-check F1 and F7 against the new head.

@DanielLeens

Copy link
Copy Markdown
Contributor

+1 to @SEZ9's request to settle the dotted-key contract with the REST-shaped test already proposed here. Preserving valid existing path semantics matters as much as accepting the regex key: a literal rebuild must not silently change how env's shade.identifier and job.mode are resolved.

Please push the map -> RestUtil.buildConfig -> ConfigShadeUtils.decryptConfig regression case with the valid dotted keys and the regex key together, and make the semantics table match its assertions. If literal reconstruction changes the valid-key behavior, the narrow invalid-path rescue is the safer direction than changing toConfig() globally. The head is unchanged, so I cannot treat that test or compatibility concern as fixed yet. I will wait for the code update; this is clarification of the existing points, not an additional review finding.

@luozihen

Copy link
Copy Markdown
Author

Hi @hutiefang76 — following up on the contract question from 23 Oct. I have not heard back for a few days, so rather than leave this open I will proceed in the direction @SEZ9 and @DanielLeens converged on, and I wanted to tell you explicitly first.

  1. The disputed row is settled by the parser itself. ConfigParseOptions.PATH_TOKEN_SEPARATOR is "->" in this repo (seatunnel-config-shade/.../ConfigParseOptions.java:23), not ".". That is why parseMap keeps job.mode / shade.identifier as literal keys (and env.hasPath("shade.identifier") is true), while a->b is the form that expands, and why ^t_.*$ still fails with BadPath. I will pin this with the REST-shaped regression and a direct toConfig() case, and align the wording of the existing test with it.

  2. I will keep the REST fix in this PR, but narrow it. @nzw921rx asked for the REST JSON path to work here, and @SEZ9 / @DanielLeens both prefer the narrow contract, so I will replace the all-literal rebuild with quote-only-invalid: a key is quoted only when it cannot be parsed as a path, everything that parses today keeps its current behavior (a->b still expands, dotted keys and quoting behave as before), and regex keys become representable. This is the narrow option we discussed, not the broad literal rebuild.

  3. Ownership. ConfigBuilder.of(Map), backfillUserVariables and ConfigShadeUtils.processConfig will share one narrow helper, so the contract lives in one place. For [Fix][Core] Preserve literal config keys across REST and file loading #12443, I suggest it rebases onto this and keeps the parts that go beyond this PR (ReadonlyConfig.toConfig(), the config-adapter path and both variable-map conversions), dropping the overlapping pieces. If you would rather keep [Fix][Core] Preserve literal config keys across REST and file loading #12443 as the only owner of the whole conversion, tell me within the next two days and I will drop 0c43f10 instead and rebase once [Fix][Core] Preserve literal config keys across REST and file loading #12443 lands.

  4. Tests in this PR. The REST-shaped case (map -> RestUtil.buildConfig -> ConfigShadeUtils.decryptConfig) with shade.identifier, job.mode, a.b, a->b and a regex key, asserting which keys expand and which stay literal; plus a direct toConfig() case in ReadableConfigTest so both entry points are pinned.

Thanks — I would like to settle this and move the PR forward; if you disagree with either the contract or the ownership, a short reply is enough and I will adapt.

@DanielLeens

Copy link
Copy Markdown
Contributor

Hi @luozihen, @hutiefang76, @SEZ9, thanks for pushing this to a concrete answer, and @luozihen, I owe you a correction.

I re-checked the shaded parser on dev: ConfigParseOptions.PATH_TOKEN_SEPARATOR is "->", and PathParser.splitTokenOnPeriod / addPathText split only on that token. So in this repository a plain dotted key such as shade.identifier or job.mode is not expanded by parseMap; it stays one literal key, and env.hasPath("shade.identifier") is true both before and after the literal rebuild. That means the premise of my earlier "Issue 1 (High)" (that 0c43f10dd stops env's dotted shade keys from being found) was wrong, and my +1 on the expansion concern was wrong for the same reason. Sorry for the detour. I also misread ReadableConfigTest#testToConfigPreservesDottedKeyExpansion: it only asserts getInt("a.b"), which passes for a literal key too, so it does not pin expansion.

What does still differ, per your table, is narrower: a->b (expands today, would become one literal key) and keys containing quote characters (normalized today, kept as-is). Those can matter for existing REST JSON users, so I agree with the plan you described: quote only the keys that fail path parsing and leave everything that parses today untouched, with the REST-shaped case (RestUtil.buildConfig -> ConfigShadeUtils.decryptConfig) asserting shade.identifier, job.mode, a.b, a->b and a regex key. With that in place I will re-review the new head and withdraw the compatibility blocker. Please also fix the comment in ConfigBuilderTest that describes the "before" shape.

Two practical notes: please settle ownership of ConfigBuilder.of(Map) / ConfigShadeUtils with @hutiefang76, since #12443 already carries the quote-only-invalid helper and its Build is green on its current head (I am approving it separately); reusing that helper, or rebasing on it, avoids two competing conversions. And the red Build here is the LLMBooleanOutputTest failure in seatunnel-transforms-v2, fixed on dev by #12938 and absent from this branch, which is 33 commits behind, so syncing dev with your next push will clear it.

@luozihen

Copy link
Copy Markdown
Author

Noting that #12443 has been approved (thanks @hutiefang76 and @DanielLeens).

To avoid two competing config conversions, I will hold further config-loading changes here until #12443 lands:

  • once it is merged, I will sync dev and drop 0c43f10dd (the ConfigBuilder.of(Map) commit) from this PR, then rebase;
  • the JDBC feature and the primary-key validation stay in this PR unchanged;
  • the REST-shaped regression (map -> RestUtil.buildConfig -> ConfigShadeUtils.decryptConfig) and the toConfig() assertions will be rebased on top of [Fix][Core] Preserve literal config keys across REST and file loading #12443's contract, so they pin the final behaviour instead of a competing one.

The head stays at d9bb1574f until then. No action needed from you — I will post the rebased head here once #12443 is merged.

@DanielLeens

Copy link
Copy Markdown
Contributor

Hi @luozihen, thanks for the clear plan, and for telling everyone before holding the branch.

This sounds right to me, and it matches the direction we converged on:

The head is still d9bb1574, so my existing review stands for now and I cannot mark the REST point as resolved yet. Once you post the rebased head, I will do a full re-review of it and update my review state accordingly. No action is needed from you until #12443 lands.

@nzw921rx nzw921rx added the don't merge There needs to be a specific reason in the PR, and it cannot be merged for the time being. label Oct 26, 2026
@nzw921rx

Copy link
Copy Markdown
Member

@luozihen Thank you for your contribution. Moving forward with this work after 3.1.0🔥

@SEZ9

SEZ9 commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

@luozihen — apologies for the slow reply on the contract question; answering it directly now.

  1. Agreed on the parser point. Given PATH_TOKEN_SEPARATOR is -> in this repo, the row we disagreed on resolves the way you describe: job.mode / shade.identifier stay literal through parseMap, a->b is the form that expands, and ^t_.*$ is the one that actually breaks with BadPath. That settles PR12015-F1 in favour of the narrow fix rather than the all-literal rebuild, so I withdraw my objection to keeping the REST fix in this PR.

  2. Quote-only-invalid is the contract I'm comfortable with: quote a key only when it cannot be parsed as a path, and leave everything that parses today untouched. Please make sure the implementation really is a no-op for every key that parses today (dotted keys, already-quoted keys, a->b), so no existing caller of toConfig() sees a change.

  3. On tests (PR12015-F7), what I need to see before I can resolve this:

    • the REST-shaped regression (map -> RestUtil.buildConfig -> ConfigShadeUtils.decryptConfig) plus a direct toConfig() case, asserting shade.identifier, job.mode, a.b, a->b and a regex key together in one test so the final behavior is pinned in one place;
    • the existing test's wording aligned with the -> separator, as you proposed.
  4. Sequencing: since [Fix][Core] Preserve literal config keys across REST and file loading #12443 (head 509fddab) carries the config-key conversion, please land that first, then sync dev and drop 0c43f10dd from this branch so the two PRs don't ship competing conversions. The head here is still d9bb1574, so my review stands until the rebased head is pushed; once it is, I'll re-review the REST point and the test together.

@nzw921rx noted — fine to take this after 3.1.0; nothing here needs to rush the release.

Nothing further is needed from you until #12443 merges. Ping me when the rebased head is up.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks @SEZ9, @nzw921rx and @luozihen. The sequencing is unchanged: #12443 remains open at 509fdda, so please land that config-key contract first, then sync this branch and remove its competing conversion while retaining the combined REST/toConfig regression. The unchanged head here does not resolve that dependency. I also respect the maintainer's after-3.1.0 scheduling note; there is no need for an empty trigger commit or unrelated patch while waiting for the prerequisite.

Gate snapshot (2026-10-28T15:57:29+00:00), head d9bb1574f0dfee9f6673533dff2616522a76e6c4: Build is FAILURE.

The blocking jobs are Run / Dead links failure; Run / unit-test (17, ubuntu-latest) failure; Run / unit-test (11, windows-latest) failure; Run / unit-test (17, windows-latest) failure; Run / unit-test (11, ubuntu-latest) failure; Run / mysql-cdc-connector-it (17, ubuntu-latest) cancelled; Run / mysql-cdc-connector-it (11, ubuntu-latest) cancelled; Run / transform-v2-it-part-2 (17, ubuntu-latest) failure.

Observed log evidence: Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project seatunnel-transforms-v2: There are test failures.

Please inspect or rerun only the named failed job where a rerun is appropriate. The logs establish the failing stage, but do not alone establish whether the current PR caused it. No matching upstream cure has been proved by this follow-up; a base sync alone is not a verified resolution, so no unrelated module/dependency patch is requested.

My previous source conclusion remains unchanged, including its independent source/documentation requests. CI is not being passed by inference, and this follow-up is not an effective approval.

Comparison recorded in this scan: base dev, diverged, ahead 33 / behind 74, no merge conflict. Branch drift is metadata here and is not an additional sync request.

@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 for the careful follow-up, and sorry for my earlier incorrect assumption about dotted keys. I re-read the complete current Apache SeaTunnel diff, the vendored path parser and the shared configuration reconstruction chain. The repository uses -> as its path separator; my earlier dotted-key/shade failure argument was not valid. The current rebased implementation and tests close the source blockers for me.

What problem does this PR solve?

User pain: one multi-table JDBC sink cannot select different key columns for different upstream tables. Fix: resolve an ordered regex-keyed primary_keys map before target-name remapping, with an unchanged legacy fallback. Example: orders use order_id while order_lines use the composite order_id,line_id.

1. Code changes

1.1 Core logic

Complete runtime path:

File / REST JSON -> ConfigBuilder -> shared quoteInvalidPathKeys contract from dev
 -> ConfigShadeUtils decrypt/rebuild -> factory optionRule structural check
 -> JdbcSinkFactory.createSink(upstream CatalogTable)
 -> validate/compile every mapping -> first matching upstream identifier
 -> expand whole primary_key / unique_key tokens -> validate column list
 -> otherwise configured legacy keys, upstream PK, then unique-key fallback
 -> target remapping -> JdbcSink.createWriter -> dialect-generated keyed writes

Key findings and correctness:

The normal per-table factory path reaches the feature before names are remapped. The cache is bounded to 256 compiled pattern maps; declaration order is preserved. Empty/null/non-string resolved keys fail before writer creation. The current diff no longer replaces the core map loader: it uses the merged shared quote-only-invalid contract. Crucially, this repository uses PATH_TOKEN_SEPARATOR="->", not a dot. job.mode and shade.identifier are literal valid keys; a->b expands. My previous claim that dotted keys necessarily expanded was incorrect, and I withdraw that consequence rather than carrying it forward. The current narrow helper preserves all already-valid path keys and protects regex keys at each reconstruction boundary.

Before:

import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.dialectenum.FieldIdeEnum;

import java.util.List;

public class JdbcSinkOptions extends JdbcCommonOptions {

After:

import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.dialectenum.FieldIdeEnum;

import java.util.List;
import java.util.Map;

public class JdbcSinkOptions extends JdbcCommonOptions {

1.2 Compatibility

Fully compatible for existing JDBC options and key fallback. The new optional mapping takes precedence only when configured and matched. Core parsing now follows the already-merged shared contract: dot is literal and -> is the path separator. No checkpoint/wire/default rename is introduced.

1.3 Performance and side effects

Regex compilation is submission-time and bounded by a synchronized 256-entry access cache. Concurrent misses may compile twice without changing results. Matching cost scales with mapping count per table, not per record; row-writing, transaction and resource ownership remain unchanged.

1.4 Errors, logging, and findings

No new source-level blocker found. Exceptions must still reach the existing job failure path; this review does not substitute for current-head CI.

I agree with @nzw921rx's earlier requested structural validation and empty-key safeguards; both are implemented. @SEZ9's parser correction is right: PATH_TOKEN_SEPARATOR is ->. The agreed #12443 sequencing is now reflected in the current source, and the REST/key-shape regressions cover that shared contract rather than a competing loader. His declaration-order/placeholder and integration requests are addressed. The earlier approval and later change requests must be assessed against this rebased head; I do not retain their now-closed source blockers.

2. Code quality

2.1 Conventions

Reviewed all changed files for license, imports, naming, core-method and state-field comments. No additional convention blocker found.

2.2 Test coverage and stability

Stability rating: Stable. Deterministic factory/config tests exercise first-match order, invalid mappings, placeholder precedence, real HOCON ordering and map/toConfig/REST-shaped rebuilds. Existing JdbcMysqlMultipleTablesIT now checks real target primary-key column order and row counts for the mapped tables, with cleanup. Exact-head upstream CI ran ConfigBuilderTest: 21 tests, zero failures/errors in unit-test JDK17 job 135377264734 (run 44469734647); all four collected unit lanes succeeded. These are downloaded CI results, not local execution. No timing-dependent assertion was identified in the added unit cases.

2.3 Documentation

Both JDBC guides explain upstream-name matching, first match, precedence, placeholders and invalid resolved keys. One minor wording nuance: an entirely empty outer multi_table_config is intentionally accepted by the validator/tests and uses fallback, whereas a nonempty malformed mapping fails. The current text should describe that distinction precisely.

3. Architecture

3.1 Change location

The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.

3.2 Maintainability

Keep the behavior, lifecycle ownership, and failure contract together. The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.

3.3 Extensibility

Prefer the existing component boundary and tests over unrelated shared abstractions.

3.4 Upgrade impact

Fully compatible for existing JDBC options and key fallback. The new optional mapping takes precedence only when configured and matched. Core parsing now follows the already-merged shared contract: dot is literal and -> is the path separator. No checkpoint/wire/default rename is introduced.

4. Findings summary

# Finding Location Severity
- No new source blocker found - -

5. Merge recommendation

Can merge once the recorded CI and repository gates are satisfied

Blocking items: No source blocker. Current-head CI and write-capable maintainer review remain independent requirements.

Non-blocking suggestions: None beyond the validation limits above.

Overall: the reviewed source path is coherent; no runtime acceptance is claimed beyond the actual CI result. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.

CI and repository state: no check reported in the Apache rollup; Build: in_progress. GitHub reports BLOCKED / CHANGES_REQUESTED.

Verification: Reviewed all changed files and the referenced call sites at 2c899fc6cb16eb376988e180f1447ce5372030a1 against merge base f1ab36f0423c8aa17766959dfd6c6b3f5bc1426a. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.

Review time: 2026-11-19T07:22:46.039521-05:00

Local evidence: git fetch obtained head 2c899fc6cb16eb376988e180f1447ce5372030a1; git merge-base returned f1ab36f0423c8aa17766959dfd6c6b3f5bc1426a; git diff --stat reports 14 files changed, 1455 insertions(+), 42 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.

@luozihen

Copy link
Copy Markdown
Author

@nzw921rx @SEZ9 @DanielLeens — following the after-3.1.0 plan, this branch is now synced with the 3.1.0 dev branch and #12443's config-key contract, and the Build is green.

Head: 2c899fc (merge of upstream/dev f1ab36f, which contains #12443)
Build: https://github.com/luozihen/seatunnel/actions/runs/44469734647 — success, including the two all-connectors partitions that previously timed out (they passed on the final attempt).

What changed:

  • ConfigBuilder.of(Map), ConfigBuilder.backfillUserVariables and ConfigShadeUtils.processConfig now come from [Fix][Core] Preserve literal config keys across REST and file loading #12443 (ConfigMapPathUtils.quoteInvalidPathKeys). git diff upstream/dev shows no changes in those files, so this PR no longer carries a competing conversion.
  • The MultiTableFailureHelper.mergeOptions workaround and its test were removed, since ReadonlyConfig.toConfig() is fixed upstream.
  • The JDBC feature, the fail-fast/empty-key validation, the docs and the regression tests remain.

Local verification: ConfigBuilderTest 21, ConfigShadeTest 20, ReadableConfigTest 18, JdbcSinkFactoryTest 47, JdbcTableOptionsConditionExtensionTest 15 — all pass; spotless check passes.

One CI bookkeeping note: the PR currently shows no attached Build check because the PR signal run for this head is still action_required, so please use the fork run link above. Ready for re-review whenever you have time.

@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, @luozihen, for the exact head and Build link. I checked the named common config classes: there is no diff against latest dev in ConfigBuilder, ConfigShadeUtils or MultiTableFailureHelper, consistent with using the merged #12443 key contract rather than carrying a competing conversion. My complete review already covers this unchanged feature head; the reported local tests are yours, not executions performed by me.

The previous CI-only blocker has changed: the exact-head fork Build is successful, including the previously incomplete connector lanes. I found no remaining source blocker in the prior full review, so I am changing my review to approve. Apache's PR-signal/workflow approval and adoption of the fork result remain distinct bookkeeping gates; the fork success should not be described as an already attached Apache Build.

Merge recommendation: Can merge from Daniel's technical perspective once repository gates are satisfied.

Blocking source items: None.

Non-blocking suggestions: Existing review suggestions are unchanged. A write-capable maintainer still owns effective approval/dismissal and workflow approval.

Checked unchanged head 2c899fc6cb16eb376988e180f1447ce5372030a1 against dev: compare diverged, ahead 34 / behind 6. This drift is recorded independently; it does not by itself request synchronization. This is a discussion/CI follow-up, not another full source review. No local build, test or runtime execution was performed. Daniel has READ repository permission; effective maintainer approval/dismissal remains a separate repository gate. Checked 2026-11-20T12:05:54.019197+00:00.

@SEZ9

SEZ9 commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

@luozihen thanks for the sync and the clear summary.

The latest review on this thread is an approval that lists no blocking source items and says the existing review suggestions are unchanged. So everything below is a non-blocking follow-up from the earlier review, not a new requirement.

CI: you report fork run 44469734647 as successful for head 2c899fc. Because the PR signal run is still action_required, that result is not yet an attached Build check on this PR. The workflow approval is a repository-side step.

Not confirmed from the comments alone

  • ReadonlyConfig.toConfig() dotted-key semantics: your summary says git diff upstream/dev shows no changes in the ConfigBuilder and ConfigShadeUtils code, and that the MultiTableFailureHelper.mergeOptions workaround was removed. It does not say whether this PR still changes ReadonlyConfig itself relative to dev. Could you confirm that, so the earlier concern about path semantics for other callers can be closed?

Earlier suggestions your comment doesn't cover

  1. Pattern order: the option is a Map<String, Object> and HOCON object keys don't guarantee declaration order. Is "the first pattern in declaration order wins" now guaranteed in code, or were the docs reworded?
  2. Identifier validation: are the resolved key columns validated before they are comma-joined into PRIMARY_KEYS and reach the generated SQL?
  3. Placeholder interaction: how does the connector-level ${primary_key} / ${unique_key} expansion interact with the engine-level TablePlaceholder replacement, and is that tested or documented?
  4. Regex validation: does the fail-fast/empty-key validation also compile user-supplied patterns up front and map failures to the new JDBC error code?
  5. Tests: does ReadableConfigTest include a regression case for the old dotted-key expansion, and is there an engine-level IT/E2E for the new JDBC option?
  6. Option name: is multi-table_config staying as is, or will it be renamed to match the JDBC sink's snake_case convention?

A short "done / not done / intentionally kept" per item is enough, with a pointer to the relevant test or doc section where one exists.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks, @SEZ9. Here are the six boundary answers on the unchanged head.

  1. JdbcSinkFactory.java:346-352 preserves the supplied map's iteration order; it does not prove HOCON declaration-order precedence. The Javadoc at 305-307,340-342 should avoid promising declaration order. Use unambiguous patterns; I am not claiming a deterministic overlapping-pattern contract.
  2. Blank/comma-only keys are checked at 284-299 before the join at 193-197; this is not a general SQL-name whitelist.
  3. TablePlaceholderProcessor.java:158-220 processes top-level strings/lists, not nested maps. JDBC's own expansion at 445-479 handles upstream primary/unique-key placeholders inside the table options.
  4. All regexes are compiled eagerly at 346-350; invalid syntax is mapped to the JDBC invalid-multi-table-config error at 362-377.
  5. ReadableConfigTest.testToConfigPreservesDottedKeyExpansion and JdbcMysqlTableOptionsIT.testTableOptionsSink exist. I did not run them. The current diff does not change ReadonlyConfig, ConfigBuilder, ConfigShadeUtils or MultiTableFailureHelper relative to dev.
  6. The existing option is multi_table_config (underscore). It should remain that spelling; no hyphenated rename is needed.

The CI fact in my earlier approval has also changed: an exact-head fork Build now exists and is successful, and Apache Build is successful too. The old missing-Build/action-required guidance no longer applies. My existing technical approval stands; optional wording cleanup and effective maintainer review remain separate.

Checked unchanged head 2c899fc6cb16eb376988e180f1447ce5372030a1 against dev: compare diverged, ahead 34 / behind 9. This drift is recorded independently; it does not by itself request synchronization. This is a discussion/CI follow-up, not another full source review. No local build, test or runtime execution was performed. Daniel has READ repository permission; effective maintainer approval/dismissal remains a separate repository gate. Checked 2026-11-21T12:06:29.365986+00:00.

@luozihen

Copy link
Copy Markdown
Author

@DanielLeens @nzw921rx @davidzollo
Could you please let me know what I need to do next to move this consolidation forward? It has been a few days since my last feedback.

@luozihen
luozihen requested a review from davidzollo November 26, 2026 07:51
@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for following up, @luozihen. From my side, you do not need another consolidation rewrite: my existing source assessment and technical approval stand on this unchanged head. The shared config-key repair from #12443 is already in your branch, and the spelling is multi_table_config; please do not reintroduce the removed competing conversion.

The concrete next step has changed: GitHub now reports merge conflicts with dev (compare: diverged, ahead 34 / behind 64). Please resolve those conflicts in your branch, retain the JDBC feature and its validation/regressions, then let the checks run on the resulting head. The current head's Apache and fork Builds are both successful; that is useful evidence for this version, but not for the future conflict-resolution commit. After your update I will re-review the complete diff. A write-capable maintainer still needs to reconcile the historical review requests and issue the effective final approval. The optional pattern-order/Javadoc wording suggestions are not a request to restart the feature.

Discussion-only follow-up on unchanged head 2c899fc6cb16eb376988e180f1447ce5372030a1; no new full source review or local build/test/runtime execution is claimed. Daniel has READ permission; effective maintainer approval and dismissal remain separate repository actions.

Resolved the only conflicts in docs/en|zh/connectors/sink/Jdbc.md by keeping both upstream's multi_table_sink_replica row/paragraph and this PR's multi_table_config section. The JDBC code and tests merged automatically.

@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 for resolving the conflicts and strengthening the real-HOCON and generated-DDL regressions, @luozihen. I re-read the complete 14-file diff at the new head. My previous source approval still holds technically; the new head needs its own completed CI result, and the earlier conflict-resolution request is superseded by this source recheck.

What problem does this PR solve?

User pain: A multi-table JDBC job can need a different composite target key for each source table; one top-level primary_keys cannot express that.

Approach: Add optional multi_table_config.primary_keys regex mappings, upstream primary/unique-key expansion, fail-fast validation, and apply the resolved keys to both sink options and catalog schema before SQL/table creation.

In one sentence: Let each source table choose its intended target key while retaining the old fallback. For example, orders can use [id, DATA_SOURCE] while another table uses a different key.

1. Code changes

1.1 Core logic

Complete runtime path:

File/REST job loading -> existing merged ConfigMapPathUtils invalid-path rescue -> shade/decrypt rebuild
  -> engine TablePlaceholderProcessor.replaceTablePlaceholder (158-181): top-level replacements only
  -> option validation -> JdbcMultiTableConfigConditionExtension.evaluate (54-67)
  -> per-table JdbcSinkFactory.createSink (105): retain upstreamTable before target remap
  -> resolveMultiTablePrimaryKeys (316): eagerly compile patterns, match original upstream name
  -> expandPrimaryKeyPlaceholder -> reject absent upstream keys / bad values
  -> applyPrimaryKeys (193): validate names, update PRIMARY_KEYS and rebuilt catalog primary key
     or applyFallbackPrimaryKeys (239): existing explicit/catalog-PK/first-unique-key behavior
  -> JdbcSinkConfig -> JdbcSink -> save-mode handler creates target DDL using rebuilt schema
  -> createWriter -> JdbcOutputFormatBuilder (77,212): resolved keys drive generated SQL
  -> normal flush/checkpoint/commit and multi-table routing remain existing implementations

Key findings and correctness:

  1. Normal generated-SQL multi-table creation reaches the new mapping before target-name remapping can alter the source matching identity. Missing/unmatched mappings preserve the original top-level/catalog fallback.
  2. The old REST/config concern is closed through the merged #12443 contract; this diff does not modify ReadonlyConfig, ConfigBuilder, ConfigShadeUtils or MultiTableFailureHelper production code. In this repository the path separator is ->, so the name of the dotted-key test does not itself prove nesting. My earlier dotted-key-expansion objection remains withdrawn.
  3. The prior pattern-order uncertainty can now be narrowed with actual source evidence: this head's ConfigParser.java:256,392 creates LinkedHashMap, SimpleConfigObject.java:428-430 renders key iteration without sorting, and its unwrapped map is LinkedHashMap (258-265). The new real-HOCON test deliberately declares a broad overlapping pattern last, and the E2E checks generated target keys. This is stronger than testing a manually constructed ordered map. Arbitrary external unordered Java maps still have their own iteration semantics; avoid promising a declaration order for those.
  4. Empty lists, blank keys, null/non-string list elements and invalid regex are rejected before writer creation. Per-table options update both the effective JDBC key list and target catalog PK, preventing DDL/upsert disagreement. The bounded 256-entry pattern cache permits harmless duplicate compilation across concurrent misses.

Before:

PrimaryKey primaryKey = catalogTable.getTableSchema().getPrimaryKey();
if (CollectionUtils.isEmpty(config.get(JdbcSinkOptions.PRIMARY_KEYS))) {
    // catalog PK, otherwise first UNIQUE key
} else {
    // rebuild schema with top-level configured keys
}

After (JdbcSinkFactory.java:144-149):

Optional<List<String>> multiTablePrimaryKeys =
        resolveMultiTablePrimaryKeys(config, upstreamTable);
if (multiTablePrimaryKeys.isPresent()) {
    catalogTable = applyPrimaryKeys(map, catalogTable, multiTablePrimaryKeys.get());
} else {
    catalogTable = applyFallbackPrimaryKeys(config, map, catalogTable);
}

Concrete CI next step: The current Build is not green. All-connectors partition 4 JDK 17 fails downloading Maven wrapper with HTTP 429, then MavenWrapperMain is missing, before tests. Partition 6 JDK 11 fails DatabendCDCSinkIT.testDatabendSinkCDC on the Flink invocation with NoResourceAvailableException / pending slot allocation, not on a JDBC key assertion. The changed files do not alter Databend or wrapper bootstrap. I checked latest dev ee0fb0d and the intervening history of those paths; no matching landed cure is established. Please rerun those failed lanes after bootstrap/resource availability recovers and keep the resulting exact-head links; syncing alone is not a verified fix. Do not add unrelated Databend/dependency patches here.

1.2 Compatibility

Fully compatible for jobs that do not use the new option: the old explicit primary_keys branch is intentionally not rewritten/revalidated, and PK/unique-key fallback is preserved. New option spelling is multi_table_config with no default. Existing public connector API, default, protocol, row/checkpoint serialization and shared config conversion are unchanged; no new dependency. The opt-in mapping intentionally overrides keys only on matched tables. Blank/comma key validation avoids ambiguity in the existing comma-delimited config representation; it is not a general SQL identifier whitelist.

1.3 Performance and side effects

Pattern compilation is cached in a synchronized access-order LRU capped at 256; per-table resolution copies mappings and iterates patterns once during sink creation, not per row. No new data buffer, per-record network operation, checkpoint state, retry policy or writer lock. Regex complexity remains user-controlled initialization work. Target DDL/SQL reflects the resolved PK while existing writer release/flush semantics remain unchanged.

1.4 Errors, logging, and findings

No new source-level blocker found. Exceptions must still reach the existing job failure path; this review does not substitute for current-head CI.

The earlier @nzw921rx change request concerned REST regex loading and empty/null key acceptance. Both are closed in the inspected current path: merged shared invalid-path rescue, eager value validation and factory-level negative tests. His earlier approval and subsequent request are historical separate records; a write-capable maintainer must reconcile them. @SEZ9 explicitly classified the later six questions as non-blocking: production config conversion is unchanged; regex compilation and column delimiter validation exist; placeholder order has an explicit new regression and bilingual docs; the engine E2E now verifies generated DDL; underscore spelling is retained. The new HOCON/DDL tests and current shaded parser address the earlier pattern-order question. I agree with the earlier technical approval from the reviewed source paths; no additional source blocker found.

2. Code quality

2.1 Conventions

Reviewed all changed files for license, imports, naming, core-method and state-field comments. No additional convention blocker found.

2.2 Test coverage and stability

Stability rating: Stable. JdbcSinkFactoryTest.java:651 exercises real HOCON overlapping-pattern precedence; line 806 exercises engine-top-level versus nested JDBC placeholder passes. Negative cases cover missing/empty/wrong-shaped primary_keys, invalid regex, empty lists, null/non-string values, blank columns, upstream-name versus target remapping and missing upstream PK. JdbcMysqlMultipleTablesIT.java:236-267 drops dedicated target tables, runs the actual config, asserts ordered information_schema PRIMARY columns and exact row counts, then drops fixtures in finally. Test keys are NOT NULL, shared fixtures remain untouched, query ordering is explicit, statements/result sets use scoped cleanup and no new hard sleep/performance threshold is added. Thus stability is Stable on inspection. REST-shaped config/shade tests and direct toConfig assertions reuse the upstream implementation; the single a.b lookup does not alone prove shape. No local tests were run.

2.3 Documentation

EN/ZH JDBC docs and placeholder guides describe regex full-match semantics, precedence, mixed static/primary/unique-key expansion and both replacement passes. File and REST regex support relies on the merged shared helper. Existing optional follow-up: docs should distinguish an entirely empty multi_table_config object (explicitly accepted as no customization at JdbcMultiTableConfigConditionExtension.java:56-57) from a nonempty object with absent/empty primary_keys (rejected). This is wording clarification, not a new source blocker.

3. Architecture

3.1 Change location

The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.

3.2 Maintainability

Keep the behavior, lifecycle ownership, and failure contract together. The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.

3.3 Extensibility

Prefer the existing component boundary and tests over unrelated shared abstractions.

3.4 Upgrade impact

Fully compatible for jobs that do not use the new option: the old explicit primary_keys branch is intentionally not rewritten/revalidated, and PK/unique-key fallback is preserved. New option spelling is multi_table_config with no default. Existing public connector API, default, protocol, row/checkpoint serialization and shared config conversion are unchanged; no new dependency. The opt-in mapping intentionally overrides keys only on matched tables. Blank/comma key validation avoids ambiguity in the existing comma-delimited config representation; it is not a general SQL identifier whitelist.

4. Findings summary

Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.

# Finding Location Severity
- No new source blocker found - -

5. Merge recommendation

Can merge once the recorded CI and repository gates are satisfied

Blocking items: No source blocker. Current-head CI and write-capable maintainer review remain independent requirements.

Non-blocking suggestions: None beyond the validation limits above.

Overall: the reviewed source path is coherent; no runtime acceptance is claimed beyond the actual CI result. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.

CI and repository state: Signal pull request update: SUCCESS; Build: IN_PROGRESS; Build: in_progress. GitHub reports BLOCKED / CHANGES_REQUESTED.

Verification: Reviewed all changed files and the referenced call sites at 4903f9c2bd224708cb19a7fffafb5c46ee77bc9b against merge base 39c74ce48b0fb5e0318326b8d57a42c7380c40c8. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.

Review time: 2026-11-27T05:07:21.867573-05:00

Local evidence: git fetch obtained head 4903f9c2bd224708cb19a7fffafb5c46ee77bc9b; git merge-base returned 39c74ce48b0fb5e0318326b8d57a42c7380c40c8; git diff --stat reports 14 files changed, 1454 insertions(+), 42 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.

@DanielLeens 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.

The exact-head Build cited as in progress is now completed/failure. The concrete causes remain those identified in the full review: all-connectors partition 4 JDK 17 fails wrapper bootstrap with HTTP 429/MavenWrapperMain missing, and partition 6 JDK 11 fails the Databend Flink invocation with zero registered TaskManagers and NoResourceAvailableException. Neither is a JDBC mapping assertion. No matching landed dev fix was established, so sync alone is not a verified cure. This attempt has finished: rerun those failed lanes after artifact/resource availability recovers and retain the new exact-head results. My source clearance stands.

5. Merge recommendation

Conclusion: Merge after fixes / remaining repository gates.

Blocking items: No remaining source blocker from Daniel. The current CI/repository gate described above still needs attention.

Non-blocking suggestions: Those from the existing complete review are unchanged; this follow-up adds no source finding. No alternative implementation or unrelated module/dependency patch is requested.

Unchanged head 4903f9c2bd224708cb19a7fffafb5c46ee77bc9b; base dev compare diverged, ahead 35 / behind 2. This drift is recorded separately and alone does not request synchronization. This is a CI/gate correction, not another full source review; no local build/test/runtime execution was performed. Daniel has READ permission, so historical requested-changes controls and an effective write-level approval/dismissal remain maintainer actions. Checked 2026-11-27T10:23:37.836897+00:00.

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

The CI fact in my previous follow-up has changed again: exact-head Build attempt 2 is now in progress on this unchanged head. The failures previously identified belong to attempt 1; they are not the result of this active rerun. Please let the existing attempt complete rather than start a duplicate. My source-level blocker remains cleared. The earlier wrapper-429 and Databend/Flink capacity diagnostics remain context for comparison if those same lanes fail again; they do not justify unrelated parser/dependency patches while this rerun is active. This is not yet successful runtime acceptance.

5. Merge recommendation

Conclusion: Merge after the remaining CI and repository gates are satisfied.

Blocking items: No source blocker from Daniel; current-head CI must complete successfully and a write-capable maintainer must provide any effective approval/dismissal required by repository policy.

Non-blocking suggestions: The existing full review is unchanged. No new source finding or alternative implementation is introduced.

Unchanged head 4903f9c2bd224708cb19a7fffafb5c46ee77bc9b; base dev, compare diverged, ahead 35 / behind 2. Branch drift alone does not request synchronization. This corrects the CI/gate fact only; no local build, test or runtime execution was performed. Daniel has READ permission, so this does not dismiss historical requested changes or replace effective maintainer review. Checked 2026-11-27T10:41:26.967182+00:00.

This branch has not been deployed

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

Labels

api connectors-v2 core SeaTunnel core module document don't merge There needs to be a specific reason in the PR, and it cannot be merged for the time being. e2e First-time contributor First-time contributor jdbc

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature][Sink] Support table-level primary_keys configuration with prefix matching

6 participants