Skip to content

[Feature][Connector-V2] Support snapshot-only startup mode for MySQL CDC - #11487

Merged
davidzollo merged 20 commits into
apache:devfrom
fatmanverse:feature-mysql-cdc-snapshot-only
Nov 9, 2026
Merged

davidzollo merged 20 commits into
apache:devfrom
fatmanverse:feature-mysql-cdc-snapshot-only

Conversation

@fatmanverse

@fatmanverse fatmanverse commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Purpose of this pull request

Closes #11036.

This pull request adds a dedicated startup.mode = "snapshot-only" option for bounded MySQL CDC bootstrap jobs. It reuses the existing snapshot split planning and reading path, reports the source as bounded, and finishes without creating an incremental split or entering continuous binlog streaming.

The snapshot-only completion path depends only on snapshot split completion, so parallel batch jobs can finish without requiring a checkpoint. When restoring from a checkpoint, the checkpointed table set remains authoritative and catalog discovery is skipped, so tables created or removed after the checkpoint do not change the bounded input.

Restore safety:

  • restoreEnumerator() rejects a mismatch between the configured startup mode and the checkpoint state type. A snapshot-only job can only restore from SnapshotPhaseState, and other startup modes cannot restore from it. Changing startup.mode across a restore fails fast; submit a new job instead.
  • IncrementalSourceReader.addSplits() rejects an incremental split under snapshot-only mode, so a restored reader state can never turn the bounded job into an unbounded change log read.
  • A snapshot-only restore fails with an error naming the tables when the checkpoint still has unread snapshot data of a table that is no longer in the configured table list or no longer exists. Without this, such a table was still split while the readers no longer captured it, and the snapshot read failed with a NullPointerException on every restart from the same checkpoint. Tables whose splits are all finished are not checked.

exactly_once remains supported. It may perform bounded low-to-high-watermark binlog backfill during the snapshot phase, but snapshot-only mode still finishes after all snapshot splits complete. Incompatible stop modes, timestamp startup, and specific-offset startup options fail before source initialization.

Scope note: shared CDC base classes

StartupMode.SNAPSHOT_ONLY and SnapshotOnlySplitAssigner already exist in dev (#11380) and are used by PostgreSQL-CDC and OpenGauss-CDC. The restore and reader guards added here live in connector-cdc-base, so they also apply to those connectors when they run in snapshot-only mode: restore uses the checkpointed table set, rejects unread tables that are no longer configured, and rejects switching between snapshot-only and another startup mode. Error messages use dialect-neutral wording for this reason. The checks of incompatible stop/startup offset options are part of the MySQL option rule (MySqlIncrementalSourceFactory, MySqlSnapshotOnlyGuards), and OceanBase-CDC inherits that rule, so it also accepts snapshot-only. The PostgreSQL-CDC and OpenGauss-CDC docs (en/zh) describe the restore behavior.

Does this PR introduce any user-facing change?

Yes.

Previously, MySQL CDC could either read a snapshot and continue into binlog streaming, or start from a binlog-oriented position. There was no first-class bounded snapshot-only mode.

Users can now configure:

startup.mode = "snapshot-only"

The source reads the configured snapshot and exits successfully without consuming subsequent binlog events. Existing startup modes keep their current behavior.

The English and Chinese MySQL-CDC docs describe:

  • the new mode, and the snapshot-only restriction on the stop.mode, startup.specific-offset.* and startup.timestamp option rows;
  • consistency under concurrent writes with exactly_once = false and exactly_once = true;
  • the server-id range requirement for bounded backfill, and that an undersized range is only reported when a reader starts;
  • that changing startup.mode across a checkpoint restore is not supported, and that a restore reads exactly the checkpointed tables.

How was this patch tested?

Verified on the latest dev (JDK 17, same Maven flags as CI):

  • ./mvnw spotless:check on all changed modules
  • Unit tests of connector-cdc-base (141), connector-cdc-mysql (59), connector-cdc-oceanbase (10), connector-cdc-postgres (93) and connector-cdc-opengauss (7): 0 failures, 0 errors
    • snapshot-only coverage: IncrementalSourceTest (including restores with an unread table that is no longer configured, one configured only in another schema, a finished table that is no longer configured, and MySQL/PostgreSQL table id shapes), SnapshotOnlySplitAssignerTest, IncrementalSourceReaderSnapshotOnlyTest, MySqlIncrementalSourceFactoryTest, OceanBaseIncrementalSourceFactoryTest
    • dev's IncrementalSourceReaderTest mocks stub getStartupConfig(), so the reader guard does not hit a null startup config
  • MysqlCDCSnapshotOnlyIT: 5 runtime invocations passed across Flink 1.13.6, 1.15.3, 1.18.0, 1.20.1 and Zeta
    • parallelism 2, checkpointing disabled, server-id = "5657-5658", 103 rows, snapshot.split.size = 1, exactly_once = true
    • the job is started asynchronously; while later splits are still pending, a row in an already completed split is deleted, and the sink must still equal the original snapshot
    • the MySQL driver is copied with DependencyJar, the same as the other MySQL CDC ITs
  • The new links from the OpenGauss-CDC docs point at the existing PostgreSQL-CDC headings Run a snapshot-only batch and 仅运行一次性快照

Check list

  • No new JAR binary package is added.
  • English and Chinese connector documentation is updated.
  • No incompatible configuration or API change is introduced.
  • Focused unit and MySQL CDC E2E coverage is included.
  • Plugin mapping, distribution dependencies, labels, and plugin configuration do not require changes for this existing connector.

@fatmanverse

Copy link
Copy Markdown
Contributor Author

Additional local E2E environment details:

  • Docker Server: 29.4.0 on OrbStack
  • The repository default Testcontainers 1.17.6 negotiates Docker API 1.32, which Docker 29 no longer accepts.
  • The E2E was therefore run with a command-line-only override: -Dtestcontainer.version=1.21.4. No dependency or POM change is included in this PR.
  • MysqlCDCSnapshotOnlyIT completed all 5 runtime invocations with 0 failures and 0 errors. The Zeta run reported 3 records read, 3 written, and 0 failed.

@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 contribution! I re-reviewed the full current diff and the relevant snapshot-state regression coverage runtime path.

I do not see a source-side blocker on the current head. The current Build failure is the shared engine MetricsApiTest baseline; CI and repository review remain outstanding.

Daniel's repository permission is read-only, so this COMMENTED review records the technical conclusion only; it does not change GitHub's approval summary. A write-capable maintainer may still need to complete the repository approval gate.

@SEZ9 SEZ9 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for working on this. I re-reviewed the latest head 991e997e72cb from scratch.

Review conclusion

Conclusion: LGTM, can merge

Nice work — thanks again for the contribution. Happy to discuss any of the above.

@nzw921rx nzw921rx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for adding the bounded snapshot-only mode. I reviewed the current head 991e997e72cb. I do not think this PR is ready to merge yet.

1. Blocker: keep the checkpointed table set authoritative during snapshot-only restore

restoreEnumerator() still reconciles HybridPendingSplitsState with the latest result of discoverDataCollections() before constructing the snapshot-only assigner.

This can add newly discovered tables to remainingTables or remove unfinished checkpointed tables. Consequently, the input of a bounded snapshot job can change after failover.

For example, a table matching table-pattern that is created after a checkpoint will unexpectedly be included after recovery. This conflicts with #11036, which explicitly lists dynamic newly-added table capture as a non-goal.

Please make the checkpointed table set authoritative for snapshot-only recovery and add a checkpoint/restore test proving that catalog changes do not alter the bounded input set.

2. Blocker: do not download the JDBC driver from inside the runtime container

The new E2E downloads MySQL Connector/J using wget from inside every SeaTunnel runtime container.

This makes the test depend on container DNS and outbound network access, bypasses Maven mirrors, retries and the local repository, and can easily cause flaky CI failures.

The test also hard-codes Connector/J 8.0.32, while the Maven-managed test dependency currently resolves to 8.0.27. The test runtime therefore uses a different driver from the declared dependency.

Current dev already provides MysqlCDCDriverResolver, introduced by merged PR #11456. Please rebase and reuse the Maven-resolved driver:

@TestContainerExtension
protected final ContainerExtendedFactory extendedFactory =
        MysqlCDCDriverResolver::copyMySQLDriverToContainer;

This resolves com.mysql.cj.jdbc.Driver from the Maven test classpath and copies its JAR into the container with copyFileToContainer, removing the unnecessary network dependency and keeping Maven as the single source of the driver version.

3. Preserve the existing public constructor overloads

Both existing public HybridSplitAssigner constructors were replaced with signatures containing the new boolean snapshotOnly argument.

External or custom CDC connectors compiled against the old constructors can fail with NoSuchMethodError, while source recompilation also fails.

Please retain the old overloads and delegate them with snapshotOnly = false.

4. Complete the snapshot configuration validation

startup.mode = snapshot rejects startup.specific-offset.*, but accepts and silently ignores startup.timestamp.

Please reject startup.timestamp as well and add a negative configuration test.

Also, validateSnapshotOnlyConfig() currently runs after datasource, dialect and deserializer initialization. MySQL schema discovery may therefore fail before the expected configuration validation. Please move this validation before database-related initialization.

Test coverage

  • The E2E changes the source only after executeJob() has returned. A terminated job cannot consume those changes, so this does not prove that an incremental reader was never started.
  • Only three rows are inserted while snapshot.split.size remains at its default. This normally creates one snapshot split despite parallelism = 2. Please set snapshot.split.size = 1 or insert enough rows to exercise multiple snapshot readers.
  • exactly_once is also used for bounded low-to-high-watermark backfill during snapshot reading. If snapshot-only must reject it, please document the concurrent-write consistency boundary or require the source to be quiesced, and add a controlled concurrent-write test.

For these reasons, I recommend requesting changes.

@github-actions github-actions Bot removed the reviewed label Jul 19, 2026
@fatmanverse
fatmanverse force-pushed the feature-mysql-cdc-snapshot-only branch from 991e997 to e22ab12 Compare July 20, 2026 02:54
@fatmanverse

fatmanverse commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor Author

@nzw921rx Thanks for the detailed review. I addressed the requested changes in commit e22ab12d7.

  1. Snapshot-only restore now treats the checkpointed table set as authoritative. It collects tables from processed tables, remaining tables, remaining snapshot splits, and assigned snapshot splits, and does not call catalog discovery on the snapshot-only restore path. Legacy checkpoint state is also marked as having checkpointed remaining tables before the snapshot assigner opens, so it cannot rediscover the catalog. The new unit coverage verifies that a newly created table is excluded after restore.

  2. The E2E now reuses MysqlCDCDriverResolver and copies the Maven-resolved Connector/J into the container. It no longer downloads a driver from inside the container, and the test uses the declared 8.0.27 driver.

  3. Both existing public HybridSplitAssigner constructors are retained and delegate to the new overloads with snapshotOnly = false.

  4. Snapshot-only validation now runs before datasource, dialect, deserializer, and offset initialization. It rejects stop modes other than never, startup.specific-offset.*, and startup.timestamp. The negative test verifies that startup.timestamp fails before source initialization.

  5. The E2E seeds 103 rows and sets snapshot.split.size = 1, so multiple snapshot splits are exercised. It starts the job asynchronously, waits until rows from early splits are visible while later splits are still outstanding, updates and deletes rows from completed snapshot ranges, and verifies that the sink remains exactly the original snapshot result. The test passed all 5 runtime invocations: Flink 1.13.6, 1.15.3, 1.18.0, 1.20.1, and Zeta. The Zeta run reported 103 records read, 103 written, and 0 failed.

  6. exactly_once remains supported for both initial and snapshot startup modes. The snapshot mode documentation now describes the bounded low-to-high-watermark backfill semantics and the controlled concurrent-write E2E coverage. Snapshot-only still never enters continuous binlog streaming.

Validation completed:

  • ./mvnw spotless:apply
  • CDC base targeted tests: 6 tests passed
  • MySQL factory tests: 2 tests passed
  • MysqlCDCSnapshotOnlyIT: 5 tests passed
  • git diff --check

The repository-wide -DskipTests verify is still blocked by pre-existing origin/dev compilation errors in connector-jdbc, including the duplicate setNullToStatementByDataType method and missing generated methods. No connector-jdbc files are changed in this PR. The full test run is also blocked by the existing seatunnel-config-shade shaded Typesafe Config ClassNotFoundException.

@fatmanverse

Copy link
Copy Markdown
Contributor Author

Follow-up audit fixes are included in aa2705213.

  • The snapshot-only E2E now uses the legal server-id = "5657-5658" range for parallelism 2.
  • The restore regression now calls restoreEnumerator() and open() directly, verifies that snapshot-only recovery never calls discoverDataCollections(), and confirms legacy state is marked with checkpointed remaining tables.
  • Negative coverage now checks stop.mode, startup.timestamp, startup.specific-offset.file, and startup.specific-offset.pos independently before source initialization.
  • The option description and both MySQL CDC FAQ pages now distinguish bounded snapshot backfill from continuous binlog streaming. The PR description has been updated to match the implementation and current validation status.

Validation on the latest head:

  • CDC base tests: 67 passed
  • MySQL factory tests: 2 passed
  • MysqlCDCSnapshotOnlyIT: 5 passed across Flink 1.13.6, 1.15.3, 1.18.0, 1.20.1, and Zeta
  • ./mvnw spotless:apply and git diff --check passed

Repository-wide verify is still blocked by the existing connector-jdbc compilation failures on dev. The full test run is still blocked by the existing seatunnel-config-shade shaded Typesafe Config ClassNotFoundException. Neither failing module is changed by this PR.

@SEZ9 SEZ9 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for working on this. I re-reviewed the latest head e22ab12d78ed from scratch.

Review conclusion

Conclusion: LGTM, can merge

Nice work — thanks again for the contribution. Happy to discuss any of the above.

@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 contribution! I rechecked the complete current-head diff and the relevant runtime path, including the deletion and external-finding ledgers. I do not see a source-level blocker in this version.

The source review is clear, but the current Build is failing, so this PR is still waiting on CI. The current failed lanes include Run / Dead links, Run / updated-modules-integration-test-part-2 (11, ubuntu-latest), Run / updated-modules-integration-test-part-5 (11, ubuntu-latest), Run / unit-test (8, ubuntu-latest), and 10 more failed lanes. The shared dead-link failure has a fix in #11502, but that fix has not merged into dev yet; syncing the current dev alone will not clear that lane today. After #11502 lands, please sync/retrigger and then diagnose only any lanes that still fail.

@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 contribution! I rechecked the complete current-head diff and the relevant runtime path, including the deletion and external-finding ledgers. I do not see a source-level blocker in this version.

The source review is clear, but the current Build is failing, so this PR is still waiting on CI. The current failed lanes include Run / Dead links, Run / updated-modules-integration-test-part-2 (11, ubuntu-latest), Run / updated-modules-integration-test-part-5 (11, ubuntu-latest), Run / unit-test (8, ubuntu-latest), and 10 more failed lanes. The shared dead-link failure has a fix in #11502, but that fix has not merged into dev yet; syncing the current dev alone will not clear that lane today. After #11502 lands, please sync/retrigger and then diagnose only any lanes that still fail.

@fatmanverse
fatmanverse force-pushed the feature-mysql-cdc-snapshot-only branch from aa27052 to 9f066d6 Compare July 21, 2026 03:25

@SEZ9 SEZ9 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for working on this. I re-reviewed the latest head 9f066d6faf57 from scratch.

What this PR fixes

  • User pain: MySQL CDC users doing one-time backfill/bootstrap had no bounded mode — jobs either continued into binlog streaming after the snapshot or had to be killed manually, and there was no documented way to get a clean bounded exit.
  • Fix approach: Introduces startup.mode = "snapshot" that reuses the existing snapshot split planning/reading path, reports the source as bounded, skips creation of the incremental split so the job finishes after all snapshot splits complete, keeps exactly_once bounded backfill working, and fails fast on incompatible stop.mode/startup.specific-offset.*/startup.timestamp combos; docs (en/zh) updated with the new enum value, a dedicated bootstrap section, and a revised FAQ entry.
  • One-line summary: Feature is functionally sound and the docs are thorough, but there are three medium issues to address before merge — the restore-with-changed-startup-mode edge case is not validated despite the fail-fast promise, the rewritten exactly_once docs silently narrow the supported-mode contract for existing users, and the snapshot-only example shows a single server-id while the mode is pitched for parallel bounded jobs that need a server-id range per reader.

Runtime chain I rechecked

MySqlIncrementalSourceFactory.createSource() -> MySqlIncrementalSource  MySqlIncrementalSourceFactory.java:~95
  IncrementalSource.getBoundedness() -> returns BOUNDED when startupConfig mode == SNAPSHOT  IncrementalSource.java:~130
  IncrementalSource.createEnumerator() -> SnapshotSplitAssigner (snapshot-only path, no HybridSplitAssigner incremental phase)  IncrementalSource.java:~170
    SnapshotSplitAssigner.getNext() -> exhausts snapshot splits -> noMoreSplits()  SnapshotSplitAssigner.java:~150
    IncrementalSourceEnumerator.assignSplits() -> context.signalNoMoreSplits(subtask)  IncrementalSourceEnumerator.java:~180
      IncrementalSourceReader.handleNoMoreSplitsMessage() -> reader completes without IncrementalSplit / binlog fetch  IncrementalSourceReader.java:~140
Restore path (checkpointed table set authoritative, discovery skipped):
  IncrementalSource.restoreEnumerator(checkpointState) -> SnapshotSplitAssigner(checkpoint) — no catalog re-discovery  IncrementalSource.java:~200
Validation (fail-fast before source init):
  MySqlIncrementalSourceFactory.createSource() -> option compatibility check: SNAPSHOT + (stop.mode != never | startup.specific-offset.* | startup.timestamp) -> throws  MySqlIncrementalSourceFactory.java:~110

Findings

Issue 1: Docs promise fail-fast for incompatible options with snapshot mode, but the change-of-startup-mode-across-restore edge case is not covered

  • Location: docs/en/connectors/source/MySQL-CDC.md:437
  • Why it matters: - Root cause: the new section states incompatible combinations "fail fast at startup", which only addresses fresh submissions. A job originally checkpointed under startup.mode = initial (hybrid state containing a pending/created incremental split) that is restored with the config flipped to snapshot presents state that snapshot-only mode is documented never to produce.
  • Impact: depending on how HybridSplitAssigner interprets a restored PendingSplitsState containing an incremental split while StartupMode.SNAPSHOT is configured, the job could either wrongly stream binlog forever (violating the bounded contract) or NPE/hang on the unexpected split. Since the PR modifies both IncrementalSource restore handling and HybridSplitAssigner (+88 lines), this edge case is squarely in scope but neither the docs nor the described tests mention it.
  • Fix: on restore, validate the checkpointed state against the configured startup mode and fail with a clear error message (e.g. "cannot restore a hybrid/incremental checkpoint with startup.mode=snapshot") rather than proceeding, and document that switching startup.mode across a checkpoint restore is not supported. Add a unit test in HybridSplitAssignerTest for a restored state that already contains an incremental split under snapshot mode.
  • Suggested fix: "Fails fast at startup" covers fresh submissions, but there is a nastier edge: restoring a checkpoint taken under startup.mode = initial (whose state may already contain the incremental split) with the config changed to snapshot. The assigner then sees state that snapshot mode should never produce — it must either reject that restore with a clear error or deterministically finish, not stream binlog or hang. Please add a restore-state validation in the assigner/source and a HybridSplitAssignerTest case for a restored state containing an incremental split under SNAPSHOT mode, and document that changing startup.mode across restore is unsupported.
  • Severity: Medium

Issue 2: The rewritten exactly_once description now claims it is only supported for initial or snapshot, which silently narrows the documented contract for existing users on other startup modes

  • Location: docs/en/connectors/source/MySQL-CDC.md:215
  • Why it matters: - Root cause: the English option table row for exactly_once was rewritten from the generic "Enable exactly once semantic." to "Supported when startup.mode is initial or snapshot", but this PR only adds a new startup mode — it does not (per the PR description) change how exactly_once interacts with earliest, latest, specific, or timestamp modes.
  • Impact: users currently running exactly_once = true with non-initial startup modes will read this as a deprecation/behavior change and may reconfigure jobs unnecessarily; conversely, if the runtime does not actually reject the combination, the doc and code contract diverge, which is exactly the kind of drift that causes support tickets and silent semantic misunderstanding around checkpoint/state guarantees.
  • Fix: either scope the sentence to what actually changed (e.g., "When startup.mode is initial or snapshot, exactly_once additionally enables bounded low-to-high-watermark binlog backfill during the snapshot phase") while keeping the original general statement, or — if the code truly restricts exactly_once to these two modes now — add explicit fail-fast validation in MySqlIncrementalSourceFactory and call the restriction out as a breaking change in the PR description.
  • Suggested fix: This rewrite reads as if exactly_once is now only supported for initial/snapshot, but the PR doesn't change its behavior for earliest/latest/specific/timestamp. Can we rephrase to keep the general statement and add the snapshot-specific note, e.g. "Enable exactly once semantics. When startup.mode is initial or snapshot, this also enables bounded binlog backfill during the snapshot phase."? Otherwise existing users on other modes will think their configuration became invalid.
  • Severity: Medium

Issue 3: Snapshot-only example uses a single server-id although the mode is advertised for parallel bounded bootstrap with exactly_once binlog backfill, which requires a server-id range per reader

  • Location: docs/en/connectors/source/MySQL-CDC.md:441
  • Why it matters: - Root cause: the new "Snapshot-Only Bootstrap" example hardcodes server-id = 5656 while the same section states that exactly_once may perform bounded low-to-high-watermark binlog backfill during the snapshot phase. Binlog backfill opens a MySQL replication connection per reader, and with parallelism > 1 each reader must use a distinct server-id, otherwise MySQL kills the duplicate replication session with ERROR 1236 / A slave with the same server_uuid/server_id.
  • Impact: users who copy this example, raise parallelism (the natural thing to do for a one-time backfill), and enable exactly_once will hit intermittent connection resets during backfill on Zeta/Flink. Notably, the PR's own E2E deliberately uses a range server-id = "5657-5658" with parallelism 2, so the documented example is weaker than the tested configuration.
  • Fix: change the example to a range (e.g. server-id = "5656-5657") or add an explicit note in the snapshot section that a server-id range covering the job parallelism is required when exactly_once = true, mirroring what the E2E config does.
  • Evidence: docs/en/connectors/source/MySQL-CDC.md:437 Because the job never enters continuous binlog streaming, snapshotmode is incompatible withstop.modevalues other thannever...exactly_once remains available for bounded backfill during the snapshot phase and does not start continuous binlog streaming.
  • Suggested fix: Since this section explicitly says exactly_once can trigger bounded binlog backfill during the snapshot phase, this example should use a server-id range instead of a single server-id = 5656. With parallelism > 1 each backfill reader opens its own replication connection and duplicate server-ids get killed by MySQL. Your own E2E uses server-id = "5657-5658" with parallelism 2 — let's document the same pattern here (e.g. server-id = "5656-5657") or add a note that the range must cover the job parallelism.
  • Severity: Medium

Review conclusion

Conclusion: can merge; the notes below are non-blocking

2. Suggested (non-blocking) follow-ups

  • Issue 1: Docs promise fail-fast for incompatible options with snapshot mode, but the change-of-startup-mode-across-restore edge case is not covered
  • Issue 2: The rewritten exactly_once description now claims it is only supported for initial or snapshot, which silently narrows the documented contract for existing users on other startup modes
  • Issue 3: Snapshot-only example uses a single server-id although the mode is advertised for parallel bounded bootstrap with exactly_once binlog backfill, which requires a server-id range per reader

Nice work — thanks again for the contribution. Happy to discuss any of the above.

@fatmanverse

Copy link
Copy Markdown
Contributor Author

Thanks @SEZ9 for the thorough follow-up review. I've addressed all three non-blocking issues in commit 628fadb4c.

Issue 1 — cross-restore startup.mode switch (fail-fast)

I traced the runtime path and found the bounded-contract violation has two distinct entry points, so I added fail-fast at both, plus a defense-in-depth check:

  • IncrementalSource.restoreEnumerator() now rejects restoring an IncrementalPhaseState when startup.mode = snapshot. This covers a job originally started with earliest/latest/specific/timestamp (which checkpoints an IncrementalPhaseState) being restored as snapshot.
  • IncrementalSourceReader.addSplits() now rejects an incremental (binlog) split under snapshot mode. This is the actual "streams forever" path: a job that ran initial, completed the snapshot, entered the binlog phase and checkpointed, then restarts with startup.mode = snapshot — the enumerator state is clean/bounded, but the reader restores an IncrementalSplit and would stream binlog indefinitely. Since IncrementalPhaseState is an empty marker and the incremental split state actually lives in the reader, the reader-side guard is essential rather than optional.
  • HybridSplitAssigner.addSplits() also rejects an incremental split under snapshot mode as defense-in-depth.

New tests: IncrementalSourceTest#testSnapshotOnlyRestoreRejectsIncrementalCheckpoint (enumerator) and HybridSplitAssignerTest#testSnapshotOnlyRejectsRestoredIncrementalSplit (assigner). Docs now state that changing startup.mode across a restore is not supported.

Issue 2 — exactly_once doc contract

You're right that the wording wrongly narrowed the contract. I confirmed via ConfigValidator that the .conditional(STARTUP_MODE, [INITIAL, SNAPSHOT], EXACTLY_ONCE) rule never rejects exactly_once at runtime (it has a default of false, so it is never treated as absent). The description now keeps the general statement and adds the snapshot-phase note, in both en and zh:

Enable exactly once semantics. When startup.mode is initial or snapshot, it additionally enables bounded low-to-high-watermark binlog backfill during the snapshot phase.

Issue 3 — snapshot-only example server-id

Changed the example to a range ("5656-5657") matching the E2E, and added a note that exactly_once backfill opens a replication connection per reader, so a server-id range covering the job parallelism is required. Fixed in both en and zh.

Validation

  • ./mvnw spotless:apply — clean
  • connector-cdc-base compiles clean (main + test)
  • Targeted tests pass: IncrementalSourceTest (3), HybridSplitAssignerTest (4)

@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 contribution! I rechecked the complete current-head diff, deletion ledger, existing reviewer findings, and the relevant runtime path. I do not see a source-level blocker in this version.

The previous source concern is resolved on 628fadb4c8dc: snapshot-only restore now treats checkpointed tables as authoritative and rejects an incompatible incremental-state restore.

The source verdict is clear, but the required Build is still pending. Please let the current checks finish; a write-capable maintainer may still need to complete the approval gate afterward.

Queue note: this head is diverged against dev (ahead_by=4, behind_by=4). I am recording that fact separately; it is not by itself a request to sync unless the CI guidance above explicitly says so.

@fatmanverse
fatmanverse force-pushed the feature-mysql-cdc-snapshot-only branch from 628fadb to 012fbd1 Compare July 22, 2026 06:24
@fatmanverse

Copy link
Copy Markdown
Contributor Author

Thanks for the recheck. I have rebased this PR onto the latest dev and resolved the documentation conflicts while preserving the snapshot, specific/GTID, and enable_concurrent_read documentation. The branch is now up to date with dev.

I also fixed the snapshot-only E2E failure. The test previously updated the primary key from id=5 to id=6 while later snapshot splits were still pending. Flink 1.18 could legitimately read id=6 from a later snapshot split, so this did not indicate that the source had entered continuous binlog streaming. The test now only deletes id=2 from an already completed split, which keeps the intended assertion without moving a row into a pending snapshot range.

The latest dev also introduced Container.ExecResult usages in MysqlCDCSpecificStartingOffsetIT without importing org.testcontainers.containers.Container, which blocked compilation of the whole MySQL CDC E2E module. I added the missing import.

Local verification completed:

  • ./mvnw spotless:apply
  • 18 related CDC unit tests passed
  • MysqlCDCSnapshotOnlyIT passed on all 5 PR runtimes: Flink 1.13, 1.15, 1.18, 1.20, and Zeta (5 tests, 0 failures, 0 errors)
  • ./mvnw -q -DskipTests -Dskip.ui=true verify passed

The original full verify without skip.ui was also attempted locally, but the unchanged seatunnel-engine-ui npm install exited with code 243, so the successful full backend verification explicitly skipped UI. The updated head is 012fbd1.

@github-actions github-actions Bot added the Zeta label Jul 22, 2026
@fatmanverse

fatmanverse commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor Author

The latest CI failure in ImportClassCheckTest has been addressed in commit 70cdf0d.

The fix is a one-line import replacement in CoordinatorServicePipelineCleanupTest, using SeaTunnel's org.apache.seatunnel.engine.common.utils.concurrent.CompletableFuture instead of java.util.concurrent.CompletableFuture, as required by the repository import rule.

Local verification completed:

  • ImportClassCheckTest: 8 tests passed
  • CoordinatorServicePipelineCleanupTest: 8 tests passed
  • ./mvnw spotless:apply: passed
  • ./mvnw -q -DskipTests -Dskip.ui=true verify: passed

This CI fix is independent of the MySQL CDC snapshot-only behavior.

@fatmanverse
fatmanverse force-pushed the feature-mysql-cdc-snapshot-only branch from 70cdf0d to d84b23b Compare July 23, 2026 02:25
@github-actions github-actions Bot removed the Zeta label Jul 23, 2026
DanielLeens

This comment was marked as outdated.

@SEZ9

SEZ9 commented Jul 25, 2026

Copy link
Copy Markdown
Collaborator

Thanks @fatmanverse for the thorough follow-ups — I've gone through e22ab12d7 and aa2705213 against my earlier review notes, and all three of my medium concerns are now addressed:

  1. Restore edge case — Making the checkpointed table set authoritative on the snapshot-only restore path (and marking legacy state as having checkpointed remaining tables before the assigner opens) is the right call. The unit test asserting discoverDataCollections() is never invoked on recovery is exactly the regression coverage I wanted.
  2. exactly_once contract — Good, keeping both initial and snapshot supported and documenting the bounded low-to-high-watermark backfill semantics resolves the doc-narrowing concern.
  3. server-id range — The 5657-5658 range with parallelism 2 in the E2E fixes the example inconsistency, and the concurrent-write test design (updates/deletes against completed snapshot ranges while later splits are outstanding, sink stays equal to the original snapshot) is a solid way to prove the bounded semantics.

Also appreciated:

  • Reusing MysqlCDCDriverResolver instead of downloading the driver inside the container — that keeps the E2E hermetic.
  • Fail-fast validation now running before datasource/dialect/offset init, with independent negative coverage for stop.mode, startup.timestamp, and both startup.specific-offset.* keys.
  • Retaining both existing public HybridSplitAssigner constructors preserves binary compatibility for other dialects.

On the environment notes:

  • The -Dtestcontainer.version=1.21.4 override for Docker 29/OrbStack is fine as a local workaround since no POM change is included — just confirming CI runs with the repo default, so we'll rely on the CI result there.
  • The connector-jdbc compilation failures and the seatunnel-config-shade issue on origin/dev are indeed pre-existing and unrelated to this PR; no action needed from you on those here.

Remaining asks before merge:

  1. Please rebase onto the latest dev once more and make sure the full CI pipeline (including the CDC E2E jobs) goes green — that's the last gate.
  2. Double-check the PR title/description reflect the final scope so the changelog entry is accurate (it sounds like you've already updated it — just flagging for a final look).

Once CI is green I'm happy to approve. Nice work on this one — the feature is well-scoped and the test coverage came out strong.

@fatmanverse

Copy link
Copy Markdown
Contributor Author

Thanks @nzw921rx for the suggestion, and @DanielLeens for the detailed follow-up.

  1. Synced with dev in ca2c755 (conflict resolution only). The conflict was in the startup.timestamp / stop.mode rows of MySQL-CDC.md (en/zh): I kept the new stop.mode = latest explanation from dev and the snapshot-only notes of this PR.
  2. Moved the snapshot-only option checks into the option rule in d28296a:
    • MySqlIncrementalSourceFactory#getOptionRuleBuilder adds a conditional(STARTUP_MODE, SNAPSHOT_ONLY, ...) rule with two Conditions.extension guards from the new MySqlSnapshotOnlyGuards: stop.mode must be never, and startup.timestamp is not allowed. They throw OptionValidationException and keep the previous wording.
    • startup.specific-offset.* is already rejected for every mode other than specific by MySqlSpecificOffsetGuards, so I dropped that duplicated check.
    • validateSnapshotOnlyConfig is removed from the base IncrementalSource, so the base class is back to dev apart from the restore changes. Postgres and OpenGauss behave as on dev (their stop.mode only accepts never). OceanBase reuses the MySQL rule, so it gets the same guards.
    • The assertions moved from DebeziumJsonFormatTest (now unchanged from dev) to MySqlIncrementalSourceFactoryTest: stop.mode latest/specific, startup.timestamp and every startup.specific-offset.* option are rejected for snapshot-only; snapshot-only alone and with stop.mode = never stays valid; timestamp mode still requires startup.timestamp.

Verified on JDK 17: connector-cdc-base (128 tests) and connector-cdc-mysql (59 tests) unit tests pass, and connector-cdc-postgres, connector-cdc-opengauss and connector-cdc-oceanbase compile.

Could you take another look when you have time? Thanks!

@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 quick turnaround on the last round, @fatmanverse! I went through the full diff against the latest head (d28296a), not only the delta. The change that landed after my last review is exactly what @nzw921rx asked for (option-combination checks moved into the declarative optionRule), plus a merge of current dev. I traced it carefully and found no new source-level blocker; the open gate is CI.

What Problem Does This PR Solve?

  • Pain point: MySQL CDC had no first-class bounded bootstrap mode; the existing startup modes either kept streaming binlog or needed a manual stop.
  • Fix approach: startup.mode = "snapshot-only" for MySQL CDC (and OceanBase-CDC, which wraps it), reusing the existing SnapshotOnlySplitAssigner, with restore validation, a reader fail-fast guard, a checkpointed table set that stays authoritative on restore, option-rule guards, E2E and en/zh docs.
  • Summary: a MySQL CDC mode that finishes after the snapshot instead of drifting into streaming.
  • Example: startup.mode = "snapshot-only" with table-names = ["db.t"] reads the snapshot and the job ends successfully.

1. Code Change Review

1.1 Core Logic Analysis

job config
  -> MySqlIncrementalSourceFactory.optionRule()                           MySqlIncrementalSourceFactory.java:105-130
       conditional(startup.mode in [initial, snapshot-only]) -> exactly_once
       conditional(startup.mode == snapshot-only) -> MySqlSnapshotOnlyGuards:
            stop.mode must be never; startup.timestamp not allowed
       startup.specific-offset.* -> existing MySqlSpecificOffsetGuards (reject unless mode == specific)
  -> IncrementalSource.createEnumerator -> SnapshotOnlySplitAssigner (bounded)
  -> restoreEnumerator                                                    IncrementalSource.java:~360-430
       validateRestoredState(startupMode, state): snapshot-only <-> SnapshotPhaseState, else IllegalStateException
       SnapshotPhaseState -> capturedTables = getCheckpointCapturedTables(state)   (no catalog discovery)
       Hybrid/Incremental states -> discovery as before
  -> IncrementalSourceReader.addSplits: incremental split under snapshot-only -> IllegalStateException

The normal user path (config validation, then enumerator creation) hits the changed logic. I verified: the option-rule API used (conditional(Option, value, Condition...)) exists in OptionRule; the guards return true for absent values (stop.mode defaults to never), so a plain snapshot-only config is accepted; OceanBase-CDC extends MySqlIncrementalSourceFactory and calls getOptionRuleBuilder(), so it inherits the guards. Forcing isRemainingTablesCheckpointed = true in SnapshotOnlySplitAssigner is safe: only the legacy (pre-flag) hybrid checkpoints have it false, and those are rejected by validateRestoredState for snapshot-only, while SnapshotSplitAssigner.snapshotState always writes true.

1.2 Compatibility Impact

Fully compatible for existing modes: the new enum value is additive, the base-class imperative validator from the earlier head is gone, and restoreEnumerator only changes behavior for SnapshotPhaseState. Two points that I checked and consider acceptable: (a) the Hybrid restore() now builds checkpointCapturedTables through the shared getCheckpointCapturedTables (it also unions the tables of remaining/assigned splits). Under the SnapshotSplitAssigner invariants every table that has splits is already in alreadyProcessedTables, so the result is the same for INITIAL-mode restores, and the existing CDC restore ITs cover that path. (b) PostgreSQL/OpenGauss snapshot-only (already on dev via #11380) now restore from the checkpointed table set instead of re-running discovery; this is intended and described in the PR.

1.3 Performance / Side-Effect Analysis

Validation-time and restore-time only. No hot-path change. The snapshot phase and backfill reuse the existing reader, so memory/CPU per split are unchanged.

1.4 Error Handling and Logging

Guards throw OptionValidationException with the option key and the reason; restore mismatches throw IllegalStateException with an actionable message ("submit a new job instead"). No sensitive data in messages.

Residual items (all non-blocking):

Issue 1 (Low): OceanBase-CDC silently gains snapshot-only

  • Location: OceanBaseIncrementalSourceFactory (extends MySqlIncrementalSourceFactory), docs/en/connectors/source/OceanBase-CDC.md (no startup.mode option list), OceanBaseIncrementalSourceFactoryTest (no snapshot-only case).
  • Problem: because the option enum is shared, OceanBase-CDC now accepts the mode (and gets the same guards), but it has no test or doc mention. Either add one factory test plus a line in the OceanBase-CDC docs, or state in the PR description that it is intentionally inherited and not separately supported.

Issue 2 (Low): the new unit tests have not executed in CI on this head yet (see CI note below). Please make sure MySqlIncrementalSourceFactoryTest (new guard cases) and the base-module tests actually run and pass once the unrelated failure is out of the way.

2. Code Quality Assessment

2.1 Coding Standards

New class has a class-level Javadoc that explains why the guards do not check the startup mode themselves; comments explain the fail-fast restore paths. The MySqlSnapshotOnlyGuards pattern mirrors MySqlSpecificOffsetGuards.

2.2 Test Coverage and Test Stability

Test-to-risk mapping (each fails if the production line is removed): testSnapshotOnlyRejectsStopMode (guard removed -> latest/specific accepted), testSnapshotOnlyRejectsStartupTimestamp, testSnapshotOnlyRejectsEverySpecificOffset (specific-offset guard dropped), testSnapshotOnlyWithoutStreamingOptionsIsValid (guard over-rejecting), testTimestampModeStillRequiresStartupTimestamp (existing timestamp rule regression); plus IncrementalSourceTest, SnapshotOnlySplitAssignerTest, IncrementalSourceReaderSnapshotOnlyTest for restore-state mismatch, authoritative table set and the reader guard, and MysqlCDCSnapshotOnlyIT (5 runtimes, parallelism 2, deletion in a completed split while later splits are pending). The assertions that moved out of DebeziumJsonFormatTest are now equal or stronger in MySqlIncrementalSourceFactoryTest (message contents checked), and DebeziumJsonFormatTest is back to its dev content, so no historical test was weakened.
Stability: Stable. The IT uses a bounded Awaitility wait and no Thread.sleep; it copies the Maven-resolved MySQL driver into the containers via DependencyJar (no download from inside the container).

2.3 Documentation Updates

docs/en and docs/zh are updated in lockstep, including the stop.mode / startup.timestamp / specific-offset restrictions and the restore constraint. Only the OceanBase note in Issue 1 is missing.

3. Architectural Soundness

3.1 Elegance

Precise fix. Moving the combination checks into the MySQL factory keeps connector-specific rules out of the shared base class, which was the maintainers' request.

3.2 - 3.3

Maintainable; one mode, one assigner, one validation location.

3.4 Historical-Version Compatibility

No persisted format changes (SnapshotPhaseState is reused unchanged). Existing jobs and checkpoints in other modes behave as before. I did not run an origin/2.6-release to current-dev upgrade; this is an inference from the diff (additive option value, no state or serialization change).

4. Issue Summary

Number Issue Location Severity
1 OceanBase-CDC inherits snapshot-only without test or doc mention seatunnel-connectors-v2/connector-cdc/connector-cdc-oceanbase/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/oceanbase/source/OceanBaseIncrementalSourceFactory.java Low
2 New unit tests have not run in CI on this head CI Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

No blocking source issue found; every earlier blocker (authoritative table set on restore, restore-state validation, reader guard, driver resolution in the E2E, option-rule migration) is verified fixed in the code. The only gate is CI:

  • On the fork run for this head, Run / unit-test failed on all four lanes (JDK 11/17, ubuntu/windows) in seatunnel-transforms-v2: LLMBooleanOutputTest.readsLegacyFactoryWrapperWithValidationDisabled fails with InvalidClassException (serialVersionUID mismatch on AbstractMultiCatalogTransform). This PR does not touch transforms. The cause is base drift on dev: #12804 (merged 2026-10-17) changed AbstractMultiCatalogTransform, and #12194 (merged 2026-10-19) added that test with a legacy serialized blob. This branch is 0 commits behind dev, so syncing will not help; a fix on dev is needed first. Because Maven stopped there, the CDC base and MySQL modules show as SKIPPED in that job, i.e. the new unit tests have not been executed by CI yet.
  • Other lanes (including mysql-cdc-connector-it) were still running or queued when I looked, so there is no final result for them.
    Please re-run the failed jobs after the dev fix, and confirm the CDC unit tests and mysql-cdc-connector-it pass.

Overall assessment: a clean, well-tested feature with restore safety handled in the right layers. Alternative considered: keeping a base-class runtime check for programmatic construction paths; the factory-level rule plus the restore/reader guards is sufficient because the mode is only reachable through the connector factories.

@fatmanverse

fatmanverse commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @DanielLeens for the re-review.

  • Issue 1 (OceanBase-CDC): 39c796a adds testOptionRuleInheritsSnapshotOnlyGuards to OceanBaseIncrementalSourceFactoryTest (a plain snapshot-only config is accepted, and stop.mode = latest is rejected by the inherited guard), plus a line in the en/zh OceanBase-CDC.md constraints that links to the MySQL-CDC snapshot-only section. Verified on JDK 17: spotless:check and the connector-cdc-oceanbase unit tests (10/10 pass).
  • Issue 2 (CI): the Build failure is LLMBooleanOutputTest.readsLegacyFactoryWrapperWithValidationDisabled on dev ([Bug][Transform-V2] Legacy LLM wrapper fixture fails on current dev #12929), unrelated to this PR. Until CI can reach the CDC modules, I ran their unit tests on 39c796a (JDK 17): connector-cdc-base 128, connector-cdc-mysql 59, connector-cdc-postgres 70, connector-cdc-opengauss 7, all passing, including IncrementalSourceTest, SnapshotOnlySplitAssignerTest, IncrementalSourceReaderSnapshotOnlyTest and the new MySqlIncrementalSourceFactoryTest cases. I will re-run the failed jobs once dev is fixed and confirm mysql-cdc-connector-it passes.

@nzw921rx The optionRule migration you suggested landed in d28296a (MySqlSnapshotOnlyGuards under conditional(startup.mode, snapshot-only), base-class check removed). Could you take another look and update your review when 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.

Thank you @fatmanverse for the two follow-up commits (d28296a1 and 39c796a2). I re-read the whole PR against current dev, not only the delta. The head moved from d28296a1 (my last review) to 39c796a2ee6f; the delta is small: a new OceanBaseIncrementalSourceFactoryTest#testOptionRuleInheritsSnapshotOnlyGuards, plus one constraints line in docs/en and docs/zh OceanBase-CDC.md. Static review only; I did not run the PR.

What Problem Does This PR Solve?

  • Pain point: MySQL CDC had no first-class bounded bootstrap mode. The existing startup modes either kept streaming the binlog or needed a manual stop.
  • Fix approach: add startup.mode = "snapshot-only" for MySQL CDC (and OceanBase-CDC, which extends the MySQL factory). It reuses the existing SnapshotOnlySplitAssigner, adds option-rule guards, restore-state validation, a reader fail-fast guard, tests and en/zh docs.
  • One sentence: a MySQL CDC mode that finishes after the snapshot phase instead of drifting into streaming.

1. Code Change Review

1.1 Core Logic Analysis

job config
  -> MySqlIncrementalSourceFactory.getOptionRuleBuilder()                         (declarative validation)
       conditional(startup.mode in [initial, snapshot-only]) -> exactly_once
       conditional(startup.mode == snapshot-only):
            MySqlSnapshotOnlyGuards.stopModeGuard          (stop.mode must be never)
            MySqlSnapshotOnlyGuards.startupTimestampGuard  (startup.timestamp not allowed)
       startup.specific-offset.* -> existing MySqlSpecificOffsetGuards (reject unless mode == specific)
  -> IncrementalSource.getBoundedness(): BOUNDED when startup.mode == SNAPSHOT_ONLY
  -> IncrementalSource.createEnumerator(): SnapshotOnlySplitAssigner (no incremental split)
  -> IncrementalSource.restoreEnumerator(): validateRestoredState(startupMode, state)
       snapshot-only <-> SnapshotPhaseState only, otherwise IllegalStateException
       SnapshotPhaseState -> getCheckpointCapturedTables(state)  (no catalog re-discovery)
  -> IncrementalSourceReader.addSplits(): incremental split under snapshot-only -> IllegalStateException

The normal user path (config validation, then enumerator creation) goes through the new logic, so this is a main-path feature rather than a recovery-only fix. I re-verified that a plain snapshot-only config passes the guards (absent stop.mode / startup.timestamp evaluate to true), that the declarative rule now carries the combination checks that @nzw921rx asked for (the earlier imperative validator in the base IncrementalSource is gone), and that OceanBaseIncrementalSourceFactoryTest#testOptionRuleInheritsSnapshotOnlyGuards exercises the inherited rule end to end (stop.mode = latest is rejected with a message containing 'stop.mode = latest', which matches the format in MySqlSnapshotOnlyGuards.StopModeGuard).

Runtime-path notes (engine/recovery relevant):

  • SnapshotOnlySplitAssigner delegates to SnapshotSplitAssigner and only forces isRemainingTablesCheckpointed = true when restoring. Only legacy pre-flag hybrid checkpoints carry false, and those are rejected earlier by validateRestoredState for snapshot-only, so there is no state-format change.
  • Split completion alone ends the job (no incremental split is ever created), so parallel batch jobs finish without needing a checkpoint, which is what the IT covers with checkpointing disabled.

1.2 Compatibility Impact

Fully compatible for existing modes. The new enum value is additive, no option was renamed or removed, no persisted state format changed (SnapshotPhaseState is reused as is), and restoreEnumerator only behaves differently for SnapshotPhaseState checkpoints. Two points I checked and consider acceptable: the Hybrid restore now builds checkpointCapturedTables via the shared helper (same result under the SnapshotSplitAssigner invariants), and PostgreSQL/OpenGauss snapshot-only (already on dev) now restores from the checkpointed table set, which the PR description discloses. I did not run an origin/2.6-release to current-dev upgrade; that conclusion is an inference from the diff (additive option value, no serialization change).

1.3 Performance / Side-Effect Analysis

Validation-time and restore-time only, no hot-path change. The snapshot and backfill phases reuse the existing reader, so per-split memory and CPU are unchanged.

1.4 Error Handling and Logging

Guards throw OptionValidationException with the option key and the reason; restore mismatches throw IllegalStateException with an actionable message. No sensitive data is logged.

No new source-level issues. Carried-over items from my previous round are resolved:

  • OceanBase-CDC inheriting snapshot-only (my previous Issue 1): now covered by the factory test and by a docs line in both languages. The anchors the cross-reference anchors from both OceanBase-CDC.md pages resolve to real MySQL-CDC headings at this head (the English one is #snapshot-only-bootstrap-one-time-backfill).
  • The new unit tests have not run in CI yet (my previous Issue 2): still open, but it is a CI-environment matter, see below.

2. Code Quality Assessment

2.1 Coding Standards

The new MySqlSnapshotOnlyGuards class has a class-level Javadoc and follows the MySqlSpecificOffsetGuards pattern. Comments explain why the guards do not check the startup mode themselves. No wildcard imports and no unrelated refactors.

2.2 Test Coverage and Test Stability

Test-to-risk mapping (each test goes red if the corresponding production line is removed or inverted): MySqlIncrementalSourceFactoryTest guard cases (stop.mode, startup.timestamp, every specific-offset option, plus a positive snapshot-only config and the unchanged timestamp-mode rule), OceanBaseIncrementalSourceFactoryTest#testOptionRuleInheritsSnapshotOnlyGuards (inherited rule dropped or bypassed in the subclass), IncrementalSourceTest (restore-state mismatch and authoritative table set), SnapshotOnlySplitAssignerTest, IncrementalSourceReaderSnapshotOnlyTest (incremental split rejected), and MysqlCDCSnapshotOnlyIT (parallelism 2, bounded Awaitility wait, deletion in an already completed split while later splits are pending). DebeziumJsonFormatTest is back to its dev content and the moved assertions are equal or stronger, so I see no weakened historical test.

Stability rating for the new UT/E2E: Stable (no Thread.sleep, driver resolved through DependencyJar, no network download from inside containers).

2.3 Documentation Updates

docs/en and docs/zh for MySQL-CDC and OceanBase-CDC are updated in lockstep and match the code (option restrictions, restore constraint, server-id range note).

3. Architectural Soundness

Connector-specific combination rules now live in the MySQL factory instead of the shared base class, which addresses the maintainers' request, and the base class carries only restore and reader safety nets that apply to every snapshot-only connector. No new dependency, no public API or SPI break. Best-fix-location check: the declarative option rule is the right place for the config combinations; the restore and reader guards belong in the base layer because they protect state shared with PostgreSQL/OpenGauss.

4. Issue Summary

# Issue Location Severity
- No source-level issue found at this head - -

CI-only item (not a code issue): see section 5.

5. Merge Recommendation

Conclusion: Ready to merge after fixes

Blockers: none on the source side. The only open gate is CI:

  • The apache-side Build is red for this head. In the fork run (fatmanverse/seatunnel run 39531433619) the four unit-test lanes (JDK 11/17, ubuntu/windows) fail in seatunnel-transforms-v2: LLMBooleanOutputTest.readsLegacyFactoryWrapperWithValidationDisabled throws InvalidClassException (serialVersionUID mismatch on AbstractMultiCatalogTransform). This PR does not touch seatunnel-transforms-v2; the failure is tracked on dev as issue #12929 (still open when I looked). Because Maven stops at that module, the CDC base and MySQL unit tests were not executed by CI on this head.
  • The branch is 1 commit behind dev (diverged, 16 ahead / 1 behind) and GitHub reports mergeable_state: blocked, which is the review and required-check gate rather than a content conflict.

Recommended next step (non-blocking for the code): once the dev fix for #12929 lands, sync and re-run the failed jobs, then confirm that the CDC unit tests and mysql-cdc-connector-it pass on the new run. Thank you also for posting the local JDK 17 results for connector-cdc-base / -mysql / -postgres / -opengauss; they are useful supporting evidence, but CI on the final head remains the gate.

Overall: a clean, well-tested feature with restore safety handled in the right layers. Thanks again for the patience through the review rounds.

@SEZ9

SEZ9 commented Oct 22, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the two follow-up commits (d28296a1 and 39c796a2). Looking at 39c796a2ee6f, the delta since d28296a1 is the new OceanBaseIncrementalSourceFactoryTest#testOptionRuleInheritsSnapshotOnlyGuards plus a constraints line in the en/zh OceanBase-CDC.md. That is a nice addition for OceanBase, but I could not find changes for the MySQL-CDC doc items from my previous round, so here is where I think each one stands:

  • F1 (server-id/parallelism mismatch under snapshot-only + exactly_once) – still only surfaces at runtime via MySQL. Could you either add a fail-fast configuration check, or let me know if you prefer to keep this as a documented limitation? Either is fine, but I would like it to be an explicit decision.
  • F2 (consistency semantics with exactly_once = false under concurrent writes) – not yet documented. A short paragraph on what users can and cannot expect from the snapshot in that mode would be enough.
  • F3 (constraints only in the startup.mode cell and prose) – the stop.mode, startup.specific-offset.* and startup.timestamp rows in docs/en/connectors/source/MySQL-CDC.md still do not carry the snapshot-only restriction themselves. A brief note on each affected row, similar to the OceanBase constraints line, would close this.
  • F4 (ZH parity) – please mirror the EN exactly_once row and FAQ updates in docs/zh/connectors/source/MySQL-CDC.md.
  • F5 (literal credentials in the new example) – please replace the hardcoded password with a placeholder in the snapshot-only example.
  • F6 ("rejected by MySQL" wording) – please reword so it reflects what actually happens with a shared server-id rather than implying MySQL rejects the connection outright.
  • F7 (example sets a server-id range without exactly_once) – please either enable exactly_once in the example or adjust the preceding paragraph so the example matches its stated condition.
  • F8 (reworded FAQ answer for initial mode) – please restore the precise description of the binlog resume position for initial mode; the snapshot-only addition should not loosen the existing text.

If any of these were addressed in a way I missed, just point me to the hunk and I will re-check. Once the doc items above are in, I am happy to take another pass.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks @SEZ9. I checked the MySQL documentation itself on 39c796a2ee6f, not just the last commit's OceanBase delta. The requested MySQL material is already present earlier in this head:

  • F1/F6: EN MySQL-CDC.md:549 explicitly documents reader-start-time range validation, start + subtask index, and MySQL terminating an earlier connection on duplicate server id. This is a stated limitation, not a claim that submission validates parallelism.
  • F2: lines 544-547 distinguish plain per-split reads without backfill from exactly-once low/high-watermark backfill, including the absence of a global point-in-time guarantee.
  • F3: the file/position/GTID/timestamp option rows at 197-202 explicitly mention snapshot-only rejection, and the stop.mode row names the never-only constraint. The skip-events/skip-rows rows remain scoped to specific mode; any further wording there would be documentation polish, not evidence those offset modes are supported in snapshot-only.
  • F4: the ZH exactly_once row is at 219; the bounded-snapshot consistency/range discussion is at 532-541, with the initial-mode FAQ at 691.
  • F5/F7: the snapshot-only example uses ${mysql_password} at 563, enables exactly_once at 566 and gives the parallelism-2 range at 567. Older unrelated examples elsewhere still use their example credentials.
  • F8: the initial-mode FAQ at 702 explicitly retains the resume position recorded at snapshot start, then separately states that snapshot-only never enters continuous streaming.

I would not ask the author to repeat these edits. This is a targeted answer on the existing head; no new full review or local execution was performed. My source conclusion remains clear, while your final direct check is still yours. Build is failed on the unrelated LLM archived-fixture path; #12938 remains open and current dev has not incorporated it. Once it lands, sync and rerun failed jobs so CDC unit tests actually execute. Final required CI and a write-capable maintainer approval remain necessary.

Current status evidence: head 39c796a2ee6f53ecb0740a4c62aff71e15c44db8, base dev, compare diverged (ahead 16, behind 10), mergeable state blocked.

CI references: current Build check.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for your patience. The upstream status has changed since my preceding note: #12938 merged into dev at 2026-10-22 10:26 UTC (merge cc54bb433357b4cb45db9cd5d0743589c3111b79). I checked that current dev contains the merge and that its diff restores the historical AbstractMultiCatalogTransform serialization UID and makes the construction-only config transient. My earlier instruction to wait for that fix is now superseded.

The archived-wrapper LLMBooleanOutputTest.readsLegacyFactoryWrapperWithValidationDisabled / InvalidClassException is the shared unit-test failure identified in the preceding review (affected job). This head is still 39c796a2ee6f53ecb0740a4c62aff71e15c44db8; the current dev comparison is diverged, ahead 16 / behind 12. Please sync with the latest dev and rerun the affected unit checks first, plus any stage whose log showed the same archived-wrapper error. Keep unrelated transform-serialization patches out of this PR. This is a targeted remedy for that known upstream failure, not a claim that syncing fixes every failed stage.

The required aggregate Build still needs a successful result on the final head. My previous source-level conclusion is unchanged. Required CI and the final write-capable maintainer review remain gates. This is a CI-status follow-up only, with no new source findings or fresh full-review claim.

@fatmanverse

Copy link
Copy Markdown
Contributor Author

Synced with the latest dev (eceeb0a) in a merge commit that only resolves conflicts: MySQL-CDC.md en/zh (kept this PR's snapshot-only rows and dev's new skip-events/skip-rows rows) and the IncrementalSourceReaderTest imports. IncrementalSourceReader merged cleanly: dev's ack handling (#12163) and this PR's snapshot-only check are in different methods. The earlier shared unit-test failures are fixed on dev (#12874 and #12929, both by #12938). On JDK 17, ./mvnw -pl connector-cdc-base,connector-cdc-mysql,connector-cdc-oceanbase test passes: base 130, mysql 59, oceanbase 10 tests, 0 failures, IncrementalSourceReaderTest 19/19.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thank you @fatmanverse for syncing with the latest dev. The head moved from 39c796a2ee6f (my last review) to 3dc9e379242e, which is a single merge commit. As always I re-read the complete current diff against dev (16 files, +1162/-48), not only the delta, and re-traced the call chain. Static review only; I did not run the PR.

What Problem Does This PR Solve?

  • Pain point: MySQL CDC had no first-class bounded bootstrap mode. The existing startup modes either kept streaming the binlog or needed a manual stop.
  • Fix approach: add startup.mode = "snapshot-only" for MySQL CDC (and OceanBase-CDC, which extends the MySQL factory). It reuses the existing SnapshotOnlySplitAssigner, adds option-rule guards, restore-state validation, a reader fail-fast guard, tests and en/zh docs.
  • One sentence: a MySQL CDC mode that finishes after the snapshot phase instead of drifting into streaming.

1. Code Change Review

1.1 Core Logic Analysis

What the merge changed: the PR now sits on dev at eceeb0abad2e. Conflicts were only in MySQL-CDC.md (en/zh) and the IncrementalSourceReaderTest imports. I verified that dev's newer rows (startup.specific-offset.skip-events / skip-rows, still documented as specific-only) and the restored-incremental-split pruning in IncrementalSourceReader#addSplits (from #12163) are intact, and that this PR's snapshot-only check sits in the incremental-split branch of the same loop, so the two do not interact.

job config
  -> MySqlIncrementalSourceFactory.getOptionRuleBuilder()               declarative validation
       conditional(startup.mode in [initial, snapshot-only]) -> exactly_once
       conditional(startup.mode == snapshot-only):
            MySqlSnapshotOnlyGuards.stopModeGuard          (stop.mode must be never)
            MySqlSnapshotOnlyGuards.startupTimestampGuard  (startup.timestamp not allowed)
       startup.specific-offset.* -> existing MySqlSpecificOffsetGuards
  -> IncrementalSource.getBoundedness(): BOUNDED for SNAPSHOT_ONLY
  -> IncrementalSource.createEnumerator(): SnapshotOnlySplitAssigner (no incremental split ever created)
  -> IncrementalSource.restoreEnumerator()  [Hazelcast operation thread]
       validateRestoredState(startupMode, state): snapshot-only <-> SnapshotPhaseState only, else IllegalStateException
       SnapshotPhaseState   -> getCheckpointCapturedTables(state)   (no catalog re-discovery, table set stays authoritative)
       HybridPendingSplitsState / IncrementalPhaseState -> discovery as on dev
  -> SnapshotOnlySplitAssigner.addSplits(): non-snapshot split -> IllegalStateException
  -> IncrementalSourceReader.addSplits(): incremental split under SNAPSHOT_ONLY -> IllegalStateException

The normal user path (option validation, then enumerator creation) hits the changed code, so this is a main-path feature and not a recovery-only fix. Findings that matter:

  • A plain snapshot-only config passes the guards: an absent stop.mode / startup.timestamp evaluates to true, and the exactly_once conditional now covers [initial, snapshot-only].
  • Forcing isRemainingTablesCheckpointed = true in SnapshotOnlySplitAssigner is safe: only legacy pre-flag hybrid checkpoints carry false, and those are rejected by validateRestoredState in snapshot-only mode.
  • The Hybrid restore path now builds checkpointCapturedTables through the shared helper, which also unions tables of remaining/assigned splits. Under the SnapshotSplitAssigner invariants that equals the old result for initial restores.
  • Compile hygiene after the merge: IncrementalSource no longer imports Stream and no longer uses it; Collectors, SnapshotSplit and StartupMode are still imported and used. The reader's new sourceConfig.getStartupConfig() call is only reached for incremental splits, and the existing reader tests that exercise that branch now stub StartupConfig (incrementalSourceConfig()), so the mocks no longer return null.

1.2 Compatibility Impact

Fully compatible. The new enum value is additive, no option was renamed or removed, no persisted state format changed (SnapshotPhaseState is reused as is), and restoreEnumerator only behaves differently for SnapshotPhaseState checkpoints. PostgreSQL/OpenGauss snapshot-only (already on dev) now also restores from the checkpointed table set; this is intended and disclosed in the PR. I did not run an origin/2.6-release to current-dev upgrade; this is an inference from the diff (additive option value, no serialization change).

1.3 Performance / Side-Effect Analysis

Validation-time and restore-time only. No hot-path change; the snapshot and backfill phases reuse the existing reader, so per-split memory and CPU are unchanged. No new threads, queues or retries.

1.4 Error Handling and Logging

Guards throw OptionValidationException with the option key and reason; restore mismatches throw IllegalStateException with an actionable message. No sensitive data in messages.

Issues found on this head: none. All earlier blockers (authoritative table set on restore, restore-state validation, reader guard, driver resolution in the E2E, option-rule migration, OceanBase coverage) remain verified fixed.

2. Code Quality Assessment

2.1 Coding Standards

The new MySqlSnapshotOnlyGuards class has a class-level Javadoc explaining why the guards do not check the startup mode themselves; comments on the fail-fast restore and reader paths explain why. ASF license headers are present on every new file; no wildcard imports.

2.2 Test Coverage and Test Stability

Test-to-risk mapping (each goes red if the production line is removed or inverted): MySqlIncrementalSourceFactoryTest guard cases (stop.mode, startup.timestamp, every specific-offset option, positive snapshot-only config, unchanged timestamp rule), OceanBaseIncrementalSourceFactoryTest#testOptionRuleInheritsSnapshotOnlyGuards (inherited rule dropped), IncrementalSourceTest (restore-state mismatch, authoritative table set), SnapshotOnlySplitAssignerTest, IncrementalSourceReaderSnapshotOnlyTest (incremental split rejected), MysqlCDCSnapshotOnlyIT (BATCH job must terminate; parallelism 2; a delete in a completed split while later splits are pending must not reach the sink). The existing IncrementalSourceReaderTest changes only add a StartupConfig stub and do not weaken any assertion; DebeziumJsonFormatTest is not touched.

Stability rating: Stable. The IT uses a bounded Awaitility wait (120 s) and no Thread.sleep, resolves the MySQL driver through DependencyJar (no download inside containers), and uses 103 snapshot splits (snapshot.split.size = 1) at parallelism 2 so the "still running" window is wide. The author reports connector-cdc-base 130, connector-cdc-mysql 59 and connector-cdc-oceanbase 10 unit tests passing on JDK 17 for this merge; that is useful supporting evidence, but CI on the final head remains the gate.

2.3 Documentation Updates

docs/en and docs/zh for MySQL-CDC and OceanBase-CDC are updated in lockstep and match the code: per-row restrictions for startup.specific-offset.*, startup.timestamp and stop.mode, the consistency discussion for exactly_once true/false, the server-id range note, a placeholder password in the example and the precise initial FAQ wording.

3. Architectural Soundness

3.1 Elegance

Precise fix. Connector-specific combination rules live in the MySQL factory, and the base class only carries restore and reader safety nets that protect state shared with PostgreSQL/OpenGauss. Best-fix-location check: the declarative option rule is the right place for config combinations; the restore and reader guards belong in the base layer.

3.2 Maintainability

One mode, one assigner, one validation location; no new dependency and no public API or SPI break.

3.3 Extensibility

Other JDBC CDC connectors can adopt snapshot-only by wiring their own guards without touching the base.

3.4 Historical-Version Compatibility

No persisted format change; existing jobs and checkpoints in other modes behave as before.

4. Issue Summary

No. Issue Location Severity
- No source-level issue found at this head - -

Community context: @SEZ9 approved earlier heads and left doc items F1-F8, which were answered with line references on 39c796a2ee6f and are unchanged by this merge; I have no new point to add to them. @nzw921rx's CHANGES_REQUESTED on 991e997e72cb (authoritative table set, driver download in the E2E) is stale: both items are fixed in code, and the later optionRule suggestion landed in d28296a1. It would help if @nzw921rx could re-check and update that review, because the formal state still reads CHANGES_REQUESTED.

5. Merge Recommendation

Conclusion: Ready to merge after fixes

Blockers (non-CI): none. The only open gates are CI and approvals:

Overall assessment: a clean, well-tested feature with restore safety handled in the right layers; the merge with dev is coherent. Thanks again for the patience through the review rounds. Alternative considered: a base-class runtime check for programmatic construction paths, which is unnecessary because the mode is only reachable through the connector factories.

@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

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

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks @nzw921rx for clarifying the after-3.1.0 schedule. I will respect that timing. The source conclusion for this unchanged head remains clear, and the old pending-CI wording is superseded by the latest check snapshot below. Any historical change-request entry still needs its owning reviewer or a write-capable maintainer to reconcile it; this reply does not dismiss another reviewer's decision.

Gate snapshot (2026-10-28T15:45:13+00:00), head 3dc9e379242e6c48a050e979c4fe23a455573e81: Build is SUCCESS.

CI was previously the only remaining technical gate in my conclusion; CI is now passing, so that CI objection is withdrawn and my technical conclusion is clear to proceed. Daniel currently has READ permission. I have not changed the effective GitHub review state to APPROVED; a write-capable maintainer must perform the final approve/dismiss action required by branch protection.

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

My source blocker is cleared, but an older CHANGES_REQUESTED opinion may remain in the review summary after a COMMENT-only technical conclusion. With Daniel currently READ-only, a write-capable maintainer must separately reconcile the effective approval/dismissal gate; this clarification does not claim that action was performed.

… that are no longer configured

The snapshot-only restore keeps the checkpointed table set. A table that
still had unread snapshot data but was removed from table-names, or
dropped, was still split, while the readers no longer captured it: the
snapshot read failed with a NullPointerException on every restart from
the same checkpoint. The restore now fails with an error that names these
tables. Tables whose splits are all finished are not checked.
@fatmanverse

Copy link
Copy Markdown
Contributor Author

While re-checking this PR against the latest dev, I found one more restore edge case and fixed it in 7cffa0f.

The snapshot-only restore keeps the checkpointed table set, as requested earlier. But if a table still had unread snapshot data and was then removed from table-names (or dropped) before restoring from the savepoint, the enumerator still split it while the readers no longer captured it. Debezium's tableFor returns null for a table outside table.include.list, so MySqlSnapshotSplitReadTask failed with a NullPointerException, again on every restart from the same checkpoint.

IncrementalSource#restoreEnumerator now rejects such a restore up front, with an error naming the tables. It checks only tables that still have unread data: tables that are not split yet, remaining splits, and assigned splits without a completion watermark. A table whose splits have all finished is not read again, so removing or dropping it does not block the restore. Matching against the configured tables ignores case and any catalog/schema the checkpointed id lacks, so a table is only rejected when it is certainly not configured. The checkpointed table set itself is unchanged, and so is discovery.

New cases in IncrementalSourceTest: an unread table that is no longer configured, one configured only in another schema, a finished table that is no longer configured, and MySQL/PostgreSQL table id shapes. The two rejection cases fail without the fix. I also added the restore behavior to the snapshot-only sections of the MySQL-CDC and PostgreSQL-CDC docs, and a short note to the OpenGauss-CDC docs (en/zh). The PR description is updated for the current scope as well.

Verified on JDK 17 with this branch merged into the latest dev (f3e1c2e): connector-cdc-base 141, connector-cdc-mysql 59, connector-cdc-oceanbase 10, connector-cdc-postgres 93 and connector-cdc-opengauss 7 unit tests, 0 failures; MysqlCDCSnapshotOnlyIT 5/5; spotless:check passes.

I know this PR is scheduled for after 3.1.0; this just keeps it ready for then.

@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 update! I re-read the complete current diff and the shared CDC restore path. The new missing-table guard handles the ordinary removed-table case, and the earlier option-rule, authoritative-state and reader safeguards remain in place. I found one remaining identity edge in that new guard. Sorry for overlooking the timing assumption in the existing E2E test in my previous review; Issue 2 below corrects that earlier stability assessment and is not a new regression.

What this PR solves

  • User pain: a MySQL bootstrap otherwise continues consuming binlog events instead of finishing.
  • Fix: expose snapshot-only, reuse snapshot splitting and bounded backfill, and reject incompatible configuration or restored streaming state.
  • In one sentence: copy the selected tables once and finish. For example, a bootstrap can copy 103 initial rows without subsequently propagating a delete from an already completed range.

1. Code Change Review

1.1 Core Logic Analysis

Reviewed all 22 changed files, including both language documentation sets and every changed UT/E2E test. The independent local review branch matches 7cffa0f133c78c4680d6ad2cecadebf76cfdf26b; Git produced the complete diff and whitespace diagnostics. This was static source analysis only; I ran no local build, test, container or job.

Before, the MySQL option enum did not expose snapshot-only and the rule only associated exactly_once with INITIAL. After:

.or(Conditions.equal(STARTUP_MODE, StartupMode.SNAPSHOT_ONLY))

The new restore check ultimately uses:

tablePath.getTableName().equalsIgnoreCase(tableId.table())

The relevant execution chain is:

FactoryUtil validation -> MySQL optionRule / MySqlSnapshotOnlyGuards
 -> IncrementalSource.createEnumerator -> discover tables / dialect case sensitivity
 -> SnapshotOnlySplitAssigner -> SnapshotSplitAssigner -> snapshot readers
 -> optional existing per-split bounded binlog backfill -> completed watermarks
 -> snapshot assigner completion -> bounded source completion; no stream split
checkpoint restore -> validateRestoredState -> checkpoint captured-table union
 -> checkUnfinishedTablesAreConfigured -> restored SnapshotOnlySplitAssigner
 -> preserve finished offsets / remaining ranges; do not rediscover extra tables
restored reader splits -> reject IncrementalSplit in snapshot-only mode

Key findings:

  • Normal MySQL factory construction reaches the declarative guards; OceanBase inherits them. PostgreSQL/OpenGauss share the base restore changes.
  • Completed-table removal is deliberately allowed; remaining tables, remaining splits and assigned splits without completed offsets remain authoritative.
  • Marking legacy remaining-table state checkpointed prevents discovery from silently expanding the bounded restore set; state fields and offsets are retained.
  • Rejecting cross-mode restore and incremental reader splits protects boundedness, but current case folding does not honor the dialect's table identity contract (Issue 1).

This is a focused feature and recovery safeguard rather than a replacement for the existing snapshot/backfill consistency algorithm. exactly_once remains per-split consistency, not a global point-in-time image.

1.2 Compatibility Impact

Additive MySQL mode with no renamed option, changed default, wire format or serialized state layout. Existing initial/streaming startup behavior remains. Restore validation intentionally rejects unsupported mode/table changes and affects the shared PostgreSQL/OpenGauss path; the documentation discloses this restriction. Issue 1 must respect case-sensitive identities when applying that restriction.

1.3 Performance / Side Effects

The new validation scans checkpoint tables against configured tables at restore, not per emitted row. No new unbounded queue, worker thread, network call, locking or retry loop is introduced in production. Existing snapshot readers retain resource ownership and backfill behavior. The E2E common-pool future has no explicit cancellation on a failed intermediate assertion (Issue 2).

1.4 Error Handling and Logging

Configuration failures identify the conflicting option; restored mode/split errors identify the unsupported state. No new credential logging was found. Formal issues, ordered by impact:

Issue 1: Honor case-sensitive checkpoint table identities in the new restore guard.

  • Location: seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/IncrementalSource.java:494 (also qualifier matching at 509).
  • Context/problem: snapshot restore checks unread checkpoint tables against current catalog tables using unconditional equalsIgnoreCase. PostgreSQL's PostgresDialect.isDataCollectionIdCaseSensitive explicitly returns true, and SnapshotPhaseState retains this flag. An unread checkpoint for db.public.Orders and a current configuration containing only distinct db.public.orders therefore passes this guard. The restored checkpoint still schedules the original identity; lower-case metadata does not make that original quoted table configured. This defeats the new fail-fast guarantee on an actual shared-connector restore path.
  • Risk: a case-sensitive table replacement can escape the intended actionable validation and repeat the same downstream missing-table/conversion failure on restart. This is conditional on a case-sensitive identity change; it is not evidence of a data-loss incident.
  • Best fix: use the dialect/checkpoint case-sensitivity contract for the table and qualifier comparisons, with connector-aware normalization for catalog/schema representation. Preserve the intentionally tolerant comparison for case-insensitive databases. Document that choice and add paired case-sensitive/case-insensitive restore tests, including two distinct quoted PostgreSQL names.
  • Severity: Medium; blocking the correctness of the new restore safeguard.
  • Already raised by others: No. Related to @nzw921rx's authoritative checkpoint-table concern, but this is the newly added matching predicate's distinct edge.

Issue 2: Make the E2E mutation window deterministic and clean up the asynchronous job on failure.

  • Location: seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mysql/MysqlCDCSnapshotOnlyIT.java:126.
  • Context/problem: Awaitility requires observing the first three sink rows while the job is unfinished and fewer than all rows are visible. 103 splits widen that window but do not guarantee a poll observes it: a fast run or paused test thread can miss it completely. If this assertion times out, execution never reaches the bounded jobFuture.get, and the background job is not explicitly cancelled or stopped.
  • Risk: environment-dependent CI failure and background execution surviving the failed assertion. This corrects my previous overly strong Stable rating for the unchanged test.
  • Best fix: establish an explicit observable barrier before releasing remaining splits, and use a finally block to stop/await the submitted job on every exit path. At minimum avoid using a briefly observable intermediate row count as the only mutation synchronization mechanism.
  • Severity: Medium, nonblocking test-stability improvement.
  • Already raised by others: Related to @nzw921rx's request for a genuine concurrent mutation test; that substantive scenario is now covered, while its scheduling guarantee remains probabilistic.

2. Code Quality Assessment

2.1 Coding Standards

The option guards are in the requested declarative factory location, the existing hybrid constructors remain, and new files have ASF headers. The state/reader guards explain their intent. Please include the case-sensitive identity contract alongside Issue 1's fix rather than leaving unconditional folding implicit.

2.2 Test Coverage and Test Stability

Factory tests cover default/never stop mode, prohibited offsets/timestamp and inherited OceanBase behavior. State tests cover removed unread/finished tables, schemas, checkpoint authority and cross-mode restore; reader/assigner tests reject incremental splits. The IT checks bounded completion with a concurrent delete and uses the shared dependency resolver. Missing coverage: distinct case-sensitive identities. Stability rating: At risk, specifically the intermediate-window assertion at MysqlCDCSnapshotOnlyIT.java:126 (Issue 2). The UT additions themselves are synchronous and have no new sleep/port/shared-clock dependency.

2.3 Documentation Updates

Both languages consistently describe mode restrictions, per-split consistency, server-id ranges, checkpoint authority and unsupported restore changes. PostgreSQL/OpenGauss documentation acknowledges the shared restore behavior. Examples use bounded batch mode and a range compatible with parallelism two.

3. Architectural Soundness

3.1 Elegance

A focused mode addition using the existing assigner and backfill implementation; keeping MySQL configuration guards out of the shared base is appropriate.

3.2 Maintainability

Checkpoint authority is explicit. Table matching should reuse the established identity policy rather than defining a competing one.

3.3 Extensibility

The shared recovery safeguards benefit other snapshot-only connectors once connector identity differences are respected.

3.4 Historical-Version Compatibility

No state-format migration is needed. Unsupported mode changes require a new job; case-sensitive restores need Issue 1 resolved.

4. Issue Summary

No. Issue Location Severity
1 Case folding accepts a different case-sensitive table IncrementalSource.java:494 Medium, blocking
2 Transient E2E mutation window / failure cleanup MysqlCDCSnapshotOnlyIT.java:126 Medium, nonblocking

+1 to @nzw921rx's checkpoint-authority and factory-validation direction: the earlier concerns are materially addressed. @SEZ9's earlier approvals and documentation feedback are useful context, but predate this new predicate. I also acknowledge the maintainer's stated plan to schedule this after 3.1.0; this review does not override that release decision or dismiss another review.

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers: Issue 1, then the repository's current CI and write-capable maintainer/release gates.
  2. Suggested improvements, nonblocking: Issue 2; it affects stability of the regression test rather than demonstrating a production streaming regression.

The earlier CI fact has changed: the exact-head fork Build is now completed successfully, with no failed jobs in the retrieved job pages. Apache has no adopted Build check on this head in the current snapshot, so fork success is not a fulfilled Apache required-check gate. This is not evidence that the contributor disabled Actions, and behind/diverged alone does not justify another sync request.

Overall, the bounded feature and earlier repairs remain coherent. The best alternative is to reuse the existing dialect/checkpoint identity policy, not add connector-specific case assumptions. My account has READ permission; a technical comment cannot dismiss historical requested changes or satisfy a write-reviewer approval requirement. Thank you for continuing to refine the recovery behavior.

Snapshot 2026-11-01T14:05:33.794539+00:00: head 7cffa0f133c78c4680d6ad2cecadebf76cfdf26b, base dev; compare diverged, ahead 18 / behind 66; merge blocked / BLOCKED, review decision CHANGES_REQUESTED. Drift is recorded separately; it does not itself request synchronization.

chen added 2 commits November 3, 2026 09:44
…-only restore check

The restore check compared table names ignoring case and matched a
qualifier against either the database or the schema of the configured
table. A checkpointed PostgreSQL table public."Orders" therefore passed
when only public.orders was configured, although they are different
tables. The check now requires the TableId that the dialects build from
the configured tables, the same key their readers look tables up by, so
it no longer folds case or skips qualifiers.
When the wait for the runtime mutation window timed out, the test left
before waiting for the submitted job, which kept running against the
shared MySQL container. On Zeta the job is now submitted with a job id
and cancelled in a finally block if it is still running; a failed cancel
is only logged so it does not hide the failed assertion. Flink cannot
submit or cancel by id, and its container is torn down after the test.
@fatmanverse

Copy link
Copy Markdown
Contributor Author

Thanks @DanielLeens. I pushed cece2bf and 6690968 for both issues.

Issue 1 (case-sensitive identities). You were right: db.public.Orders in the checkpoint passed when only db.public.orders was configured. I did not switch the comparison on SnapshotPhaseState.isTableIdCaseSensitive, because that flag does not mean the same thing in every dialect. PostgresDialect returns true for case-sensitive, while MySqlConnectionUtils.isTableIdCaseSensitive returns !"0".equals(lower_case_table_names), which is passed to Debezium's MySqlDatabaseSchema(..., boolean tableIdCaseInsensitive) and so means the opposite.

The check now uses the identity the readers already use. A table counts as configured only when its TableId is a key of CatalogTableUtils.convertTables(catalogTables), which is the table map the MySQL and PostgreSQL dialects build and look tables up in by exact TableId (MySqlDialect / MySqlSchema tableMap.get, PostgresSchema tableMap.containsKey(idWithCatalog); TableId.equals is an exact string compare). The discovered ids have the same shape as those keys: (db, null, table) for MySQL and OceanBase, (db, schema, table) for PostgreSQL and OpenGauss. Because of this, the exact match only rejects checkpoints whose tables the readers could not resolve anyway: MySQL fails when the source is built (NPE in MySqlSchema), and PostgreSQL fails with Can't obtain schema from PostgresSchema. It does not reject a restore that would have worked, including MySQL with lower_case_table_names 1 or 2, where a mismatched name never produces a checkpoint.

Tests: testSnapshotOnlyRestoreRejectsTableThatDiffersInCase checks that db.public.Orders vs db.public.orders, db.b vs DB.B, and db.public.c vs db.c are all rejected and named in the error. testSnapshotOnlyRestoreAcceptsConfiguredTables now expects exact MySQL and PostgreSQL ids, including mixed-case db.public.Orders. The MySQL-CDC and PostgreSQL-CDC docs (en/zh) now say the names must match exactly, including letter case.

Issue 2 (E2E window and cleanup). MysqlCDCSnapshotOnlyIT now stops the job on every exit path. On Zeta it submits with a JobIdGenerator id and, in a finally, cancels the job if it is still running. A failed cancel is only logged, so it does not hide the assertion that failed. Only the Zeta container implements executeJob(conf, jobId) and cancelJob, so on Flink the job is submitted as before; that container is not shared and is torn down after the test (TestCaseInvocationContextProvider AfterTestExecutionCallback), which stops the job. I kept the test enabled on Flink because it is the only E2E that checks that a MySQL snapshot-only job ends by itself there. I did not add a split-level barrier: it would need a test-only hook in the source. The window is still probabilistic but wide (103 splits of one row, batch_size = 1), and a missed window now fails cleanly instead of leaving a job running.

Verified on JDK 17 (Zeta and Flink): on the previous head, the new test fails because only db.public.c is reported (the case-folded names passed). On this head, IncrementalSourceTest passes, the cdc-base/mysql/oceanbase/postgres/opengauss UTs pass (142/59/10/93/7, 0 failures), and MysqlCDCSnapshotOnlyIT passes 5/5 with both commits.

@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 @fatmanverse for the quick and careful follow-up, and for explaining why SnapshotPhaseState.isTableIdCaseSensitive could not be reused (MySQL and PostgreSQL give that flag opposite meanings). I re-reviewed the complete current head 6690968c78d0c8801b419889db06fb4274fbdc69, covering all 22 changed files and the two new commits since my last review (cece2bf8, 6690968c). Both items from my previous review are resolved. I found no new blocking issue. Only two small non-blocking suggestions remain, and CI on this head is still running.

What Problem Does This PR Solve?

  • User pain: a MySQL CDC bootstrap job keeps consuming binlog after the initial copy, so it never finishes as a bounded job.
  • Fix: add startup.mode = "snapshot-only" for MySQL (OceanBase inherits it). The mode reuses the existing snapshot splitting and per-split bounded backfill, then ends without a stream split. It also rejects incompatible options and restores that would break the bounded contract.
  • In one sentence: copy the selected tables once and stop. Restores are checked against the checkpointed table set, so a restore cannot silently read more tables or a different set.

1. Code Change Review

1.1 Core Logic Analysis

The new commits change only the restore-time table check. The old predicate folded case and matched qualifiers loosely:

tablePath.getTableName().equalsIgnoreCase(tableId.table())
        && qualifierIsConfigured(tableId.catalog(), tablePath) ...

It now uses the same exact identity the readers use:

Set<TableId> configuredTables = CatalogTableUtils.convertTables(catalogTables).keySet();
... .filter(tableId -> !configuredTables.contains(tableId))

(IncrementalSource.java:460-478)

I traced this against the readers on the current head:

  • CatalogTableUtils.convertTables (CatalogTableUtils.java:132) builds new TableId(databaseName, schemaName, tableName). This is the same map that MySqlDialect (line 62), PostgresDialect (line 75) and the schemas look tables up in. MySqlDialect.java:130/135 uses tableMap.get(tableId) and PostgresSchema.java:73-74 uses tableMap.containsKey(idWithCatalog). Both lookups are exact.
  • Discovered ids have the same shape. MySQL/OceanBase use (db, null, table) (TableDiscoveryUtils.java:73; OceanBaseIncrementalSource extends MySqlIncrementalSource). PostgreSQL/OpenGauss use (catalog, schema, table) (postgres TableDiscoveryUtils.java:106).
  • Only MySQL, OceanBase, PostgreSQL and OpenGauss accept SNAPSHOT_ONLY. Oracle and Db2, whose table maps use transformed ids (toDb2TableId, readTableIdWithRequestedCatalog), cannot reach this path. The exact match is therefore correct for every connector that can reach it.

So the guard now rejects exactly the checkpoints that the readers could not resolve anyway. It no longer lets a case-distinct PostgreSQL table such as db.public.Orders through when only db.public.orders is configured. A restore that would have worked is not rejected.

Runtime flow (unchanged except for the marked step):

FactoryUtil -> MySQL optionRule / MySqlSnapshotOnlyGuards (stop.mode, offsets, timestamp)
 -> IncrementalSource.createEnumerator -> SnapshotOnlySplitAssigner -> SnapshotSplitAssigner
 -> snapshot readers (+ optional per-split bounded backfill) -> completed watermarks
 -> assigner completes -> bounded source finishes; no IncrementalSplit is ever created
restore -> validateRestoredState (mode vs state type)
 -> getCheckpointCapturedTables (checkpoint is authoritative, no rediscovery)
 -> checkUnfinishedTablesAreConfigured  [now: exact TableId match via convertTables]
 -> SnapshotOnlySplitAssigner(markRemainingTablesCheckpointed)
reader restore -> IncrementalSourceReader rejects IncrementalSplit in snapshot-only mode

Previous review items:

Prior item Status on current head Evidence
1. Case folding accepts a different case-sensitive table (blocking) Fixed IncrementalSource.java:464-467; IncrementalSourceTest.java:188 rejects db.public.Orders vs db.public.orders, db.b vs DB.B, db.public.c vs db.c; :170 accepts the exact MySQL/PostgreSQL ids
2. E2E mutation window / failure cleanup (non-blocking) Cleanup fixed; window still probabilistic by design MysqlCDCSnapshotOnlyIT.java:162-192 wraps the wait, mutation and jobFuture.get in try/finally with cancelIfRunning (:211)

Earlier items from @nzw921rx (checkpoint-authoritative restore, declarative factory validation) and @SEZ9 (docs and coverage) remain addressed on this head. I re-checked SnapshotOnlySplitAssigner (markRemainingTablesCheckpointed, rejection in addSplits), the reader guard (IncrementalSourceReader.java:163) and MySqlSnapshotOnlyGuards.

1.2 Compatibility Impact

  • The MySQL mode is additive. There is no renamed option, no default change and no serialized state layout change. initial/latest/specific/timestamp paths are unchanged.
  • The shared restore path changes for PostgreSQL/OpenGauss snapshot-only jobs. On dev, a restore uses rediscovered tables. With this PR, the checkpoint table set is authoritative and an unread table that is not configured is rejected. The table now has to match exactly, including case. This only rejects checkpoints whose tables the readers could not look up (PostgresSchema throws Can't obtain schema). The PostgreSQL docs in both languages disclose it. I consider this compatible.
  • Restoring older checkpoints: a legacy SnapshotPhaseState without remainingTablesCheckpointed is upgraded in memory by markRemainingTablesCheckpointed. The fields and offsets are preserved.

1.3 Performance / Side Effects

The new check builds one Map from the configured catalog tables once per enumerator restore. It does not run per row or per split. There are no new threads, queues, network calls or retries in production code. Collectors.toMap would throw on duplicate keys, but the dialects already call convertTables on the same list at construction, so this adds no new failure mode.

1.4 Error Handling and Logging

The rejection message names every offending table, sorted (IncrementalSource.java:471-478). The IT logs a failed cancel at WARN without masking the original assertion. No credentials are logged. Issues:

Issue 1: The rejection message does not mention that matching is case-sensitive.

  • Location: seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/IncrementalSource.java:471-478
  • Problem: a user who only changed the case of a table name in table-names (e.g. Orders -> orders) gets "not in the current table list or no longer exist". That is accurate, but it does not point to the cause.
  • Risk: slower troubleshooting only. Behavior is correct.
  • Best improvement: optionally add "(names are compared exactly, including letter case)" to the message, mirroring the new doc sentence.
  • Severity: Low, non-blocking.
  • Raised by another reviewer: No.

Issue 2: The E2E mutation window is still timing-dependent (residual of my earlier Issue 2).

  • Location: seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mysql/MysqlCDCSnapshotOnlyIT.java:165-178
  • Problem: the test still relies on catching the job mid-snapshot. The window is wide (103 one-row splits, batch_size = 1). A missed window now fails cleanly, and the Zeta job is cancelled in finally. I agree that a split-level barrier would need a test-only hook in the source, so this is a reasonable trade-off.
  • Risk: a rare environment-dependent failure on a very fast or very slow runner. There is no longer a leaked job on Zeta. On Flink the job relies on per-test container teardown, which I confirmed is not shared.
  • Best improvement: none required now. If it ever flakes, consider pausing the sink or a JDBC lock as the barrier instead of a source hook.
  • Severity: Low, non-blocking.
  • Raised by another reviewer: Related to @nzw921rx's earlier request for a real concurrent-mutation test, which is covered.

2. Code Quality Assessment

2.1 Coding Standards

The new Javadoc on checkUnfinishedTablesAreConfigured explains why the match is exact and links CatalogTableUtils#convertTables, which is exactly the contract I asked to be documented. cancelIfRunning has a clear Javadoc. The removed isConfiguredTable/qualifierIsConfigured helpers leave no dead code, and the unused TablePath import was dropped. New files carry the ASF header.

2.2 Test Coverage and Test Stability

  • IncrementalSourceTest.testSnapshotOnlyRestoreRejectsTableThatDiffersInCase (:188) fails on the previous head, where only db.public.c was reported. This is a real regression guard for the case-folding bug. testSnapshotOnlyRestoreAcceptsConfiguredTables (:170) guards against over-rejection with exact MySQL and PostgreSQL ids, including mixed-case Orders.
  • The existing removed-table, other-schema, finished-table and cross-mode restore tests are unchanged.
  • Unit tests are synchronous with no sleeps, ports or clocks: Stable.
  • MysqlCDCSnapshotOnlyIT: Risk present (low) at :165-178 (Issue 2). Cleanup on every exit path is now in place (:190-191, :211).

2.3 Documentation Updates

The MySQL-CDC and PostgreSQL-CDC docs now state the exact, case-sensitive match. The en and zh versions are consistent (MySQL: database and table; PostgreSQL: database, schema and table). The OpenGauss and OceanBase notes from earlier commits are unchanged in these two commits.

3. Architectural Soundness

Reusing the readers' own identity (convertTables) rather than inventing a parallel matching policy is the right design and keeps one source of truth. MySQL-specific option guards stay in the MySQL factory, and the shared restore safeguards live in the base where PostgreSQL and OpenGauss benefit too. No state migration is needed.

4. Issue Summary

No. Issue Location Severity
1 Rejection message does not hint at case-sensitive matching IncrementalSource.java:471-478 Low, non-blocking
2 E2E mutation window still timing-dependent (cleanup now fixed) MysqlCDCSnapshotOnlyIT.java:165-178 Low, non-blocking

5. Merge Recommendation

Conclusion: Ready to merge

I am leaving this as a comment rather than an approval for now, because the current-head Build is still running; once it is green, CI is the only remaining gate on my side and I will update my review to approve.

  1. Blockers (non-CI): none. My previous blocking Issue 1 is fixed and covered by a test that fails on the old head.
  2. Remaining gates: CI on this exact head is still running. The fork Build is in_progress, and Apache reports no check on this head yet. The branch has no merge conflict (diverged, 20 ahead / 67 behind dev); drift alone is not a sync request. I respect @nzw921rx's plan to merge this after 3.1.0, and a write-capable maintainer still needs to reconcile the older change-request entry. This review does not dismiss anyone's decision.
  3. Non-blocking suggestions: Issues 1 and 2 above.

Thank you for the persistent and precise work on the recovery edge cases. This is in good shape.

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

Quick follow-up on my previous review of this head (6690968c78d0c8801b419889db06fb4274fbdc69): at that time the only thing holding me back from approving was that the current-head Build was still running. That fact has changed. The fork Build finished successfully (completed 2026-11-04 02:48 UTC) and every check on this head is now green. There is no new commit, and I had no non-CI blocker, so CI was previously the only remaining blocker on my side; CI is now passing, so I am changing my conclusion to approve.

My two earlier non-blocking suggestions still stand as optional polish. For transparency: GitHub still shows an older change-request entry from another reviewer, and @nzw921rx mentioned planning to merge this after 3.1.0. This approval does not override either of those; a write-capable maintainer still needs to reconcile them.

Thanks again @fatmanverse for the careful work on the restore edge cases.

@davidzollo
davidzollo requested a review from nzw921rx November 8, 2026 01:59

@davidzollo davidzollo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

+1
Good job

@davidzollo
davidzollo added this pull request to the merge queue Nov 9, 2026
Merged via the queue into apache:dev with commit f07b3cc Nov 9, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved cdc connectors-v2 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 reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature][Connector-V2][MySQL-CDC] Add snapshot-only startup mode

6 participants