Skip to content

perf: reduce BigData hidden-ID allocation and ordinary append overhead - #29669

Merged
mergify[bot] merged 4 commits into
matrixorigin:mainfrom
LeftHandCold:fix/bigdata-main-perf-20261007
Oct 7, 2026
Merged

mergify[bot] merged 4 commits into
matrixorigin:mainfrom
LeftHandCold:fix/bigdata-main-perf-20261007

Conversation

@LeftHandCold

@LeftHandCold LeftHandCold commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

  • BUG
  • Improvement
  • Test and CI

Which issue(s) this PR fixes:

Related to #29571 and #29580. These component improvements do not automatically close either issue or establish the complete BigData wall-time target.

What this PR does / why we need it:

Main BigData still spends extra time generating hidden primary keys and appending ordinary CSV values. Reduce those costs at their existing owners. The investigation uses the complete 22-case/340-statement Main run and 4.2 attempt 2.

  • Hidden primary-key allocation: Fix Cartesian DML memory planning and transient statistics reuse #29527 bounds speculative reservations to protect visible AUTO_INCREMENT from huge planner estimates. Bulk fake-PK generation consequently makes frequent allocator requests; private COPY executes allocator metadata SQL repeatedly in its growing transaction workspace. Prefetch now follows successfully assigned actual rows, saturating at 1M, while the initial reservation remains 10k. Qualification requires authoritative hidden fake-PK ownership, default service policy, unit step and default session series. Explicit service/table policies and visible user columns retain their policy. Cold/reset owners obtain the qualification in the existing catalog snapshot.
  • Ordinary append: skip empty metadata preparation/publication only when the existing scalar, sidecar and preflight state proves the operations have no effect. Keep physical data/bitmap admission, borrowed ownership, JSON checks, metadata transitions and failure rollback.
  • Spill regression coverage: retain the codec implementation already merged in perf: improve large-query planning and adaptive memory control #29646 unchanged. Consolidate one BenchmarkSelectedRowsVarlenaDecode with inline/nullable/64B long values, 23/24B boundaries, VECF32/VECF64, account peak and reusable destinations. Preserve all upstream codec tests and the four distinct PR boundary/capacity/invalid-length/borrowed-owner cases. The real MergeGroup consumer still checks spill/reload, exact DISTINCT values and resource release; its fixed test ledger makes forced spill independent of host pressure.

The allocator change directly applies to no-PK writes and DROP-PK COPY that generate fake keys. ADD-PK COPY is a safety control here; its complete performance difference has additional contributors. Existing #26706 locking, #29664 and all main changes are preserved. No regression-runner or BigData coverage changes are included.

Review integration and fresh component comparison

Review 5444104534 is addressed by merging current main and removing this PR's duplicate production decoder rewrite. Both conflicting codec files are reconciled; there is one decoder and one benchmark. The former 72%–74% decoder improvement belongs to the now-merged #29646 and is not incremental evidence for this PR.

Fresh baseline: 3d796acf87081d48cb01449dce2a34d366534b24, including #29646 and #29663. Delivery also integrates ea011906d61dfe2b023993dbbbe2e778459776f8 (#29662); that subsequent frontend catalog lookup change is outside the measured vector/allocator dependency paths. Both benchmark binaries use the exact same fixtures; allocator qualification goes through production GetAutoColumnFromDef with a hidden column in both versions. The baseline overlay restores all six remaining production files to the named main revision and excludes only the new private-field UT when compiling the baseline.

Vector measurements use Go1.27.0, Linux/amd64, GOAMD64=v3, GOEXPERIMENT=simd, the same provenance-checked native build, CPU6, GOMAXPROCS=1 and four alternating pairs at 300ms per workload.

Workload Fresh result versus main
1M actual generated IDs in batches of 8192, private-mode and committed caches 101 → 8 range requests; 1,010,000 → 1,052,192 reserved values, initial reservation 10k
8192 ordinary BIGINT appends 34.16% lower component latency; zero allocations retained
8192 ordinary inline / area VARCHAR appends 15.12% / 17.75% lower component latency; zero allocations retained
8192 NULL BIGINT / VARCHAR appends 12.56% / 9.92% lower component latency; allocation counts unchanged
Prepared / literal / binary-prefix append controls 0.84% lower / 4.56% higher / 1.01% lower component latency
Consolidated main codec control All 18 shape/size cells pass; 3 heap allocations per reusable decode; no additional decoder speedup claimed

The literal-prefix cost is an accepted guard overhead outside the ordinary CSV path. The allocator probe uses an in-memory store: its request/reservation counts are evidence, its timing does not reproduce SQL workspace cost. The historical estimate-prefetch control still reserves 2,000,010,000 values in 3 requests; that policy is not restored. These are component measurements, not a completed billion-row or 8-hour acceptance run.

Validation after integration

  • Complete owning/consumer packages pass: vector, incrservice, group and mergeutil (669 top-level tests, all passed). The later frontend-only main commit leaves their tested source/dependency paths unchanged.
  • Complete vector/incrservice/group packages pass under race on integrated head 6537884aa4c5b936863f289fe20af43ce91d85f4.
  • Real authenticated two-CN TestBigDataBulkWriteAndPrimaryKeyCopyPreserveRows passes in 9.00s: 32,768 rows, cold catalog lookup, ADD/DROP PK COPY, exact values/NULLs/vector payloads, duplicate COPY rejection with continued writes, and visible fake-PK-name user control.
  • Existing TestIssue29602IndexBackfillLocksStayScopedToPrivateTargets passes in 0.28s, preserving fix(lock): preserve bounded ranges for large DML batches #26706 cross-CN row locks, uniqueness rejection, rollback and release.
  • Bulk-demand tests cover 2M IDs in private and committed CREATE owners, explicit config/table/session/step opt-outs, failure, terminal uint64, cold rebuild and cross-CN uniqueness. Existing estimate-gap protections remain and pass.
  • Real accounted MergeGroup VECF32/F64 spill/reload checks exact DISTINCT values, NULL and terminal memory/disk/FD release. All upstream codec UTs plus PR boundary, exact-capacity/one-byte-short, borrowed-owner and failed-decode reuse checks pass.
  • Fresh paired append measurements, both allocator count probes and all 18 consolidated codec benchmark cells reach PASS. Three independent focused source reviews have no remaining blocker.
  • vet=all for the five affected/consumer packages passes. Repository-config incremental golangci-lint v2.14.0 (Go1.27) reports zero issues; gofmt and final diff checks pass.

The original-head CI was green before main integration. Its result is historical evidence; the updated head requires its new CI checks before merge.

Commands, with the repository native prerequisites built:

GOAMD64=v3 GOEXPERIMENT=simd .agents/skills/mo-dev/scripts/mo-cgo-test \
  -count=1 -timeout=180s ./pkg/container/vector ./pkg/incrservice \
  ./pkg/sql/colexec/group ./pkg/objectio/mergeutil
GOAMD64=v3 GOEXPERIMENT=simd .agents/skills/mo-dev/scripts/mo-cgo-test \
  -race -count=1 -timeout=180s ./pkg/container/vector ./pkg/incrservice ./pkg/sql/colexec/group
GOAMD64=v3 GOEXPERIMENT=simd .agents/skills/mo-dev/scripts/mo-cgo-test \
  -count=1 -timeout=300s \
  -run '^(TestBigDataBulkWriteAndPrimaryKeyCopyPreserveRows|TestIssue29602IndexBackfillLocksStayScopedToPrivateTargets)$' \
  ./pkg/tests/issues
GOAMD64=v3 GOEXPERIMENT=simd .agents/skills/mo-dev/scripts/mo-cgo-test \
  -run '^$' -bench '^BenchmarkAutoIDCacheBulkAllocationRequests$' -benchtime=1x ./pkg/incrservice

Limits and follow-up acceptance

Successful assignment demand is not committed-row count; later SQL/transaction failure need not undo it. The adaptive asynchronous span is bounded; synchronous real-batch/concurrency demand retains its existing policy. Qualification adds one catalog aggregate to cold GetColumns, including visible-user tables, rather than each allocation. Frozen BigData YAML and the inspected operator configuration pipeline contain no explicit cache count; the installed Pod TOML was not retrieved. Verify actual activation and remaining critical-path time in the next complete BigData run before claiming end-to-end recovery.

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

Deep review of 865fdbe2559fdaa6a203b0ea4c4a818146e8af8b, against merge-base d0d7869e714c29eac53cebf95b959ae8deceaef6; latest main independently verified as 3d796acf87081d48cb01449dce2a34d366534b24. No subagents used.

Decision: REQUEST_CHANGES for one integration/validation blocker described inline. I did not find an additional demonstrated wrong-result, uniqueness, leak, or new deadlock defect in this head. The blocker is not a claim that the current head's green CI failed.

Design assessment:

  • The allocation change stays in the existing column-cache/allocator ownership. Successful assignment demand is counted under the column mutex and saturates at 1M. Initial reservation, explicit service/table policies, visible user columns (including the fake-PK spelling), non-unit steps and non-default session series retain their controls. Cold/RESET ownership is resolved from the catalog in the same metadata snapshot. Larger ranges contain numeric endpoints, not per-ID storage. Existing callback, retirement and timeout owners remain in place.
  • Ordinary append elides metadata work only when the relevant representations are ordinary. Data/bitmap admission, nonordinary sidecars, borrowed backing, JSON validation and append rollback still have their existing owners. The length-only publication shortcut is equivalent to the original publication helper when both row sidecars are absent.
  • Selected-row decode admits descriptor capacity before direct writes, grows area through the existing allocation account, and retains error reset/JSON/length/metadata checks. Its writer format is unchanged. However, the principal optimization is now also present in main via #29646.
  • This is focused component optimization, not a new subsystem or major architectural refactor; a separate design-document gate is not needed. Production delta is +131/-78 lines; test/benchmark delta is +1084/0; no documentation file is added. I reviewed both deltas. The integration test reuses the existing two-CN fixture; the new cases mostly prove distinct qualification, capacity, representation and consumer boundaries.

Verification:

  • Reused exact-head CI run 37622701588, including successful race UT, SCA and substantive BVT jobs. Inspected the UT job log and summary: TestBigDataBulkWriteAndPrimaryKeyCopyPreserveRows actually ran and passed in 9.81s, including cold-CN insert, ADD/DROP PK COPY, duplicate rejection and subsequent writes.
  • Independently built matching native prerequisites and ran 34 focused tests in incrservice/vector on Go 1.27.0, Darwin/arm64: all passed, exit 0. Selection includes qualification, partial failure/terminal uint64, cold reload, borrowed destination, exact/short allocation capacity, metadata, truncated wire, JSON rejection and append rollback controls.
  • TestAccountedMergeGroupVectorDistinctSpillConsumer passed for VECF32/VECF64 (0.03s test body), including real spill reload and terminal memory/disk/FD checks.
  • Cross-CN/cold-reload test passed under race, then passed -race -count=93 in one process (29.053s package elapsed; repetition derived from a 0.32s measured test).
  • Counted bulk probe independently produced 8 requests and 1,052,192 reserved values for 1M generated IDs in both private and committed modes. This validates request amplification, not SQL workspace timing or end-to-end BigData speedup. The 2M-row correctness test took 0.26s across its two ownership subtests locally.
  • git diff --check passed. The review worktree has no tracked/untracked source changes.

Q1/Q2/Q3 summary:

Closure Ownership/cleanup Wait termination Growth bound
ID prefetch existing cache and allocator callback owners existing context/allocator timeout paths retained demand counter and speculative span capped; existing range ownership
Append/decode vector/account owns admitted backing; error reset and eventual Free retained no new asynchronous wait existing account and varlena area limits retained

There were no earlier human reviews or inline review threads to resolve; the only existing issue comment was the Qodo service notice. Data/wire compatibility was considered; mixed-version rollout was not required by the requested scope.

Before approval, resolve the overlapping implementation and benchmark with current main, then validate only the affected integrated closure and report the remaining incremental performance benefit. A new full billion-row run is not required to establish these component changes; the PR correctly does not claim completion of the overall BigData target.

Comment thread pkg/container/vector/selection_codec.go Resolved
@LeftHandCold
LeftHandCold requested a review from XuPeng-SH October 7, 2026 16:19
@LeftHandCold LeftHandCold changed the title perf: reduce BigData hidden-ID allocation and vector overhead perf: reduce BigData hidden-ID allocation and ordinary append overhead Oct 7, 2026

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

Deep re-review of 6537884aa4c5b936863f289fe20af43ce91d85f4 against freshly verified main/merge-base ea011906d61dfe2b023993dbbbe2e778459776f8. Reviewed the complete remaining diff and the integration changes. No subagents used.

APPROVE: no remaining blocking finding in the reviewed scope.

Previous review closure

The sole previous request in review 5444104534 is addressed in source, not merely marked resolved: selection_codec.go is identical to current main, including #29646's writer and decoder optimizations. There is one consolidated BenchmarkSelectedRowsVarlenaDecode; nullable/long-value controls, upstream byte-format and failed-decode reuse tests are retained. The duplicate production decoder rewrite is removed. The updated description attributes the former 72–74% decoder improvement to #29646, names a fresh main baseline, and makes no additional decoder speedup claim. GitHub reports MERGEABLE. There are no other historical human review findings to close.

Design and adversarial review

  • Hidden-ID allocation (R3): the existing column cache remains the demand owner, with updates under its mutex after successful assignments. The counter saturates at 1M; a fresh owner has no old demand history. Qualification requires authoritative hidden fake-PK ownership, unit step, default service/table/session policy. Explicit configuration, visible user columns including the same spelling, non-default session series and demand-only policy preserve their controls. CREATE derives ownership from the table definition; cold/RESET reads it from the catalog in the same snapshot, using the replacement physical table for RESET. No extra persistent metadata, allocator worker or lifecycle is introduced. Cross-CN uniqueness still belongs to the existing store reservation protocol.
  • Append fast path (R3, hot path): the guard excludes prepared/string-source sidecars, scalar nonordinary provenance, active binary metadata and pending source preflight. Compared the skipped preparation/publication with the unchanged source-aware and full preparation paths: with both row sidecars absent, the ordinary publication helper only changes length. Data/bitmap admission, borrowed materialization, JSON validation and error rollback retain their existing owners. Adjacent tests cover scalar-to-mixed transitions, ownerless/NULL prefixes, allocation refusal, payload failure, rollback and preflight retention.
  • Codec/consumer tests (R2): production codec now has no PR delta. The added cases prove inline/area and array boundaries, exact/insufficient account capacity, failed-decode reuse, invalid framing and borrowed producer isolation. The real partial Group -> MergeGroup consumer checks exact DISTINCT values/NULL, actual spill reload, and memory/disk/FD release. Its fixed budget isolates forced spill from host pressure. Existing catalog/public SQL fixtures are reused.
  • Q1/Q2/Q3: no new cleanup owner or wait is introduced. Existing allocator callbacks complete reservations; waiters release the column lock while waiting and retain cancellation/error handling; retirement blocks new prefetch. Demand growth and adaptive speculative span are bounded, with ranges storing endpoints rather than one heap object per ID. Vector and Group teardown retain their existing account/lease/generation owners. The 1M bound applies to the adaptive speculative policy, not arbitrary synchronous batch/concurrency demand.

The focused optimization is exempt from a separate feature-design document. Production delta is +76/-16; tests/benchmarks +1101/-28; no documentation files are added. I reviewed these separately. The larger test delta exercises distinct ownership/policy/public-consumer boundaries and reuses fixtures; it does not add a new testing framework. The 2M-ID correctness test across its two modes took 0.26s locally, and the real Group spill test took 0.03s. Wire/catalog data formats are unchanged. Mixed-version rollout was outside the requested scope.

Validation on this head

Independently ran with Go 1.27.0, Darwin/arm64, matching native prerequisites through mo-cgo-test; all commands reached exit 0:

  • Normal complete packages: vector, incrservice, group, mergeutil — 669 top-level tests passed.
  • Complete race packages: vector, incrservice, group — 656 top-level tests passed; package elapsed 7.388s / 8.487s / 18.534s.
  • One-iteration functional/count probes: all 18 consolidated codec cells and all 8 append controls passed. Codec retained 3 heap allocations per warmed decode. Both allocator ownership modes produced 8 requests and 1,052,192 reserved values for 1M generated IDs. These one-iteration runs are not latency comparisons.
  • git diff --check passed; isolated review checkout remains source-clean.

Reused the author's reported integrated public-path validation (two-CN bulk/COPY test 9.00s, scoped index-backfill locking control 0.28s) and incremental vet/lint result, with exact test/revision/mode recorded in the PR. Earlier independent race stress remains supporting evidence for the unchanged allocator path. The new complete package/race runs above validate the changed integration.

Performance and limits

The author's paired Linux measurements against main containing #29646/#29663 report 101 -> 8 allocator requests, ordinary BIGINT append latency -34.16%, and ordinary VARCHAR append -15.12%/-17.75%; I inspected the shared production-qualified benchmark fixture but did not independently repeat those Linux timing pairs. The count reduction is independently reproduced above. The reported literal-prefix +4.56% guard cost and one extra catalog aggregate per cold GetColumns are documented tradeoffs. Successful assignment demand is not committed-row count, and cold reload discards demand history. No end-to-end BigData wall-time or issue-closure claim follows from these component measurements.

At submission preparation, current-head CI run 37651036154 still has UT/SCA/coverage/BVT work in progress and no reported failed checks. This approval records the completed code review and local evidence; CI must still complete before merge.

@mergify

mergify Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-07 17:32 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-10-07 17:33 UTC · at f20f5ca147c44b012343d0f48dfcd84b6a5986a1 · squash

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

Required conditions to merge

@mergify
mergify Bot merged commit f20f5ca into matrixorigin:main Oct 7, 2026
@mergify mergify Bot removed the queued label Oct 7, 2026
XuPeng-SH added a commit that referenced this pull request Oct 16, 2026
….2-dev] (#30005)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue #29903

## What this PR does / why we need it:

Backport of #29903 to `4.2-dev` (companion to #30004 on `main`).

A `FULLTEXT` index carries a hidden `auto_increment` fake primary key
(`__mo_fake_pk_col`) on its index table. When an `INSERT` into the base
table synchronously populates the index, the index table's `PRE_INSERT`
generates that fake key and the preinsert operator published it into the
session `LAST_INSERT_ID`, so `LAST_INSERT_ID()` returned a hidden index
value instead of the base table's business key. On `4.2-dev` the publish
is unconditional (`SetLastInsertID`), so the index value simply
overwrites the base key.

**Fix.** Port of the minimal core of `main`'s design (main's own #29903
commit is a 12-line change that relies on three earlier main PRs not on
`4.2-dev`: #27315, #28528, #29669). Names and shape follow `main` so
later backports apply cleanly.

- **Hidden-key ownership** (`pkg/incrservice`): `AutoColumn.isInternal`
marks the allocator-owned hidden fake primary key, from the table
definition on create and from a hidden-column check against `mo_columns`
on load. A user-visible column that happens to be named
`__mo_fake_pk_col` still publishes. `InsertValues` reports the first
generated value of a non-internal column.
- **Reset after DELETE-to-truncate**: `Reset` reads allocator offsets
from the old table but ownership from the replacement
(`autoColumnPolicyTableKey`), since the truncate has already deleted the
old table's `mo_columns` rows.
- **Statement insert id** (`Base.StatementLastInsertID`): the OK-packet
`insert_id` reports only the value the statement generated;
`LastInsertID` keeps the session value for `LAST_INSERT_ID()`. Cleared
before each statement, and on a compile retry, which also restores the
`LAST_INSERT_ID` the statement started with. `PRE_INSERT` publishes only
a generated (non-zero) value, so a hidden index table never clobbers the
base table's value.
- **Parallel publication**: the parallel `PRE_INSERT` scopes of one
statement share the process state. They publish through
`SetStatementLastInsertIDIfLater`, which writes `StatementLastInsertID`
and `LastInsertID` together under one mutex and keeps the largest value
since the per-statement reset, so the OK packet and the next statement's
`LAST_INSERT_ID()` agree. On `4.2-dev` the allocator reports each
batch's last generated value, so the largest value is the statement's
last generated id, the value a serial scope already reported.

**Tests.**
- Client level: `TestIssue29903InsertIDOkPacket` (embedded cluster,
`database/sql`): OK-packet `insert_id` and `LAST_INSERT_ID()` for an
explicit id after a generated one, a fulltext-indexed table, and
DELETE-to-truncate then explicit insert.
`TestIssue29903RetryKeepsEarlierStatementLastInsertID`: another session
holds an uncommitted delete of row 100, so the explicit-id `insert into
t2 values (100, …)` of a multi-statement COM_QUERY waits on the row lock
and is retried after the holder commits. The OK packets are `[1, 0]`,
and `select last_insert_id()` later in the same COM_QUERY returns the
earlier statement's id (with the old restore it returns the value at the
start of the COM_QUERY).
- Unit: `TestInsertValuesExcludesInternalFakePKFromLastInsertID`,
`TestInsertValuesReportsFirstGeneratedUserColumn`,
`TestResetResolvesFakePKOwnershipFromReplacementTable`,
`TestSQLStoreGetColumnsMarksInternalFakePK`,
`TestSQLStoreGetColumnsOwnershipFromReplacementTable`,
`TestRetryRestoresStatementStartLastInsertID`,
`TestSetStatementLastInsertIDIfLater`,
`TestParallelScopesPublishOneLastInsertID` (`-race`). The client, reset
and retry regressions each fail with their fix reverted.
- End to end: a 2M-row `INSERT ... SELECT` (parallel `PRE_INSERT`)
followed by `SELECT LAST_INSERT_ID()` in one COM_QUERY returns `max(id)`
for both the OK packet and the function, over three runs.
- BVT: `auto_increment/auto_increment.result` expects 10 (the generated
user value) where it expected the hidden key 12;
`auto_increment/last_insert_id_hidden_pk` (adds the truncate-reset
case), `fulltext/fulltext_last_insert_id`, and the `auto_increment`
suite at 100%.

**Out of scope.**
- `LAST_INSERT_ID()` after a multi-row insert returns the last generated
value on `4.2-dev` (MySQL returns the first); `main` fixed this in
#27315 with a statement-level coordinator plus a protocol gate.
- REPLACE and LOAD DATA do not report their generated id in the OK
packet, as on the merge-base; `main` added REPLACE in #27315.
- Remote propagation of the statement insert id across CNs, as on the
merge-base.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: XuPeng-SH <[email protected]>

This branch was previously deployed

1 inactive deployment
ci — 6537884a Deployed Oct 7, 2026 by mergify[bot]
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 kind/enhancement kind/test-ci size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants