Skip to content

[4.2] fix(plan): lock the resolved ODKU row - #31957

Merged
XuPeng-SH merged 1 commit into
matrixorigin:4.2-devfrom
LeftHandCold:fix/42-odku-resolved-target-lock-20261101
Nov 1, 2026
Merged

XuPeng-SH merged 1 commit into
matrixorigin:4.2-devfrom
LeftHandCold:fix/42-odku-resolved-target-lock-20261101

Conversation

@LeftHandCold

@LeftHandCold LeftHandCold commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

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

Which issue(s) this PR fixes:

Fixes #31955 and #31959 on 4.2-dev.

Root cause

The 4.2 ODKU planner resolves a secondary-UNIQUE conflict to an existing base row's target_pk, but constructs the base-table LockTarget from the incoming INSERT primary key. For an omitted AUTO_INCREMENT key, the plan can update PK 1 while locking/checking PK 10001.

This breaks both serialization against an ordinary UPDATE and stale-snapshot validation after another ODKU commits. LockOp checks changes for the wrong primary key, so a stale base/index RowID can reach index maintenance. The unique-index lock alone does not repair a stale resolved plan after the winner has released its locks.

Local validation on exact QA revision 71498157cc21f833b8e717f45d50d1f926be3134 reproduced two independent public-SQL entry paths from a healthy table:

  1. Ordinary UPDATE on CN0 versus auto-PK ODKU on CN1: both commit; both CNs observe base=2, distinct PK=1, distinct RowID=2, unique index=1, regular index=2. Reproduced 3/3 without injected bad data, merge bypass, or a test scheduling hook.
  2. Two ODKUs held at the existing pre-lock testing hook, then A commits and B resumes its resolved old input. Without flush, base/index become 2/2. With a real flush before B resumes, base=1 but regular index=2; two subsequent serial ODKUs amplify base rows 1→2→4 while the unique index remains 1. The hook changes timing only; it does not alter data, lock responses, or conflict-check results. The rollback-before-flush control stays consistent.

These establish the code defect, not the exact historical transaction ordering of a production incident. Already-corrupt tables still need separate data repair.

What this PR does / why we need it

Append one lock-key expression, coalesce(target_pk, incoming_pk), to the existing resolution PROJECT and use it for the base LockTarget. Keep the original nullable target expression for DEDUP: NULL must continue to mean INSERT.

The fallback is essential: merely changing the lock column to target_pk would make genuinely new rows skip their primary-key lock. Main already enforces resolved-row locking through its newer ODKU arbitration (#28265); this is a small 4.2 adaptation, not a backport of that larger redesign.

  • No new join/project node, scan, executor, mutable state, retry mechanism, or goroutine.
  • No changes to storage format, wire protocol, TN dedup, merge, assignment ordering, or index maintenance.
  • Ordinary INSERT and ODKU without secondary UNIQUE constraints retain their existing lock path.
  • Cost is one additional scalar lock projection per input row, with no new storage I/O. The local A/B below found no material median-latency regression for the measured workload; no performance improvement is claimed.

Regression coverage

  • Reuse the planner's existing table/index fixture. Evaluate the real remapped expressions for a resolved unique-key target, a new row, and a resolved primary-key target; verify DEDUP still consumes the original nullable target.
  • Cover explicit/generated primary keys, nullable UNIQUE values, ordinary INSERT, and no-secondary-UNIQUE ODKU. The clean-base overlay fails all three affected planner cases; both unchanged controls pass.
  • Add a multi-session pessimistic BVT for resolved-row lock timeout, release/retry, incoming-PK locking for new rows, and mixed existing/new nullable-UNIQUE rows.

Local validation

Base: 4.2-dev@382001d00671113e6255d0606dc9181c182ac71b, Go 1.26.4, Linux amd64. All manually initiated tests ran on the local host; no QA/IDC/TKE changes or remote workload runs.

  • Focused planner test: PASS, five subcases.
  • Complete go test ./pkg/sql/plan: PASS (24.007s).
  • go vet ./pkg/sql/plan: PASS.
  • Repository-configured package-scoped incremental golangci-lint: PASS, zero issues.
  • gofmt and diff whitespace checks: PASS.
  • Exact QA source plus this production patch: repeated two-CN SQL checks pass, including UPDATE/ODKU commit and rollback, new-row lock timeout/retry, changed nullable values, repeated same-transaction rewrites, and rollback.
  • Manual SQL A/B for [Bug]: Concurrent ODKU through different UNIQUE keys duplicates a row (v4.2.6) #31959 on the exact base and PR head: two concurrent ODKUs resolve the same row through different UNIQUE indexes while supplying different incoming PKs. On the base, both statements succeeded and the target PK became visible twice; on the PR head, all 12 paired cases left one row per target (12 rows, 12 distinct PKs). The start barrier only synchronized statement submission; SQL and storage/index work used the embedded two-CN cluster. This is local validation, not a committed regression test.
  • Local performance A/B: 8,192-row ODKU workload, 6 warm-ups and 24 measured samples. Secondary-UNIQUE path median was 634.9 ms on base and 638.1 ms on PR head (+0.5%). Concurrent same-host stress caused long-tail outliers, so p95 is not used as a conclusion.
  • Exact latest-4.2 patch: combined two-CN endpoint acceptance PASS (32.443s), including all seven public-SQL/timing-controlled cells, real flush RowID transfer, and bounded serial follow-up ODKUs. Base and both hidden indexes remain consistent on both CNs.
  • Native mo-tester comparison of the new SQL/result pair: PASS twice on the same local instance, 27/27 statements each (2.142s and 2.140s), no ignored/abnormal cases. Database teardown was checked after each round; expected results were not regenerated.

Native libraries were reused read-only from the verified exact-QA build: the CGo source tree is unchanged on the target amd64 branch. No full-repository CI or production-environment acceptance is claimed.

Lock the existing primary key selected by secondary UNIQUE resolution; retain the incoming key for new rows and keep DEDUP's nullable target unchanged. Add planner and multi-session BVT regressions.

Fixes matrixorigin#31955
@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 commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 52a02f81ca9552221ad4a7d77c26dbcbadfda6a3

Review completed. Read the assessment.

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

mo-bot review · mo-bot-local · review

Commit: 52a02f81ca9552221ad4a7d77c26dbcbadfda6a3

Assessment: approve

The fix aligns locking and stale-version checks with the resolved ODKU row while preserving incoming-key fallback and DEDUP’s NULL-means-INSERT behavior. No actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a1869d-820c-7212-9788-aecfb86a4141 · slot 0 · generation 2

Validation:

  • Focused regression passed all five cases; 100 focused race repetitions passed.

  • Full planner package passed normally: 1,692 test roots, with three unrelated skipped subtests.

  • Reviewed the complete delta, lock/retry/rollback consumers, BVT oracles, linked issue and discussion.

  • Source remained unchanged. Receipts and retained logs were reconciled in validation-manifest.json; final audit passed.

Limitations:

  • Full-package race validation timed out with over 51,000 retained incrservice goroutines from unchanged mock infrastructure. The stopped test passed separately under race. Full normal and focused repeated race coverage were accepted for this scoped fix.

  • Two-CN and BVT scenarios were not rerun locally; frozen CI successes and author reports were considered without claiming independent reproduction.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review conclusion: PASS — no blocking findings

Reviewed 52a02f81ca9552221ad4a7d77c26dbcbadfda6a3 against 4.2-dev@382001d00671113e6255d0606dc9181c182ac71b (also the merge-base). Read all four changed files, issue #31955 and its follow-ups, the existing review, and the affected planner/executor consumers. No source changes were made. This is a focused correctness fix, not a feature or major-refactor design gate.

Design and correctness

  • The planner is the right owner: the existing conflict resolver already selects the target row, while LockOp already owns serialization and stale-version checking. Correcting the supplied key closes that mismatch without duplicating either mechanism.
  • coalesce(target_pk, incoming_pk) locks the resolved existing row, but still locks the incoming key when no target exists. The original nullable target remains the DEDUP key, preserving NULL-means-INSERT behavior. Deep-copying the expressions avoids changing the shared resolution expression or creating a same-project output reference.
  • Traced projection preservation/column remapping, constructLockOp, performLock, hasNewVersionInRange, and PrimaryKeysMayBeModified, including in-memory and persisted/tombstone checks. Both lock acquisition and the version check use the corrected column. The existing retry path suppresses outdated batches, quiesces the old execution, rolls back statement workspace, and re-executes under the refreshed snapshot.
  • Ordinary INSERT, no-secondary-UNIQUE ODKU, fake-PK paths and internal index metadata upserts do not acquire the new branch. Conflict priority, assignment rules and downstream index maintenance are unchanged. No storage/wire/catalog format change is introduced.

Unhappy paths and cost

Audit Result for this delta
Q1: ownership/cleanup New expression results stay with the existing projection executors and their reset/free lifecycle; row locks remain transaction-owned and use existing commit/rollback cleanup.
Q2: waits/retry No new wait mechanism. Correctly conflicting writes use existing lock timeout/cancellation and statement retry paths; the BVT verifies timeout, rollback and release/retry.
Q3: growth Bounded additional expression/result-vector work per input batch; no new registry, cache, background task or retained history.

The patch adds scalar projection work (including the copied target-resolution expression) and result-vector storage, not another scan/join/RPC. Same-row writers can now wait/retry where they previously bypassed required serialization; this is necessary correctness behavior, not a promise of unchanged hotspot throughput. No separate performance benchmark was run.

Evidence checked/reused

  • Exact-head CI completed successfully. Checked the run SHA and UT checkout logs: 52a02f81..., Go 1.26.4, Linux/amd64. UT logs show 1,692 planner test roots executed in eight fresh race-detector processes. SCA, coverage, shared build and multi-CN BVT checks also succeeded.
  • Read the pessimistic BVT job's actual report: new on_duplicate_key_resolved_target_lock.sql passed 27/27, 2.133s, zero ignored/abnormal cases. Existing on_duplicate_key_modern.sql passed 203/203, on_duplicate_key_edge.sql 67/67, and insert_duplicate.sql 575/575.
  • Inspected the new five-case planner regression and the SQL/result pair, including existing-target locking, new-row fallback, mixed nullable-UNIQUE input, and preservation of the DEDUP target. Reused the exact-head author's normal/focused validation and existing reviewer report; did not rerun an equivalent heavy local suite or independently reproduce the author's controlled two-CN/flush harness.
  • Local git diff --check passed; isolated review worktree remained clean. No inline review threads are currently present/unresolved.

Scope limitation: this prevents the reported wrong-lock-key corruption path; it neither repairs already-corrupt tables nor proves the historical ordering of a production incident. All CNs that may execute affected writes need the planner fix before considering this path closed cluster-wide.

Recommendation: approve from the code-review perspective. This authenticated account is also the PR author, so this is a COMMENT review, not a self-APPROVE. The existing independent approval is unchanged.

@XuPeng-SH

XuPeng-SH commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 52a02f81ca9552221ad4a7d77c26dbcbadfda6a3

New discussion was assessed; the previous review remains unchanged.

@XuPeng-SH
XuPeng-SH merged commit 7a161fd into matrixorigin:4.2-dev Nov 1, 2026
XuPeng-SH added a commit that referenced this pull request Dec 1, 2026
…31979)

## What type of PR is this?

- [x] BUG
- [x] Improvement
- [x] Documentation
- [x] Test and CI
- [x] Code Refactoring

## Which issue(s) this PR fixes

Fixes #31956, fixes #31961, fixes #31962. Adds scalar ENUM coverage for
#31958 and retains the resolved-row locking fix from #31957 for #31955
and #31959.

## Problem and design

Inputs in one `INSERT ... ON DUPLICATE KEY UPDATE` can reach the same
row through different UNIQUE indexes or through a key inserted or moved
earlier in the statement. Resolving every action from the initial
snapshot loses updates or raises false duplicate errors.

- `PreInsertUnique` owns ordered row images, physical PK/UNIQUE claims,
and typed SQL no-op checks. The planner binds assignments and key
encodings. The compiler validates the coordinator owner before starting
producers and publishes logical affected rows after writer success.
- Immutable keys use the snapshot join. Generated-key moves use the
engine's statement view of stored and workspace rows, including
partitions. Failure rolls back the statement and retry starts with fresh
state.
- Retires the unreachable legacy ODKU rewrite, redundant plan marker and
scratch images, and unused HashBuild copy/cleanup paths. Compiler
preflight finds the owner in its validation pass.

- The action owner validates the inserted row or the fully assigned
duplicate row. A later input sees evaluated values, including signed
zero and JSON representations. A standalone payload-only no-op reports
zero affected rows and leaves the stored image intact. The physical-key
index follows actual moves even when the SQL affected count is zero.
- Insert-only output keeps old-image columns as constant NULL vectors.
Each append sets their length from the cumulative batch row count. This
fixes the valid 60,000-row wide-table upsert that previously failed at
the downstream writer with error 20301.

[Design and acceptance
criteria](https://github.com/matrixorigin/matrixone/blob/a76c71369e9452d589de8a9018cd8e7f705e0f08/docs/design/ordered-odku-4.2.md)

## Validation

Rebased on `4.2-dev@95679da`. The rebase retains the release timeout
classifier, both wire fields and final-row CHECK behavior. The feature
head is `a76c71369e`.

- Red/green through the MySQL frontend. The old output length
calculation failed with `invalid vector window`; the corrected owner
returned 60,000 affected rows, 60,000 stored rows and the expected
payload sum. The operator regression also reproduced the mismatch of
7,371 batch rows and a 1,421-entry old-image column.
- Embedded public SQL exercises #31956, #31961 and #31962, repeated
assignments and generated keys, statement rollback on a later CHECK or
writer memory error, and competing connections. A dedicated test under
the race detector verifies that a signed-zero key move reports zero
affected rows, frees the old key and preserves the moved owner through a
forced-index read.
- Six repository BVT fixtures passed all 1,264 checked statements. They
cover CHECK and generated columns, historical and modern duplicate
handling, nullable defaults and cast errors.
- Five affected owner packages passed their CI-short race suites on this
rebase. Reordered inputs, signed-zero key movement and the upstream
query-timeout cases passed under race. Seven affected packages passed
configured static analysis. The previous integration had also passed its
broader 37-package race run and repository-wide static analysis.

## Current performance

The previous PR revision showed a 9.73% p50 slowdown for 8,192
existing-PK updates. The updated owner batches column copies for
independent snapshot rows. Repeated targets and general expressions
retain ordered scalar evaluation.

| Public MySQL workload | Release p50 | Updated PR p50 | Median change |
Release p95 | Updated PR p95 | Release / PR median spread |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| Update 8,192 existing primary keys | 46.74 ms | 42.93 ms | -8.14% |
119.71 ms | 114.24 ms | 1.16% / 0.81% |
| Ordinary INSERT of 8,192 rows | 67.86 ms | 68.57 ms | +1.06% | 102.20
ms | 90.25 ms | 1.90% / 1.35% |

This release comparison used 322 verified MySQL executions per version
per workload in 336 time blocks. In the separate three-version
diagnostic the existing-PK p50 was 49.37 ms on release, 54.58 ms on the
previous PR and 45.91 ms on the updated PR. Previous-PR process spread
was 6.48%. Full-matrix release qualification remains open.
[Measurements, variation and raw
samples](#31979 (comment))
· [Previous
comparison](#31979 (comment))

## Earlier Linux comparison on `0e4db02ddd` and `9085200685`

Linux amd64, Go 1.26.4, three in-process CNs, identical native libraries
and the same public MySQL benchmark. Each version verifies the final
rows after each untimed setup and timed execution. Each comparison used
base, candidate, candidate, base process order and three warmups per
workload per process. Times are in milliseconds. Spread is the
difference between the two process medians divided by the smaller
median. Peak RSS across the full-sweep processes was 1.47 GiB for the
base and 1.40 GiB for the candidate.

The initial 15-workload sweep produced 14 measured executions per
workload per version. Fourteen workloads exceeded their same-version
spread limit. The 512-byte insert was the one workload meeting
precision, and its p50 was 13.6% above base. A focused repeat with CPU
profiles and 42 measurements per version gave 91.37 → 92.86 ms (+1.6%)
for the same workload. Its p95 increased from 738 to 1,439 ms.
Empty-table PK inserts also met the focused p50 and spread budgets. The
complete performance acceptance remains open, including tail behavior.

| Focused workload | Base p50 | PR p50 | Change | Base p95 | PR p95 |
Base spread | PR spread |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| varlen512_insert_8192 | 91.37 | 92.86 | +1.6% | 737.85 | 1438.74 |
3.60% | 0.41% |
| pk_bulk_insert_8192 | 29.39 | 31.73 | +8.0% | 31.92 | 34.11 | 1.39% |
3.51% |
| pk_bulk_existing_8192 | 51.04 | 47.31 | -7.3% | 774.29 | 1478.62 |
10.59% | 3.36% |
| single_noop | 1.00 | 1.03 | +2.9% | 1.31 | 1.41 | 6.31% | 6.13% |
| ordinary_bulk_insert_8192 | 73.72 | 71.76 | -2.7% | 1336.95 | 814.53 |
7.13% | 1.77% |

The generated-unique workload passed its forced-index oracle at a
standalone candidate p50 of 38.61 ms (seven executions, 512 actions per
execution).

<details>
<summary>All 15 workloads from the first sweep</summary>

| Workload | Base p50 | PR p50 | Change % | Base p95 | PR p95 | Base
spread % | PR spread % | Gate |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| single_insert | 16.62 | 21.80 | +31.2 | 20.52 | 601.22 | 6.40 | 22.20
| spread |
| single_conflict | 4.96 | 6.81 | +37.2 | 6.72 | 11.79 | 6.42 | 41.92 |
spread |
| single_noop | 0.91 | 1.59 | +75.5 | 1.46 | 1.97 | 29.13 | 8.49 |
spread |
| bulk_insert_8192 | 73.61 | 82.19 | +11.7 | 79.25 | 584.41 | 6.24 |
0.72 | spread |
| bulk_existing_8192 | 74.90 | 77.80 | +3.9 | 1965.00 | 1261.82 | 14.17
| 19.70 | spread |
| bulk_hot_8192_100keys | 13.54 | 15.08 | +11.3 | 16.92 | 19.49 | 3.00 |
6.91 | spread |
| bulk_noop_8192 | 45.90 | 42.84 | -6.7 | 49.11 | 52.89 | 2.88 | 17.46 |
spread |
| varlen512_insert_8192 | 86.99 | 98.79 | +13.6 | 257.85 | 652.22 | 2.97
| 4.79 | regression |
| varlen512_existing_8192 | 129.75 | 105.14 | -19.0 | 1182.88 | 1153.56
| 267.99 | 2.28 | spread |
| varlen512_hot_8192_100keys | 31.90 | 28.64 | -10.2 | 38.77 | 31.95 |
15.62 | 7.85 | spread |
| pk_single_insert | 8.72 | 9.60 | +10.1 | 14.04 | 11.80 | 34.85 | 9.71
| spread |
| pk_single_conflict | 5.27 | 4.86 | -7.7 | 8.02 | 7.24 | 28.01 | 18.92
| spread |
| pk_bulk_insert_8192 | 28.94 | 32.93 | +13.8 | 35.03 | 43.00 | 13.17 |
26.14 | spread |
| pk_bulk_existing_8192 | 41.71 | 47.76 | +14.5 | 190.52 | 585.36 | 9.51
| 8.36 | spread |
| ordinary_bulk_insert_8192 | 83.80 | 103.83 | +23.9 | 2003.04 | 733.85
| 69.45 | 17.39 | spread |

</details>

## Earlier performance evidence

Before this rebase, the target and candidate used the same three-CN
MySQL fixture, native libraries, Go 1.26.4 and Darwin arm64 host. Each
comparison alternated target and candidate processes in ABBA order. The
fixture validates resulting rows outside the timing window. The
empty-table PK row uses a dedicated rerun with the ordinary INSERT
control after the broader focused run found excess baseline spread.

| 8,192-row workload | Samples per version | Target → PR p50 (ms) | p50
delta | Target → PR p95 (ms) | Target / PR spread | p50 gate |
| --- | ---: | ---: | ---: | ---: | ---: | --- |
| Existing-PK ODKU | 84 | 45.78 → 47.96 | +4.8% | 55.59 → 67.08 | 3.06%
/ 1.97% | Pass |
| Empty-table PK ODKU | 56 | 28.77 → 30.68 | +6.6% | 33.57 → 36.33 |
0.35% / 4.61% | Pass |
| Ordinary INSERT | 84 | 75.53 → 74.80 | -1.0% | 92.63 → 85.25 | 2.16% /
1.89% | Pass |

On this earlier Darwin comparison, both review-targeted PK workloads met
the 10% batch p50 budget and the 5% process-spread limit in focused
runs. The 15-workload sweep checked SQL results in both versions;
several workloads, including the ordinary INSERT control, exceeded the
process-spread limit. Full-suite performance acceptance remains open. An
isolated 512-byte insert follow-up measured p50 86.51 → 92.83 ms and p95
99.17 → 106.10 ms. The companion ordinary INSERT control spread was
6.01% on the candidate in that run.

The previous `2996355` comparison reported +36.1% for existing-PK ODKU
and +21.3% for empty-table PK ODKU. The review requested a reduction and
a repeat comparison.
[Review](#31979 (review))

This branch was previously deployed

1 inactive deployment
ci — 52a02f81 Deployed Oct 31, 2026 by LeftHandCold
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/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants