Skip to content

perf(colexec): expression evaluation takes the selection bitmap (#33181 PR 4) - #33266

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

fengttt merged 26 commits into
matrixorigin:mainfrom
fengttt:sels-bitmap-33181-pr4

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 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

fengttt and others added 18 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]>
…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]>
…in#33181 PR 3)

The filter built its selection one row at a time: a closure per row
over the predicate's bools, an iterator plus Remove to narrow it, and
a []int64 (SelectionRows, flatSels) to compact with Union or Shrink.

- Both filter paths build the TRUE rows with InitWithBools, a word at
  a time; a later predicate narrows with And on a scratch bitmap.
- Compaction gathers by the bitmap: compactByMask (UnionByMask, or
  ShrinkByMask in place on the filter's own batch), Batch.CompactInto
  and the scan's compactInto. CompactInto loses its row scratch.
- UnionByMask's NULL and varlen loops work a word at a time with no
  per-row closure; a NULL slot's descriptor is cleared.

BenchmarkFilterBlock (8192 rows, a > 10 keeps 45%, 1 in 13 NULL):
flat 55 -> 40.6 us, selected output 43.6 -> 29.6 us; no allocations.

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

The filtered scan turned the predicate's bools into a []int64
(compactPredicateRows), and blockio turned that list back into the
published selection bitmap (InitWithRows).

- 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, Apply). Count and RowList read either form;
  ReaderFilterRequest.RowList gives loaders that read by list (the late
  columns, membership's physical map) a reused buffer.
- table_scan's Select builds the mask with InitWithBools; a later
  predicate, evaluated over the gathered survivors, is composed back
  with the verified InitDeposit, and the survivors are gathered with
  UnionByMask.
- blockio publishes a mask by copying its words (no InitWithRows),
  shrinks or gathers early columns by the mask, and validates the
  mask's length and count.

BenchmarkReaderSelect (8192 rows, 1 in 11 NULL): one predicate
34.9 -> 28.8 us, a chain of two 53 -> 42.3 us. Tests: the mask matches
the Apply path's rows over five predicate chains; publishReaderSelection
with a list and with a mask.

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

- blockio: the publish-selection test runs with a list, a separate mask
  (published by copying its words) and the publish bitmap itself; every
  total-membership case also runs with a mask residual; the selected
  late read and the scoped immutable-cache read return masks;
  validateReaderFilterResult rejects a mask of the wrong length or count
  or one that comes with a list.
- filter: constant TRUE, FALSE and NULL conditions on both paths, alone
  and after a partial predicate.
- table_scan: constant conditions in the Select chain match Apply.

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

ExpressionExecutor.Eval and EvalWithoutResultReusing take a
*bitmap.Bitmap selection instead of []bool; nil selects every row.
Filter, projection and table_scan pass their selection bitmaps directly,
so Batch.SelectionMask (ExpandBools per batch) is removed.

- IF, CASE, COALESCE and JSON ELT build branch rows in two
  executor-owned bitmaps, allocated once and freed in Free. COALESCE
  narrows the remaining rows by each argument's NULL bitmap word-wise.
- evalSelectedRows gathers inputs with UnionByMask and scatters the
  compact result with the new Vector.ScatterByMask (fixed-width values a
  word at a time, unselected rows NULL a run at a time).
- Kernels are called only with every row selected and get one constant
  all-rows FunctionSelectList instead of a per-call copy (kept non-nil:
  some kernels branch on nil).

BenchmarkEvalSelection, 8192 rows, half selected: a+b 218->84 us,
IF 573->257, CASE 750->282, COALESCE 250->55; no change at all rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@mergify

mergify Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

…181-pr4

upstream/main's tree equals PR 3's head (f856983), which this branch
already contains, so the tree is unchanged.

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

XuPeng-SH commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 6b686471fffb704328a74d9f6c35d0ef21d48461

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: 6b686471fffb704328a74d9f6c35d0ef21d48461

Assessment: request_changes

The bitmap-based expression design reuses the existing selection machinery, with separate scatter paths for fixed-width and variable-length values. A row-domain error breaks some COALESCE expressions, and two existing benchmarks now accumulate bitmap allocations inside their timed loops.

Model: gpt-6.1-terra / max

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

  • P2 pkg/sql/colexec/evalExpression.go:1633: A COALESCE argument returns a nullable vector reused from a larger batch, and a later argument is an external routine.
    Impact: A valid query can fail on the smaller batch because the routine receives a selection whose length exceeds the current input row count.
    Evidence: Bitmap.And grows the receiver to the larger operand, while clearing a vector's NULL bitmap retains its length. In the full-expression probe, COALESCE initially returned [1, 21, 3], then failed after 128-row-to-3-row vector reuse with "external routine selection has 128 rows, expected 3". Intersect within the current row domain and add a regression covering reuse and the routine consumer.

  • P2 pkg/sql/colexec/evalExpressionDecimalMulSub_test.go:277: Running a masked case of BenchmarkDecimalMulSubExpression or the partial-selection case of BenchmarkORLikeSubjectReuseBatch.
    Impact: Each timed iteration now includes bitmap construction and retains its pool allocation, distorting the benchmark and allowing memory use to grow with the iteration count.
    Evidence: boolSelection allocates bitmap words from a global pool without freeing them; the second affected loop is in pkg/sql/colexec/evalExpressionSubjectReuse_test.go:887. A bounded probe retained 524288 bytes after 512 conversions of an 8192-row mask, even after garbage collection. Construct each benchmark's bitmap once outside the timed loop and free it during teardown.

Validation:

  • Private /tmp and loopback preflight passed; receipt checks/1795912187387026519-5.json.

  • Focused vector, batch, colexec, filter, projection and table_scan tests passed; receipt checks/1795912410903357843-5.json and focused-tests.log.

  • Conditional-expression and plan tests passed; receipt checks/1795912706273957649-5.json and conditional-tests.log.

  • The COALESCE full-expression probe and benchmark-allocation probe failed as described; receipts checks/1795912650864164104-5.json and checks/1795912917665855297-5.json, with retained logs.

Limitations:

  • The external-routine probe exercised the real evaluator with a mock runtime; public SQL execution was not run.

  • The reported benchmark comparisons and a BVT run for this head were not independently reproduced.

@fengttt
fengttt merged commit a682166 into matrixorigin:main Nov 29, 2026
35 checks passed
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 29, 2026
… into sels-bitmap-33181-pr5

PR 3 and PR 4 were squash-merged upstream after this branch was cut from
PR 4's draft. The tree is upstream/main plus this branch's one commit
(e88c27d). Upstream removed Batch.Attrs (matrixorigin#33199), so the offset
window copy no longer copies attribute names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
XuPeng-SH added a commit that referenced this pull request Nov 29, 2026
## What type of PR is this?

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

## Which issue(s) this PR fixes:

Related to #33181

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

Follow-up to the review of #33266. A reused nullable vector can retain a
NULL bitmap longer than the current batch. Intersecting it with the
remaining rows in `COALESCE` grew the selection and caused a later typed
Python routine to reject the batch.

Use a read-only prefix view for the longer NULL bitmap. This keeps the
current selection length and avoids an allocation. Shorter and
equal-length bitmaps use the existing word-wise intersection. The
external routine keeps checking its input row domain.

The Decimal mul/sub and OR-LIKE reuse benchmarks now construct their
partial mask once before timing and release it at subbenchmark teardown.
The expression selection benchmark also releases its existing hoisted
mask.

Validation

- The new bound expression regression fails on the base with a 128-row
selection on a 3-row batch. On the fix, it returns the expected values
before and after a 128-row batch, with only the selected NULL rows
reaching the mock routine runtime.
- Off-heap allocation checks for the three targeted 8,192-row benchmark
cases show zero bytes retained in the selection pool after teardown. The
same base cases retained 66,560, 68,608, and 2,048 bytes.
- Incremental formatting, vet, molint and golangci-lint passed. The unit
suites for `colexec`, `filter`, `projection`, and `table_scan` passed
with `-race -short`.
- Five alternating local runs of the 8,192-row COALESCE benchmark showed
median changes of +1.5% for all rows and -0.1% at both partial
densities. Allocations per operation matched the base in each case.
- The checked-in `udf_python/control_flow` BVT covers the 8,192-row
batch and 3-row tail. Normal mo-tester comparison passed all 26
statements twice on the same worker-enabled instance, with database
cleanup confirmed after each run. The same case failed only the new
statement on the base with `external routine selection has 8192 rows,
expected 3`; the candidate returns 33,738,797.
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 previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants