Skip to content

fix: migrate null unique key oom - #24616

Merged
XuPeng-SH merged 8 commits into
matrixorigin:3.0-devfrom
ULookup:fix/migrate-null-unique-key-oom
May 28, 2026
Merged

XuPeng-SH merged 8 commits into
matrixorigin:3.0-devfrom
ULookup:fix/migrate-null-unique-key-oom

Conversation

@ULookup

@ULookup ULookup commented May 27, 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:

Cherry-pick from main:

What this PR does / why we need it:

Backport two fixes from main to 3.0-dev:

1. Fix concurrent INSERT with NULL unique key false duplicate errors (#24054)

SQL defines NULL != NULL, but the duplicate checker treated NULL values as comparable:

  • fuzzyCheck: NULL Varlena serialized to empty string → multiple NULLs counted as duplicates
  • checkPKDup: NULL rows not skipped for any type
  • PKPersistedBetween: InplaceSort reorders data but not the null bitmap → NULL positions misaligned after sort
  • constructColBuf: SetVector() pointer aliasing causes data race

Fix: skip NULLs across all three duplicate-checking layers, Dup() replaces SetVector(), clone before InplaceSort.

2. Prevent OOM in PKPersistedBetween under high-concurrency lock checks (#24373)

Under 1000 concurrent TPCC NEW_ORDER transactions, each LockOp triggers PKPersistedBetween, causing a thundering-herd of block I/O that exhausts mpool capacity → OOM.

Fix: three mitigations — changed objects cap 64 / candidate blocks cap 32 / global semaphore at 16 concurrent. Returns true conservatively above thresholds (one extra read under RC, correctness unaffected).

Why #24373 is included

Both PRs modify PKPersistedBetween in txn_table.go. #24054 adds cloneNonNullKeys() and an InplaceSort fix inside this function; #24373 adds OOM guardrails around the same block loop. If we only backport #24054, the NULL handling fix is in place but the concurrent lock-check path in PKPersistedBetween remains unbounded — high-concurrency workloads can still OOM on 3.0-dev. The two fixes apply to the same function, address independent problems, and are safe to ship together.

XuPeng-SH and others added 2 commits May 26, 2026 19:49
…rors (matrixorigin#24054)

**1. NULL handling bug (logic error)**
SQL defines NULL != NULL, but the duplicate checking code treated NULL values as comparable:
- `fuzzyCheck.firstlyCheck()` / `genCollsionKeys()`: NULL Varlena serialized as empty string → multiple NULLs counted as duplicates
- `checkPKDupGeneric()` / `checkPKDup()`: NULL entries not skipped for any type
- `PKPersistedBetween()`: `InplaceSort()` reorders data but **not** the null bitmap → null positions become misaligned after sort

**2. Concurrent vector sharing (data race)**
- `PreInsert.constructColBuf()` used `SetVector()` (pointer alias) instead of `Dup()` (deep copy)
- Concurrent `MergeRun()` scopes cause reads/writes on shared bitmap structures

| File | Fix |
|------|-----|
| `fuzzyCheck.go` | Skip NULL rows in `firstlyCheck`/`genCollsionKeys`; fix `vectorToString` per-row null check |
| `txn.go` | Skip NULL rows in `checkPKDupGeneric` (all types) and `checkPKDup` (string/array types) |
| `txn_table.go` | Add `cloneNonNullKeys()` to filter NULLs and break aliasing; clone before `InplaceSort` in `PKPersistedBetween` |

- ❌ `bitmap.RecalculateCount()` — unnecessary once concurrency is fixed
- ❌ `EmptyByFlag` removal from `Nulls.Contains()` — masks deeper issue
- ❌ `Range()` Clone — performance hit on every `Window()` call
- ❌ Varlena fast-path removal from `GetUnionAllFunction` — performance regression
- ❌ `appendOneFixed` TryExpand — hot-path overhead

Tests in `fuzzyCheck_test.go` (27 sub-tests) and `txn_test.go` (32 sub-tests):
- `TestVectorToStringNullHandling` — 13 types including per-row null check
- `TestFirstlyCheckNullValues` — NULL-only, mixed, no-null, all-null batches
- `TestGenCollisionKeysNullHandling` — NULL skip in collision key generation
- `TestCheckPKDupGenericNullHandling` — all fixed-width types + workspace/rawrows
- `TestCheckPKDupNullHandling` — string/array types null skip

| Function | Coverage |
|----------|----------|
| checkPKDupGeneric | 100% |
| checkPKDup | 85.7% |
| vectorToString | 93% |
| firstlyCheck | 78% |
| genCollisionKeys | 80% |

Approved by: @gouhongshen, @aunjgr, @ouyuanning
…ecks (matrixorigin#24373)

Under 1000 concurrent TPCC NEW_ORDER transactions, each `LockOp` triggers `PKPersistedBetween` to verify primary key conflicts. This path loads object metadata, bloom filters, and block PK columns for all changed objects since the transaction's snapshot. With many concurrent writers on the same table (e.g., `stock`), this produces a thundering-herd of block I/O that exhausts mpool capacity → OOM.

```
LockOp.Call → callNonBlocking → doLock → hasNewVersionInRange
→ PKPersistedBetween
→ GetChangedObjsBetween (many objects under high concurrency)
→ ForeachCommittedObjects (load meta + BF for each)
→ LoadColumns for each candidate block (mpool allocation)
```

1000 goroutines × N candidate blocks × ~683KB/block = unbounded peak memory.

**`pkg/vm/engine/disttae/txn_table.go`** — Three mitigations in `PKPersistedBetween`:

| Mechanism | Threshold | Effect |
|-----------|-----------|--------|
| Changed objects cap | 64 | Conservatively return `true` to skip expensive I/O |
| Candidate blocks cap | 32 | Avoid reading too many blocks that passed zonemap + BF |
| Global semaphore | 16 concurrent | Cap peak mpool allocations from `LoadColumns` |

Returning `true` conservatively means the transaction gets a refresh timestamp and re-reads at a newer snapshot — correct RC behavior, just one extra read.

**`pkg/sql/plan/apply_indices.go`** — Extend selectivity guard in `getIndexForNonEquiCond`:

- Previously only `>=/>/<=/< ` (single range ops) were guarded against non-selective secondary index scans on large tables
- Now `in_range` is also guarded, preventing two-sided range conditions from triggering full index table scans

Approved by: @ouyuanning, @XuPeng-SH, @gouhongshen, @aptend, @aunjgr
@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 →

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

Manual review completed on head 70f1ecd. I did not find blocking issues in the NULL duplicate-check fixes or the PKPersistedBetween guard changes. Local package tests could not be run in this environment because an unrelated native dependency header (usearch.h) is missing.

@aptend aptend 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. Backport of two validated fixes from main to 3.0-dev:

  1. NULL unique key false duplicate errors (#24054) — skips NULLs in firstlyCheck, genCollsionKeys, checkPKDup, fixes vectorToString per-row null check, adds dupVectorWithoutNulls for safe InplaceSort
  2. PKPersistedBetween OOM guardrails (#24373) — changed objects cap (64), candidate blocks cap (32), global semaphore (16 concurrent)

plus clean backport adaptations (T_year support, T_enum type fix, test syntax).

Tests cover all modified paths with good null/edge-case/concurrency coverage.

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

Reviewed from multiple angles: this is a clean 3.0-dev backport of the NULL-unique-key fix and the PK check OOM guardrails. The NULL handling changes are correct across fuzzy check / in-batch PK dedup / persisted PK checks, the defensive clone-before-sort fix is in place, and the PKPersistedBetween bailout + semaphore logic is conservative and correctness-safe for RC. Targeted Go tests with -race also passed. Approving.

This branch was previously deployed

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

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants