Repository navigation
perf: reduce BigData hidden-ID allocation and ordinary append overhead - #29669
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
XuPeng-SH
left a comment
There was a problem hiding this comment.
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:
TestBigDataBulkWriteAndPrimaryKeyCopyPreserveRowsactually 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.
TestAccountedMergeGroupVectorDistinctSpillConsumerpassed 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=93in 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 --checkpassed. 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.
XuPeng-SH
left a comment
There was a problem hiding this comment.
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 --checkpassed; 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.
Merge Queue Status
This pull request spent 25 seconds in the queue, including 2 seconds running CI. Required conditions to merge
|
….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]>
What type of PR is this?
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.
BenchmarkSelectedRowsVarlenaDecodewith 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 integratesea011906d61dfe2b023993dbbbe2e778459776f8(#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 productionGetAutoColumnFromDefwith 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.
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
6537884aa4c5b936863f289fe20af43ce91d85f4.TestBigDataBulkWriteAndPrimaryKeyCopyPreserveRowspasses 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.TestIssue29602IndexBackfillLocksStayScopedToPrivateTargetspasses in 0.28s, preserving fix(lock): preserve bounded ranges for large DML batches #26706 cross-CN row locks, uniqueness rejection, rollback and release.vet=allfor 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:
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.