Skip to content

fix: align REPLACE/ODKU affected-rows with MySQL - #25318

Merged
mergify[bot] merged 21 commits into
matrixorigin:mainfrom
ck89119:issue-24907-main
Jul 10, 2026
Merged

mergify[bot] merged 21 commits into
matrixorigin:mainfrom
ck89119:issue-24907-main

Conversation

@ck89119

@ck89119 ck89119 commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #24907

What this PR does / why we need it:

Align affected-rows for REPLACE and INSERT ... ON DUPLICATE KEY UPDATE with MySQL:

Statement Before After MySQL
REPLACE existing key 1 2 2
REPLACE new key 1 1 1
ODKU real update 1 2 2
ODKU no-op (same values) 1 0 0
ODKU insert new 1 1 1

Changes

  • proto: add count_delete_affect_rows field to UpdateCtx
  • executor (multi_update/types.go): count DELETE side for upsert when flagged
  • compile/partition: propagate the flag through operator construction
  • plan: set flag on main-table UpdateCtx for ODKU and REPLACE; add NOT(<=>) no-op FILTER for ODKU to detect unchanged rows
  • tests: 7 executor-level + 3 plan-level unit tests

🤖 Generated with Claude Code

REPLACE and INSERT ... ON DUPLICATE KEY UPDATE now return
MySQL-compatible affected-rows values:

  - REPLACE over existing key:   2 (was 1)
  - REPLACE new key:             1 (unchanged)
  - ODKU real update:            2 (was 1)
  - ODKU no-op (same values):    0 (was 1)
  - ODKU insert new:             1 (unchanged)

Changes:
  - proto/plan.proto: add count_delete_affect_rows field to UpdateCtx
  - multi_update/types.go: count DELETE for actionUpdate when flagged
  - compile/operator.go, multi_update_partition.go: propagate flag
  - bind_insert.go: set flag + add NOT(<=>) no-op FILTER for ODKU
  - bind_replace.go: set flag on main-table UpdateCtx for REPLACE
  - Unit tests: 7 executor-level + 3 plan-level tests

Co-Authored-By: Claude <[email protected]>
@ck89119
ck89119 requested review from aunjgr and ouyuanning as code owners July 1, 2026 08:11
@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 →

…gular index tables

The no-op FILTER referencing scanTag columns was placed after the PROJECT
node, which remaps all columns to its own binding tag. This caused a
"Column remapping failed" error on tables with irregular indexes
(fulltext, vector/ivfflat).

Move the FILTER right after the DEDUP JOIN chain, before the PROJECT,
so scanTag columns are directly accessible during column remapping.

Also remove the outdated TestReplaceIntoAffectedRows which tested
the old (pre-fix) REPLACE behavior.

Co-Authored-By: Claude <[email protected]>
@matrix-meow matrix-meow removed the size/M Denotes a PR that changes [100,499] lines label Jul 3, 2026

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

No-op detection runs AFTER ON UPDATE CURRENT_TIMESTAMP fires, so UPDATE v=v still counts as a real change. Must build the equality predicate before implicit auto-update columns are applied.

…derived generated column

End-to-end coverage for the two review scenarios: a no-op ON DUPLICATE KEY
UPDATE must neither advance an implicit ON UPDATE CURRENT_TIMESTAMP column
nor a stored generated column derived from it, while a real change must
advance both.  Verified with mo-tester (170/170 pass).

Co-Authored-By: Claude <[email protected]>

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

Re-reviewing the latest head: the earlier blocker around implicit ON UPDATE columns defeating the ODKU no-op filter is fixed now, including the generated-column case you asked about earlier.

However, I still see one remaining substantive blocker on the latest head:

CountDeleteAffectRows is not preserved when MultiUpdate is duplicated or rebuilt for remote execution.

That flag is what makes the executor count the delete side for REPLACE / real-update ODKU so affected rows become MySQL-compatible (2 instead of 1). The current head sets it when the operator is first built from the plan, but then drops it in both:

  • the operator clone path (pkg/sql/compile/operator.go, vm.MultiUpdate case), and
  • the remote pipeline serialize / rebuild path (pkg/sql/compile/remoterun.go, vm.MultiUpdate case).

So any execution path that clones or ships a MultiUpdate can silently fall back to the old behavior, even though the local/direct path is fixed.

Suggested fix:

  1. preserve CountDeleteAffectRows in the dupOperator path for vm.MultiUpdate;
  2. preserve it across remote pipeline round-trip as well — either as a top-level field or by reconstructing it from the incoming plan.UpdateCtx entries;
  3. add a regression that duplicates / remote-round-trips a MultiUpdate with CountDeleteAffectRows=true and verifies the delete side is still counted.

ck89119 and others added 5 commits July 4, 2026 17:03
…te pipeline round-trip

CountDeleteAffectRows was only set when MultiUpdate is first built from
the plan (constructMultiUpdate), so it was silently dropped when the
operator is duplicated for parallel scopes (dupOperator) or shipped to a
remote CN (pipeline serialize/rebuild), falling back to the old
affected-rows behavior on those paths.

- dupOperator now copies CountDeleteAffectRows, matching what the
  PartitionMultiUpdate clone path already does.
- convertToPipelineInstruction carries the flag in each serialized
  plan.UpdateCtx (the proto field already exists), and
  convertToVmOperator ORs it back, matching constructMultiUpdate.
- Regression tests: dupOperator clone keeps the flag; serialize/rebuild
  round-trip keeps the flag (and stays false when unset).

Co-Authored-By: Claude Fable 5 <[email protected]>
…eep-copy CountDeleteAffectRows

Two fixes for the ODKU affected-rows work:

1. The no-op guard FILTER compared old vs new images with NOT(all <=>),
   but the dedup-join output also carries non-conflicting rows whose old
   image is all-NULL. Inserting an all-NULL row into a nullable UNIQUE
   key never conflicts (SQL NULL semantics), yet every NULL <=> NULL
   comparison is true, so the row was silently dropped instead of
   inserted. The keep predicate is now
   isnull(old __mo_rowid) OR NOT(all <=>): only rows that actually hit
   an existing conflict are subject to the no-op check.

2. DeepCopyUpdateCtxList did not copy CountDeleteAffectRows, so any
   deep-copied MULTI_UPDATE (e.g. prepared-statement plan copies) lost
   the flag and conflicting-row affected rows fell back from 2 to 1.

Plan UTs updated for the new filter shape, plus a DeepCopyNode
round-trip test asserting the flag survives.

Co-Authored-By: Claude Fable 5 <[email protected]>
…able unique key

An all-NULL row never conflicts on a nullable UNIQUE key, so ON DUPLICATE
KEY UPDATE must insert it; the case also re-checks normal conflict update
and no-op semantics on the same table.

Co-Authored-By: Claude Fable 5 <[email protected]>

@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 on current head 35e061c.

There is still a correctness gap in the ODKU no-op guard for real-PK tables when the conflict is resolved through a secondary UNIQUE key and the incoming PK is different from the existing row's PK.

Repro shape:

create table t(id int primary key, u int unique, v int);
insert into t values (1, 10, 5);
insert into t values (2, 10, 5) on duplicate key update v = v;
select row_count(); -- MySQL: 0

The update clause is a no-op against the conflicting row, so affected rows should be 0. On this PR the no-op FILTER can keep the row as a real update because it compares immutable key columns from the old row against the incoming row image.

The relevant planner path is:

  • bind_insert.go resolves a secondary-unique conflict to target_pk and keys the main DEDUP UPDATE join on that value (useTargetPk, then rightPkPos = targetPkPos).
  • But the no-op guard later iterates every visible column and builds old scanTag col <=> new selectTag col using colName2Idx[table.col] (bind_insert.go:2033-2062). For the PK column this is still the incoming PK position, not the resolved target row's existing PK/final immutable value.

I verified this with a temporary planner test using:

insert into constraint_test.dept(deptno, dname, loc)
values (999, 'Sales', 'NY')
on duplicate key update loc = loc;

The generated no-op predicate included:

old dept.deptno <=> col_pos:4

where col_pos:4 is the incoming-side deptno from the dedup output. So an incoming PK like 999 makes the all-cols-equal predicate false even though the user update does not change the conflicting row.

Suggested fix:

  1. Build the no-op predicate from the actual final row image that will be written, not from the raw incoming row image; or explicitly exclude immutable PK/unique conflict-resolution columns that are not user-updated and compare only columns whose final stored value can actually change.
  2. Preserve the existing old __mo_rowid IS NULL OR ... guard for non-conflicting inserts.
  3. Add regression coverage with ROW_COUNT() for secondary-unique no-op with a different incoming PK, e.g. the SQL above. This PR currently has good unit coverage for helper accounting/flag propagation, but the SQL BVT does not directly assert ROW_COUNT() for the issue's affected-rows contract.

Local checks I ran:

  • go test ./pkg/sql/colexec/multi_update -run 'TestUpsertAffectRowsAccounting|TestAddInsertAffectRows|TestAddDeleteAffectRows' passed
  • go test ./pkg/sql/plan -run 'TestUpsertAffectRowsPlan' passed
  • go test ./pkg/sql/compile -run 'TestDupOperatorMultiUpdateCountDeleteAffectRows|TestConvert.*MultiUpdate|Test.*CountDeleteAffectRows' passed for the matching compile test present in this head

Those tests do not cover this secondary-unique no-op case.

…e the dedup-update join

The ON DUPLICATE KEY UPDATE no-op guard compared every visible column of the
old image against the raw incoming row image. When a conflict is resolved
through a secondary UNIQUE key and the incoming PK differs from the existing
row's PK, the immutable PK column (never written by the update) compared
old-vs-incoming and always mismatched, turning a genuine no-op update into a
counted one (affected rows 2 instead of MySQL's 0).

Compare only the columns the update actually writes (updateExprs), against
their final written value rather than the incoming image. Columns absent from
updateExprs keep their old value and are trivially unchanged, so immutable
key columns resolved through a secondary-unique conflict are excluded.

This exposed a latent pushdown bug: when the update writes a column to a pure
function of its old value (e.g. v = v), the no-op predicate references only the
old-image (left) side, and the optimizer pushed it below the dedup-update join
onto the raw old-table scan. A DEDUP-update join NULL-extends its left side, so
on the scan isnull(old rowid) is never true and the matching old row is dropped;
the incoming row then looks like a fresh insert and the secondary-unique FAIL
dedup raises a spurious "Duplicate entry" error. Keep left-only filters above a
DEDUP join that carries a DedupJoinCtx, exactly as OUTER joins already require.

Adds plan unit tests (secondary-unique no-op compares only written columns;
dedup-update join keeps left filters above the join while plain dedup still
pushes them down) and a BVT case asserting a no-op through a secondary-unique
conflict with a different incoming PK does not advance an ON UPDATE timestamp.

Co-Authored-By: Claude Fable 5 <[email protected]>
@ck89119

ck89119 commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Thanks for the thorough review.

Regarding ROW_COUNT(): MO's row_count() is currently a stub that always returns 0 (pkg/sql/plan/function/func_unary.go:6797 — it returns opNoneParamToFixed[uint64](..., func() uint64 { return 0 })). Neither mo-tester's genrs records affected-rows counts in .result files, so we can't use ROW_COUNT() as a BVT assertion today.

Instead the new BVT case (t_odku_sec_uk) asserts the no-op via an ON UPDATE timestamp column — the same deterministic technique already used by the existing t_odku_onupdate and t_odku_onupdate_gen cases in the same file:

  • no-op (v=v through a secondary-unique conflict with a different incoming PK): updated_at must NOT advance → ts_unchanged = 1
  • real update (v=v+1): updated_at must advance → ts_advanced = 1

Additionally, I verified protocol-level affected-rows correctness via a database/sql E2E (Go RowsAffected() directly against the running server):

  • no-op v=v → RowsAffected = 0
  • no-op v=v with a different incoming non-key value (2,10,99) → RowsAffected = 0 (final written value = old value, still no-op)
  • real update v=v+1 → RowsAffected = 2
  • fresh insert (7,70,7) → RowsAffected = 1

All align with MySQL semantics.

…t re-run the assignment

The previous no-op guard compared the old image against a fresh copy of the
update assignment expression. The dedup-update join already evaluates each
assignment once to produce the stored value, so re-executing it in the guard
double-evaluates non-deterministic assignments (e.g. v = floor(rand()*2)): the
guard's value can disagree with what was actually written, either dropping a
real update (data loss) or counting a genuine no-op as an update.

Compare the old image against the final written value the dedup-update join
materialized into the new-image (selectTag) column at colName2Idx instead. That
column holds the single evaluation the join stored, so the no-op decision always
matches the persisted value. Non-deterministic assignments are now evaluated
exactly once.

Referencing the new-image column also makes the predicate span both join sides,
so it can no longer be pushed below the dedup-update join onto the raw old-table
scan. This removes the need for the previous pushdown.go guard, which is
reverted.

Adds a plan test asserting every no-op <=> compares against a bare new-image
column reference (never a re-evaluated function), covering both a trivial
(loc = loc) and a computed (loc = substring(loc,1,2)) assignment. Updates the
secondary-unique BVT to insert a differing incoming value (v = v with incoming
99 over stored 5) so it asserts the guard uses the materialized old value, not
the raw incoming image.

Co-Authored-By: Claude Fable 5 <[email protected]>
@ck89119

ck89119 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Good catch — fixed in 59b2050.

You are right: the previous guard re-evaluated the assignment expression, which double-evaluates a non-deterministic update (v = floor(rand()*2)) and can disagree with the value the dedup-update join actually stored — dropping a real update or counting a genuine no-op.

The fix compares the old image against the final written value the dedup-update join already materialized, rather than re-running the assignment. At runtime the join evaluates each UpdateColExprList expression once and writes the result back into the new-image (build/selectTag) column at colName2Idx (pkg/sql/colexec/dedupjoin/join.go — joinBat1.Vecs[pos] = vecs[j], emitted via rp.Rel == 1). The guard now references that column, so the no-op decision always uses the exact value that gets stored; non-deterministic assignments are evaluated exactly once.

A side benefit: referencing the new-image column makes the predicate span both join sides, so it can no longer be pushed below the dedup-update join. That removes the need for the earlier pushdown.go guard, which is reverted in this commit.

Verification (Go database/sql, RowsAffected() against a running server):

  • insert (2,10,99) on duplicate key update v = v over stored (1,10,5) → RowsAffected = 0, row stays v = 5 (incoming 99 is not written — proves the guard compares the materialized value, not the raw incoming image)
  • v = v + 1 → 2
  • v = floor(rand()*2) (stored v = 6) → 2, stored value ends up in {0,1} and the update is always applied; repeated 5x with no drop and no error

Also added a plan test asserting every no-op <=> compares against a bare new-image column reference (never a re-evaluated function), for both loc = loc and loc = substring(loc,1,2); and the secondary-unique BVT now uses a differing incoming value so it asserts the materialized-value semantics.

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

LGTM.

The implementation side looks consistent with the MySQL affected-rows contract you are targeting:

  • REPLACE and ODKU now opt into counting the DELETE side where appropriate.
  • The ODKU no-op guard is placed early enough to compare old-image vs final written value, and it correctly skips implicit ON UPDATE / derived generated-column noise.
  • The new flag is threaded through dupOperator and remote pipeline serialization.

The only things I still see are non-blocking coverage gaps: the new SQL/BVT file does not directly assert ROW_COUNT() yet, and the partition/remote propagation is mostly field-copy/round-trip tested rather than query-level affected-row assertions. Given the code path itself and the existing unit/planner/operator coverage, I don't see a substantive correctness blocker here.

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

LGTM.

The implementation side looks consistent with the MySQL affected-rows contract you are targeting:

  • REPLACE and ODKU now opt into counting the DELETE side where appropriate.
  • The ODKU no-op guard is placed early enough to compare old-image vs final written value, and it correctly skips implicit ON UPDATE / derived generated-column noise.
  • The new flag is threaded through dupOperator and remote pipeline serialization.

I did not find a substantive correctness blocker in the code path itself. The remaining gaps are test-only: the new SQL/BVT file still does not directly assert ROW_COUNT(), and the partition/remote propagation is mostly field-copy/round-trip tested rather than query-level affected-row assertions. Those are worth adding, but they are not enough on their own to block this PR.

@mergify

mergify Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-10 08:08 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-07-10 11:35 UTC · at b324100f396a593f9a33ef92f0dddd0afd51c1d1 · squash

This pull request spent 3 hours 27 minutes 8 seconds in the queue, including 1 hour 28 minutes 59 seconds running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]
  • github-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-neutral = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-skipped = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64

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/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants