Skip to content

fix(frontend): apply Data Branch updates in place - #27996

Merged
XuPeng-SH merged 8 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-27992-efe51699
Sep 3, 2026
Merged

XuPeng-SH merged 8 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-27992-efe51699

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG

Which issue(s) this PR fixes:

Related to #27992

What this PR does / why we need it:

Scope

This PR covers stable-primary-key, non-key updates. A source primary-key move with ON UPDATE CASCADE needs durable old/new row identity in the Data Branch change stream; that separate behavior is tracked in #28026 and is not claimed here.

Root cause

Data Branch represents a source-side non-key update as a DELETE/INSERT diff pair. Replaying the delete first transiently removes a referenced destination row, so foreign-key validation rejects an otherwise valid update.

The staged UPDATE JOIN remedy must carry generated identity values without assigning them. SET/ENUM and spatial values cannot be assigned through that join. Non-indexed values can use a bounded staged ON DUPLICATE KEY UPDATE path, but MatrixOne rejects an ODKU assignment to a primary or unique-key column.

Changes

  • Keep a dedicated update stage of writable values plus destination-key aliases, including generated-key values used only for matching.
  • Apply ordinary non-key assignments with one staged UPDATE JOIN, retaining the destination row and foreign-key validity.
  • Partition assignment handling by the actual changed value and destination-index metadata: non-indexed SET/ENUM/spatial values use one staged ODKU per bounded batch; a changed special column in a unique secondary index uses the exact-key native UPDATE path.
  • Omit indexed special columns from staged ODKU assignments, while ordinary updates in the same schema remain staged and batched.
  • Preserve exact-key handling for FLOAT/DOUBLE, fake-primary-key delete/insert behavior, independently deleted destination-row restoration, and PICK ACCEPT replacement handling.

Issue-to-test proof

  • [Bug]: Data Branch MERGE/PICK rejects non-key updates on referenced rows #27992: merge_foreign_key_update proves MERGE applies a non-key branch update to a referenced row, including an ACCEPTed destination conflict.
  • [Bug]: Data Branch MERGE/PICK rejects non-key updates on referenced rows #27992: pick_foreign_key_update proves clean, FAIL-atomic, and ACCEPTed PICK paths, including an independent source insert.
  • TestDataBranchDiffAsFile/update_apply_special_columns covers generated-key and SET MERGE/PICK, SET with a referencing child, GEOMETRY32, non-conflicting indexed-ENUM MERGE/PICK, target-side unique conflicts that roll back MERGE/PICK atomically, and payload-only updates in a table with an indexed ENUM.
  • TestDataBranchUpdateRequiresNativeUpdate and focused output tests prove that only a changed indexed special value takes the native path; unchanged indexed special values keep ordinary updates staged.
  • TestDataBranchOutputBatchesMixedSchemaSpecialUpdates sends maxSqlBatchCnt + 1 updates through the mixed schema path and asserts two staged special-update statements, one per bounded stage batch.

Tests

  • .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=600s ./pkg/frontend
  • .agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=300s -run '^TestDataBranchDiffAsFile/update_apply_special_columns$' ./pkg/tests/dml
  • git diff --check
  • Fresh CI will rerun the existing Data Branch BVT coverage for this head.

Residual risk

Primary-key-changing Data Branch updates, including ON UPDATE CASCADE, remain outside this PR and are tracked in #28026.

ACCEPT replacement refinement

  • When the destination independently changed an indexed SET/ENUM/spatial value, split only the matching source update rows from the staged batch and apply them with the full-row exact-key native UPDATE, so WHEN CONFLICT ACCEPT replaces every writable destination value with the source row.
  • Leave all other rows in the original bounded staged batch.
  • TestDataBranchDiffAsFile/update_apply_special_columns/indexed_enum_conflict_accept proves MERGE and PICK source-wins behavior; TestSplitDataBranchBatchForNativeUpdate proves only matched rows leave the staged batch.

@mergify mergify Bot added the kind/bug Something isn't working label Sep 2, 2026
@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Sep 2, 2026
@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Sep 2, 2026
@gouhongshen
gouhongshen force-pushed the agent/issue-27992-efe51699 branch from 90c4219 to baef7a2 Compare September 2, 2026 07:55
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

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

Deep-reviewed exact head ad143902644719e65fa703df6397a011dc7d7dfa against base 17c161a31b47a22e71ca222839143f66717ac365, including MERGE/PICK diff provenance, ACCEPT conflict mapping, generated/composite identity keys, staged SQL ordering, schema evolution, special types, FK semantics, performance, cleanup, tests, and the full #27992 issue discussion.

The central fix is sound for the original non-key case: a real-PK source update is now recognized as one logical update, the destination key is carried in a dedicated stage alias, and one staged UPDATE JOIN preserves the referenced row instead of replaying DELETE/INSERT. Generated PK values are used only for matching and are not assigned. Existing and focused exact-head tests for ordinary/composite/generated-key, SET, geometry, and PICK mixed update+insert pass.

Two blocking gaps remain:

  1. [P1 correctness] The PR does not solve #27992's documented primary-key update / ON UPDATE CASCADE case. The issue discussion explicitly adds the case where the branch changes a referenced primary key and ordinary UPDATE cascades the child FK. This implementation skips every primary-key assignment in both stagedUpdateSQL (data_branch_output.go:331-342) and dataBranchDirectUpdateSQL (data_branch_output.go:2154-2157). More fundamentally, once the PK changes, the old and new rows no longer have the same hash identity, so they are not emitted as a fromUpdate pair and still take the old DELETE/INSERT path.

    I reproduced this on the exact head with: parent row id=2, child FK REFERENCES parent(id) ON UPDATE CASCADE, branch UPDATE ... SET id=3 WHERE id=2, then DATA BRANCH MERGE ... WHEN CONFLICT ACCEPT. It still fails with Cannot delete or update a parent row: a foreign key constraint fails; the ordinary UPDATE control cascades successfully. Thus the PR body's “#27992 issue-to-test proof” overstates closure. Preserve old/new identity and apply a native PK UPDATE so FK update actions execute, with deterministic MERGE and PICK regressions. If PK-changing apply is intentionally a separate feature, split it into an explicit tracked issue and make this PR/body unambiguously a partial non-key fix rather than proof that #27992 is resolved.

  2. [P1 performance] The special-type fallback is table-wide, not assignment-specific, and can turn a large otherwise ordinary update into one SQL statement per row. dataBranchUpdateNeedsDirectSQL scans all writable columns in the table and returns true when any SET/ENUM or spatial column exists (data_branch_output.go:2049-2070), regardless of whether that column changed. dataBranchStagesUpdate then disables batching for the entire update batch, and appendOrExecuteDataBranchApplyRow invokes runSql once per row. For example, updating only payload VARCHAR on one million rows of (id PK, payload VARCHAR, status ENUM) produces one million parse/plan/execute cycles. This contradicts the PR body's claim that only SET/ENUM/spatial assignments use the exact-row path and undermines the stated large-PICK scalability goal. Classify the columns/rows actually changed (or otherwise omit unchanged planner-incompatible columns from the staged SET list), retain bounded batching for ordinary changes in mixed schemas, and add a mixed-schema large-row regression/benchmark that asserts bounded SQL execution count.

Unhappy-path note: apply tables are regular user-schema tables, but deferred dropApplyTables reuses the operation context. Cancellation can therefore leave __mo_diff_del_*, __mo_diff_ins_*, and the new __mo_diff_upd_* tables behind. This predates the PR for the first two tables, so I am not treating it as a separate blocker here, but the new table expands the leak and should be cleaned with a bounded lifecycle-owned context and covered by cancellation testing.

Validation at exact head:

  • substantive GitHub CI: green
  • git diff --check: pass
  • focused frontend staged/direct update tests under -race -count=10: pass
  • TestDataBranchDiffAsFile/update_apply_special_columns: pass
  • TestDataBranchPick/accept_mixed_update_and_insert: pass
  • review counterexample TestReviewDataBranchPrimaryKeyUpdateCascade: fails as described with the FK constraint error

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Thank you for the exact-head review. I verified both P1 findings.

  1. The special-type performance finding was valid. dataBranchUpdateNeedsDirectSQL is gone: normal columns use the staged UPDATE JOIN; SET/ENUM/spatial columns use a staged INSERT ... SELECT ... ON DUPLICATE KEY UPDATE, once per bounded stage batch. TestDataBranchOutputBatchesMixedSchemaSpecialUpdates feeds maxSqlBatchCnt + 1 rows and asserts exactly two special-update statements. Embedded DML now covers an ordinary payload update in an ENUM schema, generated-key SET MERGE/PICK, SET MERGE/PICK with a referencing child, and a direct-control PICK ACCEPT conflict.

  2. The primary-key ON UPDATE CASCADE counterexample is also valid, but is a distinct change-stream provenance gap: the existing update pairing is keyed by the primary key, so a key move leaves no durable old/new association. Guessing a pair from order or timestamp could conflate independent DELETE/INSERT operations and is unsafe. I opened [Bug]: DATA BRANCH cannot apply primary-key updates with ON UPDATE CASCADE #28026 for that behavior and narrowed this PR description to [Bug]: Data Branch MERGE/PICK rejects non-key updates on referenced rows #27992's stable-key non-key update scope; the PR no longer claims PK-moving cascade support.

The cancellation observation remains unchanged and pre-existing; I left it out of this focused fix.

Validation on new head 22fbede3d5635c6c9d364820a7c78fcf5b82cc1c:

  • focused frontend staged-update tests
  • TestDataBranchDiffAsFile/update_apply_special_columns (PASS)
  • git diff --check (PASS)

Could you please re-review the updated head?

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

[P1] Preserve UPDATE semantics for indexed special columns

stagedSpecialUpsertSQL routes every ENUM/SET/spatial assignment through INSERT ... ON DUPLICATE KEY UPDATE, but MatrixOne explicitly rejects an ODKU assignment when the assigned column participates in a primary/unique key. ENUM columns are valid unique-index columns, so this remains inside the PR's stated stable-primary-key/non-key-update scope and makes a valid Data Branch update fail.

I reproduced this at exact head 22fbede3d5635c6c9d364820a7c78fcf5b82cc1c with a review-only embedded test:

create table update_enum_unique_base (
  id int primary key,
  status enum('new','paid','shipped'),
  unique key uk_status(status)
);
insert into update_enum_unique_base values (1, 'new'), (2, 'paid');
data branch create table update_enum_unique_branch from update_enum_unique_base;
update update_enum_unique_branch set status = 'shipped' where id = 1;
data branch merge update_enum_unique_branch into update_enum_unique_base when conflict accept;

The target value shipped is unused, so the corresponding ordinary UPDATE is valid. The merge instead fails with:

Error 20313 (HY000): unsupported DML: update unique key on duplicate

The rejection comes from pkg/sql/plan/build_constraint_util.go, which disallows updating a PK/unique-key column in ODKU. Because the special-column partition is schema-wide, the generated ODKU can also be emitted when another column is the actual changed column.

Please route special columns that participate in unique keys through a semantics-preserving update path, and add MERGE/PICK regression coverage for both a non-conflicting indexed ENUM update and a duplicate-value failure with unchanged target data.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Addressed the indexed-special-column P1 in cae24dc.

Changed SET/ENUM/spatial columns that participate in a unique secondary index are now marked during hash diff and applied with the existing exact-key native UPDATE. They are omitted from staged ODKU assignments; non-indexed special changes remain bounded staged ODKU, and an ordinary change in the same indexed-ENUM schema remains a staged UPDATE JOIN.

The regression uses a valid branch update and creates the duplicate only in the destination after branching, so it verifies the actual apply-time conflict and transactional target preservation. It covers MERGE and PICK success, MERGE and PICK duplicate failures, and a payload-only update with a unique ENUM.

Validation: full pkg/frontend test package and TestDataBranchDiffAsFile/update_apply_special_columns pass; git diff --check passes. The PR description is updated. Could you please re-review this head?

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

Requesting changes for one correctness blocker on cae24dc9caa172452e40beb7855cd0220a3bfc1e.

[P1] Preserve the complete source row for WHEN CONFLICT ACCEPT.

The new native/staged decision is made from the source-side update relative to the LCA. That is insufficient once the destination changed an indexed special column independently. If the source changes only an ordinary column, requiresNativeUpdate stays false; the staged path then deliberately omits every indexed special column, so ACCEPT keeps the destination value instead of replacing it with the source value. The result is a source/destination hybrid row, contradicting the documented “source value wins” contract.

I reproduced this on the exact head with both MERGE and PICK:

create table t (
  id int primary key,
  payload varchar(32),
  status enum('new','paid','shipped'),
  unique key uk_status(status)
);
insert into t values (1, 'base-one', 'new'), (2, 'two', 'paid');
-- create source branch from t
update source_t set payload = 'source-one' where id = 1;
update t set status = 'shipped' where id = 1;
-- MERGE/PICK source_t into t WHEN CONFLICT ACCEPT

Expected row 1: (1, 'source-one', 'new') (the complete source row).
Actual row 1: (1, 'source-one', 'shipped').

Both focused integration tests fail deterministically with that mismatch. This is within the PR's supported scope: stable primary key, non-key updates, and an indexed ENUM column.

Please make accepted replacement rows use a semantics-preserving full-row apply whenever an omitted indexed-special value can differ in the destination (or use another mechanism that applies every writable source value), and add this cross-column conflict regression for both MERGE and PICK.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Verified the cross-column WHEN CONFLICT ACCEPT P1 and addressed it in c9e33a5.

A destination update that changed an indexed SET/ENUM/spatial value is recorded by primary key. If the matching source update changes only ordinary data, that one row is split out of its staged batch and applied with the existing full-row exact-key native UPDATE; all other rows remain staged. This restores the complete source row rather than retaining a destination special value.

TestDataBranchDiffAsFile/update_apply_special_columns/indexed_enum_conflict_accept now proves both MERGE and PICK. TestSplitDataBranchBatchForNativeUpdate, the full frontend package, the full special-update DML test, and git diff --check pass. The PR description is updated. Could you please re-review this head?

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

Deep-reviewed exact head c9e33a5cddcb1d662c880976d845b488ea1cc97e against base 17c161a31b47a22e71ca222839143f66717ac365.

The previous source-wins blocker is resolved. For WHEN CONFLICT ACCEPT, a destination-side update of an indexed SET/ENUM/spatial column is now remembered by exact primary key; only a matching ordinary source-update row is split from the staged batch and routed through the full-row native UPDATE. This restores every writable source value instead of retaining an omitted destination indexed-special value. Unmatched rows remain on the bounded staged path.

I checked the change from correctness, conflict semantics, batching/performance, composite-key identity, unique-index failure atomicity, cancellation/ownership, and MERGE/PICK perspectives. I found no blocking issue.

Counterexample validation on this exact head:

  • the prior MERGE and PICK cross-column repro now returns the complete source row;
  • a mixed update batch correctly routes only the conflicting row through native UPDATE while retaining the other row;
  • a composite primary key containing a comma plus a composite unique ENUM index matches the correct row;
  • when the accepted source row would violate another destination unique key, MERGE fails and leaves the full destination state unchanged;
  • focused batch-split and staged/native output tests pass under -race -count=3;
  • git diff --check and all substantive GitHub CI checks pass.

Performance remains proportional to the affected data. The extra primary-key maps and scan are linear; the per-row native path is restricted to changed indexed-special rows and accepted cross-column conflicts, while normal and non-indexed-special updates retain bounded staging. Primary-key-changing updates remain explicitly outside this PR and are tracked by #28026.

@mergify

mergify Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-03 03:01 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-09-03 03:40 UTC · at 095a0f7a53a456c47077d7ca9e51ab787e5717fc

This pull request spent 39 minutes 22 seconds in the queue, with no time running CI.

Waiting for
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
    • check-success = Matrixone CI / SCA Test on Linux/arm64
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
All conditions
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
    • check-success = Matrixone CI / SCA Test on Linux/arm64
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]

Reason

Pull request #27996 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Failing checks:

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

This branch was previously deployed

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

Labels

kind/bug Something isn't working size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants