Skip to content

perf(blockio): apply delete masks with ShrinkByMask (#33181 PR 2) - #33232

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

fengttt merged 18 commits into
matrixorigin:mainfrom
fengttt:sels-bitmap-33181-pr2

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 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. [Subtask]: TAE container cleanup: remove tae vector. #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

fengttt and others added 11 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]>
… PR 2)

The storage read path turned every block's delete mask into a []int64
with ToI64Array and then called Shrink(neg) per column. It now passes
the mask to ShrinkByMask: BlockDataReadInner (both full-read paths),
blockDataReadWithFilter, BlockDataReadBackup, and TAE CompactByBitmap.

shrinkFixedByMask works a word at a time: removing rows copies each run
of kept rows at once, keeping rows moves a full word with one copy.
8192 int64 rows, 1% deleted: 2.1 us vs 3.9 us for ToI64Array + Shrink;
30% deleted: even. No allocations; the per-block delete list is gone.

Tests: ShrinkByMask against Shrink over types, sizes, densities, offsets
and both directions; backup read with tombstones and no commit column;
ordered-limit fallback read with a row-id column; CompactByBitmap.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt and others added 2 commits November 24, 2026 22:18
…3181 PR 2)

UnionBatch copied a fixed-width range with one copy but set its NULLs
one row at a time with Contains and Add. For 8192 nullable int64 rows
that was 14 us of a 16 us append.

Bitmap.OrShifted(b, src, dst, cnt) sets row dst+k for every set row
src+k of b, a word at a time: each destination word takes its source
rows with one bitsFrom, masked to the range. It is in the Gobra-verified
core (bitmap_select.go): row r is set exactly when it was set or
dst <= r < dst+cnt and b has row r-dst+src. gobra/verify.sh: all 72
runs verified; nulls: 0 errors.

BenchmarkUnionBatchNullable (8192 int64, 1 in 17 NULL): 15.8 us -> 1.35 us,
no allocations.

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

Bitmap.Word goes through the general unaligned loader, about 4.5 ns a
word, so UnionByMask spent 630 ns on the 128 words of an 8192-row mask
with one row set. OwnedWords returns an owned bitmap's words (nil for a
read-only view); the vector's maskReader indexes them and falls back to
Word for views. Correct because owned bitmaps keep the verified
TailClear invariant. One set row: 640 ns -> 142 ns.

Search results stay []int64: measured against a gather by an existing
list, a mask gather is slower at every density (1 row: 4 vs 142 ns;
4096 rows: 1.1 vs 1.9 us), the producers build lists natively, and the
tombstone chain stops early on an empty list. The design doc records
the measurements and narrows decision 1 accordingly.

Also: TestUnionBatchNullsAtOffsets, BenchmarkUnionBatchNullable and
TestMaskGatherWithViewMask.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comments at ReadFilterSearchFuncType, engine.DataSource.ApplyTombstones
and blockio.ReadDataByFilter: the rows are kept as a sorted list on
purpose for now, with a pointer to the measurements in the design doc.
The design doc marks the decision as to be re-examined later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@XuPeng-SH

XuPeng-SH commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: ee534d5970cff99585d7a1bc49a1633baf62822c

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Commit: ee534d5970cff99585d7a1bc49a1633baf62822c

Assessment: request_changes

The delete-mask conversion reuses the existing vector shrink operation, and retaining storage search lists is a reasonable scoped tradeoff. The updated variable-length mask gather, however, can reserve memory for unselected values and fail an operation that previously succeeded.

Model: gpt-6.1-terra / max

Session: 01a2230f-39de-7f00-bf9a-e19ded95bd85 · slot 0 · generation 39

  • P2 pkg/container/vector/union_mask.go:195: Call UnionByMask on a variable-length vector with 100 rows: 20 unselected values of 60 KiB each and 80 selected inline values, using a 1 MiB destination pool. The same issue occurs when the source is a small borrowed window into a larger vector.
    Impact: The dense-mask path requests the entire 1.2 MiB source area even though the selected values need no out-of-line payload. The gather fails with an mpool capacity error; without a tight cap, it needlessly retains the oversized allocation.
    Evidence: The branch uses len(w.area) whenever at least three quarters of rows are selected, but that area can contain unselected values or an entire parent vector's payload. The exact-head probe failed while its list-gather control passed. The identical probe passed against a clean merge-base checkout. Bound the reservation by the selected live payload, including for borrowed windows, while retaining the dense-path optimization where it is safe.

Validation:

  • Private /tmp and loopback preflight passed: checks/1795897883711406304-5.json.

  • Full bitmap and vector package tests passed: checks/1795898366787682162-2.json and bitmap-vector-tests.log.

  • Focused bitmap, vector, blockio backup and ordered-limit, and TAE batch-compaction tests passed: checks/1795898228964396888-2.json and focused-tests.log.

  • The bounded-memory probe failed on the assigned head with its list control passing, and passed against the clean merge base: checks/1795898477107569016-5.json, checks/1795898635344097109-5.json, bounded-head.log, and bounded-full-base.log.

  • The assigned checkout remained clean and git diff --check passed: checks/1795898686697323340-2.json.

Limitations:

  • The reproduced failure is at the existing vector/batch API boundary; no in-tree SQL operator currently calls Batch.UnionByMask.

  • Gobra and the author's TPC-H performance measurements were not independently rerun. The linked TAE concurrent-release concern predates this change and is not attributed to it.

A selection of 75% or more rows reserved len(w.area) instead of counting
the selected rows' out-of-line payload. That area also holds unselected
values and, for a window, the payload of the whole parent vector, so a
dense gather of small values could request megabytes and fail on a
capped pool where Union and UnionBatch, which count exactly, succeed.

The gather now always counts, with a direct word loop instead of a
per-row closure. BenchmarkMaskGather varchar40, reused destination:
50% 49.0 -> 44.1 us, 90% 68.4 -> 79.5 us. Growing the area on demand
instead was cheaper only for a reused destination; from an empty one it
was 1.8x slower than the old reservation.

TestUnionByMaskVarlenaReservesSelectedPayload covers both cases with a
1 MiB pool: dense inline rows next to large unselected values, and a
window over a parent with a large area. Both failed before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fengttt

fengttt commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. The P2 finding on pkg/container/vector/union_mask.go is real, and it's fixed in 7706b98.

I checked both scenarios on the old head before changing anything:

  • Dense inline rows next to large unselected values: the gather requested 1,228,800 bytes from a 1 MiB pool and failed.
  • Window over a parent with a large area: readOnlyWindowInto shares the parent's whole area, and the gather requested 2,457,600 bytes. This only reproduces when the mask selects most but not all rows. A mask that selects every row goes to UnionBatch instead, which counts exactly.

Union and UnionBatch both size the area by the selected payload already, so the dense shortcut was the only place that didn't.

Fix. The gather always counts the selected non-NULL, out-of-line bytes and grows the area once. The count is now a direct word loop instead of a per-row closure, which pays back most of the cost. BenchmarkMaskGather varchar40 with a reused destination:

density before after
50% 49.0 µs 44.1 µs
90% 68.4 µs 79.5 µs

I also tried skipping the reservation on dense masks and letting the copy grow the area geometrically. That matched the old speed with a reused destination, but from an empty destination it was 1.8× slower than the old reservation, so I didn't keep it.

Test. TestUnionByMaskVarlenaReservesSelectedPayload runs both scenarios against a 1 MiB pool and checks the values and that the pool returns to zero. Both cases fail on the old code and pass now. The vector, batch and blockio packages pass under -race.

🤖 Generated with Claude Code

@matrix-meow matrix-meow added size/XL Denotes a PR that changes [1000, 1999] lines and removed size/L Denotes a PR that changes [500,999] lines labels Nov 28, 2026
@fengttt
fengttt merged commit 4a2b9f4 into matrixorigin:main Nov 28, 2026
18 of 23 checks passed
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]>
mergify Bot pushed a commit that referenced this pull request Nov 29, 2026
…#33444) (#33445)

## 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 #33444 (subtask of #33181)

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

#33444 asks two questions. Was PR 2 (#33232) right to keep storage search results as `[]int64`? And can the mask loops (`UnionByMask` and the others) be made faster? This PR converts storage search results to bitmaps end to end and measures the whole chain. It rewrites the mask gather to remove its fixed per-call cost, and reports the hybrid (list for small selections) experiment. It also fixes a latent `UnionByMask` bug.

### What changes

Storage search results are a `*bitmap.Bitmap`, owned by the caller:

- **Searches.** `vector.SearchFunc` and `objectio.ReadFilterSearchFuncType` set bits in a cleared bitmap. This covers the PK search factories, the cached varlen `ReadFilterSearch`, bloom/membership hits and `LinearSearchOffsetByValFactory`.
  - Ranges are one `AddRange`. A sorted `<`/`>` finds its first failing row and sets the prefix or suffix once.
  - OR-ed disjuncts and multi-term searches set their rows in the same bitmap. The dense mark arrays and their compaction are gone.
  - `pk > x` no longer returns rows in descending order, so `ApplyTombstones` no longer sorts.
- **Visibility and tombstones.**
  - `FilterCachedRowsByCommitTS*` and `AnyCachedTSInRange*` take the bitmap.
  - `engine.DataSource.ApplyTombstones(ctx, bid, rows *bitmap.Bitmap, policy) error` removes rows in place, as do `Tombstoner.ApplyInMemTombstones` and `Tombstoner.ApplyPersistedTombstones`.
  - The persisted pass is the new `Bitmap.AndNot`, which walks the smaller side.
  - A sorted in-memory pass merges the selection with the block's deletes, galloping, when the selection is smaller than the deletes.
- **Block read path.**
  - `ReadDataByFilter` fills a caller-owned bitmap.
  - `BlockDataReadInner`, `blockDataReadWithFilter`, the exact-scan and membership entries, and the loaders (`LoadColumnsDataInto`, the new `CopyCachedVectorMask` and `ConstructRowidColumnToWithMask`) take bitmaps.
  - The residual filter's kept rows map back to physical rows with `InitDeposit`, replacing two hand-written merges. Ordered limits use `KeepFirstN`, and live rows are the complement of the delete mask.
- **TopN.** The candidate input of `TopNVector`, `ReadColumnTopN`, `BlockTopNRead.TopN` and the fused loaders is a bitmap, with nil meaning all rows. Winners stay a ranked `[]int64` plus distances, and are turned into a mask once where columns are loaded for them.
- **disttae.** The workspace insert scan keeps its carry-over rows in a source-owned bitmap, freed in `Close`. The PK-dedup probes use the bitmap too.

### Boundaries kept on purpose

- **TopN winners** are a ranked result, not a search result, so they stay `[]int64` with their distances.
- **Residual predicate evaluators** (the exact-scan predicates, the membership stage's physical row map) keep their working lists. They receive the storage selection as a bitmap and convert it once at entry.
- **Sampling picks** (`cached_index_sample.go`) are not a search result and still use `CopyCachedVectorRows`.

### Memory ownership

Every new bitmap has one owner and is freed on every exit path. The read path's selection bitmaps are private scratch, so they come from `mp.Base()`. They are never charged to an output allocation view (`readerOutputMP`), matching the row lists they replace; `TestMembershipScratchDoesNotStarveOutput` caught this.

### Bug fix: `UnionByMask` with a mask shorter than the column

`gatherFixedByMask`, `forSelectedRows` and `selectedWord` cut the mask's last word at `rows%64`, instead of only the column's last word. A 98-bit mask over a 196-row column lost rows 68–97. Masks on `main` always matched the column length, so the bug was latent. This branch passes shorter masks (for example the checkpoint reader's `[start, end)`). The regression test is `TestUnionByMaskShortMask`.

### Mask gather (#33444)

`BenchmarkMaskGatherByCount` (new, vector) gathers k of 8192 rows, either scattered or as one run, by mask and by list. Before this PR, `UnionByMask` cost about 330 ns even for one row. Three things caused it:

- **`CountRange`:** it counted the whole mask, although an owned mask already knows its count.
- **Per-word overhead:** every word was read through an indirect reader with per-word branches, including all-zero words.
- **No early exit:** the loop kept scanning words after the last selected row.

The gather now works as follows:

- **Word access and early exit:** it reads an owned mask's words directly, handles the column's last word once outside the loop, and stops when every selected row is copied.
- **Strategy per nonzero word:**
  - A full word is one copy.
  - A sparse word (fewer than 16 rows) uses the plain loop, inline.
  - A word that is mostly runs (a range result) is copied run by run.
  - A dense scattered word is split into two 32-row halves. Their `x &= x-1` chains are independent, so the CPU overlaps them instead of waiting on one serial chain.

| case (8192-row int64 column) | list `Union` | mask, main | mask, this PR |
|---|---:|---:|---:|
| 1 row | 7 ns | 324 ns | 29 ns |
| 16 scattered | 12 ns | 350 ns | 79 ns |
| 64 scattered | 35 ns | 374 ns | 127 ns |
| 256 scattered | 145 ns | 487 ns | 259 ns |
| 4096 scattered | 2114 ns | 4062 ns | 2588 ns |
| 16 in a run | 12 ns | 338 ns | 42 ns |
| 128 in a run | 70 ns | 367 ns | 45 ns |
| 1024 in a run | 539 ns | 463 ns | 173 ns |
| 4096 in a run | 2123 ns | 757 ns | 604 ns |

On the existing `BenchmarkMaskGather`, int32, int64 and varchar10 are 20–55% faster at 2%, 50% and 90% density, and roughly even at 14%. varchar40 (out-of-line, where payload copying dominates) is even. `BenchmarkUnionByMask` is −35%, `BenchmarkUnionByMaskDense` −61%, and the `ShrinkByMask` benchmarks are unchanged. Varchar results are in `BenchmarkMaskGatherByCount` and follow the int64 ones.

**The hybrid (a list for small selections), measured and not included:** UnionByMask gathered selections of up to K rows by position, from a stack list collected out of the mask. Against the optimized mask path:

- At K = 32 it lost or tied at every count, for both int64 and varchar (for example, 32 rows in a run: 118 ns by list vs 60 ns by mask).
- Smaller K changed nothing, because the cost is structural: collecting the positions takes the same word scan the gather does, plus a second pass.
- The remaining gap to a list gather at small k is the 20–60 ns scan that finds the few set bits. Closing it would need the hybrid inside `Bitmap` itself (keep a small selection as a sorted list, with no words to scan). That changes the Gobra-verified core and every bitmap user, so it is left as an open question in the design doc.

Other measured choices:

- **Position-list gather in `copyCachedVector` for up to 64 or 128 rows:** slower, because its buffer escapes to the heap. Not included.
- **A `UnionOne` special case for one row:** about 1% faster end to end, so dropped to keep one gather path.
- **Search bitmap allocation:** the search bitmap now comes from objectio's reusable bitmap pool (`GetSearchBitmap`), which saves a pooled allocation and free per block.
- **`Bitmap.First`:** now scans an owned bitmap's words directly.

### End to end

`BenchmarkStorageSearchChain` (new, readutil) reads a persisted 8192-row block through `BlockDataRead`. The block has a sorted int64 PK (pk = 2·row) and int64 and varchar payloads. The benchmark covers search, then tombstones, then a gather of 3 columns. `tomb_7` deletes every 7th row through the production `FastApplyDeletesByRowIds` on both sides; the main binary uses an equivalent list stub. Figures are medians of 6 alternating main/branch runs on an Apple M2 Max, with spread ≤ 6%.

| case | main µs | branch µs | Δ | B/op | allocs/op |
|---|---:|---:|---:|---:|---:|
| eq/tomb_0/sorted | 2.5 | 2.8 | +11% | 1944 → 2032 | 18 → 19 |
| eq/tomb_0/unsorted | 12.0 | 10.0 | -17% | 1944 → 2032 | 18 → 19 |
| eq/tomb_7/sorted | 2.5 | 2.9 | +16% | 1944 → 2032 | 18 → 19 |
| eq/tomb_7/unsorted | 12.0 | 10.2 | -15% | 1944 → 2032 | 18 → 19 |
| in16/tomb_0/sorted | 3.2 | 3.7 | +14% | 2184 → 2032 | 22 → 19 |
| in16/tomb_0/unsorted | 52.6 | 50.8 | -4% | 2128 → 2032 | 19 → 19 |
| in16/tomb_7/sorted | 7.7 | 4.1 | -47% | 2184 → 2032 | 22 → 19 |
| in16/tomb_7/unsorted | 57.1 | 51.3 | -10% | 2128 → 2032 | 19 → 19 |
| in256/tomb_0/sorted | 11.9 | 11.5 | -3% | 6024 → 2032 | 26 → 19 |
| in256/tomb_0/unsorted | 718.2 | 698.7 | -3% | 5968 → 2032 | 23 → 19 |
| in256/tomb_7/sorted | 18.4 | 13.6 | -26% | 6024 → 2032 | 26 → 19 |
| in256/tomb_7/unsorted | 724.5 | 701.4 | -3% | 5968 → 2032 | 23 → 19 |
| range 82 rows/tomb_0/sorted | 2.8 | 2.8 | -1% | 2640 → 2032 | 18 → 19 |
| range 82 rows/tomb_0/unsorted | 17.8 | 17.6 | -1% | 3976 → 2032 | 25 → 19 |
| range 82 rows/tomb_7/sorted | 4.0 | 3.6 | -11% | 2640 → 2032 | 18 → 19 |
| range 82 rows/tomb_7/unsorted | 19.1 | 18.4 | -3% | 3976 → 2032 | 25 → 19 |
| range 4096 rows/tomb_0/sorted | 18.2 | 7.4 | -59% | 34704 → 2032 | 18 → 19 |
| range 4096 rows/tomb_0/unsorted | 39.2 | 23.5 | -40% | 130184 → 2032 | 33 → 19 |
| range 4096 rows/tomb_7/sorted | 51.2 | 17.8 | -65% | 34704 → 2032 | 18 → 19 |
| range 4096 rows/tomb_7/unsorted | 72.3 | 34.2 | -53% | 130184 → 2032 | 33 → 19 |
| `pk >=` 4096 rows/tomb_0/sorted | 27.9 | 12.1 | -57% | 130184 → 2032 | 33 → 19 |
| `pk >=` 4096 rows/tomb_0/unsorted | 31.4 | 22.1 | -29% | 130184 → 2032 | 33 → 19 |
| `pk >=` 4096 rows/tomb_7/sorted | 63.8 | 22.7 | -64% | 130184 → 2032 | 33 → 19 |
| `pk >=` 4096 rows/tomb_7/unsorted | 67.4 | 32.9 | -51% | 130184 → 2032 | 33 → 19 |
| OR of 2 ranges/tomb_0/sorted | 15.7 | 4.9 | -69% | 80528 → 2032 | 20 → 19 |
| OR of 2 ranges/tomb_0/unsorted | 46.8 | 35.0 | -25% | 97408 → 2032 | 40 → 19 |
| OR of 2 ranges/tomb_7/sorted | 30.9 | 12.2 | -61% | 80528 → 2032 | 20 → 19 |
| OR of 2 ranges/tomb_7/unsorted | 61.8 | 42.3 | -32% | 97408 → 2032 | 40 → 19 |

- **Faster:**
  - Dense, range, `>` and OR filters are 25–69% faster.
  - Sparse lookups with deletes are 11–47% faster.
  - Every unsorted (linear-search) case is even or faster.
  - Every read allocates a flat 2.0 KB instead of up to 130 KB.
- **Slower:**
  - The one remaining loss is a sorted point or IN-16 lookup without deletes: +11% to +16%, or 0.3–0.5 µs.
  - The 82-row sorted range is now even with main.

The design doc section "Storage search results are bitmaps" has these numbers and the hybrid analysis.

### Testing

- **New tests:**
  - `TestSearchLessGreaterMatchesOracle` and `TestSearchFixedSizeAndVarlenLessGreaterMatchesOracle`: random sorted and unsorted inputs with NaN, checked against a per-row oracle, including the `quick` first-failure semantics.
  - `TestSearchFuncsUnionIntoOneBitmap`, `TestAndNotAndFirst` (including read-only views) and `TestUnionByMaskShortMask`.
  - `TestCopyCachedVectorMaskMatchesRows`: against `CopyCachedVectorRows`, covering one-row and dense masks, short masks, NULLs and the past-the-end rejection.
  - `TestScatterByMaskInvertsUnionByMask` and `TestUnionByMaskShortMask` cover the rewritten gather loops.
  - `TestFastApplyDeletesByRowIdsMatchesModel`: covers both the merge path and the walk path, with other blocks' rowids around.
- **Existing tests:** the tests in objectio, ioutil, readutil, blockio and disttae now use bitmaps. Expectations changed only where the type makes a case unrepresentable:
  - `>` results are now ascending.
  - Unsorted, duplicate and negative selection inputs became their set equivalents, or were removed where they cannot be represented.
  - TopN ties on a once-unsorted selection now resolve in row order.
- **Package tests pass:** bitmap, vector, objectio/..., vm/engine, disttae, readutil, blockio and tae/logtail. The 34 packages under vm/engine/tae/... and vm/engine/test/... also pass.
- **Race build passes** for bitmap, vector, objectio, ioutil, readutil and blockio.
- **Lint:** `golangci-lint` reports 0 issues; `molint`, `go vet`, `gofmt` and the license-eye header check are clean.
- **Not run:** BVT, and TPC-H against main.

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


Approved-by: XuPeng-SH <[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/enhancement size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants