Skip to content

perf(colexec,vector): gather and scatter varlena by mask without copying the area (#33457) - #33459

Merged
fengttt merged 11 commits into
matrixorigin:mainfrom
fengttt:perf/varlena-borrow-area
Nov 30, 2026
Merged

fengttt merged 11 commits into
matrixorigin:mainfrom
fengttt:perf/varlena-borrow-area

Conversation

@fengttt

@fengttt fengttt commented Nov 29, 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:

issue #33457 (subtask of #33181)

Follows #33272, now merged. The diff against main holds only this PR's three commits: db22ed69a0 (area borrowing), 5f484ee0cc and 8113b054f8 (bounds-check elimination), across 8 files in pkg/container/vector and pkg/sql/colexec.

What this PR does / why we need it:

When a selection covers only some rows, the expression executor (FunctionExpressionExecutor.evalSelectedRows) evaluates a function in three steps:

  1. It gathers the selected rows of each argument into a compact vector.
  2. It calls the kernel on the compact vectors.
  3. It scatters the compact result back to the selected row positions.

A variable-length value longer than 23 bytes lives in the vector's area, and its 24-byte descriptor holds the value's offset there. Before this PR:

  • The gather copied each selected payload into a new area and rewrote its descriptor. That meant reading every selected descriptor whenever the source had an area.
  • The scatter went a row at a time, with a UnionOne per selected row and a NULL append per unselected row. It decoded and re-encoded every descriptor, even for short inline strings.

Neither copy is needed in this one place:

  • A compact argument is read only during one kernel call, while its source is unchanged.
  • The compact result is not needed after the scatter.

Changes

  • vector.AreaBorrowingGather
    • Copies the selected descriptors and NULLs unchanged into storage it owns.
    • Returns a read-only vector (mp == nil) over those descriptors and the source's area.
    • Copies no payload and rewrites no offset. Its descriptor storage is never exposed except through that view.
  • Vector.ScatterByMaskTakingArea
    • Scatters only the descriptors and moves the compact result's area into the result.
    • Both vectors must be owned and from the same pool. The compact result is left empty, holding the result's old area as spare capacity.
    • Unselected and NULL rows get zeroed descriptors, so no stale offset is left.
    • Any other case falls back to ScatterByMask.
  • Executor: evalSelectedRows uses the gather for variable-length, non-constant arguments, and the scatter for the result. The gathers are freed in the executor's Free.
  • Refactor: the inline-only descriptor gather in unionVarlenByMask is extracted as gatherVarlenaDescriptorsByMask and shared.

Ownership

  • The borrowed state is confined to evalSelectedRows.
  • UnionByMask and ScatterByMask are unchanged. Their other callers (batch, filter, table_scan, blockio) still get independently owned copies.
  • The Vector struct is unchanged. The view is an ordinary read-only vector.
  • Kernel audit: no kernel in pkg/sql/plan/function keeps or returns its argument vector; there is no SetResultVector there. The kernels that read GetArea() directly (builtInHash, tryReserveAssignedText, cast overlap checks) only read through descriptors, so a borrowed area that also holds unselected rows is correct. At worst they size a buffer from the larger area.

Benchmark

BenchmarkEvalSelectionVarlen (new): one 8192-row varchar batch, every 7th row NULL, 16/64/256-byte values. Medians of 6 alternating runs, base = #33272 head, Apple M2 Max, spread ≤ 8%. Times in µs.

case all 90% half tenth
length(s) w16 23.0 → 23.0 77.2 → 77.2 57.4 → 57.3 14.3 → 14.3
length(s) w64 35.0 → 35.0 132.7 → 88.3 (−33%) 90.6 → 64.3 (−29%) 21.9 → 15.9 (−27%)
length(s) w256 35.1 → 35.0 167.3 → 88.2 (−47%) 111.3 → 64.2 (−42%) 26.7 → 16.0 (−40%)
upper(s) w16 303 → 302 434 → 332 (−24%) 335 → 212 (−37%) 170 → 49 (−71%)
upper(s) w64 720 → 720 888 → 713 (−20%) 595 → 426 (−28%) 224 → 95 (−58%)
upper(s) w256 2402 → 2448 (+2%, noise) 2484 → 2274 (−8%) 1494 → 1309 (−12%) 409 → 276 (−33%)
concat(s, s) w16 308 → 309 475 → 352 (−26%) 360 → 225 (−37%) 175 → 52 (−70%)
concat(s, s) w64 364 → 365 632 → 404 (−36%) 449 → 253 (−43%) 195 → 58 (−70%)
concat(s, s) w256 423 → 424 836 → 460 (−45%) 559 → 287 (−49%) 218 → 65 (−70%)
  • all is unchanged by design. A full selection never gathers or scatters.
  • length at w16 has a fixed-width result, and its inline-only source already took the header-only gather path, so it is unchanged.
  • Inline strings still gain on a string result. upper and concat at w16 gain 24–71% because of the scatter: the old one re-encoded every row even when all values were inline.
  • Allocations are unchanged. What remains comes from the kernels.

Bounds-check elimination in the mask gather and scatter (5f484ee0cc, 8113b054f8)

Go doesn't vectorize these loops. On arm64 the per-row gather and scatter compiled to scalar moves plus a bounds check on every row copied.

  • Words with 8 or more selected rows: the loops read and write through a 64-row array view ((*[64]T)) indexed by TrailingZeros & 63, and range over a destination slice of exactly the selected rows. -d=ssa/check_bce shows no per-row checks left in these loops, only per-word slicing and the partial last word. Words of 8–15 rows use one check-free loop; the run and two-chain paths still start at 16 rows.
  • Words with fewer than 8 rows: these keep the original loop, and their test comes first so it costs one comparison. Setting up the views costs two checks per word, more than one or two rows save.
  • Choosing the cutoff: using the views for every word was up to 41% slower on 2% selections. A cutoff of 16 lost no sparse case but missed the medium-density gains. Cutoffs of 8 and 4 measured the same on dense words; 4 cost 3–5% more on the sparsest gathers. The cutoff is the constant maskViewMinRows.

The table compares against db22ed69a0, using BenchmarkMaskScatter (new) and the existing gather and selection benchmarks. Times are ns/op, medians of 5 alternating runs. It lists every case that moved at least 4%; across all the mask cases, none is more than 2% slower.

case before after Δ
MaskGather int64 14% / 50% 764 / 2475 683 / 2370 −11% / −4%
MaskGather int32 14% 1777 1664 −6%
MaskGather varchar10 14% / 50% / 90% 1641 / 4716 / 6787 1500 / 4333 / 6486 −9% / −8% / −4%
MaskGatherByCount int64, 1024 / 4096 scattered 676 / 2491 607 / 2380 −10% / −4%
MaskGatherByCount varchar, 4096 scattered 4803 4323 −10%
MaskScatter int64 50% / 90% 27216 / 30615 25856 / 28467 −5% / −7%
MaskScatter varchar 50% / 90% 43368 / 39219 40551 / 36971 −6% / −6%
UnionByMask 2544 2405 −5%
EvalSelection COALESCE, half selected 52196 49460 −5%
Sparse (2%, 1–256 scattered rows) and contiguous runs — — within ±2%

TestMaskGatherScatterWordShapes (new) checks gather and scatter for 1-, 2-, 4-, 8-, 16- and 24-byte elements against a row-at-a-time oracle. It covers empty, full, sparse, run and dense scattered words, with a full or partial last word.

l last word.

End to end

This PR's head was compared with main at 3d3f579edf. The PR build also contained #33272, which has since merged. Builds ran alternately, on one Apple M2 Max.

  • TPC-H SF10: freshly loaded and flushed; each query's median over 6 passes per build. The 22 queries total 7,230 ms on main and 7,178 ms with the PR (−0.7%), with identical results for every query. Only Q11 (−5.8%) and Q18 (−2.9%) moved beyond the run-to-run range; no query is reliably slower. TPC-H filters mostly feed joins and aggregations over fixed-width columns, so this shows the change is neutral there; it doesn't measure the gains.
  • sysbench: 10 × 100k rows, 16 threads, 60 s per workload. Point select, random points and ranges, read-only, read-write and update-index are all within ±6%, with no consistent direction except oltp_update_index at +5–6% in both pairs. A single run per pair can't resolve differences that small.

Tests

  • TestAreaBorrowingGatherMatchesUnionByMask
    • Compares the gather with UnionByMask over random lengths, NULL rates and densities, with inline and out-of-line values.
    • Includes window sources and masks shorter and longer than the source.
    • Checks that the view is read-only, the source is unchanged, and only descriptors and NULLs are allocated.
  • TestAreaBorrowingGatherRejectsConstAndFixed.
  • TestScatterByMaskTakingAreaMatchesScatterByMask
    • Compares with ScatterByMask, using a reused result vector.
    • Checks that the source is consumed and that NULL descriptors are zero.
    • Covers the fallbacks: a non-empty destination, a constant source, a source from another pool.
  • TestEvalSelectionVarlenMatchesFullEvaluation
    • length, upper, concat and a nested concat(upper(b), lower(concat(a, a))), under random selections.
    • The same executors run over batches of different sizes, so scratch reuse and a borrowed argument that is itself a scattered result are covered.
    • Selected rows must equal a full evaluation; the others must be NULL.

Validation:

🤖 Generated with Claude Code

fengttt and others added 4 commits November 29, 2026 09:54
…PR 6)

Vector.Shrink(sels, negate), Batch.Shrink and the negate form of
nulls.FilterInPlaceOrdered are removed. Callers that built a delete list or
a selection one row at a time now fill a bitmap and use ShrinkByMask:
TAE containers (Compact, sorted dedup), the GC executor, logtail backup,
disttae deleteBatch / workspace shrink / object rewrite (CopyBlockData
takes a mask), logtail replay filters, readutil PK IN normalization,
IVF-FLAT relation filters (now return ReaderFilterResult.Mask) and
data_branch_hashdiff (one list-to-mask conversion; the LCA probe no longer
relies on ORDER BY).

A keep-only Vector.ShrinkByRows remains for rows that arrive as a list
(storage search, membership, TopN); PR 7 folds it into the RemapList gather.
The nulls Gobra proof re-verifies with the narrower contract.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since PR 4 the expression executor calls a kernel only when every row is
selected, passing one constant all-rows list. The kernels' masking paths
were dead. Remove them, the FunctionSelectList type and the kernel
parameter: a function implementation is now
func(parameters, result, proc, length) error.

The change was made mechanically: every check was folded with the value the
executor passes (non-nil, nothing masked), then the parameter and its call
arguments were dropped. Row-skip helpers that became constant were inlined
and deleted. Constant folding and zone-map evaluation passed a nil list;
folding the original both ways finds one kernel that differed for nil
(string equality's compareVarlenaEqual header path), which is deleted so
folding takes the same path as execution.

Tests whose subject was masked or all-NULL selections are removed with the
code they tested; mixed tests keep their unmasked cases, and tests whose
mask hid an invalid row now use a NULL row instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ing the area (matrixorigin#33457)

A selected-row evaluation gathers the selected rows of each argument,
calls the kernel on them, and scatters the compact result back. For
variable-length values both steps copied the out-of-line payload and
rewrote its offset, and the scatter went a row at a time.

Neither copy is needed there. A compact argument lives for one kernel
call while its source is unchanged, and the compact result is dead once
scattered:

- vector.AreaBorrowingGather copies the selected descriptors unchanged
  and returns a read-only view over them and the source's area.
- Vector.ScatterByMaskTakingArea scatters only the descriptors and
  moves the compact result's area into the result (same pool, both
  owned); it falls back to ScatterByMask otherwise.

Both are used only by FunctionExpressionExecutor.evalSelectedRows.
UnionByMask and ScatterByMask, which other callers rely on for owned
copies, are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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 →

@matrix-meow matrix-meow added the size/L Denotes a PR that changes [500,999] lines label Nov 29, 2026
@mergify

mergify Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@XuPeng-SH

XuPeng-SH commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 1efb7127e2a62a8147ae4ea019822d7d70caeec8

PR head changed during fetch

The array-view loops now start at 8 selected rows per word, not 16, with
the cutoff in one constant (maskViewMinRows). A word of 8 to 15 rows uses
a check-free single loop; the run and two-chain paths still start at 16.
The sparsest test comes first, so a word of fewer than 8 rows still costs
one comparison.

Against cutoff 16 (medians of 5 alternating runs): int64 gather at 14%
-10%, 1024 scattered int64 rows -10%, int32 at 14% -5%; every sparse,
run and dense case within noise. Cutoffs of 8 and 4 measured the same on
the dense side; 4 cost more on the sparsest gathers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-area

# Conflicts:
#	pkg/sql/plan/function/func_cast_integer_assignment.go
@fengttt
fengttt marked this pull request as ready for review November 29, 2026 22:34
@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 Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 89d238a6c1bb9634e321d57f5d37f76edeeada12

"interrupted"

This branch was successfully deployed

No deployments
ci — 89d238a6 Deployed Nov 30, 2026 by fengttt via Matrixone Utils CI / pr-size-label #66935
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/enhancement size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants