Skip to content

refactor(vector,function): remove the row-list Shrink and FunctionSelectList (#33181 PR 6 + 6b) - #33272

Merged
fengttt merged 5 commits into
matrixorigin:mainfrom
fengttt:sels-bitmap-33181-pr6b
Nov 29, 2026
Merged

fengttt merged 5 commits into
matrixorigin:mainfrom
fengttt:sels-bitmap-33181-pr6b

Conversation

@fengttt

@fengttt fengttt commented Nov 26, 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 #33181

What this PR does / why we need it:

PR 6 and PR 6b of the row-selection plan in docs/design/20261124-row-selection-bitmap-remaplist.md, on current main:

  1. PR 6 removes the row-list shrink APIs and converts their remaining callers to selection bitmaps. This was refactor(vector,batch): remove the row-list Shrink (#33181 PR 6) #33271, which is closed in favor of this PR.
  2. PR 6b removes FunctionSelectList, the kernels' masking paths and the kernel parameter.

PR 6: remove the row-list Shrink

API changes

  • Vector.Shrink(sels, negate) is removed. Callers whose rows are already an ascending list use the new keep-only Vector.ShrinkByRows(sels, mp). These are storage search and membership results, TopN winners, and table_scan's runtime-filter membership. PR 7 folds it into the RemapList gather. The type-ops table's shrink entry loses its negate form with it.
  • Batch.Shrink is removed.
  • nulls.FilterInPlaceOrdered loses its negate form. The Gobra contract is narrowed to match, and the nulls proof still verifies.

Callers converted to bitmaps

Each of these built a delete list or a selection one row at a time.

  • TAE
    • The GC executor. It already held a bitmap and turned it into a list twice.
    • The logtail backup reader's visible rows and tombstone ranges (new removeRowRange).
    • blockio.CopyBlockData now takes the deletes as a bitmap.
  • disttae
    • deleteBatch.
    • The workspace entry shrink. Its offsets can be unordered and repeat, and the mask takes each row once, so the sort and dedup are gone.
    • The object rewrite. Its mask is sized by the largest deleted row, because no block metadata is loaded there. Upstream's merged tombstone offsets go into the same mask.
  • Logtail replay: all four filters in change_handle.go.
  • readutil: the primary-key IN filter drops NULL rows by mask.
  • IVF-FLAT: the relation filters return a Mask result. Blockio already checks and consumes that form.
  • Data-branch diff and clear: their row lists become a mask once (new shrinkBatchByRowList). As a result, the LCA probe no longer depends on ORDER BY returning rows in ascending order.
  • Publication: the snapshot-visibility filter builds one delete mask for all columns.

PR 6b: remove FunctionSelectList

Since PR 4, the expression executor calls a kernel only when every row is selected (partial selections are gathered, evaluated and scattered by mask), and always passes one constant all-rows list. The kernels' masking code was therefore unreachable. A function implementation is now func(parameters, result, proc, length) error and evaluates every row it is given.

How

The change is mechanical, made with two throwaway AST rewriters:

  1. Fold. Every selection check was replaced with the value the executor passes (non-nil, nothing masked) and simplified until nothing changed. This removed the masking branches and loops.
  2. Drop. Using type information, the parameter was removed from every signature and the argument from every call.

Row-skip helpers that became constant were inlined and deleted, among them functionRowSkipped, maskUnselectedRows and applyFunctionSelection. Comments that described masking were updated.

One behavior change

Constant folding and zone-map evaluation passed a nil list, not the all-rows one. Folding the original code both ways and comparing finds exactly one kernel that behaved differently for nil. String equality took a header-compare fast path (compareVarlenaEqual) only for nil callers, never during execution. It is deleted, so folding now takes the same path as execution.

Rebase onto main

The branch is rebuilt on main after PR 5 (#33267) merged, so the diff holds only these two changes. Where upstream changed the same code, its version is kept:

  • Vector.ShrinkByRows is built on upstream's type-ops table and keeps its T_any (all-NULL) handling.
  • The TAE vector wrapper is gone upstream, so its Compact change no longer applies.
  • POW keeps upstream's NULL result for a negative base with a fractional exponent, and the legacy overload 0 keeps its error.
  • <> keeps upstream's geometry and BIT cases.
  • Upstream tests whose only subject was a FunctionSelectList mask (TestGeometryNotEqualSelectedRows, two POW legacy subtests, a geometry inline-mask block) are removed. Their unmasked assertions are covered by the neighbouring cases.

Tests

  • New in PR 6: TestShrinkBatchByRowList and TestRemoveRowRange.
  • PR 6b removes about 60 test functions whose only subject was masked or all-NULL selections, with the code they tested. Masked cases inside mixed tests are removed, and the unmasked cases stay. Where a mask hid an invalid input row, the test now uses a NULL row and keeps its assertions.
  • go build ./... and go vet -tags matrixone_test ./pkg/... pass. Unit tests pass for every package changed by the two commits.
  • Nulls Gobra proof: 0 errors on PR 6 before the rebase. The rebase brings in only upstream's own changes to nulls and bitmap.
  • Execution already took the all-rows path, so no performance change is expected.

🤖 Generated with Claude Code

@mergify mergify Bot added the kind/refactor Code refactor label Nov 26, 2026
@matrix-meow matrix-meow added the size/XXL Denotes a PR that changes 2000+ lines label Nov 26, 2026
fengttt and others added 3 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]>
@fengttt
fengttt force-pushed the sels-bitmap-33181-pr6b branch from 9fd640e to 52bf86e Compare November 29, 2026 18:02
@fengttt fengttt changed the title refactor(function): remove FunctionSelectList (#33181 PR 6b) refactor(vector,function): remove the row-list Shrink and FunctionSelectList (#33181 PR 6 + 6b) Nov 29, 2026
@fengttt
fengttt marked this pull request as ready for review November 29, 2026 18:02
@fengttt
fengttt merged commit 99d7502 into matrixorigin:main Nov 29, 2026
5 of 7 checks passed
fengttt added a commit that referenced this pull request Nov 30, 2026
)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue #33181

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

PR 7 of the row-selection plan in
`docs/design/20261124-row-selection-bitmap-remaplist.md`: the RemapList
type and one gather kernel. It is one commit on current main, after PR 6
+ 6b (#33272) merged.

- **`pkg/common/remaplist.List`**: an mpool-owned list of `int64` source
rows with `Init`, `Free`, `Reset`, `Identity`, `Append`, `Repeat`, `Len`
and `Rows`. It allocates through `mpool.MakeSlice`/`FreeSlice`, without
`unsafe`. `BuildBuckets` comes with its first user in PR 8, `InvertInto`
in PR 11.
- **`Vector.Union` and `Batch.Union` are the one row-list gather**: rows
in any order, repeats allowed. `UnionInt32` is the same kernel for the
remaining `int32` lists until PR 8 moves them.
- **NULLs** are gathered one output word (64 rows) at a time in a
register and published with the new Gobra-verified `Bitmap.OrWord`,
instead of a `Contains` and an `Add` per row.
- `apply` moves to `int64` rows.

**Rows are `int64`.** The index width does not change speed, measured
pinned to one core: gathering 8192 values in random order takes 7.5 µs
with `int32` rows and 7.1 µs with `int64` rows (2.17 / 2.21 ms for 1M
rows); sorting a permutation takes 456 / 457 µs (109 ms for 1M rows
either way). `int64` has no 2^31-row cap on whole-input sorts and is
what `pkg/sort`, `Union`, every `Shuffle` caller and the top heaps
already use.

### Rebase onto main

- Upstream moved `ShrinkByRows` onto the vector type-ops table
(`ops.shrink`), which already replaced its per-type switch. This PR
keeps upstream's version, so the earlier hunk that made `ShrinkByRows`
reuse the gather's value loop is dropped.
- `TestBatchUnionRows` uses `batch.NewWithSize`, since upstream removed
`batch.New` with the batch attribute names.

### Benchmarks

`BenchmarkUnionRows`, 8192 rows, one in ten NULL, before → after
(interleaved, pinned to one core): int64 3.4×, int32 3.7×, decimal128
2.9×, varchar 1.9× faster; int64 without NULLs unchanged.
`BenchmarkPermute`: a gather into scratch plus swap matches or beats
`Shuffle` for every type, which supports replacing `Shuffle` in PR 9.
Tables are in the design doc.

### Tests

- New tests for `remaplist`, the gather (against `UnionOne` for every
payload width, from windows, const sources, into itself, empty and pool
mismatch), `Batch.Union` and `OrWord`; `-race` clean.
- `pkg/container/...`, `pkg/common/bitmap`, `pkg/common/remaplist`,
`pkg/sql/colexec/...`, `pkg/sql/compile/...` and TAE `mergesort` pass.
- Gobra: `select:OrWord` verifies against main's bitmap (0 errors).

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

Co-authored-by: Claude Opus 5.5 <[email protected]>
fengttt added a commit that referenced this pull request Nov 30, 2026
…ing the area (#33457) (#33459)

## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [x] 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:
- After merging `main` (with #33272): unit tests pass for
`pkg/container/vector/...`, `pkg/sql/colexec/...`,
`pkg/sql/plan/function/...` and `pkg/container/batch/...` (77 packages).
- The race build is clean for the new tests in `vector` and `colexec`.
- `golangci-lint` reports 0 issues; `molint`, `go vet -tags
matrixone_test` and `gofmt` are clean.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

This branch was successfully deployed

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

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants