Skip to content

perf(onduplicatekey): replace O(N²) linear scan with O(1) hash map - #24069

Merged
mergify[bot] merged 5 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix/upsert-ondup-hashmap-perf
Apr 7, 2026
Merged

mergify[bot] merged 5 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix/upsert-ondup-hashmap-perf

Conversation

@jiangxinmeng1

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 #24030

What this PR does / why we need it:

The OnDuplicateKey operator previously used a linear scan (checkConflict function) to detect uniqueness conflicts within the same INSERT batch. For each new row, it copied values into every row of checkConflictBatch and evaluated expressions on all rows, resulting in O(N²) time complexity and unbounded memory growth.

This commit replaces the linear scan with hash map-based conflict detection:

  • Extract unique key column indices from UniqueColCheckExpr at init time
  • Serialize unique key values via vector.GetRawBytesAt() into length-prefixed byte strings for use as hash map keys
  • Use map[string]int per unique constraint for O(1) conflict lookups
  • Eliminate the checkConflictBatch (2x memory overhead) from the hot path
  • Properly handle NULL values (never conflict per SQL semantics)
  • Update hash maps after in-place row modifications

Key new functions:

  • extractColIndicesFromExpr: walks expression tree to get column positions
  • serializeUniqueKey: length-prefixed binary serialization of key columns
  • findConflictByHashMap: O(1) conflict detection replacing O(N) scan
  • addToConflictMaps: maintains hash maps as rows are inserted

Performance impact: INSERT...ON DUPLICATE KEY UPDATE with N rows in a single batch improves from O(N²) to O(N) for intra-batch conflict detection.

…r intra-batch conflict detection

The OnDuplicateKey operator previously used a linear scan (checkConflict function)
to detect uniqueness conflicts within the same INSERT batch. For each new row, it
copied values into every row of checkConflictBatch and evaluated expressions on all
rows, resulting in O(N²) time complexity and unbounded memory growth.

This commit replaces the linear scan with hash map-based conflict detection:

- Extract unique key column indices from UniqueColCheckExpr at init time
- Serialize unique key values via vector.GetRawBytesAt() into length-prefixed
  byte strings for use as hash map keys
- Use map[string]int per unique constraint for O(1) conflict lookups
- Eliminate the checkConflictBatch (2x memory overhead) from the hot path
- Properly handle NULL values (never conflict per SQL semantics)
- Update hash maps after in-place row modifications

Key new functions:
- extractColIndicesFromExpr: walks expression tree to get column positions
- serializeUniqueKey: length-prefixed binary serialization of key columns
- findConflictByHashMap: O(1) conflict detection replacing O(N) scan
- addToConflictMaps: maintains hash maps as rows are inserted

Performance impact: INSERT...ON DUPLICATE KEY UPDATE with N rows in a single
batch improves from O(N²) to O(N) for intra-batch conflict detection.

Co-authored-by: Copilot <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

Review Summary by Qodo

Replace O(N²) linear scan with O(1) hash map conflict detection

✨ Enhancement

Grey Divider

Walkthroughs

Description
• Replace O(N²) linear scan with O(1) hash map for intra-batch conflict detection
• Extract unique key column indices at initialization time
• Serialize unique key values using length-prefixed binary format
• Eliminate checkConflictBatch memory overhead from hot path
• Properly handle NULL values per SQL semantics
• Update hash maps after in-place row modifications
Diagram
flowchart LR
  A["Linear Scan O(N²)"] -->|"Replace with"| B["Hash Map O(1)"]
  B -->|"Extract indices"| C["uniqueKeyColIndices"]
  B -->|"Serialize keys"| D["conflictMaps"]
  C -->|"Used by"| E["findConflictByHashMap"]
  D -->|"Updated by"| F["addToConflictMaps"]
  E -->|"Eliminates"| G["checkConflictBatch"]
Loading

Grey Divider

File Changes

1. pkg/sql/colexec/onduplicatekey/on_duplicate_key.go ✨ Enhancement +117/-36

Implement hash map-based O(1) conflict detection

• Replaced checkConflictBatch with hash map-based conflict detection using uniqueKeyColIndices
 and conflictMaps
• Added three new helper functions: extractColIndicesFromExpr(), serializeUniqueKey(),
 findConflictByHashMap(), and addToConflictMaps()
• Changed conflict detection from O(N) linear scan to O(1) hash map lookup in
 resetInsertBatchForOnduplicateKey()
• Added logic to save old keys before in-place updates and update hash maps after modifications
• Kept legacy checkConflict() function with deprecation comment for backward compatibility

pkg/sql/colexec/onduplicatekey/on_duplicate_key.go


2. pkg/sql/colexec/onduplicatekey/types.go ✨ Enhancement +10/-1

Add hash map fields to container struct

• Added uniqueKeyColIndices field to store column indices for each unique constraint
• Added conflictMaps field to store serialized unique key to row index mappings
• Marked checkConflictBat as deprecated with explanatory comment
• Updated Reset() method to reinitialize conflict maps
• Updated Free() method to clean up new hash map fields

pkg/sql/colexec/onduplicatekey/types.go


Grey Divider

Qodo Logo

@qodo-code-review

qodo-code-review Bot commented Apr 7, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX Issues (0)

Grey Divider


Action required

1. Conflict map overwrites earliest 🐞 Bug ≡ Correctness
Description
After an in-place ON DUPLICATE KEY UPDATE, the code unconditionally assigns conflictMaps[newKey] =
oldConflictRowIdx, overwriting any earlier row already mapped to that key. This can make subsequent
duplicates update the wrong row compared to the legacy scan which returns the first conflicting row
index in batch order.
Code

pkg/sql/colexec/onduplicatekey/on_duplicate_key.go[R200-208]

+			// Update hash maps after in-place modification
+			for k, colIndices := range insertArg.ctr.uniqueKeyColIndices {
+				if oldKeys[k] != "" {
+					delete(insertArg.ctr.conflictMaps[k], oldKeys[k])
+				}
+				newKey := serializeUniqueKey(insertBatch.Vecs, colIndices, oldConflictRowIdx)
+				if newKey != "" {
+					insertArg.ctr.conflictMaps[k][newKey] = oldConflictRowIdx
  	}
Evidence
Legacy conflict detection returns the first conflicting row index by iterating the boolean result
vector in row order and returning on the first true flag. The new map-based update path overwrites
any existing mapping for the updated key, which can replace an earlier row index with a later one
and therefore change the chosen conflict row for later inputs.

pkg/sql/colexec/onduplicatekey/on_duplicate_key.go[200-209]
pkg/sql/colexec/onduplicatekey/on_duplicate_key.go[410-446]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
When updating `conflictMaps` after an in-place row modification, the code overwrites any existing `newKey` entry. This can change conflict resolution behavior (which row is treated as the duplicate target) compared to the legacy scan that returns the first conflicting row.
### Issue Context
Legacy `checkConflict` returns the first matching conflicting row index in increasing row order. The new map should preserve that ordering invariant (or explicitly error if the update creates a second in-batch duplicate).
### Fix Focus Areas
- pkg/sql/colexec/onduplicatekey/on_duplicate_key.go[200-209]
- pkg/sql/colexec/onduplicatekey/on_duplicate_key.go[335-347]
### Suggested fix
- When setting `conflictMaps[k][newKey]`, do not blindly overwrite:
- If `newKey` is absent: set it.
- If `newKey` exists with `existingIdx`:
- Either keep the smaller index (`min(existingIdx, oldConflictRowIdx)`) to match legacy “first row wins”,
- Or (preferably, if semantics require) raise a constraint violation when `existingIdx != oldConflictRowIdx` because the update created a new in-batch duplicate.
- Apply the same “don’t overwrite earlier index” rule in `addToConflictMaps` defensively (even if duplicates are expected to be prevented upstream).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Raw bytes break '=' semantics ☑ 🐞 Bug ≡ Correctness
Description
serializeUniqueKey builds conflict keys from vector.GetRawBytesAt, but SQL '=' for some types is not
raw-byte equality (e.g., float32 comparisons can round based on scale before comparing). This can
cause intra-batch conflict detection to disagree with the executor-based '=' semantics previously
used by checkConflict.
Code

pkg/sql/colexec/onduplicatekey/on_duplicate_key.go[R293-312]

+// serializeUniqueKey serializes unique key column values into a string for hash map lookup.
+// Returns empty string if any column is NULL (NULL never conflicts per SQL semantics).
+func serializeUniqueKey(vecs []*vector.Vector, colIndices []int32, row int) string {
+	var buf bytes.Buffer
+	for _, colIdx := range colIndices {
+		v := vecs[colIdx]
+		if v.GetNulls().Contains(uint64(row)) {
+			return ""
+		}
+		b := v.GetRawBytesAt(row)
+		// Length-prefix each field to avoid ambiguity for variable-length types
+		l := len(b)
+		buf.WriteByte(byte(l >> 24))
+		buf.WriteByte(byte(l >> 16))
+		buf.WriteByte(byte(l >> 8))
+		buf.WriteByte(byte(l))
+		buf.Write(b)
+	}
+	return buf.String()
+}
Evidence
The new hot path serializes keys via raw storage bytes from vectors. The legacy approach evaluates
the generated UniqueColCheckExpr using the '=' function (ExpressionExecutor.Eval). In the function
implementation for '=', float32 with non-zero scale is rounded before comparison, meaning two values
can be considered equal by SQL '=' while having different raw byte representations; the raw-bytes
hash key would treat them as different and miss conflicts.

pkg/sql/colexec/onduplicatekey/on_duplicate_key.go[293-312]
pkg/container/vector/vector.go[333-343]
pkg/sql/colexec/onduplicatekey/on_duplicate_key.go[410-444]
pkg/sql/plan/utils.go[2237-2286]
pkg/sql/plan/function/func_compare.go[274-347]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`serializeUniqueKey` uses `vector.GetRawBytesAt` to build hash keys. This is not guaranteed to match SQL '=' semantics used by the legacy executor path (notably float32 with scale-based rounding).
### Issue Context
- Unique check expressions are generated using '=' and previously evaluated via executors.
- The '=' implementation rounds float32 values when the type scale is > 0.
- Hash keys should be built from a canonical representation that matches equality semantics.
### Fix Focus Areas
- pkg/sql/colexec/onduplicatekey/on_duplicate_key.go[293-312]
- pkg/container/vector/vector.go[333-343]
- pkg/sql/plan/function/func_compare.go[323-339]
### Suggested fix
Update `serializeUniqueKey` to encode values in a canonical form aligned with '=' semantics, for example:
- For float32 vectors with `typ.Scale > 0`, apply the same rounding logic used by `equalFn` before encoding into the key.
- Consider canonicalization for other types where '=' differs from raw bytes (e.g., normalize -0/+0 for floats if applicable).
- Prefer encoding typed values (using fixed getters + explicit encoding) instead of directly appending raw backing bytes for fixed-size types, so the key reflects semantic equality rather than physical representation.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

jiangxinmeng1 and others added 2 commits April 7, 2026 11:00
… extraction

- Add defensive validation: error out if extractColIndicesFromExpr returns
  empty indices instead of silently disabling conflict detection
- Add extractColRefFromExpr to recursively unwrap cast/function expressions
  when extracting column references, for future-proofing
- Replace per-call bytes.Buffer allocation in serializeUniqueKey with a
  reusable keyBuf stored in the container struct
- Use clear() instead of make(map[string]int) to reuse map storage and
  reduce GC pressure (Go 1.21+)

Co-authored-by: Copilot <[email protected]>
Match SQL '=' semantics for float types in hash-based conflict detection:
- float32 with Scale>0: apply same rounding as func_compare.go equalFn
- float32/float64: normalize -0.0 to +0.0 (IEEE 754 -0 has different
  bytes but SQL treats -0 == +0)

This ensures the hash map agrees with the expression-based '=' operator
for all float value edge cases.

Co-authored-by: Copilot <[email protected]>
@jiangxinmeng1

Copy link
Copy Markdown
Contributor Author

the short commit msg is truncated

fixed by 057678b

@aunjgr aunjgr changed the title perf(onduplicatekey): replace O(N²) linear scan with O(1) hash map fo… perf(onduplicatekey): replace O(N²) linear scan with O(1) hash map Apr 7, 2026
@aunjgr
aunjgr self-requested a review April 7, 2026 10:28
@mergify mergify Bot added the queued label Apr 7, 2026
@mergify

mergify Bot commented Apr 7, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-04-07 15:31 UTC · Rule: main
  • ✅ Checks skipped · PR is already up-to-date
  • 🚫 Left the queue — 2026-04-07 15:32 UTC · at 057678b28f1c46d8a11bd3aa935d8e961490fe99

This pull request spent 59 seconds in the queue, with no time running CI.

Required conditions to merge
  • #approved-reviews-by >= 1 [🛡 GitHub branch protection]
  • #changes-requested-reviews-by = 0 [🛡 GitHub branch protection]
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • branch-protection-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 / SCA Test on Ubuntu/x86
    • check-neutral = Matrixone CI / SCA Test on Ubuntu/x86
    • check-skipped = Matrixone CI / SCA Test on Ubuntu/x86
  • 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

Reason

The pull request #24069 has been manually updated

Hint

If you want to requeue this pull request, you can post a @mergifyio queue comment.

@mergify

mergify Bot commented Apr 7, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-04-07 16:28 UTC · Rule: main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-04-07 16:29 UTC · at eb3d7e25909630337e275b3c1d3b202359c4422d

This pull request spent 45 seconds in the queue, including 2 seconds running CI.

Required conditions to merge
  • #approved-reviews-by >= 1 [🛡 GitHub branch protection]
  • #changes-requested-reviews-by = 0 [🛡 GitHub branch protection]
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • branch-protection-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 / SCA Test on Ubuntu/x86
    • check-neutral = Matrixone CI / SCA Test on Ubuntu/x86
    • check-skipped = Matrixone CI / SCA Test on Ubuntu/x86
  • 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

@mergify
mergify Bot merged commit c829bb1 into matrixorigin:main Apr 7, 2026
24 of 25 checks passed

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/enhancement size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants