Skip to content

[Fix][Format] Preserve unchanged CDC before-image fields - #12867

Open
hutiefang76 wants to merge 3 commits into
apache:devfrom
hutiefang76:frank/thirty-cdc-before-20261019
Open

hutiefang76 wants to merge 3 commits into
apache:devfrom
hutiefang76:frank/thirty-cdc-before-20261019

Conversation

@hutiefang76

@hutiefang76 hutiefang76 commented Oct 18, 2026 •

Copy link
Copy Markdown
Collaborator

Yes, contributing this fix to Apache SeaTunnel.

Purpose of this pull request

Fixes #12864. Canal and Maxwell reconstructed update before-images using a recursive field-name search. A changed field in another Canal row, or inside a nested Maxwell field, could make an unchanged column in the current row become null.

Check direct membership in the matching old row instead. Canal uses old[i] for data[i]; Maxwell checks only the top-level old fields. Explicit JSON nulls remain changed values and are not overwritten with after-image data.

The English and Chinese Canal/Maxwell format docs describe matching old rows, direct field membership and explicit-null handling.

Does this PR introduce any user-facing change?

Update before-images retain unchanged values correctly. For a two-row Canal update where only row 1 changes weight and row 2 changes name, both before-images now keep their own remaining values. A nested Maxwell field no longer changes an unrelated top-level field with the same name.

No option, default, public API, dependency or timestamp handling changes.

How was this patch tested?

JDK 17.0.18:

  • The new multi-row Canal and nested-field Maxwell cases fail before the fix; explicit-null controls pass before and after.
  • Affected Canal/Maxwell suites: 12 tests passed.
  • All JSON format suites: 59 tests passed, zero failures/errors/skips.
  • Scoped spotless:apply, build-time spotless:check and root ./mvnw -q -DskipTests verify passed. Root verify skips test execution.
  • Independent review of the full four-file diff completed. Remote CI, maintainer review and merge remain separate.
./mvnw -B -pl seatunnel-formats/seatunnel-format-json -am \
  '-Dtest=org.apache.seatunnel.format.json.**.*Test' \
  -Dsurefire.failIfNoSpecifiedTests=false package

Formatting and root verify also passed with the paired documentation included.

Check list

  • Regressions added to the existing Canal and Maxwell suites.
  • Explicit-null behavior preserved.
  • Formatting and required local verification completed.
  • No new dependencies or connector registration.

Implementation and tests assisted by DeepSeek and Codex; this description was drafted and posted by an AI assistant for @hutiefang76.

Signed-off-by: hutiefang76 <137664623+hutiefang76@users.noreply.github.com>
Signed-off-by: hutiefang76 <137664623+hutiefang76@users.noreply.github.com>

@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, @hutiefang76. I reviewed the current head (dd51b95) in full, including docs and tests.

What Problem Does This PR Solve?

Canal and Maxwell deserializers rebuild the UPDATE_BEFORE image by copying "unchanged" columns from the after image. "Unchanged" was decided with oldNode.findValue(fieldName) == null, which searches the whole subtree recursively. In Canal, old is an array parallel to data, so a changed column in row 2 hid an unchanged column in row 1 (it came out as null). In Maxwell, a same-named key inside a nested object of old did the same for a top-level column (#12864).

1. Code Change Review

1.1 Core logic

Canal (CanalJsonDeserializationSchema.java, UPDATE branch around line 168):

// before
SeaTunnelRow before = convertJsonNode(oldNode.get(i));
if (before.isNullAt(f) && oldNode.findValue(fieldNames[f]) == null) ...
// after
JsonNode oldRowNode = oldNode.get(i);
SeaTunnelRow before = convertJsonNode(oldRowNode);
if (before.isNullAt(f) && oldRowNode.get(fieldNames[f]) == null) ...

Maxwell (MaxWellJsonDeserializationSchema.java around line 148): oldNode.findValue(name) -> oldNode.get(name).

Semantics verified: JsonNode.get(name) returns a NullNode (non-null) for an explicit JSON null, so "present but null" still counts as changed and the null is kept; only an absent key is back-filled from the after image. This is exactly the intended Canal/Maxwell contract (old holds only changed columns, positional per row in Canal). Runtime path: Kafka source -> deserialize(...) -> UPDATE case -> before/after rows emitted as -U/+U. Insert/delete paths are untouched.

1.2 Compatibility

Fully compatible for well-formed messages whose old only has top-level changed columns (the normal case): output is identical. Output changes only in the buggy cases (multi-row Canal updates, or nested same-name keys in Maxwell), where it now becomes correct. No option, default, or schema shape changes. Users who unknowingly relied on the wrong null before-image would see corrected values; I consider that a bug fix rather than a break.

1.3 Performance / side effects

Positive: findValue traversed the entire old subtree for each column and row (O(rows x columns x size)); get is a direct map lookup.

1.4 Error handling / logging

Issue 1

  • Location: seatunnel-formats/seatunnel-format-json/src/main/java/org/apache/seatunnel/format/json/canal/CanalJsonDeserializationSchema.java:~170
  • Problem: If a Canal message has fewer old entries than data entries, oldNode.get(i) returns null and convertJsonNode(null) fails. This is pre-existing (the old code did the same call), not introduced here.
  • Potential risk: Only for malformed upstream messages; behavior is unchanged by this PR.
  • Best improvement: Optional follow-up, not for this PR.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding standards

Small, focused, comments explain the positional old/data relationship and the "absent means unchanged" rule.

2.2 Test coverage

Canal: multi-row update (row 1 changes weight, row 2 changes name) with exact before/after strings; explicit-null control. Maxwell: nested meta.name vs top-level name; explicit-null control. The multi-row and nested tests fail with the old findValue code; the null controls guard against over-correcting. Existing tests unchanged. Stability: Stable.

2.3 Docs

en and zh Canal/Maxwell docs explain positional old, absent-vs-null semantics with the example. Accurate against the code.

3. Architectural Soundness

Fix is at the single point where the changed/unchanged decision is made, in each deserializer. No shared code touched.

4. Issue Summary

# Severity Location Summary
1 Low CanalJsonDeserializationSchema.java:~170 Pre-existing: old shorter than data NPEs; not part of this PR

5. Merge Recommendation

Conclusion: Ready to merge

Blocking items: none in the code. CI: the Build check on this head is action_required (fork workflow not approved/run), so there is no CI result yet; it should be approved and run green before merging.

Heads-up: this PR edits MaxWellJsonSerDeSchemaTest.java and docs/*/maxwell-json.md, which #12866 and #12870 also touch, so whichever merges later will probably need a trivial rebase.

@hutiefang76

Copy link
Copy Markdown
Collaborator Author

The shorter-old malformed-message case is recorded for a separate follow-up. The positional before-image and explicit-null regressions in this PR remain unchanged.

I also tried Build for dd51b950: GitHub returned HTTP 422, Actions has been disabled for this repository, despite enabled fork permissions and an active workflow. No run was created. The 59 local tests passed, but the remote CI gate remains open; could a maintainer run the upstream checks?

AI-assisted follow-up for @hutiefang76.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for the follow-up, @hutiefang76. Recording the shorter-old malformed-message case as a separate follow-up works for me: I agree it is pre-existing (the old code made the same oldNode.get(i) call) and not something this PR needs to change.

On CI: the apache-side Build check for dd51b950 is still action_required and there is no run in the fork for this head, so there is no CI verdict yet. I cannot approve or dispatch the workflow from my side. Two things that may help: (1) in the fork, check Settings > Actions > General and make sure Actions are allowed to run, then run the Build workflow from the fork's Actions tab (or push an empty commit); the HTTP 422 you saw suggests the fork-level setting is what is rejecting the dispatch; (2) a maintainer can approve the pending run on the apache side. The branch is also 8 commits behind dev, so it would be good to sync once before the run, and to expect the small rebase with #12866 and #12870 that I mentioned earlier.

My review conclusion on the code is unchanged: no source-level blocker, the remaining gate is a green Build on the final head.

@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 again for the work here, @hutiefang76. This is a full re-review of the current head (ca171ba). Since my last review (dd51b95) the only new commit is a merge of dev (no change to the four-file fix), and I have re-read the full diff, docs and tests against it. I also read the thread: your note about the malformed shorter-old case being a separate follow-up is fine with me.

What Problem Does This PR Solve?

  • User pain point: for Canal and Maxwell UPDATE events, the -U (before) row is rebuilt by copying "unchanged" columns from the after image. "Unchanged" was decided by oldNode.findValue(name) == null, a recursive subtree search. In a multi-row Canal update, a changed column in row 2 made an unchanged column in row 1 come out as null; in Maxwell, a same-named key inside a nested object of old did the same to a top-level column (#12864). This silently produces wrong retract rows for downstream sinks.
  • Fix approach: check direct membership only: Canal uses old[i].get(name) for data[i]; Maxwell uses old.get(name).
  • Summary: replaces a recursive lookup with a direct, row-scoped lookup so before-images keep their own unchanged values.

1. Code Change Review

1.1 Core Logic Analysis

Canal (CanalJsonDeserializationSchema.java, OP_UPDATE branch, ~line 168-178):

// before
SeaTunnelRow before = convertJsonNode(oldNode.get(i));
if (before.isNullAt(f) && oldNode.findValue(fieldNames[f]) == null) ...
// after
JsonNode oldRowNode = oldNode.get(i);
SeaTunnelRow before = convertJsonNode(oldRowNode);
if (before.isNullAt(f) && oldRowNode.get(fieldNames[f]) == null) ...

Maxwell (MaxWellJsonDeserializationSchema.java, ~line 148): oldNode.findValue(name) becomes oldNode.get(name).

Findings:

  • ObjectNode.get(name) returns NullNode (non-null) for an explicit JSON null and null only for an absent key. So an explicit null still counts as "changed" and is kept, while only absent keys are back-filled from the after image. This matches the Canal/Maxwell contract (old holds only changed columns; positional per row in Canal).
  • Runtime path: Kafka source -> format deserialize(...) -> OP_UPDATE case -> before/after rows emitted as -U/+U. The normal user path reaches the changed lines for every UPDATE event, so the problem is real on the main path (not only an edge path). INSERT/DELETE are untouched. No engine/checkpoint/serialization code is involved.
  • I grepped seatunnel-format-json/src/main for other findValue uses on this pattern; only these two sites existed, so no sibling site is left unfixed.

1.2 Compatibility Impact

Fully compatible. For well-formed messages whose old has only top-level changed columns, output is byte-identical. Output changes only in the previously buggy cases (multi-row Canal, nested same-name key in Maxwell), where it now becomes correct. No option, default, schema shape or public API changes.

1.3 Performance / Side-Effect

Positive: findValue walked the whole old subtree per column per row; get is a hash lookup. No new allocation or state.

1.4 Error Handling and Logging

Issue 1

  • Location: CanalJsonDeserializationSchema.java:~170 (oldNode.get(i) then convertJsonNode(oldRowNode) / oldRowNode.get(...))
  • Problem description: if old has fewer entries than data, oldNode.get(i) returns null and the conversion fails. This is pre-existing (the original line made the same call) and not introduced here.
  • Potential risk: only malformed upstream messages; behavior unchanged by this PR.
  • Best improvement: track as a separate follow-up, as you proposed; not needed in this PR.
  • Severity: Low
  • Raised by another reviewer: Yes (my earlier round; the author agreed it is a follow-up)

2. Code Quality

2.1 Coding Standards

Minimal and focused. The new comment in the Canal branch explains the positional old/data relationship, and the existing comments on "absent means unchanged" are retained. No new nontrivial methods or fields.

2.2 Test Coverage and Test Stability

  • CanalJsonSerDeSchemaTest.testDeserializeUpdateWithOldImageOfMultipleRows: row 1 changes weight, row 2 changes name; exact -U/+U strings. Reverting to findValue makes row 1's name and row 2's weight become null, so it fails on the old code.
  • MaxWellJsonSerDeSchemaTest.testDeserializeUpdateWithNestedFieldInOldImage: nested meta.name must not mask top-level name; fails on findValue.
  • Both ...WithNullFieldInOldImage tests are controls guarding against over-correction (explicit null stays a changed value).
  • Inputs are static strings, with no time, network or ordering dependence.
  • Rating: Stable.

2.3 Documentation

en and zh Canal/Maxwell docs are updated in parity and accurately describe positional old, direct-membership and explicit-null semantics, consistent with the code.

3. Architectural Soundness

3.1 Fix Type

Precise fix at the single decision point in each deserializer.

3.2 Maintainability

The replacement is simpler than the original and easier to reason about; no shared code is touched.

3.3 Extensibility

Neutral. A future shared helper for "changed column detection" could unify Canal/Maxwell/Debezium handling, but it is not needed here.

3.4 Historical-version Compatibility

No config, SPI or state format change; well-formed historical messages decode identically. Only previously incorrect before-images change, which is a bug fix.

4. Issue Summary

Number Issue Location Severity
1 Pre-existing: old shorter than data fails in Canal UPDATE (follow-up, not this PR) CanalJsonDeserializationSchema.java:~170 Low

5. Merge Recommendation

Conclusion: Ready to merge

Blockers: none in the code.

Non-blocking: Issue 1 as a separate follow-up.

CI note: on head ca171ba the fork run's code-style, license header, dead links, dependency licenses and all unit-test jobs (JDK 11/17, ubuntu and windows, which include the format-json suites) passed. The apache-side Build check shows timed_out because the fork run was cancelled at all-connectors-it-3 (11, ubuntu-latest) after about 2.5 hours; that is a connector E2E shard that does not exercise Canal/Maxwell deserialization, so it looks unrelated to this change (this is an inference from the job name and the diff scope, not something I reproduced). I would suggest re-running only that failed job rather than the whole workflow. I have not run anything locally.

Overall assessment: a small, correct, well-tested root-cause fix with matching docs. Thank you for the clean and well-scoped contribution.

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.

[Bug][Format] CDC before-image lookup loses unchanged fields

3 participants