Skip to content

perf(colexec,frontend): remaining row selections as bitmaps (#33181 PR 5) - #33267

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

fengttt merged 27 commits into
matrixorigin:mainfrom
fengttt:sels-bitmap-33181-pr5

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

fengttt and others added 19 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]>
…igin#33181 PR 5)

Sites that built an ascending row list a row at a time and then shrank or
gathered by it now build an operator-owned bitmap (allocated once, freed
in Reset/Free) and use ShrinkByMask / UnionByMask:

- DML: IgnoreFill.DropNullPkRows (kept rows = complement of the key's
  NULL bitmap), FilterRowIdForDel, the MULTI_UPDATE target and ODKU
  filters, PREINSERT's target selector, PREINSERT_UNIQUE's accepted rows,
  LOCK_OP SKIP LOCKED.
- MERGE_CTE inserted rows (CacheBatch takes a bitmap), TIME_WINDOW NULL
  time rows, the Iceberg delete filter.
- table_scan's Apply path (evalFilter) works on the Select path's bitmaps
  and returns ReaderFilterResult.Mask; scan selection bitmaps come from
  the process pool, not the output allocation. blockio's IVF-FLAT TopK
  residual path maps a mask result (it read only Sels before).
- OFFSET copies its contiguous tail window instead of copy + shrink.
- SHOW VARIABLES / SHOW COLLATION WHERE use colexec.InitBoolSelection,
  which treats NULL and constant conditions correctly (a constant TRUE
  kept only row 0 before).

bitmap.InitWithBools packs eight bools per multiply via packBools, which
the Gobra proof trusts through a contract in bitmap_pack.gobra
(TestPackBools checks it); about 4x faster.

BenchmarkBooleanFilterSelection (8192 rows): all true 12.0->2.0 us,
nullable 31.9->21.5, all false 2.15->2.06, two thirds true 8.9->10.2.

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

fengttt commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Addressed in 1845bfd and bee57ae; the branch is also merged with upstream main (99bd2de).

P2 bool_selection.go: SHOW ... WHERE NULL / WHERE 1

Fixed. The new plan.PredicateExpr casts the bound condition to BOOL, as a query's WHERE does in splitAndBindCondition. SHOW VARIABLES and SHOW COLLATION now use it, so an untyped NULL selects no rows and a number uses MySQL truth semantics.

  • Unit test: TestShowWhereConditionIsPredicate runs through doShowVariables and handleShowCollation. It covers null, 0, 0.0, null and 1 (no rows) and 1, 2.5, true, null or 1 (all rows). It fails before the fix with "filter condition is not boolean".
  • BVT: dml/show/show.test gets the same cases through SQL. They pass on a node built from this branch, as do charset_collation and system_variable.

P2 constraint_util.go: bitmap reuse under a different pool

Fixed once in bitmap, not at each call site. In prepareInit, a bitmap that holds no words now takes the pool it's initialized with, since nothing of the old pool is left to return. A bitmap that still holds words must match its pool, as before. This covers IgnoreFill and the DELETE, PREINSERT, PREINSERT_UNIQUE, SKIP LOCKED and merge CTE reset paths without changing them. The Gobra contract of prepareInit (n.mp == mp on success) is unchanged.

  • TestBitmapOwnsPoolWords covers moving a freed bitmap from one pool to another and back.
  • TestIgnoreFillDropNullPkRowsAcrossPools reuses an IgnoreFill under a second process pool. It reproduced "bitmap: mpool does not match the bitmap's pool" before the fix.

P2 blockio/read.go: IVF-FLAT INCLUDE persisted path

From SQL, no query reaches the Mask branch, so this hunk changes no SQL-visible result:

  • blockDataReadWithSelectedFilterTopK is reached only through ReadWithFilterAndTopK.
  • The only caller of ReadWithFilterAndTopK is the IVF plan reader (vectorindex/ivfflat/plan_reader.go). Its filter, filterRelationBatchRows, always returns Sels or All.
  • The table-scan filters are the only producers of Mask, and they never go through this reader.

To confirm it, I ran the whole test/distributed/cases/vector directory (100% pass) on a node built from this branch with a temporary log line on each branch. The Sels branch fired 11 times and the Mask branch never fired. A persisted IVF-FLAT INCLUDE index with a partial residual filter, flushed and compared against mode=force, doesn't reach it either: the include predicate becomes an index filter.

So the Mask branch only keeps this consumer correct for the ReaderFilterResult contract, which allows either form. read_test.go covers it, and vector_ivf_persisted_filter_topk.sql already checks the Sels branch with a non-identity row map against the full-scan oracle.

Also in this update: table_scan keeps the selection bitmaps' words across Reset (4f307d7). A cached prepared statement had been allocating its predicate bitmap from the pool on every execution, which cost 0.7% of CPU in sysbench point_select.

# Conflicts:
#	pkg/vm/engine/tae/blockio/read.go
#	pkg/vm/engine/tae/blockio/read_test.go
@XuPeng-SH

XuPeng-SH commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 8a403c5b9be10995dde2970d652c6a974109fba4

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: 8a403c5b9be10995dde2970d652c6a974109fba4

Assessment: request_changes

The migration reuses the existing bitmap and vector selection operations, and the earlier SHOW predicate and bitmap pool-reuse concerns are resolved. The earlier request for public SQL coverage of the IVF Mask branch is not supported by the current caller path, which supplies Sels or All; the direct block-reader test passes for both representations. Two new selection buffers bypass the execution memory admission previously used by their owners.

Model: gpt-6.1-terra / max

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

  • P2 pkg/sql/colexec/timewin/timewin.go:1650: An accounted time-window query processes a batch containing both NULL and non-NULL timestamps when the query or CN budget has less remaining capacity than the selection bitmap needs.
    Impact: The bitmap is allocated outside the execution account, allowing live memory to exceed the configured budget and omitting the allocation from owner attribution. The buffer grows with the input batch; sort and merge-order can pass time-window batches larger than 8,192 rows.
    Evidence: The replaced code reserved selection scratch through ctr.allocation.ReserveMetadata, whereas proc.Mp() does not use that account. An isolated operator probe with 8,192 rows and a 512-byte cap rejected an equivalent account-owned bitmap but allowed the new filter to finish; the merge-base timewin.go, overlaid into the same checkout, returned the capacity error. Allocate the bitmap through ctr.allocation.MP(proc) or an equivalent admitted scratch mechanism, and retain the existing release path.

  • P2 pkg/sql/colexec/mergecte/mergecte.go:216: A recursive UNION DISTINCT processes a batch while its allocation account is bound and the execution budget has insufficient remaining capacity for the selection bitmap.
    Impact: The reusable bitmap remains live until reset or free without being charged to the query or CN budget. Its capacity can therefore exceed the limit and is absent from allocation attribution; multiple recursive operators or larger input batches compound the gap.
    Evidence: The previous GrowSetOperationSlice used MakeSliceAccounted when an account was bound, but the replacement initializes through the unaccounted proc.Mp(). After warming the distinct hash table, an isolated 8,192-row probe with 512 bytes of headroom rejected an account-owned bitmap while filterInsertedRows retained 1,024 unaccounted bytes. Initialize this bitmap through ctr.allocation.MP(proc), or otherwise admit its physical capacity through the existing owner.

Validation:

  • Private /tmp and loopback preflight passed, and git diff --check passed; receipts are checks/1795948922402236053-3.json and checks/1795948968565469803-3.json.

  • Built native prerequisites in the diagnostic directory from the frozen source archive and compared all 198 native input files with the assigned head; native-build.log and native-provenance.log have matching successful receipts.

  • The complete pkg/common/bitmap suite and focused scan, boolean-selection, cross-pool reuse, OFFSET and preinsert tests passed; see bitmap-native.log and focused-test.log.

  • Focused SHOW predicate, block-reader Top-K residual selection, and Iceberg delete-application tests passed; see frontend-test.log, blockio-test.log and iceberg-test.log.

  • The current-head and merge-base time-window budget probes passed their respective assertions; the recursive CTE budget probe and existing time-window/CTE behavior tests also passed. See timewin-probe.log, timewin-baseline.log, cte-probe.log and timewin-cte-tests.log; each has a successful check receipt.

  • The supplied exact-head CI snapshot reports successful x86 unit tests and multi-CN BVT jobs.

Limitations:

  • The first local bitmap test could not compile because native jemalloc headers were absent; it passed after the matching native prerequisites were built.

  • No public SQL or live Iceberg end-to-end test was run locally. The supplied CI snapshot marks Iceberg E2E skipped.

  • The author's reported SQL runs and performance percentage were not independently reproduced from retained local artifacts.

@fengttt
fengttt merged commit e5e8eaf into matrixorigin:main Nov 29, 2026
5 of 7 checks passed
fengttt added a commit that referenced this pull request Nov 29, 2026
…ectList (#33181 PR 6 + 6b) (#33272)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue #33181

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

PR 6 and PR 6b of the row-selection plan in
`docs/design/20261124-row-selection-bitmap-remaplist.md`, on current
main:
1. **PR 6** removes the row-list shrink APIs and converts their
remaining callers to selection bitmaps. This was #33271, which is closed
in favor of this PR.
2. **PR 6b** removes `FunctionSelectList`, the kernels' masking paths
and the kernel parameter.

## PR 6: remove the row-list Shrink

### API changes

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

### Callers converted to bitmaps

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

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

## PR 6b: remove FunctionSelectList

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

### How

The change is mechanical, made with two throwaway AST rewriters:
1. **Fold.** Every selection check was replaced with the value the
executor passes (non-nil, nothing masked) and simplified until nothing
changed. This removed the masking branches and loops.
2. **Drop.** Using type information, the parameter was removed from
every signature and the argument from every call.

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

### One behavior change

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

## Rebase onto main

The branch is rebuilt on main after PR 5 (#33267) merged, so the diff
holds only these two changes. Where upstream changed the same code, its
version is kept:
- `Vector.ShrinkByRows` is built on upstream's type-ops table and keeps
its T_any (all-NULL) handling.
- The TAE vector wrapper is gone upstream, so its `Compact` change no
longer applies.
- `POW` keeps upstream's NULL result for a negative base with a
fractional exponent, and the legacy overload 0 keeps its error.
- `<>` keeps upstream's geometry and BIT cases.
- Upstream tests whose only subject was a `FunctionSelectList` mask
(`TestGeometryNotEqualSelectedRows`, two `POW` legacy subtests, a
geometry inline-mask block) are removed. Their unmasked assertions are
covered by the neighbouring cases.

## Tests

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

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

---------

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

This branch was successfully deployed

No deployments
ci — cdeba63c Deployed Nov 29, 2026 by fengttt via Matrixone Utils CI / pr-size-label #66900
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