Skip to content

perf(storage): storage search results are bitmaps; faster mask gather (#33444) - #33445

Merged
mergify[bot] merged 4 commits into
matrixorigin:mainfrom
fengttt:perf/search-results-bitmap
Nov 29, 2026
Merged

mergify[bot] merged 4 commits into
matrixorigin:mainfrom
fengttt:perf/search-results-bitmap

Conversation

@fengttt

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

Storage search results were []int64 row lists. They are now a
*bitmap.Bitmap end to end:

- PK and bloom/membership searches, the cached varlen search and the
  commit-ts filter set bits in a caller-owned bitmap.
- ApplyTombstones and the Tombstoner, and the block read path's
  selections, take the bitmap.
- The TopN candidate input and the in-memory workspace scan take it too.

On BenchmarkStorageSearchChain (persisted 8192-row block, PK filter,
search + tombstones + gather), dense, range, `>` and OR filters are
27-63% faster, and every read allocates a flat 2 KB instead of up to
130 KB. Sorted lookups that select a few rows and have no deletes pay
about 0.5-1.3 us more.

Also fixes UnionByMask, which dropped rows when the mask was shorter
than the column: it cut the mask's last word at the column's length.
@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 29, 2026 •

Copy link
Copy Markdown
Contributor

Queue requested — the merge queue status continues in this comment ↓.

…in#33444)

UnionByMask cost about 330 ns even for one selected row of 8192, so a
mask gather was far behind a row-list gather on sparse selections.

The fixed cost had three sources:
- CountRange counted the whole mask when its own count answers.
- Every word went through an indirect reader, even the zero words.
- The scan did not stop after the last selected row.

The gather now reads owned words directly, keeps the tail clear out of
the loop and stops early. For each nonzero word it picks:
- one copy for a full word;
- the plain loop, inline, for a sparse word;
- a copy per run for a run-heavy word (range results);
- two independent 32-bit chains for a dense scattered word (ILP
  instead of one serial x &= x-1 chain).

Results (BenchmarkMaskGatherByCount, 8192 rows):
- 1 row: 324 -> 29 ns.
- A 128-row run: 367 -> 45 ns.
- Dense random selections: 35-48% faster.

A position-list tier for small selections (the hybrid idea) was
measured and lost to this path at every size, so it is not included.

The search result bitmap now comes from objectio's reusable bitmap pool,
and Bitmap.First scans owned words directly.

On BenchmarkStorageSearchChain, the remaining loss on sorted point or
IN lookups without deletes drops to about 0.3-0.5 us (+11-16%). Every
other case is even or faster, by up to 69%.
@fengttt fengttt changed the title perf(storage): storage search results are bitmaps (#33181) perf(storage): storage search results are bitmaps; faster mask gather (#33444) Nov 29, 2026
@XuPeng-SH

XuPeng-SH commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 39166cf0be21c316b438a01468d29c7cfd289c57

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: 39166cf0be21c316b438a01468d29c7cfd289c57

Assessment: approve

No actionable defects found. The change reuses the existing bitmap and pooling mechanisms for storage selections while retaining row-distance pairing for TopN winners. The author's component benchmark reports substantial gains for several range and OR workloads, alongside 11–16% slower sorted point or IN-16 cases.

Model: gpt-6.1-terra / max

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

Validation:

  • Reviewed the complete change, affected search, tombstone, workspace and block-read consumers, linked issues, and all indexed discussion.

  • Isolation preflight passed: checks/1795937631190350377-2.json and preflight.log.

  • A source-extracted gatherWord probe passed against a naive oracle for contiguous runs and 100,000 deterministic masks using Go 1.26.6 and test-exec. The function extraction was verified against the frozen source. See gather-probe.log and checks/1795938298520273199-2.json and checks/1795938358246875327-2.json.

  • git diff --check passed, and the source checkout remained clean. See checks/1795938121725317506-2.json and checks/1795938358295023547-2.json.

  • The frozen CI snapshot reports successful x86 unit, ARM64 SCA, and multi-CN proxy and pessimistic BVT jobs for the assessed head. The author also reports package, race and benchmark results.

Limitations:

  • Local repository package tests were not run: the required Go 1.27.1 toolchain download timed out. See toolchain.log and checks/1795937786363181530-2.json. The extracted Go 1.26.6 probe is a narrow algorithm check, not a substitute for those package tests.

  • Individual CI test logs and the author's raw benchmark artifacts were not included in the supplied evidence; the benchmark results were not independently repeated.

@mergify mergify Bot added the queued label Nov 29, 2026
@mergify

mergify Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

✅ Merged into main as d1c4fc8 at 07:47 UTC

Less than a minute in the queue, with no time running CI.

So far

  • ✅ Entered the queue Sun 29 Nov, 07:47 · rule main · triggered by rule Automatic queue on approval for main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged 07:47 · d1c4fc8 · squash
3 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection
  • any of · required by GitHub branch protection:
    • check-success = CI Required
    • check-neutral = CI Required
    • check-skipped = CI Required

Times in UTC · dashboard · how the merge queue works

@mergify
mergify Bot merged commit d1c4fc8 into matrixorigin:main Nov 29, 2026
34 checks passed
@mergify mergify Bot removed the queued label Nov 29, 2026

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/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants