Skip to content

[Feature][Connector-V2] Add Canal update merging to Kafka sink - #13430

Draft
fatmanverse wants to merge 1 commit into
apache:devfrom
fatmanverse:feat/kafka-canal-merge
Draft

fatmanverse wants to merge 1 commit into
apache:devfrom
fatmanverse:feat/kafka-canal-merge

Conversation

@fatmanverse

@fatmanverse fatmanverse commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Purpose of this pull request

Yes, I am contributing to Apache SeaTunnel.

Related to #13408. This is a draft for implementation and semantics review, not ready to merge.

Kafka Sink currently emits Canal update images as DELETE and INSERT. This patch exposes the existing Canal merge serializer through the opt-in merge_update_event option, defaulting to false. With the option enabled, adjacent UPDATE_BEFORE / UPDATE_AFTER rows at one writer produce one UPDATE containing the full before-image in old and the after-image in data. The writer suppresses the buffered before-image instead of publishing its null serialized payload as a Kafka tombstone. Key serialization keeps merge mode disabled.

The patch also clears the Canal serializer's pending before-image after a non-before row, preventing reuse by a later unrelated update, and corrects the existing serializer test to serialize each input only once. This format-level change also affects file sinks using merge mode and requires broader lifecycle review.

Rebased onto current dev (dfdee68897d5f85b5e39d9c9dd8b698d77dc1fd6), preserving the upstream KafkaSinkSerializer extraction. Includes English/Chinese Kafka documentation, focused unit tests, and an extension to the existing KafkaFormatIT: the same input is written to default and merge-enabled sinks; the new assertions expect 9 INSERTs, 2 UPDATEs with full before/after values, and 1 DELETE, with no tombstones.

Does this PR introduce any user-facing change?

Yes. Kafka Sink accepts merge_update_event = true when format = "canal_json". The default remains false and retains the existing DELETE/INSERT behavior. No new dependencies, connector registration, or state format changes are introduced.

Merge blockers / decisions needed

The draft deliberately does not close #13408 or claim production readiness. Maintainer feedback on these semantics will guide the follow-up implementation.

How was this patch tested?

Executed remotely on the user-designated Linux server with JDK 17 and the repository Maven wrapper; no local tests were run.

  • Targeted reactor install (including compile/package/verify): 44 tests passed, zero failures/errors/skips: KafkaFactoryTest (23), DefaultSeaTunnelRowSerializerTest (14), CanalJsonSerDeSchemaTest (7).
  • Spotless apply/check on Kafka, JSON format, and Kafka E2E modules.
  • E2E compilation is not yet verified: direct compilation lacked local MySQL CDC artifacts. The subsequent -am -DskipTests -DskipIT=true -DskipITs=true -Dskip.ui=true install reactor reached CDC Base, then failed because org.apache.seatunnel:seatunnel-shade-hikari:4.0.3-3.0.1 is not cached in offline mode. This is separate from the successful Kafka/JSON targeted reactor. UI build was explicitly skipped.
  • Full repository tests and recovery/fault-injection testing were not run.
  • Maven Wrapper download initially failed with TLS EOF; reused the already-cached wrapper JAR and Maven cache with offline mode. No repository dependency configuration was changed.
  • Live KafkaFormatIT execution is blocked by the unavailable postgres:alpine3.16 image: Docker Hub pull returns EOF. This is not reported as a passed E2E test.
./mvnw -o -B \
  -pl seatunnel-connectors-v2/connector-kafka,seatunnel-formats/seatunnel-format-json \
  -am -Dskip.ui=true -DskipIT=true -DskipITs=true \
  -Dtest=KafkaFactoryTest,DefaultSeaTunnelRowSerializerTest,CanalJsonSerDeSchemaTest \
  -Dsurefire.failIfNoSpecifiedTests=false -Dsurefire.timeout=60 install

./mvnw -o -B \
  -pl seatunnel-connectors-v2/connector-kafka,seatunnel-formats/seatunnel-format-json,seatunnel-e2e/seatunnel-connector-v2-e2e/connector-kafka-e2e \
  spotless:check

Check list

  • English and Chinese documentation updated.
  • Focused unit tests added/updated.
  • Existing Kafka E2E case extended.
  • Complete live E2E and lifecycle/recovery coverage.
  • Resolve unmatched-image, pairing and routing semantics before marking ready.

@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 contributing to Apache SeaTunnel! I reviewed the complete current diff and followed its entry points and failure paths. The items below need attention before merging; I hope the concrete paths make the next step straightforward.

What problem does this PR solve?

User pain: Kafka Canal output currently turns an update into separate DELETE/INSERT events.

Fix: expose the existing Canal merge serializer as an opt-in Kafka sink option and suppress sending the buffered before row.

In one sentence: an ordered same-writer before/after pair can become one Canal UPDATE with old/new values. For example, name=old -> name=new emits one UPDATE instead of two Kafka messages.

1. Code changes

1.1 Core logic

Complete runtime path:

KafkaSinkFactory optional merge_update_event -> KafkaSink / writer config
  -> DefaultSeaTunnelRowSerializer value schema gets merge=true; key schema stays false
  -> KafkaSinkWriter.write -> serializeRow
      UPDATE_BEFORE -> Canal cache stores row; value=null -> writer returns without send
      UPDATE_AFTER -> consume and clear cache -> old=[before], data=[after], type=UPDATE -> sender.send
      INSERT/DELETE -> clears stale before cache, normal event
  -> prepareCommit / snapshotState -> existing Kafka transaction state only
E2E: PER_CLASS TestSuiteBase -> KafkaFormatIT.startUp once -> shared one-partition topic
  -> each TestTemplate engine invocation appends another12 events
  -> new check seeks to beginning and requires absolute endOffset12

Key findings and correctness:

  • The default false preserves existing message behavior; non-Canal formats do not activate the writer suppression. Key serialization is deliberately not buffered, avoiding null Kafka keys for before rows.
  • Normal adjacent same-writer Canal pairs reach the new path. The cache is cleared after the next non-before input, preventing a previously cached before from leaking across an intervening INSERT/DELETE.
  • Pair order and writer affinity are genuine preconditions, as the bilingual guides state; this does not add pairing across partitions, filtered before rows, different writers or recovery. Kafka snapshotState stores transaction metadata, not this serializer cache, so a checkpoint/recovery pair-boundary guarantee is not established by these tests.
  • The E2E validates actual message shape/count rather than job exit alone, but its absolute topic offset and seek-to-beginning conflict with the shared multi-engine TestTemplate fixture.
  • The test-loop correction to serialize once is necessary now that serialization consumes cached state; serializing twice would destroy the before image.

Before:

                    .withDescription(
                            "Semantics that can be chosen EXACTLY_ONCE/AT_LEAST_ONCE/NON, default NON.");

    public static final Option<String> TRANSACTION_PREFIX =
            Options.key("transaction_prefix")
                    .stringType()

After:

                    .withDescription(
                            "Semantics that can be chosen EXACTLY_ONCE/AT_LEAST_ONCE/NON, default NON.");

    public static final Option<Boolean> MERGE_UPDATE_EVENT =
            Options.key("merge_update_event")
                    .booleanType()
                    .defaultValue(false)
                    .withDescription(
                            "Only used when format is canal_json. When true, an UPDATE_BEFORE and UPDATE_AFTER pair is emitted as one UPDATE event.");

    public static final Option<String> TRANSACTION_PREFIX =
            Options.key("transaction_prefix")
                    .stringType()

1.2 Compatibility

Fully compatible by default: the new boolean defaults false and existing option names/APIs/protocols remain. Opting in intentionally changes Canal update message cardinality and payload. Existing Kafka transaction/checkpoint state format is unchanged; this is not evidence that cached pairs survive recovery.

1.3 Performance and side effects

One before-row reference is retained per serializer until the next row; no unbounded map/thread/lock is added. Opt-in paired updates reduce sends by one. Existing synchronous writer ownership applies; sharing this stateful serializer concurrently would be unsupported. Transaction retry/commit cleanup is unchanged, and cached rows are not independently checkpointed.

1.4 Errors, logging, and findings

Issue 1: Make the merged-output E2E independent of prior engine invocations

  • Location: seatunnel-e2e/seatunnel-connector-v2-e2e/connector-kafka-e2e/src/test/java/org/apache/seatunnel/e2e/connector/kafka/KafkaFormatIT.java:617.
  • Description and risk: The fixture uses PER_CLASS with @BeforeAll topic creation. TestTemplate runs the same job against multiple discovered engines, and the new sink writes the same topic on every invocation. The second invocation has endOffset24 or more, while the new assertion requires12 before entering Awaitility. Seeking to beginning also reconsumes the prior invocation. This is a deterministic cross-invocation contamination when more than one engine is selected, not a publish-readiness wait.
  • Best improvement: Capture the partition start offset before the job and consume/assert exactly the range written by that invocation, or allocate a distinct topic per invocation. Keep the strict no-tombstone and old/new payload assertions; do not relax them to any matching12 records or rely on test order.
  • Responsibility and trade-off: Keep the feature in Kafka configuration/writer wiring and the existing Canal schema. Fix the E2E invocation ownership in the current fixture rather than adding a separate test container or weakening assertions.
  • Severity: High; blocking: true.
  • Previously raised by another reviewer: No, unless explicitly attributed above.

Issue 2: Document the new stateful message-check helper contract

  • Location: seatunnel-e2e/seatunnel-connector-v2-e2e/connector-kafka-e2e/src/test/java/org/apache/seatunnel/e2e/connector/kafka/KafkaFormatIT.java:611.
  • Description and risk: This new nontrivial helper changes the shared consumer assignment/position and asserts ordered event contents. It has no comment explaining fixture ownership, the invocation-specific range or why the expected count is12. Those constraints are essential to maintaining this regression test.
  • Best improvement: Add a short method comment describing its consumer-position changes, one-partition ordering and the invocation isolation chosen for Issue1.
  • Responsibility and trade-off: Keep the feature in Kafka configuration/writer wiring and the existing Canal schema. Fix the E2E invocation ownership in the current fixture rather than adding a separate test container or weakening assertions.
  • Severity: Medium; blocking: true.
  • Previously raised by another reviewer: No, unless explicitly attributed above.

Community input: no independent technical finding or maintainer approval/change request was present in the collected discussion.

2. Code quality

2.1 Conventions

Reviewed all changed files for license, imports, naming, core-method and state-field comments. See the numbered findings for the required changes.

2.2 Test coverage and stability

Stability rating: High risk. High risk. Pure serializer/factory UTs have deterministic inputs, no sleeps or global mock state. KafkaFormatIT.java:611-625 uses Awaitility for consumption, which is good, but its new topic is created once in @BeforeAll and shared across engine invocations (TestSuiteBase.java:51). Each testFormatCanalCheck appends12 new events; requiring absolute endOffsets=12 and rereading from beginning fails on subsequent invocations. Isolate the invocation range and assert its12 records. Add cache-consumption and interrupted-pair checks at the writer boundary; the current UT tests the serializer but not the actual skipped send. Current Build45369471408 was queued at collection, so no passing CI is claimed.

2.3 Documentation

Both Kafka sink guides describe the option, false default and ordered same-writer prerequisite consistently. No other connector gains this Kafka option. Clarify recovery limitations if the intended contract includes checkpoints between the pair.

3. Architecture

3.1 Change location

Keep the feature in Kafka configuration/writer wiring and the existing Canal schema. Fix the E2E invocation ownership in the current fixture rather than adding a separate test container or weakening assertions.

3.2 Maintainability

Keep the behavior, lifecycle ownership, and failure contract together. Keep the feature in Kafka configuration/writer wiring and the existing Canal schema. Fix the E2E invocation ownership in the current fixture rather than adding a separate test container or weakening assertions.

3.3 Extensibility

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

3.4 Upgrade impact

Fully compatible by default: the new boolean defaults false and existing option names/APIs/protocols remain. Opting in intentionally changes Canal update message cardinality and payload. Existing Kafka transaction/checkpoint state format is unchanged; this is not evidence that cached pairs survive recovery.

4. Findings summary

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

# Finding Location Severity
1 Make the merged-output E2E independent of prior engine invocations seatunnel-e2e/seatunnel-connector-v2-e2e/connector-kafka-e2e/src/test/java/org/apache/seatunnel/e2e/connector/kafka/KafkaFormatIT.java:617 High
2 Document the new stateful message-check helper contract seatunnel-e2e/seatunnel-connector-v2-e2e/connector-kafka-e2e/src/test/java/org/apache/seatunnel/e2e/connector/kafka/KafkaFormatIT.java:611 Medium

5. Merge recommendation

Merge after fixes

Blocking items: Issues 1, 2. Current-head CI and write-capable maintainer review remain independent requirements.

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

Overall: the approach addresses a real path, but the listed blockers must be closed. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.

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

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

Review time: 2026-11-24T07:08:47.500850-05:00

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

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

  1. Please include any in-memory data awaiting a merge in the checkpoint. On restore, reload that data into memory so the merge can resume.

  2. For the E2E test, please use a CDC source and a Kafka sink, with the Kafka records serialized in Canal JSON format.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks, @nzw921rx. +1 on both points: the pending Canal before-row is currently transient serializer state, while checkpointing only retains the existing writer/transaction state, and the current format E2E does not exercise CDC recovery. These align with the outstanding blocking items in my full review on this same head. Please preserve and restore each writer's pending merge state and add a CDC-to-Kafka Canal regression covering a checkpoint between UPDATE_BEFORE/UPDATE_AFTER, then restore and assert the final Kafka records. The existing shared-topic E2E offset isolation also needs to remain part of that correction. No fix is confirmed until the code is pushed and reviewed; a passing format-only run would not close these items.

This is a discussion follow-up on unchanged head dcc37905e5825994477107d6dcb875528327fddb, not a new full source review. I inspected the named local source paths; no local build, test or SeaTunnel runtime was executed. Daniel has READ permission; effective maintainer approval and historical review dismissal remain separate repository actions.

@DanielLeens

Copy link
Copy Markdown
Contributor

The merge-gate fact cited previously has changed: GitHub now reports actual content conflicts with dev on this unchanged head. Please resolve those conflicts against current dev while retaining the reviewed feature, fixes and regression coverage, then obtain checks for the resulting head. This request is based on a content conflict, not merely on being behind; it does not claim that synchronization cures the existing CI failure.

The Canal checkpoint-state regression, shared-topic offset isolation and documentation findings remain open; CI is also failed.

Unchanged head dcc37905e5825994477107d6dcb875528327fddb; base dev; compare diverged, ahead 1 / behind 54. This is a CI/merge-state correction, not another full source review. No local build/test/runtime execution was performed. Daniel has READ permission; effective maintainer approval and historical-review dismissal remain separate actions.

Current snapshot (2026-11-27T02:58:05.230289+00:00): Signal pull request update: SUCCESS; Build: FAILURE; merge state DIRTY; review decision CHANGES_REQUESTED.

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature][Kafka] Add merge_update_event for Canal JSON in Kafka Sink

3 participants