Skip to content

perf(index): reduce repeated work in combined scalar filters - #11552

Merged
jackye1995 merged 2 commits into
lance-format:mainfrom
jackye1995:codex/combined-filter-performance
Nov 27, 2026
Merged

jackye1995 merged 2 commits into
lance-format:mainfrom
jackye1995:codex/combined-filter-performance

Conversation

@jackye1995

@jackye1995 jackye1995 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Combined scalar filters repeat expensive bitmap work even when the indexes are warm. Bitmap ranges rebuild unions on every query, exact results compute the same AND/OR for both identical bounds, and LabelList attaches list-NULL masks when a top-level WHERE filter has disabled NULL tracking.

Reuse merged bitmap ranges through the existing bounded index cache, using the first and last matched posting offsets as the normalized key. Entries share the existing per-index/remapping namespace and cache budget; NULL tracking stays outside the cached union. Empty and single-value ranges bypass the merged-range cache, and concurrent misses share one union computation.

Compute exact-result AND/OR once and retain both result bounds. Apply the same optimization to NULL removal only when NULLs exist, preserving the cheap ownership-based path otherwise. Honor SearchOptions in LabelList and its value lookups; default searches and NOT subexpressions retain NULL tracking. Regression coverage includes range boundaries, eviction, namespaces, concurrent loads, disabled caches, null lists/elements, empty lists, multiple fragments, allow/block masks, and both row-selection domains.

Adds a dense combined-mask benchmark and a read-only existing-dataset benchmark:

cargo bench -p lance-select --bench combined_filter
LANCE_FILTER_BENCH_URI=<table-uri> cargo bench -p lance --bench combined_filter

The dataset benchmark expects score, label, and tags columns with their scalar indexes. LANCE_FILTER_BENCH_EXPECT_COMBINED optionally checks the combined count against an independently established oracle. Its timed queries use a warm cache, including merged ranges; distinct uncached ranges still compute their union.

On the same indexed 100M-row dataset, the native warm count benchmark improves from 141.53 ms to 37.53 ms for the combined predicate (3.77x), and from 67.63 ms to 9.32 ms for the score range (7.26x), preserving the 2,152,382-row combined count. The targeted selection/bitmap/label-list suites and clippy pass on ARM, and all current-head CI checks pass.

@github-actions github-actions Bot added performance A-index Vector index, linalg, tokenizer labels Nov 27, 2026
@jackye1995
jackye1995 marked this pull request as ready for review November 27, 2026 04:43

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@lance-gatekeeper lance-gatekeeper Bot 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.

✅ Gate recommendation: approve.

No merge-blocking issues found in the result algebra, NULL handling, or range-cache isolation.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 27, 2026
@jackye1995
jackye1995 merged commit 239aaea into lance-format:main Nov 27, 2026
52 checks passed
Xuanwo added a commit that referenced this pull request Dec 1, 2026
…alarIndexExpr (#11176)

Closes #11155

## Summary

### Root Cause
1. **`ScalarIndexExpr::optimize`** left contiguous `Or` trees unbalanced
and did not deduplicate repeated disjuncts or exact duplicate conjuncts.
2. **`ScalarIndexExpr::evaluate_with_options`** evaluated `And` / `Or`
via unbounded recursive `try_join!`, re-loading and re-searching
identical repeated leaves (e.g., `grp = 'hot_grp'` / `'cold_grp'` across
256 `OR` branches), keeping hundreds of full-dataset `RowAddrTreeMap`
masks live concurrently, and evaluating wide predicates unconditionally
alongside narrow/empty conjuncts.
3. **`ScopedScalarIndexLoader`** did not bound physical-address leaf
hits to `fragment_scope` when a shared index segment matched
out-of-scope fragments, and **`fragments_covered_by_index_query`**
walked duplicate index references repeatedly.

### Changes
- **Borrowed-RHS 3VL algebra (`lance-select`)**:
- Added `BitAnd<&Self>` and `BitOr<&Self>` on `NullableRowAddrMask`
(`BitAndAssign<&Self>` / `BitOrAssign<&Self>` on `NullableRowAddrSet`),
mutating `self` in place without cloning `rhs` while preserving SQL
Kleene three-valued logic.
- Added `BitAnd<&Self>` and `BitOr<&Self>` on `NullableIndexExprResult`,
retaining `#11012` `MaskDomain` invariants and `#11552` single-mask fast
paths when `self.exact && rhs.exact`.
- **Expression optimization (`lance-index`)**:
- Updated `ScalarIndexExpr::optimize` with iterative contiguous `Or`
flattening, first-seen-order disjunct deduplication, and balanced
`rebuild_or_tree` (`O(log2 N)` depth).
- Made `collect_and_leaves` and `needs_recheck` iterative and
deduplicated exact duplicate conjuncts in `optimize_and_leaves`.
- **Evaluation engine (`rust/lance-index/src/scalar/eval.rs`)**:
- Pre-evaluation iterative duplicate-only leaf CSE pass allocating
`CseSlot` (`OnceCell` for native and reconciled `RowAddress` results)
only for leaves appearing `>= 2` times under `(column, index_name,
index_type, needs_recheck, track_nulls, query)`; unique leaves (`count
== 1`) bypass caching so bitmaps drop immediately after folding.
- Expression-wide unique leaf search budget
(`MAX_LEAF_SEARCH_CONCURRENCY = 32`) enforced via a per-evaluation
semaphore acquired strictly when a unique leaf search starts
(`eval_search`): parent `Not` / `And` / `Or` nodes awaiting children and
duplicate CSE callers awaiting an in-flight `OnceCell` consume zero
slots.
- Selective-first `And` ordering (`ConjunctPriority`),
`track_nulls`-aware short-circuiting, and 3-phase `And` evaluation: (1)
zero-I/O drain of ready CSE leaves, (2) lone initial selective probe,
and (3) bounded tail overlap (`MAX_AND_CONCURRENCY = 8`,
`MAX_NESTED_AND_CONCURRENCY = 4` under `Or`), plus `MAX_OR_CONCURRENCY =
8` incremental `Or` folding.
- Preserved native `MaskDomain::RowAddress` / `MaskDomain::RowId` on
leaves (`#11012`), reconciling mixed domains lazily via
`ScalarIndexLoader::row_id_result_to_row_addrs` with per-slot
memoization and cooperative polling (`drive_with_in_flight`).
- **Fragment-scoped index loading & coverage (`lance`)**:
- Retained `#11045` per-segment coverage in `open_scalar_index_segments`
/ `LogicalScalarIndex` and wrapped subset-scoped physical-address
indices in `FragmentScopedScalarIndex` so `selected` and `nulls` are
restricted via `retain_fragments` while preserving native domains and
`Exact` / `AtMost` / `AtLeast` bounds.
- Deduplicated `(column, index_name)` pairs iteratively in
`ScalarIndexExec::fragments_covered_by_index_query`.

## Benchmark (`lance#11155` repeated-leaf comparison vs rebased `main`
`1b778e120`)

Fixture: 2,000,000 rows across 40 fragments (50,000 rows/frag) with
`item_id` BTree, `grp` Bitmap, and `ts` BTree; 256-branch composite `OR`
`(grp = 'hot_grp'|'cold_grp' AND item_id = ... AND ts >= ... AND ts <=
...)`. Measured against rebased parent `1b778e120` (includes `#11042`
bitmap read coalescing, `#11045`, `#11012`, and `#11552`), `--profile
release-with-debug`, median of 5 fresh child processes (all modes
returned exact `[("item_0_0", 0)]`):

| Mode | Scope | Variant | Median (ms) | RSS delta (MB) | `parts_loaded`
| `index_comparisons` |
| --- | --- | --- | ---: | ---: | ---: | ---: |
| `enable_stable_row_ids=false` | `fragments=[frag0]` | `main`
(`1b778e120`) | 415.77 | +328.28 | 214 | 3,138,944 |
| `enable_stable_row_ids=false` | `fragments=[frag0]` | **This PR** |
**117.71** (-71.7%) | **+83.85** (-74.5%) | **213** | **1,098,881** |
| `enable_stable_row_ids=false` | Full dataset (40 frags) | `main`
(`1b778e120`) | 403.38 | +330.80 | 214 | 3,138,944 |
| `enable_stable_row_ids=false` | Full dataset (40 frags) | **This PR**
| **184.32** (-54.3%) | **+89.83** (-72.8%) | 214 | 3,138,690 |
| `enable_stable_row_ids=true` | `fragments=[frag0]` | `main`
(`1b778e120`) | 386.27 | +324.24 | 214 | 3,138,944 |
| `enable_stable_row_ids=true` | `fragments=[frag0]` | **This PR** |
**114.09** (-70.5%) | **+81.53** (-74.9%) | **213** | **1,098,881** |
| `enable_stable_row_ids=true` | Full dataset (40 frags) | `main`
(`1b778e120`) | 412.16 | +303.69 | 214 | 3,138,944 |
| `enable_stable_row_ids=true` | Full dataset (40 frags) | **This PR** |
**175.48** (-57.4%) | **+89.30** (-70.6%) | 214 | 3,138,690 |

---------

Co-authored-by: Xuanwo <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-index Vector index, linalg, tokenizer K-approved Latest Gatekeeper recommendation permits acceptance. performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants