Skip to content

feat(insert): align ON DUPLICATE KEY UPDATE with MySQL, drop legacy operator - #24973

Merged
mergify[bot] merged 18 commits into
matrixorigin:mainfrom
ck89119:issue-24939-main
Jun 27, 2026
Merged

mergify[bot] merged 18 commits into
matrixorigin:mainfrom
ck89119:issue-24939-main

Conversation

@ck89119

@ck89119 ck89119 commented Jun 13, 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 #24939
fixes #25000

What this PR does / why we need it:

Replace the legacy Node_ON_DUPLICATE_KEY operator with the modern
DEDUP JOIN + MULTI_UPDATE path for INSERT ... ON DUPLICATE KEY UPDATE,
and make real-PK tables align with MySQL.

Behavior change (real-PK, MySQL alignment)

Previously, on a table with a real primary key, only a primary-key conflict
triggered the update; any unique-key conflict raised a duplicate-entry error.
Now any unique-key conflict (PRIMARY or a secondary UNIQUE key) updates the
first conflicting row, in PRIMARY > unique-key definition order — matching
MySQL.

Implementation: real-PK ODKU resolves a single UPDATE target up front via
target_pk = coalesce(pk-existence-probe, uk1_pri, uk2_pri, ...) (treating
PRIMARY as the 0th index) and keys the main dedup-update join on target_pk.
The conflicting row is updated in place (its primary key and non-SET columns
are preserved). The per-unique-key FAIL dedup is kept as in-batch duplicate
protection: two brand-new rows that share a new unique-key value in the same
statement still error deterministically (documented gap vs MySQL's in-batch
sequential semantics).

Modern path coverage

Cleanup

Remove the now-dead Node_ON_DUPLICATE_KEY enum, the OnDuplicateKeyCtx and
pipeline.OnDuplicateKey messages, and the OnDuplicateKey vm opcode
(reserved in proto).

Tests

  • Plan unit tests for real-PK single / composite unique-key resolution.
  • End-to-end behavior cross-checked against MySQL 8.4.
  • BVT: insert_duplicate, on_duplicate_key_edge (rewritten),
    on_duplicate_key_modern (real-PK multi-UK + in-batch protection +
    irregular-index cases); the whole dml/insert suite passes on the
    multi-CN cluster.

🤖 Generated with Claude Code

@ck89119
ck89119 requested a review from a user June 13, 2026 07:46
@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 →

@matrix-meow matrix-meow added the size/XL Denotes a PR that changes [1000, 1999] lines label Jun 13, 2026
@mergify mergify Bot added kind/feature kind/refactor Code refactor labels Jun 13, 2026
# Conflicts:
#	pkg/sql/plan/build_dml_util_test.go

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

I found two substantive correctness issues in the current head.\n\n1. pkg/sql/plan/bind_insert.go:869-880 still resolves real-PK ODKU conflicts against the raw incoming column for every single-column unique index. That is wrong for prefix unique indexes like UNIQUE KEY u(col(4)): the hidden index table stores the truncated/materialized prefix key, so a conflict such as existing abcdxxxx vs incoming abcdyyyy will not resolve to the existing row here. The later unique-index dedup is prefix-aware, so the statement will still fail with duplicate-entry instead of doing the required UPDATE. The same file already materializes prefix-aware single-column unique keys at :1140-1163 for locking; target-PK resolution needs to use that materialized __mo_index_idx_col value as well, not the raw source column.\n\n2. pkg/sql/plan/bind_insert.go:227-235 routes every non-regular index into the new “irregular” maintenance path, which includes MASTER indexes. But the delete side in buildIrregularIndexDeleteMaintenance (:531-553) only handles FULLTEXT and IVF, while the insert side explicitly has a MASTER branch (:473-476). That means ON DUPLICATE KEY UPDATE / REPLACE can insert fresh MASTER-index entries for the new row image without ever deleting the stale old ones, leaving wrong search state behind. Please either add MASTER delete maintenance here or keep MASTER indexes out of getIrregularIndexes until the delete path is implemented.\n\nI would also add a targeted ODKU regression case for a single-column unique prefix index once the first bug is fixed.

ck89119 and others added 2 commits June 20, 2026 12:37
…micity CI

Review (XuPeng-SH):
- Prefix unique-index ODKU: buildOnDupTargetPkResolution now resolves single-part
  unique conflicts with the prefix-aware key (makeIndexPartExpr), matching what the
  hidden index table stores, so e.g. UNIQUE KEY u(col(4)) correctly upserts
  'abcdxxxx' vs 'abcdyyyy' instead of failing with duplicate-entry. Adds a targeted
  regression case.
- MASTER/HNSW indexes: removed from getIrregularIndexes / the irregular insert
  maintenance (their delete side is unimplemented, so ODKU/REPLACE would leave
  stale entries). Such tables now defer plain INSERT/LOAD to the legacy planner,
  and reject ODKU/REPLACE with a clear unsupported error instead of corrupting.

CI:
- atomicity.result: the PR had regenerated the external-table SELECTs to 0 rows
  (its env could not resolve the resource CSV); restore the 4 CSV rows the file
  reads, matching CI, while keeping the modern ODKU error messages.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The duplicate-entry error reports the user column name under the pessimistic
dedup-join (DedupColName) but the hidden index column __mo_index_idx_col under
the optimistic index-table fuzzy filter (PkName), so no single key name passes
both LAUNCH modes. Match the stable "Duplicate entry '<val>' for key" prefix with
-- @regex instead of the key name, in fk_base and insert_duplicate.

Co-Authored-By: Claude Opus 4.8 <[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.

I re-checked the latest head. The earlier two blockers I raised are addressed, but I still see one remaining correctness issue in the new MASTER/HNSW gate, plus a few concrete follow-up suggestions.

Blocking issue

pkg/sql/plan/bind_insert.go:75-84 and pkg/sql/plan/bind_replace.go:47-50 now reject any table carrying a legacy-only irregular index (MASTER/HNSW) before the planner determines whether the statement can ever hit an existing row. That is too early.

For fake-PK tables with no usable primary/unique key, this PR already treats:

  • INSERT ... ON DUPLICATE KEY UPDATE as a plain INSERT / legacy-degenerate case (bind_insert.go:1040-1049)
  • REPLACE as INSERT-like when there is no unique index (bind_replace.go:99-103)

In those cases there is no conflict-driven delete/update work at all, so there is no stale-entry problem to avoid. But the new early hasLegacyOnlyIrregularIndex() gate makes such statements fail up front anyway on tables with MASTER/HNSW indexes. A table like create table t(a int, b varchar(100), master index(b)); insert into t values (1,'x') on duplicate key update b='y'; should still be able to behave like INSERT here, not be rejected before key analysis.

Concrete implementation suggestions

  1. Move the MASTER/HNSW rejection later, after key analysis.

    • For ODKU, only reject once you know the statement can actually take the UPDATE path (real PK or a usable unique key exists).
    • Keep the existing isFakePK && firstUniqueIdxPos < 0 fallback reachable for MASTER/HNSW tables.
  2. Do the same for REPLACE.

    • First compute whether any unique/PK conflict path exists.
    • If not, keep the current REPLACE behaves like INSERT path reachable even on MASTER/HNSW tables.
  3. Add targeted SQL/BVT coverage for the user-visible behavior.
    I would add all of these while you are here:

    • ODKU on a MASTER/HNSW table without PK/UK -> behaves like INSERT
    • REPLACE on a MASTER/HNSW table without PK/UK -> behaves like INSERT
    • ODKU on a MASTER/HNSW table with a real conflict key -> explicit unsupported error
    • REPLACE on a MASTER/HNSW table with a real conflict key -> explicit unsupported error

Non-blocking but worthwhile remaining coverage suggestions

  • LOAD DATA + IVF/fulltext sync maintenance still deserves one end-to-end proof
  • FK ODKU update-branch should still get an invalid-parent unhappy-path case

Once the early gate is narrowed to the true conflict-driving cases, I am happy to re-check.

… modern

MASTER indexes now have full synchronous modern maintenance (insert + delete),
so INSERT / ON DUPLICATE KEY UPDATE / REPLACE maintain them on the modern
dedup+MULTI_UPDATE path instead of being rejected or deferred to legacy:

- isModernMaintainedIrregularAlgo / getIrregularIndexes now include MASTER.
- Insert side reuses buildPreInsertMasterIndex from the modern source step.
- Delete side: new buildIrregularMasterDeleteByPk joins on the master index
  table's independent __mo_index_pri_col (origin pk) == old/final pk — the same
  clean pk-join fulltext uses on doc_id, so no re-tokenization is needed.
- Removed hasLegacyOnlyIrregularIndex / isFakePKWithoutUniqueKey and all the
  MASTER gates in bindInsert/bindReplace/bindLoad, the master/hnsw unsupported
  messages, legacyIrregularIndexCause/Msg, and the build.go fallback branch.

HNSW/CAGRA/IVF-PQ are cron-maintained (idxcron, off the base-table CDC), so
they ride the modern path with no inline sub-plan — they are no longer flagged
as legacy-only.

Also fixes a pre-existing bug in the REPLACE irregular-index delete on the
merged-scan path (tables with no unique secondary key): the captured old-PK
placeholder was not reliably materialized into the irregular-delete sink, so
stale fulltext/IVF/master entries were left behind. Merged-scan only runs when
there is no unique key, so every conflict is a PK conflict (old PK == new PK);
key the irregular delete on the immutable new PK at its natural position.

Tests: TestGetIrregularIndexes now keeps MASTER; dropped
TestHasLegacyOnlyIrregularIndex. BVT: secondary_index_master gains INSERT/ODKU/
REPLACE coverage verifying the master index via prefix queries;
replace_irregular_index gains a no-unique-key merged-scan REPLACE regression;
new vector_hnsw_modern_dml exercises ODKU/REPLACE on an HNSW table.

Co-Authored-By: Claude Opus 4.8 <[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.

I re-checked this PR from a first-principles / unhappy-path angle. The overall direction is understandable, but I found two blocker regressions and one important scope mismatch.

  1. INSERT IGNORE on FK child tables loses IGNORE semantics

    • bind_insert.go encodes INSERT IGNORE as the nil-sentinel shape (len(OnDuplicateUpdate)==1 && OnDuplicateUpdate[0]==nil) and classifies it as Node_IGNORE.
    • But build.go still keys only on len(stmt.OnDuplicateUpdate) > 0, so it routes INSERT IGNORE through the ODKU FK path.
    • The modern FK path uses assert(...) filters for child->parent existence checks, so a missing parent becomes a hard error instead of “skip this row”.
    • Existing behavior for INSERT IGNORE on FK violations is to ignore the offending row, not fail the statement (see test/distributed/cases/dml/insert/insert_ignore.sql / .result).
    • Suggestion: distinguish the nil IGNORE sentinel from real ODKU at planner entry. Either keep FK-table INSERT IGNORE on the legacy path, or teach the modern FK path to drop/warn offending rows instead of asserting.
  2. ODKU child-FK validation regressed from row-scoped to whole-table checks

    • For real INSERT ... ON DUPLICATE KEY UPDATE, build.go now falls back to whole-table DetectSqls generated by genSqlsForCheckFKConstraints(...).
    • Those SQLs scan the entire child table (SELECT DISTINCT ... FROM child ... EXCEPT SELECT DISTINCT ... FROM parent), not just the statement’s final row image.
    • That means a one-row upsert can fail because of an unrelated orphan row already in the table (for example, one inserted earlier under FOREIGN_KEY_CHECKS=0), and validation cost now scales with table size.
    • The comments in build.go already acknowledge this exact false-positive problem for plain INSERT; ODKU still takes the whole-table path.
    • Suggestion: reuse a row-scoped FK check for the ODKU final image, rather than generating whole-table DetectSqls.
  3. Test coverage is missing the highest-risk unhappy paths

    • I do not see a regression test for INSERT IGNORE on an FK child table staying row-skip / non-failing under the new path.
    • I also do not see a test showing ODKU only validates the statement’s final row image rather than failing on unrelated pre-existing orphan rows.
    • Suggestion: add both tests before merge; they directly protect the two regressions above.

Given the semantic regression on INSERT IGNORE and the table-wide ODKU FK validation regression, I think this should be changes requested before merge.

ck89119 and others added 2 commits June 23, 2026 14:26
…d tables

Addresses two regressions in the modern insert path's child→parent foreign-key
handling, both now enforced row-scoped and in-plan over the statement's own rows:

- ON DUPLICATE KEY UPDATE used a whole-table DetectSql
  (genSqlsForCheckFKConstraints) that scanned the entire child table. A one-row
  upsert could fail on an unrelated orphan row (e.g. inserted earlier under
  FOREIGN_KEY_CHECKS=0) and its cost scaled with table size. ODKU now asserts
  parent existence over the materialized final merged image, the same row-scoped
  in-plan check plain INSERT already uses (modernInsertFkCheckEnabled +
  appendForeignConstrantPlan, deferred to finishIrregularIndexMaintenance).

- INSERT IGNORE lost its row-skip semantics: routed through the ODKU FK path, a
  missing parent became a hard error instead of skipping the offending row. New
  buildInsertIgnoreFkFilter LEFT JOINs each referenced parent and FILTERs out
  rows whose foreign key has no parent (NULL FK satisfies MATCH SIMPLE and is
  kept), feeding only the surviving rows to the MULTI_UPDATE. It is built with
  binding tags so it survives the full optimizer, unlike the tagless assert
  sub-plan, and so can gate the inserted rows.

build.go now emits only self-referencing FK DetectSqls for both plain INSERT and
ODKU. The now-dead genSqlsForCheckFKConstraints, the childFkCheckPrefix constant,
and the compile.go CHILD_FK_CHK: handling are removed.

Tests: new TestInsertOnDupChildParentFKUsesInPlanCheck and
TestInsertIgnoreChildParentFKDropsRows; TestInsertOnDupFKUsesModernPath /
TestInsertOnDupSelfReferFKUsesModernPath updated (ODKU child→parent FK is now
in-plan, so DetectSqls is empty). BVT on_duplicate_key_modern gains an ODKU case
proving it ignores a pre-existing orphan and still fails on a real violation, and
an INSERT IGNORE case proving missing-parent rows are skipped.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…key FK tables

A plain INSERT (or INSERT IGNORE) into a foreign-key child table that also
carries a unique key panicked with "unsafe slice cast: from length 16 ... 72"
(e.g. join/fulljoin_constraints.sql:198). The modern path materialized the
new-row image with appended index-helper columns (a unique key's serial) and
set modernFkCheck, so finishIrregularIndexMaintenance ran the legacy
appendForeignConstrantPlan over that image; its tagless child pass-through gets
mis-typed by column pruning, crashing the FK hash join.

- Add buildModernChildFkAssert: assert child->parent FK existence in the data
  flow with a binding-tagged parent LEFT JOIN + FILTER (mirrors
  buildInsertIgnoreFkFilter), robust to the appended index-helper columns.
- Route plain INSERT (Node_FAIL) through it instead of the deferred
  modernFkCheck / appendForeignConstrantPlan path.
- Guard "modernFkCheck = odkuNeedFkCheck" with onDupAction == UPDATE so plain
  INSERT and INSERT IGNORE (already enforced in-flow) no longer also run the
  panicking legacy assert. This also fixes the latent INSERT IGNORE crash on a
  unique-key FK child.
- Drop the now-constant needFkCheck; relax TestInsertIgnoreChildParentFKDropsRows
  to accept the optimizer's LEFT->RIGHT join rewrite.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…iplication

The in-flow plain-INSERT / INSERT IGNORE child-FK check used a LEFT join against
the parent table. When the foreign key references a non-unique parent column
(e.g. the leading prefix of a composite primary key, `FOREIGN KEY(f_a)
REFERENCES f1(a)` where f1's PK is `(a, b)`), the LEFT join multiplied each child
row by the number of matching parent rows, corrupting the inserted data
(foreign_key/foreign_key.sql:255 and friends).

Replace it with a MARK join (via insertMarkJoin), which emits exactly one output
row per input row carrying a boolean "parent matched" marker, so existence is
checked without multiplying rows. Factor the shared parent-existence build into
appendModernChildFkMarkOks, returning a per-FK boolean used by:
- buildModernChildFkAssert: assert(ok) per FK (plain INSERT, fail on missing parent);
- buildInsertIgnoreFkFilter: keep rows where every FK ok (INSERT IGNORE row-skip).

A NULL foreign-key value still satisfies the constraint (MATCH SIMPLE). Update
TestInsertIgnoreChildParentFKDropsRows to accept the MARK join.

Co-Authored-By: Claude Opus 4.8 <[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.

I re-checked the current head.

The earlier blockers around prefix-unique target resolution and MASTER/HNSW gating look improved, but I still see two substantive correctness regressions in the latest version.

  1. INSERT IGNORE on FK child tables still loses IGNORE semantics

    • bind_insert.go encodes INSERT IGNORE as the nil-sentinel shape (len(OnDuplicateUpdate)==1 && OnDuplicateUpdate[0]==nil) and classifies it as Node_IGNORE.
    • But build.go still keys only on len(stmt.OnDuplicateUpdate) > 0, so it routes INSERT IGNORE through the ODKU FK path.
    • The modern FK path uses assert(...) filters for child->parent existence checks, so a missing parent becomes a hard error instead of “skip this row”.
    • Existing behavior for INSERT IGNORE on FK violations is to ignore the offending row, not fail the statement.
    • Suggestion: distinguish the nil IGNORE sentinel from real ODKU at planner entry. Either keep FK-table INSERT IGNORE on the legacy path, or teach the modern FK path to drop/warn offending rows instead of asserting.
  2. ODKU child-FK validation still regressed from row-scoped to whole-table checks

    • For real INSERT ... ON DUPLICATE KEY UPDATE, build.go still falls back to whole-table DetectSqls generated by genSqlsForCheckFKConstraints(...).
    • Those SQLs scan the entire child table (SELECT DISTINCT ... FROM child ... EXCEPT SELECT DISTINCT ... FROM parent), not just the statement’s final row image.
    • That means a one-row upsert can fail because of an unrelated orphan row already in the table (for example, one inserted earlier under FOREIGN_KEY_CHECKS=0), and validation cost scales with table size.
    • Suggestion: reuse a row-scoped FK check for the ODKU final image instead of generating whole-table DetectSqls.

Additional coverage I still want

  • a regression for INSERT IGNORE on an FK child table staying row-skip / non-failing under the new path
  • a regression proving ODKU validates only the statement’s final row image, not unrelated pre-existing orphan rows

So on the current head, I still think this should remain changes requested.

@ck89119

ck89119 commented Jun 25, 2026

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Thanks for the re-check. Both blocking points were already addressed on the current head (commit 78cfa40ad, with follow-ups 43dd5e985 / 3476a26b4); I think the review was against an earlier snapshot, since the code it cites no longer exists. Concrete evidence below.

1. INSERT IGNORE keeps row-skip semantics (does not assert)

INSERT IGNORE is no longer routed through the ODKU FK path:

  • It is classified as Node_IGNORE at the planner entry via the nil sentinel — bind_insert.go:1302 (len(astUpdateExprs)==1 && astUpdateExprs[0]==nil).
  • It is handled by buildInsertIgnoreFkFilter — bind_insert.go:1440-1446, which FILTERs out (drops) the rows whose foreign key has no parent instead of asserting, feeding only surviving rows to the MULTI_UPDATE. A NULL FK satisfies MATCH SIMPLE and is kept.
  • The len(stmt.OnDuplicateUpdate) test in build.go is now only the legacy-fallback gate (build.go:83); it does not route FK handling at all.

2. ODKU child→parent FK is row-scoped, not whole-table

  • genSqlsForCheckFKConstraints (and childFkCheckPrefix / the CHILD_FK_CHK: handling) were removed — git grep genSqlsForCheckFKConstraints returns nothing.
  • ODKU sets modernFkCheck over the materialized final merged image (bind_insert.go:2254) and the check runs via appendForeignConstrantPlan in finishIrregularIndexMaintenance (bind_insert.go:853) over the statement's own rows only — so it never false-positives on an unrelated orphan row and does not scale with table size.

3. Regression coverage already present

test/distributed/cases/dml/insert/on_duplicate_key_modern.sql (added in 78cfa40ad) covers exactly the two unhappy paths you asked for:

  • ODKU validates only the final image: seeds an orphan child row under FOREIGN_KEY_CHECKS=0 (pid=99), then proves the valid-row ODKU succeeds (orphan ignored), the FK-column update to a missing parent still fails, and a genuine missing-parent insert still fails.
  • INSERT IGNORE row-skip: insert ignore into t_ign_fk_child values (10,1),(11,2),(12,4),(13,1),(14,NULL) keeps the valid rows and the NULL-FK row, drops pid=4.

Plan-level UTs also assert the in-plan behavior: TestInsertIgnoreChildParentFKDropsRows, TestInsertOnDupChildParentFKUsesInPlanCheck, TestInsertOnDupFKUsesModernPath, TestInsertOnDupSelfReferFKUsesModernPath (all green).

Could you re-load the latest head and re-check? Happy to add more coverage if anything still looks off.

@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-checked the latest head. The broader MASTER/HNSW gating concerns look improved, but the composite nullable-unique-key issue is still present.

In the current REPLACE path, skipUniqueIdx only stays true when every part of a unique index is statically NULL. That is still too narrow. For a composite UNIQUE(a,b), a row like (NULL, 1, ...) cannot conflict with any existing row, because the composite unique key serializes to NULL as soon as any input part is NULL. But the current fake-PK REPLACE privilege gate still treats that table as delete-capable and requires DELETE.

So the remaining blocker is unchanged:

  • fake-PK + composite nullable unique key
  • one component statically NULL
  • REPLACE is still insert-only semantically
  • frontend still over-requires DELETE

I would keep this at request changes until that composite-null case is handled and covered by a unit/BVT regression.

@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-checked the latest head. I still think this should stay at request changes, and this time I’m collecting the remaining blockers together.

  1. Composite nullable unique-key REPLACE still over-requires DELETE.
    The current static-null shortcut only skips a unique index when every part is NULL. For a composite UNIQUE(a,b), a row like (NULL, 1, ...) still cannot conflict, because the composite unique key serializes to NULL as soon as any input part is NULL. But the fake-PK REPLACE privilege gate still treats that table as delete-capable and requires DELETE.

  2. REPLACE on child FK tables still has no parent-existence check.
    The modern REPLACE path now allows FK tables, but the build path only wires self-referencing FK checks. I do not see a REPLACE-side equivalent of the child→parent existence validation that plain INSERT / INSERT IGNORE now perform in-flow. So REPLACE can still insert orphan child rows.

  3. ODKU FK checking still skips other FKs when one FK column is NULL.
    ODKU still routes child→parent FK checking through appendForeignConstrantPlan, whose helper first builds one global isnotnull(...) filter across all FK columns. If one nullable FK column is NULL, the entire row is filtered out of the check step, so other non-NULL FKs on that same row are never validated.

Concrete suggestions

  • For (1), treat a composite unique index as insert-only when any nullable part is statically NULL, and add a unit/BVT case for that path.
  • For (2), run a child→parent FK existence check for REPLACE’s final inserted image, analogous to the modern INSERT path.
  • For (3), move ODKU child→parent FK checking onto the same per-FK MARK/null-aware logic you now use for INSERT / INSERT IGNORE, instead of one global NULL prefilter.

A fake-PK REPLACE whose composite unique key serializes to NULL (any part
statically NULL) can never conflict and is never stored in the unique index
table -- the same rule the INSERT path applies. But the REPLACE path computed
skipUniqueIdx as "every part NULL" and never consumed it, so it still probed and
maintained the index for such a row, inserting a NULL-key entry that INSERT
skips. INSERT and REPLACE were therefore inconsistent for NULL composite keys.

- Compute skipUniqueIdx as "any part statically NULL", for unique indexes only
  (serial(...) is NULL as soon as one part is NULL); non-unique indexes use
  serial_full (NULL preserved) and are never skipped.
- Consume skipUniqueIdx in the unique-conflict probe, the old-RowID fetch and
  the index MULTI_UPDATE, so a NULL-key unique index is neither probed nor
  maintained -- matching bind_insert's NULL-key skip.

The main-table LEFT JOIN is kept; its NULL join condition never matches, so no
existing row is deleted and the new row is inserted. The plan also drops the
now-unneeded index-table scans and DEDUP join for the skipped key.

Tests: TestReplaceFakePKCompositeNullableUKSkipsNullKeyIndex (+ mock table
fake_pk_comp) asserts the NULL-key unique index is not maintained while a fully
non-NULL key still is; BVT replace.test covers no mis-delete, multiple NULL keys
coexisting, and a real conflict replacing.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@ck89119

ck89119 commented Jun 25, 2026

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Thanks. I've handled the composite-null case in 359de752a. Summary of what changed, plus two points where I took a different tack than the literal suggestion — happy to discuss.

Fixed: a NULL composite unique key is now consistent between INSERT and REPLACE

You're right that skipUniqueIdx was too narrow and, on the REPLACE path, was never actually consumed. Concretely, for a fake-PK table with UNIQUE(a, b) and a statically-NULL part, REPLACE was still probing and maintaining that unique index — inserting a NULL-key entry into the index table that the INSERT path deliberately skips (bind_insert.go:1893). That INSERT/REPLACE divergence is the real bug here.

  • skipUniqueIdx is now "any part statically NULL" (unique indexes only; serial(...) is NULL as soon as one part is NULL; non-unique indexes use serial_full and are never skipped).
  • It is now consumed in the unique-conflict probe, the old-RowID fetch, and the index MULTI_UPDATE, so a NULL-key unique index is neither probed nor maintained — matching INSERT.

Coverage: unit test TestReplaceFakePKCompositeNullableUKSkipsNullKeyIndex (asserts the NULL-key unique index is not maintained, while a fully non-NULL key still is) + a BVT in dml/replace/replace.test (no mis-delete, multiple NULL keys coexisting, a real conflict replacing).

Two deliberate deviations — would like your read

  1. The plan is not structurally insert-only. I did evaluate routing this REPLACE through the existing fake-PK insert-only branch (which drops the main-table LEFT JOIN). That branch doesn't populate the per-index metadata (idxTableDefs/idxObjRefs), while the shared post-branch code has several index loops that require it, so it nil-panics for any table that actually carries a unique index — a non-trivial refactor (multi-part serial old-cols, non-unique maintenance). Instead I kept the main-table LEFT JOIN: its join condition includes the NULL part, so it never matches, no existing row is deleted, and the row is inserted. So it is insert-only semantically at runtime, just not structurally; the redundant index-table scans and the DEDUP join are gone. If you consider the structural form a blocker, I'm glad to do the full insert-only refactor as a follow-up.

  2. Privilege still requires INSERT+DELETE. REPLACE privilege is decided from the AST (determinePrivilegeSetOfStatement), unconditionally INSERT+DELETE, matching MySQL ("you must have both the INSERT and DELETE privileges"). Making it depend on whether a particular statement's values happen to be NULL would make the required privilege vary per-statement for the same template — unpredictable for auditing and a divergence from MySQL. My preference is not to special-case that; if you feel insert-only REPLACE should drop DELETE, I'd suggest treating it as a separate, explicit design decision rather than folding it in here.

Let me know your thoughts on (1) and (2).

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

I re-checked the latest head from the FK / unhappy-path angle. The legacy ODKU operator removal is moving in the right direction, but I still see two correctness blockers before I can approve.

Blocker 1: REPLACE on a non-self child FK table does not check parent existence

bindReplace() temporarily sets IgnoreForeignKey so REPLACE can use the modern path, but the modern REPLACE path never adds a child->parent parent-existence check for non-self FKs. After createQuery(), bindAndOptimizeReplaceQuery() only generates self-referencing FK DetectSqls / self-ref pre-check SQLs. There is no equivalent of the INSERT/ODKU row-scoped parent check for normal child FKs.

So a statement like:

create table p(id int primary key);
create table c(id int primary key, pid int, foreign key(pid) references p(id));
replace into c values (1, 999);

can be planned without any parent-existence assert. That should fail with the normal child-row FK error. Please add a regression test for both insert-only REPLACE and conflict REPLACE producing a final child row that references a missing parent.

Blocker 2: ODKU final-image FK check can still skip a valid FK check when another FK column is NULL

ODKU sets builder.modernFkCheck and then finishIrregularIndexMaintenance() calls the old appendForeignConstrantPlan() over the materialized final image. That helper first builds a single FILTER containing isnotnull for every FK column across all FKs before it does the parent joins.

That is not per-FK MATCH SIMPLE semantics. With two child FKs, if FK1 is NULL and FK2 is non-NULL but points to a missing parent, the row is filtered out before FK2's parent join/assert runs. The statement can pass even though FK2 should fail.

Please replace this ODKU check with the same per-FK MARK-join logic used by the new INSERT / INSERT IGNORE path, or otherwise make the NULL handling per FK rather than a global pre-filter. A focused regression test should cover: one FK column NULL, another FK column non-NULL and invalid -> ODKU must fail; the same NULL FK with the other FK valid -> must pass.

The existing planner tests pass locally, but they do not cover either of these cases.

Two foreign-key correctness fixes on the modern DML path.

1. REPLACE on a non-self child FK table never validated parent existence.
   bindReplace bypasses the FK-table rejection to take the modern path, but the
   modern REPLACE path only emitted self-referencing FK DetectSqls, so an orphan
   reference (e.g. `replace into c values (1, 999)`) was planned without any
   parent-existence assert. REPLACE now runs the same row-scoped per-FK MARK-join
   assert as the modern INSERT (buildModernChildFkAssert) over its inserted image,
   covering both insert-only and conflict REPLACE.

2. ON DUPLICATE KEY UPDATE skipped valid FK checks when another FK column was NULL.
   ODKU routed its child->parent check through appendForeignConstrantPlan, which
   first builds one global isnotnull filter across ALL FK columns, so a row with
   any NULL FK column was dropped from the entire check -- a second FK pointing at
   a missing parent was never validated. ODKU now uses the per-FK MARK-join check
   (appendModernChildFkMarkOks: each FK is valid when its parent exists OR one of
   its own columns is NULL, correct MATCH SIMPLE) over the final merged image.
   Unlike plain INSERT it does NOT re-project to a fresh tag, so the downstream
   MULTI_UPDATE still sees both the merged image and the delete columns. The
   now-unused modernFkCheck plumbing is removed; appendForeignConstrantPlan stays
   for the legacy UPDATE path.

Tests: TestReplaceChildParentFKUsesInPlanCheck (new) and an enhanced
TestInsertOnDupChildParentFKUsesInPlanCheck assert the per-FK MARK join. BVT:
on_duplicate_key_modern covers multi-FK ODKU (one FK NULL + another invalid fails,
one FK NULL + the other valid passes); replace covers a REPLACE orphan reference
failing for both insert-only and conflict REPLACE.

Co-Authored-By: Claude Opus 4.8 <[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-checked current head c2c95bc7b05fac03bd322affd826827c7b1ef1d8 from correctness and unhappy-path angles.

The previous blockers I raised look addressed now:

  • INSERT IGNORE on child FK tables now uses the in-flow MARK-join FK filter, preserving row-skip semantics instead of failing the whole statement.
  • ODKU child->parent FK checking is row-scoped over the final merged image, so it no longer false-positives on unrelated orphan rows and the multi-FK MATCH SIMPLE case is checked per FK.
  • REPLACE now validates the inserted child row against its parent in the modern path, covering both insert-only and conflict REPLACE.
  • The composite nullable unique-key REPLACE path now skips statically NULL unique keys correctly; runtime INSERT/ODKU NULL-key filtering still happens at index-table insert time.

I also checked the latest added BVT/UT coverage around orphan rows, INSERT IGNORE row skipping, multi-FK NULL handling, and REPLACE FK enforcement. PR CI is green. Local targeted go test ./pkg/sql/plan ... still cannot build in my environment because native headers (usearch.h, xxhash.h) are missing, so I am relying on code review plus CI for execution coverage.

Approved from my side.

@mergify

mergify Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Queued — the merge queue status continues in this comment ↓.

@mergify

mergify Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-06-26 10:06 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🚫 Left the queue — 2026-06-26 11:02 UTC · at c2c95bc7b05fac03bd322affd826827c7b1ef1d8

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

Reason

Pull request #24973 has been dequeued

Queue conditions are not satisfied:

  • -conflict [📌 queue requirement]

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.

Requeued — the merge queue status continues in this comment ↓.

Resolve conflicts:
- pipeline.pb.go: regenerate from merged proto (drops legacy OnDuplicateKey,
  keeps SessionInfo.lock_wait_timeout from mo/main)
- bind_replace.go: keep our commented skipUniqueIdx 'any static-NULL part'
  logic (functionally equivalent to mo/main's independent fix)
- mock.go: union both composite fake-PK test schemas (fake_pk_comp +
  fake_pk_composite_t), each referenced by its own test
- index_table_dml_test.go: pass the new irregularIndexes arg to
  appendDedupAndMultiUpdateNodesForBindReplace

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@mergify

mergify Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-06-27 04:25 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-06-27 05:33 UTC · at 850388b4473b2cbe381e6ebd46f5f2f21c67caca · squash

This pull request spent 1 hour 8 minutes 11 seconds in the queue, including 1 hour 7 minutes 53 seconds running CI.

Required conditions to merge
  • #approved-reviews-by >= 1 [🛡 GitHub branch protection]
  • #review-threads-unresolved = 0 [🛡 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/feature kind/refactor Code refactor size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: REPLACE on a table with a vector/fulltext index does not maintain the index (rows not immediately searchable)

4 participants