Skip to content

feat(bitmap): verified row-selection primitives and UnionByMask (#33181 PR 1) - #33213

Merged
fengttt merged 12 commits into
matrixorigin:mainfrom
fengttt:sels-bitmap-33181
Nov 28, 2026
Merged

fengttt merged 12 commits into
matrixorigin:mainfrom
fengttt:sels-bitmap-33181

Conversation

@fengttt

@fengttt fengttt commented Nov 25, 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 1 of the row-selection plan in docs/design/20261124-row-selection-bitmap-remaplist.md (#33183). It adds the bitmap primitives that later PRs use to replace []int64 sels with bitmaps. No caller is converted yet.

Stacked on #33144 (pool-owned bitmaps). Until #33144 merges, this diff also contains #33144's commits. The commits of this PR are the last three on the branch.

Design doc update

  • RemapList lives in its own package, pkg/common/remaplist, as remaplist.List (decision 5). InvertInto writes into a List the caller owns.
  • Review corrections:

Bitmap primitives (pkg/common/bitmap/bitmap_select.go, Gobra-verified)

Contracts are stated in terms of Has, the ghost "row is set" predicate.

Primitive Proven behaviour Replaces
InitWithBools(values, nulls, mp) row r is set iff values[r] is true and r is not in nulls bool predicate → sels → InitWithRows
InitDeposit(base, sel, mp) row r is set iff r is in base and sel holds r's rank in base per-row rank/select loops over a delete mask
KeepFirstN(k) a row stays iff it was set and fewer than k set rows lie below it positional split of sels
Word(i), NumWords() bit b of Word(i) is row 64i+b per-row Contains / iterator in gather loops

Vector and Batch

  • Vector.UnionByMask / Batch.UnionByMask append the selected rows of a source without building a row list.
    • They handle const sources, a source that is the destination itself (or a window of it), varlen area pre-growth, and NULLs.
    • The loop is word-at-a-time, and full words copy 64 rows at once.
  • Shrink asserts strictly increasing, non-negative sels in race builds.

Benchmarks (8192 rows, 0 allocations for the new paths)

new path it replaces
InitWithBools vs bools → sels → InitWithRows 3.3–4.6 µs 8.2–12 µs
UnionByMask vs ToI64Array + Union, 50% selected 2.6–2.9 µs 3.0–3.7 µs
same, 95% selected 5.3–5.5 µs 6.1–6.8 µs

Gobra verification

  • Results:
    • gobra/verify.sh: all 70 runs verified, including the 7 members of bitmap_select.go.
    • pkg/container/nulls/gobra/verify.sh: 0 errors.
    • Vacuity check (assert false planted at the entry and exit of every new and restructured member): caught in all 22 variants.
  • Split file: bitmap_select.go is verified with bitmap.go loaded. Runs for bitmap.go's own members leave it out, so the new members don't change existing proofs' context.
  • Existing proofs made robust: removeOrderedWord/removeOrdered and removeMaskWord/removeMask passed or failed depending on unrelated edits elsewhere, and even on the directory Gobra ran in, with identical files.
    • Their output relation is now a named ghost function (RemoveRel, RemoveMaskRel), so each check matches one term.
    • All four verify from every directory tried.
  • Split proofs: KeepFirstN timed out after 40 minutes as a single method. It is split into the helper keepLowBits and the heap-free lemma keepFirstRows, and each part verifies in minutes. InitDeposit is split the same way, with the lemmas depositWordRows and depositStep.
  • Bit loops: the loops over set bits use TrailingZeros64 plus &^, because the bit model has no axiom for w & -w. Benchmarks are unchanged.
  • pkg/common/bitmap/gobra/README.md documents the proofs and these lessons.

Testing

  • Unit tests:
    • Every bitmap primitive is compared against a per-row model, with read-only shifted views as inputs and the pool's CurrNB() back to zero.
    • UnionByMask is compared against Union(sels) across fixed widths 1/2/4/8/16/32/24 bytes and varchar (inline and out-of-line values), with NULLs, const sources, self-aliasing, and masks longer than the source.
  • Packages: go test passes for pkg/common/bitmap, pkg/container/{nulls,vector,batch} and pkg/objectio. go build ./... and go vet are clean.
  • Race build: the race tests pass for all 21 packages that call Shrink, and the new ascending assertion never fires.

🤖 Generated with Claude Code

fengttt and others added 9 commits November 23, 2026 23:29
A bitmap now carries the pool that owns its words. Words are allocated
off-heap from that pool and returned by Free; Reset frees them too and
keeps the pool. A bitmap without a pool is read-only: every write panics
and growth returns an error. Creating functions (InitWithSize, InitWith,
Clone, Filter, InitWithRows, InitWithInvertedBits) take the pool and
return errors.

InitView makes a zero-copy, read-only view of a bitmap's rows with a bit
shift. Readers of read-only bitmaps mask at Len, so a view sharing a word
with later rows never exposes them; Marshal and the C word accessors
write clean, unshifted words.

Vectors: the null bitmap uses the vector's pool and Vector.Free releases
it. Window's nulls are a view of the source's bitmap instead of a Go-heap
copy, a read-only decode references the encoded null bytes instead of
cloning them, and the stream decoder reads straight into pool words.
DetachNulls gives a window that must outlive its source (an Arrow prefix
whose lease moves) its own copy. A nullable function result reserves its
null capacity when it is prepared, so an admission failure is an error
rather than a panic in an in-place write. ResetWithSameType keeps the
bitmap's words for reuse.

Every bitmap user now has a pool and a matching Free: bloom filters, TAE
batch deletes (windows get views), row selections and dedup bitmaps,
objectio's bitmap pool, join matched bitmaps and their mailboxes, the
join map's delete rows, filter and table-scan selections, deletion and
multi-update block bitmaps, the integer IN operator (now with a free
hook) and function temporaries.

The unused tae/compute.ShuffleByDeletes is removed. Tests that pinned
"null bitmaps are Go-owned and uncharged" now assert that they are
charged and that accounts drain to zero.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve conflicts with matrixorigin#33115 (vector test consolidation) and
matrixorigin#33127/matrixorigin#33133 (dedupjoin captured-vector owner pool): carry the
read-only-NULL fixture to minmax_test.go, keep the pool-owned bitmap
tests in mpool_test.go, and free both the captured vectors (with their
owner pool) and the worker's matched/captured bitmaps in
freeWorkerJoinMsg. Port upstream's new tests to the pool-taking
bitmap API.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- bitmap_mem.go: use util.UnsafeSliceCast for the word/byte views, as
  molint checkunsafe forbids importing unsafe in this file (SCA).
- TestChaos1 read view.Deletes after view.Compact(), which now releases
  the deletes bitmap, so the count was always 0. Count first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Gobra:
- bitmap core: all 63 per-member runs verify; nulls verifies against the
  new pool-owned bitmap contracts (bitmap_mem.gobra, mpool stub).
- verify.sh caps each Gobra JVM at 2 GB (GOBRA_JAVA_OPTS) and sizes
  VERIFY_JOBS from available memory, so parallel runs no longer exhaust RAM.

Leak review fixes:
- objectio.BitmapPool: free bitmaps allocated on pool overflow (regression
  from pool-owned bitmaps); test proves the pool returns to baseline.
- tae Scan/HybridScanByBlock: close a partly built batch on error; fixes a
  use of a closed batch in ReadMergeSettingsBatch.
- frontend convertRowsIntoBatchInLocation, batch.OwnReadOnlyVectors: free
  partial results on error.
- blockio: release a discarded bitmap; hashbuild: free IgnoreRows before
  reallocating; vector.WindowInto rejects a target owning its nulls;
  remove unused anode.FillBlockView (aliased delete bitmap).

Docs: mo-dev skill reference bitmap-memory.md (ownership model, G-BITMAP).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- HybridScanByBlock: a Scan failure and a tombstone failure close the
  partly built batch and return nil; an error before Scan keeps the
  caller's batch. baseObject.Scan and HybridScanByBlock share
  closeBatchOnError.
- batch.OwnReadOnlyVectors frees the replaced originals (one owning its
  nulls) when a later Dup fails.
- vector.WindowInto rejects a read-only target that owns its nulls.
- frontend convertRowsIntoBatch frees earlier columns when a later one
  fails to convert.

Each test fails on the code before the fix.

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

Issue matrixorigin#33181

## What

Adds `docs/design/20261124-row-selection-bitmap-remaplist.md`, the
design and implementation plan for matrixorigin#33181. The plan has two parts:

- **Bitmap as the only row selection.** Every `sels` list that selects
rows (ascending, unique) becomes a bitmap, following the existing
batch-selection model: the producer owns the bitmap and lends it to
consumers through the batch.
- **One `RemapList` type for reordering.** Sort permutations, join
gathers, hash buckets and inverse maps move into one type with one
gather kernel.

The doc covers:

- the four row-selection representations in use today, and the
conversions between them on the hot paths;
- a classification of the call sites;
- the ownership rule: one owner, one allocation and one free per query;
- the bitmap primitives to add, and the `RemapList` API;
- an 11-PR plan, with a benchmark for each step;
- risks and open questions.

This PR changes documentation only.

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

Co-authored-by: Claude Opus 5.5 <[email protected]>
- RemapList is remaplist.List in pkg/common/remaplist (decision 5); the
  location open question is closed. InvertInto writes into an owned List.
- InitWithSize already reuses words on matrixorigin#33144; PR 1 drops it.
- New bitmap primitives in bitmap.go carry Gobra contracts.
- Leak checks are pool CurrNB tests (there is no bitmapleak build), and the
  ascending-sels assertion is new (Shrink does not check today).

Issue matrixorigin#33181

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…33181 PR 1)

Bitmap (pkg/common/bitmap/bitmap_select.go):
- InitWithBools: build a selection from a bool predicate and its nulls a
  word at a time (8192 rows: 3.7us vs 12.4us for bools -> sels ->
  InitWithRows; 0 allocs).
- InitDeposit: map a selection over a base's set rows back to base
  positions (the "compose" of the design; delete mask -> physical rows).
- KeepFirstN: keep the k lowest set rows.
- Word / NumWords: word access for word-at-a-time loops over a selection.
All read other bitmaps through the verified bitsFrom, so read-only views
work. They are outside the Gobra proof for now.

Vector/Batch:
- UnionByMask appends the selected rows of a source without a row list;
  handles const sources, self/window aliasing, varlen area pre-growth and
  NULLs. 8192 int64 rows: 2.6us vs 3.3us (50% selected), 5.1us vs 6.5us
  (95%) for ToI64Array + Union.
- Shrink asserts strictly increasing, non-negative sels in race builds.

Tests compare every primitive with a per-row model, including read-only
shifted views and pool CurrNB back to zero.

Issue matrixorigin#33181

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rigin#33181 PR 1)

The row-selection primitives move from the unverified bitmap_select.go into
the Gobra-verified core. bitmap_select.go now carries contracts and proofs
and is verified by gobra/verify.sh with bitmap.go loaded; runs for
bitmap.go's own members leave it out, so new members do not change the
proof context of existing ones.

Proven (in terms of Has):
- InitWithBools: row r set iff values[r] && r not in nulls.
- InitDeposit: row r set iff r in base and sel holds r's rank in base.
- KeepFirstN: a row stays iff it was set and fewer than k set rows lie
  below it (word loop in keepLowBits, rank facts in lemma keepFirstRows).
- Word, NumWords, depositBits.
Loops over set bits use TrailingZeros64 + &^ (the bit model has no axiom
for w & -w); benchmarks are unchanged.

Existing proofs made robust: removeOrderedWord/removeOrdered and
removeMaskWord/removeMask passed or failed depending on unrelated edits and
even on the directory Gobra ran in (identical files). Their output relation
is now named (RemoveRel, RemoveMaskRel), so each check matches one term;
all four verify from every directory tried.

Results: gobra/verify.sh 70/70 runs verified; nulls verify 0 errors;
vacuity (assert false at entry and exit) caught in all 22 variants of the
new and restructured members.

Issue matrixorigin#33181

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shrink takes strictly increasing sels; the race build asserts it since
matrixorigin#33181 PR 1. TestVarlenaAreaDisjointLifecycle duplicated a descriptor with
Shrink([0, 0]); Shuffle is the API for repeated rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The branch was stacked on bitmap-mpool-ownership (matrixorigin#33144), which has
since been squash-merged into main with its review fixes (matrixorigin#33231). This
merge takes main for everything that branch carried, and keeps only this
PR's own changes on top: the row-selection primitives, UnionByMask, their
Gobra contracts, and the RemapList package decision in the design doc.

Adapted to main: Batch.UnionByMask rejects a selected batch (matrixorigin#33184), and
tests use NewWithSize (batch.New removed in matrixorigin#33199).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fengttt
fengttt marked this pull request as ready for review November 28, 2026 17:35
@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 →

@mergify

mergify Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@matrix-meow matrix-meow added size/XL Denotes a PR that changes [1000, 1999] lines and removed size/XXL Denotes a PR that changes 2000+ lines labels Nov 28, 2026
@fengttt
fengttt merged commit c4b0548 into matrixorigin:main Nov 28, 2026
4 of 6 checks passed
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 28, 2026
PR 1 (matrixorigin#33213) is now squash-merged into main, so this merge drops the
stacked PR 1 commits and keeps only PR 2's own changes.

matrixorigin#33336 removed the TAE vector wrapper and with it CompactByBitmap, which
PR 2 had switched to ShrinkByMask. Main inlined CompactByBitmap's
mask-to-[]int64 conversion at its three callers; they now pass the
delete mask to ShrinkByMask directly: containers.Batch.Compact,
txnimpl anode window reads, and the tombstone transfer in table.go.
PR 2's CompactByBitmap test moves to TestBatchCompactByDeletes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt added a commit that referenced this pull request Nov 28, 2026
…3232)

## 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 2 of the row-selection plan in
`docs/design/20261124-row-selection-bitmap-remaplist.md`. The changes:

- The storage read path applies delete masks as bitmaps, without
building a row list.
- `UnionBatch` moves NULLs a word at a time, using a new Gobra-verified
primitive.
- Mask loops read an owned bitmap's words directly.
- Storage search results stay lists, a decision backed by measurements.

#33213 (PR 1) and #33144 are merged; this diff is PR 2 alone.

### Changes

- The read path turned each block's delete mask into a `[]int64` with
`ToI64Array`, then called `Shrink(neg)` on every column. It now passes
the mask to `ShrinkByMask`. The converted sites:
- `BlockDataReadInner`, both full-read paths. One of them carried a
`TODO: avoid this transformation`.
  - `blockDataReadWithFilter`, for the early columns.
  - `BlockDataReadBackup`, for an object without a commit-ts column.
- TAE compaction by delete mask. #33336 removed
`vectorWrapper.CompactByBitmap` and inlined it at its callers, so the
mask goes straight to `ShrinkByMask` in `containers.Batch.Compact`,
`txnimpl` anode window reads, and the tombstone transfer in
`txnimpl/table.go`.
- `shrinkFixedByMask` now works a word at a time:
  - When removing rows, it copies each run of kept rows at once.
  - When keeping rows, a full word moves 64 rows with one copy.
- NULLs go through the existing verified
`nulls.FilterByMaskInPlaceWithOffset`.

### `UnionBatch` NULLs (`Bitmap.OrShifted`)

- **Problem:** `UnionBatch` copied a fixed-width range with one copy but
set its NULLs one row at a time.
- **New primitive:** `Bitmap.OrShifted(b, src, dst, cnt)` sets those
NULLs a word at a time. Each destination word takes its source rows with
one `bitsFrom`, masked to the range.
- **Verified:** it is in the Gobra-verified core (`bitmap_select.go`).
The proven result is that row `r` is set exactly when it was set before,
or when `dst <= r < dst+cnt` and `b` has row `r-dst+src`.
- **Result:** `BenchmarkUnionBatchNullable` (8192 `int64` rows, 1 in 17
NULL) goes from 15.8 µs to 1.35 µs, with no allocations.

### Mask loops read owned words

- **Problem:** `Bitmap.Word` goes through the general unaligned loader,
at about 4.5 ns per word. `UnionByMask` therefore spent 630 ns on an
8192-row mask with one row set.
- **Fix:** `OwnedWords()` returns an owned bitmap's words, or nil for a
read-only view. The vector's `maskReader` indexes those words and falls
back to `Word` for views.
- This is correct because owned bitmaps keep the verified `TailClear`
invariant.
- `Word` itself could not get under Go's inlining budget, which is why
the fast path lives in the caller.
- **Result:** one selected row goes from 640 ns to 142 ns. The dense
`UnionByMask` benchmarks also improved.

### Storage search results stay lists (to be re-examined)

The PK search functions, bloom-filter hits, `ApplyTombstones` and the
`ioutil` row loaders keep `[]int64`.

| selected of 8192 | `Union(sels)` | `UnionByMask` |
| --- | --- | --- |
| 1 | 4 ns | 142 ns |
| 256 | 82 ns | 220 ns |
| 4096 | 1.1 µs | 1.9 µs |

The measurements gather by an existing list.

- **Why keep lists:**
- A mask gather is slower at every density, because its `word &= word-1`
loop is a serial dependency chain.
- The searches produce lists natively, and every consumer gathers by
list.
  - The tombstone chain stops early on an empty list.
- **Where this is recorded:** the design doc section "Storage search
results stay lists" has the measurements. Comments at
`ReadFilterSearchFuncType`, `engine.DataSource.ApplyTombstones` and
`blockio.ReadDataByFilter` point to it.
- **Status:** it will be re-examined later.

### Benchmarks

Shrinking 8192 `int64` rows (`BenchmarkShrinkDeletes*`). The list path
includes the `ToI64Array` that the reader used to run:

| deleted | `ToI64Array` + `Shrink` | `ShrinkByMask` |
| --- | --- | --- |
| 1% | 3.9 µs | 2.1 µs |
| 30% | 6.4 µs | 6.2 µs |

Neither path allocates. On a full block read
(`BenchmarkBlockDataReadInnerDeletes*`: 8192 rows, 4 columns), the
per-block delete list is gone:
- 1% deleted: 22 → 21 allocations per read, 3.2 KB → 2.5 KB.
- 10% deleted: 22 → 21 allocations per read, 9.3 KB → 2.5 KB.

Decoding dominates the read time, and the timings were too noisy on a
shared machine to report.

### TPC-H regression fix (commit `e3a142794c`)

TPC-H SF100 against main showed q12 and q19 slower on the full #33181
stack. CPU profiles traced part of that to this PR:

- `Bitmap.Contains` dispatched to `shiftedContains` for read-only views.
That put `Nulls.Contains` over Go's inline budget (cost 86 > 80), so
every per-row NULL check in function evaluation became a call. In q19,
`validateVectorBinary` went from 22 s to 39 s of CPU.
- `Contains` is now one expression that handles both owned bitmaps and
shifted views. `Nulls.Contains` inlines again (cost 47).
- `shiftedContains` is removed. Gobra verifies `bitmap.go` with the new
`Contains` (all members pass).
- `UnionByMask` for varlena columns:
- When the source has no out-of-line data (every value inline), it
gathers the descriptors as fixed-width values and clears NULL
descriptors a word at a time.
- Otherwise it counts the selected rows' out-of-line bytes exactly, with
a direct word loop, and grows the area once. (An earlier version
reserved the source's whole area for masks of 75% or more; that
over-reserves for large unselected values and for windows, and was
removed in review. The TPC-H run below predates that change; at the
microbenchmark level the exact count is 10% faster at 50% density and
16% slower at 90%.)

With the fix applied across the stack, a full ABBA run (2×3 runs per
image) gives a sum of per-query bests of 123.7 s vs 124.4 s for main
(−0.6%): q12 −3.9%, q19 −2.5%, 132/132 golden results on both.

### Testing

- New tests:
- `TestShrinkByMaskMatchesShrink` compares against `Shrink` over 6
types, sizes 1 to 1000, densities 0 to 1, offsets and both directions,
and the pool's `CurrNB()` returns to zero.
- `TestBlockDataReadBackupNoCommitTSAppliesTombstones`,
`TestBlockDataReadInnerOrderedLimitFallbackAppliesDeletes` (including
the row-id column) and `TestBatchCompactByDeletes`.
- `TestOrShifted` checks 3000 random cases against a per-row model,
including read-only views, unaligned starts and growth.
  - `TestUnionBatchNullsAtOffsets` and `TestMaskGatherWithViewMask`.
  - Every changed line is covered.
- Gobra: `gobra/verify.sh` verified all 72 runs, and
`pkg/container/nulls/gobra/verify.sh` reports 0 errors.
- Package tests pass for blockio, containers, readutil, vector, batch,
TAE tables/txn, disttae and objectio.
- Race build: bitmap, vector, nulls and blockio pass. All 23 packages
that call `Shrink` pass with PR 1's ascending-sels assertion on.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 28, 2026
PR 1 (matrixorigin#33213) and PR 2 (matrixorigin#33232) are squash-merged into main, so this
merge keeps only PR 3's own changes. Main's matrixorigin#33184 moved a published
selection into the batch that carries it (OwnSelection / FreeSelection,
SetSelection(sel)); PR 3 keeps that ownership and its word-wise bitmaps:

- filter: the selected path builds its rows into the view's own
  selection with InitWithBools and ANDs later predicates through one
  filter-owned scratch bitmap (pred), which the compacting path also
  gathers by. Reset and Free return pred to its pool, as main already
  does for the view's selection.
- table_scan: keep, pred and dep stay scan-owned scratch; reset now
  frees them too, so their words go back to the execution's pool.
- blockio: publishBatchSelection fills output.OwnSelection from the
  mask (InitWith) or the list (InitWithRows); the caller-owned publish
  bitmap is gone, and with it the test case where the mask was that
  bitmap.
- vector: unionVarlenByMask keeps PR 3's word loop with PR 2's review
  fix: the area is always sized by the selected payload, never by
  len(w.area).
- Tests: batch.New and the two-argument SetSelection are gone on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt added a commit that referenced this pull request Nov 28, 2026
… and filter (#33181 PR 3) (#33236)

## 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 3 of the row-selection plan in
`docs/design/20261124-row-selection-bitmap-remaplist.md`. The selection
now stays a bitmap from blockio through the scan filter, the filter
operator and projection. Compaction gathers by the bitmap.

#33213 (PR 1), #33232 (PR 2) and #33144 are merged; this diff is PR 3
alone. It is merged with main after #33184, which moved a published
selection into the batch that carries it (`OwnSelection` /
`FreeSelection`); this PR keeps that ownership. The filter's and the
scan's scratch bitmaps go back to the execution's pool in `Reset`, as
the published selection already does.

### Conversions removed

Before this PR, the filtered scan converted the selection at every hop.
Two of those conversions are gone:

- The predicate's bools no longer become a `[]int64`
(`compactPredicateRows`).
- blockio no longer turns that list back into the published bitmap
(`InitWithRows`).
- Every compaction now gathers by the bitmap instead of `SelectionRows`
→ `Union`.

The remaining conversion, expanding the bitmap to `[]bool` for `Eval`,
is PR 4.

### Scan filter (`table_scan`, `blockio`, `engine`)

- `engine.ReaderFilterResult` gains `Mask`, the kept rows as a bitmap
over the input rows.
- `Sels` stays for producers that build a list: membership, exact scan,
and `Apply`.
  - `Count` and `RowList` read either form.
- `ReaderFilterRequest.RowList` gives the loaders that read by list a
buffer reused across blocks. Those are the late columns and membership's
physical row map; storage search results stay lists (see #33232).
- table_scan's `Select` builds the mask with `InitWithBools`.
- A later predicate in the chain is evaluated over the gathered
survivors.
- Its result is composed back onto the block's rows with the
Gobra-verified `InitDeposit`.
  - The survivors are gathered with `UnionByMask`.
- blockio handles a mask result directly:
- It publishes the mask by copying its words into the output batch's own
selection, with no `InitWithRows`.
  - It shrinks or gathers early columns by the mask.
  - It validates the mask's length and count.

### Filter operator, projection, compaction

- Both filter paths (compacting and selected output) build the kept rows
with `InitWithBools`, a word at a time.
  - They used to call a closure per row.
- A later predicate narrows the selection with `And` on a scratch
bitmap, where it used to iterate and `Remove` row by row.
- Compaction gathers by the bitmap:
- the filter's `compactByMask`, which uses `UnionByMask`, or
`ShrinkByMask` in place on its own batch;
  - `Batch.CompactInto`, which loses its row scratch;
  - the scan's `compactInto`.
- `UnionByMask`'s NULL and varlen loops work a word at a time, with no
per-row closure. A NULL slot's varlena descriptor is cleared.

### Benchmarks (8192 rows, PR 2 → PR 3, no allocations either way)

| Benchmark | PR 2 | PR 3 |
| --- | --- | --- |
| `BenchmarkFilterBlockFlat` (a > 10 keeps 45%, 1 in 13 NULL, compacted)
| 55 µs | 40.6 µs |
| `BenchmarkFilterBlockSelected` (same, selected output) | 43.6 µs |
29.6 µs |
| `BenchmarkReaderSelectOne` (one predicate, 1 in 11 NULL) | 34.9 µs |
28.8 µs |
| `BenchmarkReaderSelectTwo` (chain of two) | 53 µs | 42.3 µs |

### Decode the selection once per multi-column gather (commit
`e237de3502`)

TPC-H SF100 profiles showed q12 slower than main: the scan's mask gather
in `gatherSelectedColumns` and `compactInto` cost 153 s of CPU against
93 s on main. A mask gather walks the set bits of the mask once per
column, and that bit loop costs about 0.5 ns per bit, so per column it
is about 2× slower than a gather by row list.

- When two or more columns are gathered, the scan now decodes the mask
into a row list once (`bitmap.AppendRows`), reuses it across blocks in
`selectionState`, and gathers every column with `Union`.
- A single column still gathers by the mask.
- Two kernel variants (a branchless dense pass, a per-word index array)
were measured and were slower; they are not included.

With the fix applied across the stack, a full ABBA run gives a sum of
per-query bests of 123.7 s vs 124.4 s for main (−0.6%): q12 −3.9%, q19
−2.5%, 132/132 golden results on both.

### Testing

- `TestCompactIntoGathersThroughRowList` checks `compactInto` against
`Union` over the selected rows, for several columns (row-list path:
int64 and short/long varchar with NULLs, a nil and an empty column) and
for one column (mask path). `TestSelectionGatherRows` covers the
fallback to the mask when a selected row lies past the source.
- New tests:
- `TestSelectReaderFilterMaskMatchesApply`: the scan's mask keeps the
same rows as the list-based `Apply` path over eight predicate chains
(partial, all-true, none, NULLs, constant TRUE, FALSE and NULL).
- blockio: the publish-selection test runs with a list and with a mask,
with and without deletes. Every total-membership case also runs with a
mask residual. The selected late read and the scoped read return masks.
`TestValidateReaderFilterResultMask` covers mask validation.
- `TestFilterConstantConditions`: constant conditions on both filter
paths, alone and after a partial predicate.
- Changed-line coverage: 86%. The rest is error handling.
- `go test` passes for `pkg/sql/colexec/...`, blockio, readutil,
disttae, `pkg/container/...`, ivfflat and bitmap.
- Race build: table_scan, filter, projection, blockio, vector and batch
pass.
- BVT has not been run yet.

🤖 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 29, 2026
… PR 4) (#33266)

## 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 4 of the row-selection plan in
`docs/design/20261124-row-selection-bitmap-remaplist.md`. Expression
evaluation takes the selection as a bitmap. This removes the last
per-batch conversion on the scan, filter and projection path: expanding
the selection bitmap to `[]bool` for `Eval`.

PRs 1–3 (#33213, #33232, #33236) and #33144 have merged, so the diff is
this PR only.

### Changes

- **`Eval` takes a bitmap.** `ExpressionExecutor.Eval` and
`EvalWithoutResultReusing` take `sel *bitmap.Bitmap` instead of
`[]bool`. nil still selects every row.
- Filter, projection and table_scan pass their selection bitmaps
directly.
- `ExternalRoutineEval` (added upstream since this PR was drafted) takes
the bitmap too: its strict row-count check uses `Len`, and membership
uses `Contains`.
  - `Batch.SelectionMask` (which called `ExpandBools`) is removed.
- **Branch selections are bitmaps.** IF, CASE, COALESCE and JSON ELT
build the rows each branch is evaluated on in two bitmaps owned by the
executor. They are allocated from the executor's pool on first use,
re-initialized per batch, and freed in `Free`.
- COALESCE narrows the remaining rows by each argument's NULL bitmap, a
word at a time.
- **Gather and scatter by mask.** `evalSelectedRows` gathers row-aligned
inputs with `UnionByMask` and scatters the compact result back with the
new `Vector.ScatterByMask`.
- `ScatterByMask` is the inverse of `UnionByMask`. Fixed-width values go
a word at a time, and the unselected rows are marked NULL a run at a
time.
  - Variable-length types are scattered a row at a time.
- **No per-call `FunctionSelectList` copy.** A kernel is called only
when every row is selected, since partial selections are compacted
first. So it receives one constant all-rows list.
- The list stays non-nil. Some kernels choose their path by whether it
is nil: string `=` takes a varlena fast path, and `arithmetic.go` treats
nil like a partial selection.
- The kernels' own masking paths are no longer reached from the
executor. Removing them is part of PR 6.

### Benchmark

`BenchmarkEvalSelection`: one 8192-row batch, µs, PR 3 → PR 4. Both
builds were run alternately, pinned to the same cores, and the table
shows the minimum.

| expression | all rows | half | tenth |
| --- | --- | --- | --- |
| `a + b` | 52.9 → 52.8 | 218 → 84 | 29.7 → 19.7 |
| `IF(a > 0, a + b, b)` | 317 → 207 | 573 → 257 | 94 → 63 |
| `CASE` with two conditions | 294 → 202 | 750 → 282 | 144 → 73 |
| `COALESCE(a, b)` | 84 → 40 | 250 → 55 | 38 → 14 |

### Tests

- `TestScatterByMaskInvertsUnionByMask`: across types, row counts,
densities and NULL rates, scattering the `UnionByMask` gather of a
source restores every selected row and makes the others NULL.
- `TestScatterByMaskConst`: constant, constant NULL and varchar NULL
sources, and an error when the source has too few rows.
- Existing tests now build selections with a `boolSelection([]bool)`
helper. Test mocks of `ExpressionExecutor` take the new signature.
- Unit tests and `-race` pass for colexec, filter, projection,
table_scan, vector, batch and plan, and for the operator packages whose
mocks changed.
- PR 3's BVT run on a 2-CN dev cluster found no regressions. Every
failure there was an environment difference: tracing off,
`AUTO_ID_CACHE` off, loopback services, optimistic suites, timezone, or
leftover state.

🤖 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 29, 2026
…R 5) (#33267)

## 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 5 of the row-selection plan in
`docs/design/20261124-row-selection-bitmap-remaplist.md`. The remaining
operator and frontend sites that built an ascending row list one row at
a time, then shrank or copied by it, now use a selection bitmap.

PRs 1–4 (#33213, #33232, #33236, #33266) and #33144 have merged, so the
diff is this PR only.

### Changes

- **DML operators.** Each bitmap is allocated once by the operator and
freed in `Reset` and `Free`.
- INSERT IGNORE's NULL primary key filter keeps the complement of the PK
NULL bitmap.
  - DELETE's row-id dedup (`FilterRowIdForDel`) fills a bitmap.
  - MULTI_UPDATE's target and ODKU filters.
  - PREINSERT's target selector.
  - PREINSERT_UNIQUE's accepted rows.
  - LOCK_OP's SKIP LOCKED rows.
- **Other operators.**
- The CTE cache (`cteaccount.CacheBatch`) takes the inserted rows as a
bitmap.
  - TIME_WINDOW's non-NULL time rows.
  - The Iceberg delete filter uses `InitWithBools`.
- OFFSET copies the contiguous tail with `UnionWindow` instead of
copying the batch and shrinking it.
- **Scan fallback filter.** `table_scan`'s `evalFilter` works on the
same bitmaps as the main path and returns a `Mask`. Its scratch bitmaps
come from the process pool, so they are not charged to the scan's output
memory account.
- **Frontend.** The `SHOW VARIABLES` and `SHOW COLLATION` WHERE filters
share a new `colexec.InitBoolSelection` helper and shrink by mask.
- **Faster `InitWithBools`.** It packs eight bools per multiply, about
4× faster. That code uses `unsafe`, which Gobra can't check, so it is
trusted through a contract in `bitmap_pack.gobra`. `TestPackBools`
checks the code against that contract. The Gobra README lists it in the
trusted base. All 72 Gobra runs verify.

### Bugs fixed

- **IVF-FLAT TopK residual path**
(`blockDataReadWithSelectedFilterTopK`). It read only the `Sels` form of
a filter result, so a `Mask` result would have dropped rows. A new test
case fails without the fix. No existing case reached that path.
- **SHOW WHERE filters.** They ignored NULLs, and a constant condition
such as `WHERE 1` kept only the first row.

### Benchmark

`BenchmarkBooleanFilterSelection`: the scan's fallback filter on one
8192-row batch, µs, PR 4 → PR 5. Both builds were run alternately,
pinned to the same cores, and the table shows the minimum.

| filter result | PR 4 | PR 5 |
| --- | --- | --- |
| all rows true | 12.0 | 2.0 |
| a quarter NULL | 31.9 | 21.5 |
| all false | 2.15 | 2.06 |
| two thirds true | 8.9 | 10.2 |

The two-thirds case is about 15% slower: shrinking a 1-byte column in
place by mask costs more there than by list. A table-based variant only
helped at 90% density, so it was left out.

Two cases of this benchmark failed on both branches because the input
was built in the wrong memory pool. That is fixed.

### Deferred to PR 6

These are forced when the list APIs are removed:

- Set operators' per-row flags. A bitmap would need an offset-aware
copy, with no clear gain.
- Join gathers. These belong to the RemapList track (PR 10).
- `data_branch_hashdiff`. Some of its lists come from conflict checks,
and one relies on ORDER BY.
- Storage and TAE sites.

### Tests

- `TestPackBools`, a test for `InitBoolSelection`, and `mask=true`
variants plus a `storage_selection_residual` case in
`TestBlockDataReadWithFilterAppliesVectorTopKAfterResidual`.
- Unit tests and `-race` pass for bitmap, colexec, deletion,
multi_update, preinsert, preinsertunique, lockop, mergecte, cteaccount,
timewin, table_scan, offset, filter and blockio. Frontend unit tests
pass.
- golangci-lint is clean.
- BVT has not been run for this PR.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

This branch was successfully deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/feature size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants