Repository navigation
perf(index)!: normalize stable-row-id scalar index results to row-address domain - #11012
Conversation
e716e35 to
9ce150a
Compare
| /// addresses via its row-id index (an id -> address lookup, cheap and | ||
| /// batched — the opposite direction, address -> id, requires a | ||
| /// per-fragment row-id sequence scan and is deliberately not exposed | ||
| /// here; see `ScalarIndexExpr::evaluate_with_options`). |
There was a problem hiding this comment.
| /// addresses via its row-id index (an id -> address lookup, cheap and | |
| /// batched — the opposite direction, address -> id, requires a | |
| /// per-fragment row-id sequence scan and is deliberately not exposed | |
| /// here; see `ScalarIndexExpr::evaluate_with_options`). | |
| /// addresses via its row-id index (an id -> address lookup, cheap and | |
| /// batched). |
We can probably optimize the other direction in the future if needed. No need to go into too much detail here.
| /// Converts whichever side is row-id-domain into row-address domain (via | ||
| /// [`ScalarIndexLoader::row_id_result_to_row_addrs`]) — never the reverse, | ||
| /// since that conversion is a cheap, batched row-id-index lookup, while the | ||
| /// reverse (row-address -> row-id) requires a per-fragment row-id-sequence | ||
| /// scan. Same-domain pairs (the common case) pass through untouched. |
There was a problem hiding this comment.
| /// Converts whichever side is row-id-domain into row-address domain (via | |
| /// [`ScalarIndexLoader::row_id_result_to_row_addrs`]) — never the reverse, | |
| /// since that conversion is a cheap, batched row-id-index lookup, while the | |
| /// reverse (row-address -> row-id) requires a per-fragment row-id-sequence | |
| /// scan. Same-domain pairs (the common case) pass through untouched. | |
| /// Converts whichever side is row-id-domain into row-address domain (via | |
| /// [`ScalarIndexLoader::row_id_result_to_row_addrs`]) |
The point is not performance but that we want the two domains to be the same
| // in the `And`/`Or` arms above, not here. This avoids the | ||
| // address -> row-id -> address round trip a stable-row-id | ||
| // dataset used to pay for every address-domain leaf. |
There was a problem hiding this comment.
| // in the `And`/`Or` arms above, not here. This avoids the | |
| // address -> row-id -> address round trip a stable-row-id | |
| // dataset used to pay for every address-domain leaf. | |
| // in the `And`/`Or` arms above, not here. |
Avoid commenting about the specific issue as it will be stale
| //! Each result also carries a [`MaskDomain`] saying whether the u64s inside | ||
| //! its mask are physical row addresses or stable row ids. Both domains are | ||
| //! stored in the *same* `RowAddrMask`/`NullableRowAddrMask` container (both | ||
| //! are just u64-keyed tree maps) — there is no separate row-id-shaped result | ||
| //! type. `BitAnd`/`BitOr` require both sides to already agree on domain | ||
| //! (callers reconcile mismatched domains before combining, since doing so | ||
| //! generally requires an async index lookup that the pure boolean algebra | ||
| //! here can't perform). |
There was a problem hiding this comment.
| //! Each result also carries a [`MaskDomain`] saying whether the u64s inside | |
| //! its mask are physical row addresses or stable row ids. Both domains are | |
| //! stored in the *same* `RowAddrMask`/`NullableRowAddrMask` container (both | |
| //! are just u64-keyed tree maps) — there is no separate row-id-shaped result | |
| //! type. `BitAnd`/`BitOr` require both sides to already agree on domain | |
| //! (callers reconcile mismatched domains before combining, since doing so | |
| //! generally requires an async index lookup that the pure boolean algebra | |
| //! here can't perform). | |
| //! Each result also carries a [`MaskDomain`] saying whether the u64s inside | |
| //! its mask are physical row addresses or stable row ids. Both domains are | |
| //! stored in the *same* `RowAddrMask`/`NullableRowAddrMask` container (both | |
| //! are just u64-keyed tree maps) — there is no separate row-id-shaped result | |
| //! type. `BitAnd`/`BitOr` require both sides to already agree on domain | |
| //! (callers reconcile mismatched domains before combining, since doing so | |
| //! generally requires an async index lookup that the pure boolean algebra | |
| //! here can't perform). | |
| //! | |
| //! Stable row id masks are a legacy case from old indices. All newer | |
| //! indices should produce row addresses as the result. |
Let's be clear that the row id case is the legacy case
| } | ||
| let index_input = if use_external_mask && self.external_row_mask.is_some() { | ||
| let mask = self | ||
| .external_row_mask_as_row_addrs() |
There was a problem hiding this comment.
User provided row ids will be id-domain in stable row id datasets so we still need to convert to addresses in this case.
There was a problem hiding this comment.
Makes sense, thanks for confirming.
| /// shortcut ("this whole physical fragment matches") that no row-id-domain | ||
| /// index ever produces, since a row-id-domain index has no notion of | ||
| /// physical fragment layout to begin with. | ||
| pub(crate) fn translate_row_id_treemap_to_row_addrs( |
There was a problem hiding this comment.
This is called by Scanner::row_ids_as_take_input. We might want to investigate those call sites to see if we can provide the input as row addresses. For example, in merge-insert's stale row replay. That can be a follow-up.
There was a problem hiding this comment.
Filed as a follow-up rather than rolled into this PR, to keep this one scoped to the domain-tagging/reconciliation change.
| /// `BlockList` are supported here: either way, only the ids actually listed | ||
| /// in the mask need a lookup, never the full id universe (see | ||
| /// [`translate_row_id_treemap_to_row_addrs`]). | ||
| pub(crate) fn translate_row_id_mask_to_row_addrs( |
There was a problem hiding this comment.
This is only called when we have one index in the row id domain and one in the row addr domain and we need to combine the results from the two. Should be extremely rare and we should just migrate the id domain index.
There was a problem hiding this comment.
Agreed — this path should only ever be hit while a migration is in progress (one index type already on row-address domain, another not yet migrated). Once every builtin type is address-domain this becomes fully dead code.
| /// Plain-[`RowAddrMask`] (post-`drop_nulls`) sibling of | ||
| /// [`translate_row_id_mask_to_row_addrs`], for finalizing an | ||
| /// [`lance_select::IndexExprResult`] to row-address domain. | ||
| pub(crate) fn translate_row_id_plain_mask_to_row_addrs( |
There was a problem hiding this comment.
This is called as part of Scanner::external_row_mask_as_row_addrs when the user provides row ids.
| /// Unlike the (now-removed) address -> row-id direction, this does not | ||
| /// restrict to `self.fragments` first: a row id carries no reliable | ||
| /// fragment component to scope by (only a vestigial "home fragment" from | ||
| /// assignment time, which drifts from the row's current location), and | ||
| /// the row-id index lookup this delegates to is already a cheap, | ||
| /// dataset-wide, batched operation, so there's no over-fetching to avoid. |
There was a problem hiding this comment.
| /// Unlike the (now-removed) address -> row-id direction, this does not | |
| /// restrict to `self.fragments` first: a row id carries no reliable | |
| /// fragment component to scope by (only a vestigial "home fragment" from | |
| /// assignment time, which drifts from the row's current location), and | |
| /// the row-id index lookup this delegates to is already a cheap, | |
| /// dataset-wide, batched operation, so there's no over-fetching to avoid. |
No need to explain why we stopped doing something or comment about things we are not doing unless it is truly not obvious.
| /// Unlike [`finalize_to_row_addrs`], this is the slow direction (a | ||
| /// `RowIdSequence` scan per fragment) — it exists for [`MaterializeIndexExec`], | ||
| /// whose take-by-id contract genuinely needs row ids, and for | ||
| /// [`super::prefilter_union::PrefilterUnionExec`], whose `missing` branch is | ||
| /// pinned to row-id domain (see that module); the fast path to | ||
| /// [`super::filtered_read::FilteredReadExec`] never calls this. |
There was a problem hiding this comment.
Create follow-ups to investigate these paths and convert them to the row address domain if possible
There was a problem hiding this comment.
Filed as a follow-up rather than rolled into this PR, to keep this one scoped to the domain-tagging/reconciliation change.
9ce150a to
4e1ed86
Compare
4e1ed86 to
aef0a3c
Compare
aef0a3c to
f438408
Compare
f438408 to
1cab0a8
Compare
There was a problem hiding this comment.
The fragment-scope fix addresses the remaining blocker. The author-accepted wrapper/domain limitation remains: other plan wrappers can still cause search failures by interpreting stable IDs as addresses.
Please mark this PR with the breaking-change label: lance_index::scalar::expression::ScalarIndexLoader::row_addr_result_to_row_ids is replaced by row_id_result_to_row_addrs, so custom scalar-index loaders must update their override.
wjones127
left a comment
There was a problem hiding this comment.
Thanks, this is a nice simplification. Making row addresses the canonical domain removes the address → id → address round trip from #10960, and filtered_read.rs routing becomes plain arithmetic on the address. The mixed-domain tests in expression.rs and the zero-mask_to_offset_ranges assertion pin the core behavior well.
Approving. Nothing here blocks. Since you're out this week, I'll pick up the smaller items and the follow-ups myself:
- Domain in the type: a typed
IndexResult(inline) would remove thedebug_assert, the constructor default and theis_prefilter_uniondowncast. I'll open a follow-up for it. - Wire domain: cheap protection for untagged masks before #10961 (inline).
- Composition with #11018 and scoped I/O in
SelectionVectorToPrefilter. - Breaking-change marker, a
subtract_rangesunit test, a shared translate helper, and a few test/comment tweaks.
|
|
||
| /// Deserialize from a record batch produced by [`Self::serialize`]. | ||
| /// | ||
| /// The wire format carries no domain bit: every producer of this format |
There was a problem hiding this comment.
question(non-blocking): This changes what an untagged ScalarIndexExec batch means (row ids before, addresses now), and #10961 plans to read untagged masks as row-id domain. Mixed-version clusters are niche, so I'm OK deferring the full tag. But could we get cheap protection now by giving the address-domain layout its own column names (e.g. lower_addr/upper_addr), the same way deserialize already distinguishes TwoMask from ThreeVariant by the first column? Then an old reader fails loudly instead of misreading, a new reader can treat "lower" as legacy row ids, and deserialize gets a real domain to read instead of assuming RowAddress.
There was a problem hiding this comment.
I looked at this and I do not think it is as cheap as it looks, so I have left it out — tell me if you disagree and I will add it.
The TwoMask/ThreeVariant discrimination works because the two layouts are two separate IndexExprResultWireFormat variants: schema() is a property of the format, chosen at plan time, and PrefilterUnionExec asserts batch.schema() == format.schema(). Domain is a property of the result, not the format, so lower_addr/upper_addr cannot just be swapped into TWO_MASK_RESULT_SCHEMA — it would need a third variant plus a rule for picking it, which is format negotiation, i.e. #10961 with extra steps and a second encoding to keep forever.
It also would not buy the loud failure in the case you want it for. An old reader is an old binary, which only ever asks for the format it knows; a new writer emitting lower_addr would have to have been told to, and whatever told it could equally have told it to stay on the old contract. The mixed-version hole is the negotiation, and the column names do not close it.
What is true today and worth stating plainly: within one process the contract is "serialized means address domain", enforced at ScalarIndexExec (finalize before serialize) and documented on deserialize — with the one exception of PrefilterUnionExec, which the follow-up above removes. Across versions there is no protection until #10961, and I think that is the right place for it.
| /// Precise result — every row in `mask` is in the answer and every | ||
| /// row outside is not. Equivalent to the old `Exact` variant. | ||
| /// | ||
| /// Defaults to [`MaskDomain::RowAddress`] — the common case now that every |
There was a problem hiding this comment.
suggestion: Did you consider making the domain part of the type rather than a field? Most consumers have a fixed domain (routing/take/FTS want addresses, vector prefilter wants ids), and the field leaves that to convention: the debug_assert in &/|, the RowAddress default in constructors, and the is_prefilter_union downcast are all ways a mistag slips through.
Something like this at the evaluation boundary:
pub enum IndexResult {
Addrs(IndexExprResult<RowAddr>),
Ids(IndexExprResult<RowId>),
}
impl IndexResult {
async fn into_addrs(self, ds: &Dataset) -> Result<IndexExprResult<RowAddr>>;
async fn into_ids(self, ds: &Dataset) -> Result<IndexExprResult<RowId>>;
}into_addrs/into_ids would be the only place the domain is resolved, and a mixed & wouldn't compile. The wire still needs a tag, so this complements #10961. Not blocking this PR; I'll pick it up as a follow-up.
There was a problem hiding this comment.
I like this and did not do it here — the retagging this PR adds is exactly the kind the type would make unrepresentable, and exact/at_most/at_least defaulting to RowAddress is a default I am not thrilled about shipping.
Two things worth carrying into the follow-up. First, the debug_assert in &/| disappears for free: a mixed combine stops compiling. Second, MaskDomain is only three of the five mistag sites — is_prefilter_union is the wire boundary, not the in-memory one, so it needs the serialized selections to agree on a domain (see the thread on utils.rs) rather than a typed IndexResult. The two land independently and both are needed to delete the downcast.
| // `PrefilterUnionExec`'s own output stays row-id domain regardless of this | ||
| // wrapping; this is the one place that distinction is still recovered by node | ||
| // identity rather than an explicit tag (see `SelectionVectorToPrefilter`). | ||
| pub(crate) fn is_prefilter_union(node: &Arc<dyn ExecutionPlan>) -> bool { |
There was a problem hiding this comment.
suggestion: I wonder if we can design this away rather than widen the downcast. Any other semantics-preserving wrapper (RepartitionExec, CoalesceBatchesExec, two coalesces) still makes the consumer read row ids as addresses. Two options that each leave one rule:
- The serialized result carries its domain (pull perf(index): extend IndexExprResult wire format with a row-id/row-address domain tag #10961's tag in), and
SelectionVectorToPrefilterjust reads it. Thenis_prefilter_unionandwith_already_row_id_domaingo away. PrefilterUnionExecemits addresses too, converting itsmissingrow ids forward through theRowIdIndex(the cheap direction). Then every serialized selection is address domain, and consumers that need ids finalize them.
Which of these is the planned follow-up? If it's soon, I'm fine leaving this as is for now.
There was a problem hiding this comment.
Option 2 — PrefilterUnionExec emits addresses too. That is the one that leaves a single rule rather than a second one: every serialized selection is address domain, is_prefilter_union and with_already_row_id_domain both delete, and no wrapper can reintroduce the bug because there is no distinction left for a wrapper to lose.
Option 1 still leaves the tag as something each consumer has to read and act on, and it is blocked on #10961 landing, which I would rather not make this depend on.
The shape of it: the missing branch is a _rowid scan feeding FilteredRowIdsToPrefilter, so it would ask for _rowaddr instead — free, not the reverse conversion. The union output then stays address domain, and the one consumer that genuinely needs ids (the vector prefilter, since PQ is keyed by id) finalizes once at the end. Net slow-direction work is the same as today, except FTS stops paying for it entirely once #11018 lands. It needs touching FilteredRowIdsToPrefilter, the missing-branch plan construction, and each consumer, which is why it is not in here.
So: not blocking on my side either, and happy to leave this as is for now.
| // support both the TwoMask and the legacy ThreeVariant wire formats | ||
| // that ScalarIndexExec may emit. | ||
| let (result, _) = IndexExprResult::deserialize(&batch)?; | ||
| // Vector/PQ indices are keyed by stable row id (trained with |
There was a problem hiding this comment.
question(non-blocking): How does this compose with #11018? There, FTS prefilters translate this mask back to addresses (translate_filter_in_domain). After both land, an FTS query with a scalar prefilter would go addresses → ids here (the slow RowIdSequence direction), then ids → addresses there. That's the round trip #10960 is removing. Could the loader hand back the domain-tagged result and let each consumer finalize to what it needs? Vector search needs ids, but address-domain FTS doesn't.
Also, #11018 adds its own id → address translator next to translate_row_id_treemap_to_row_addrs here, and they handle a whole-fragment marker differently (that one passes it through untranslated, this one errors):
lance/rust/lance/src/io/exec/utils.rs
Lines 489 to 504 in 517d53c
Could we settle on one?
There was a problem hiding this comment.
On composition: yes, that ordering would be a round trip, and it is the same thing the follow-up above fixes — if PrefilterUnionExec emits addresses and each consumer finalizes to what it wants, the FTS path converts zero times and only the vector path pays, once. Short of that, the loader handing back the tagged result and letting consumers finalize is the right split; the obstacle is the serialization boundary in between, not the loader (see #10961). I would rather land #11018 against today's contract and then do the single conversion that removes both halves, than add a second partial rule here.
On the two translators: they should be one, and it should error. The whole-fragment (Full) marker is an address-domain-only shortcut — "this physical fragment matches" — and a row-id-domain index has no notion of physical fragment layout to produce one with. So a Full in a row-id-domain mask is a mistagged mask, and passing it through untranslated silently reinterprets stable ids as addresses, which is the failure mode this PR exists to remove. translate_row_id_treemap_to_row_addrs already errors on it and documents why. Since the duplicate lives in #11018, settling it there (delete the local one, call this) seems cleanest — but say the word and I will do it in whichever lands second.
| let result = if self.already_row_id_domain { | ||
| result | ||
| } else { | ||
| super::scalar_index::finalize_to_row_ids(&self.dataset, result).await? |
There was a problem hiding this comment.
question(non-blocking): Before this PR, ScopedScalarIndexLoader cut the address mask down to the scan's fragments before translating to ids. Now ScalarIndexExec emits the unscoped mask, and this converts all of it, loading row-id sequences and deletion vectors for fragments outside the scope. That looks like the same regression that was fixed in CountFromMaskExec and PrefilterUnionExec. Should this restrict to the scan's fragments first (maybe the coverage bitmap deserialize returns, if that's the right set)? A test like scoped_union_reads_only_scoped_deletions for this path would pin it.
There was a problem hiding this comment.
Fixed. SelectionVectorToPrefilter::load now narrows the mask to the producer's fragments_covered (the coverage bitmap deserialize already hands back — index coverage already intersected with ScalarIndexExec's fragment scope, and the extent over which the result is authoritative, since FilteredReadExec full-scans everything outside it) before finalize_to_row_ids. Added scoped_selection_vector_reads_only_scoped_deletions in utils.rs, modelled on scoped_union_reads_only_scoped_deletions: a mask listing matches across three fragments with coverage [1]. It fails without the narrowing (reads all three deletion files and returns 9 ids) and passes with it (fragment 1's deletion file only, ids {4, 6, 7}).
One deliberate asymmetry versus PrefilterUnionExec: only an allow-list narrows. A block list names the rows that do not match, so dropping an entry unblocks that row, and here this mask is the only thing bounding what the vector search considers. PrefilterUnionExec can narrow either shape because it intersects the scope's own allow-list immediately afterwards; there is no equivalent bound on this path. Noted in the comment on restrict_to_covered_fragments.
| } | ||
|
|
||
| /// Subtract `holes` from `ranges`. Both must be sorted, non-overlapping ranges. | ||
| fn subtract_ranges(ranges: &[Range<u64>], holes: &[Range<u64>]) -> Vec<Range<u64>> { |
There was a problem hiding this comment.
suggestion: The block-list arm of intersect_index_ranges and this subtract_ranges are new for every dataset, not just stable-row-id ones. Before, both cases went through mask_to_offset_ranges. Could we add a small unit test for this pure function: a hole spanning two ranges, a hole touching a range edge, holes past the end, plus a Full block entry in intersect_index_ranges?
There was a problem hiding this comment.
Added both, as pure unit tests next to the functions:
test_subtract_ranges: a hole inside a range (splits), one covering it (removes), holes touching either edge (trims), a hole spanning two ranges (the case wherehihas to stay put so the second range still subtracts it), two such spans, and holes past the end.test_intersect_index_ranges_by_domain: all three selections on both sides — missing /Full/Partialfor an allow-list and for a block-list — plus a case proving another fragment's entries never leak into this one.
| return Ok(result.with_domain(MaskDomain::RowAddress)); | ||
| } | ||
| let Some(row_id_index) = get_row_id_index(self).await? else { | ||
| // No row-id index built yet (e.g. an empty dataset) means no row has |
There was a problem hiding this comment.
suggestion: get_row_id_index only returns None when the dataset doesn't use stable row ids, which we've already checked above. So this arm is unreachable, and the comment about an empty dataset doesn't match:
lance/rust/lance/src/dataset/rowids.rs
Lines 224 to 230 in d829354
The same pattern in external_row_mask_as_row_addrs maps None to allow_nothing(), which would be wrong for a block-list mask if it were ever reached:
lance/rust/lance/src/dataset/scanner/source.rs
Lines 645 to 658 in 1cab0a8
Could the four copies of "check stable ids, get the index, translate" (here, finalize_to_row_addrs, row_ids_as_take_input, external_row_mask_as_row_addrs) share one helper that treats the missing index as an internal error?
There was a problem hiding this comment.
You are right on both counts, and both are gone. There is now one helper in rowids.rs:
/// The `RowIdIndex` a row-id -> row-address translation needs, or `None` when
/// the dataset has no stable row ids and an id already *is* an address, so there
/// is nothing to translate.
pub(crate) async fn row_id_index_for_translation(dataset: &Dataset) -> Result<Option<Arc<RowIdIndex>>>None now means exactly one thing — no stable row ids, nothing to translate — and a stable-row-id dataset with no index is an internal error instead of a guess. All four call sites go through it: Dataset::row_id_result_to_row_addrs, finalize_to_row_addrs, row_ids_as_take_input, and external_row_mask_as_row_addrs. That also fixes the latent None -> allow_nothing() you spotted: both take-input sites now return the input unchanged in the no-stable-ids case, which is correct for a block list too.
| .evaluate_nullable(&loader, &crate::metrics::NoOpMetricsCollector) | ||
| .await | ||
| .unwrap(); | ||
| assert_eq!(loader.conversion_count(), 1); |
There was a problem hiding this comment.
suggestion: An empty result would also come from a conversion that dropped everything. Could the address side include 2 + TEST_ADDR_OFFSET (and 3 + ...) so the expected intersection is non-empty and only matches if the row-id side was shifted?
There was a problem hiding this comment.
Good catch — an empty expectation passed for the wrong reason too easily. The address side is now {1, 2, 3, 2 + TEST_ADDR_OFFSET, 3 + TEST_ADDR_OFFSET}, so the expected intersection is {2 + OFFSET, 3 + OFFSET}: non-empty, and only reachable if the row-id side was shifted first. Combining before converting would give {2, 3} instead, so the assertion now distinguishes the two orders rather than just confirming emptiness.
| assert!(matches!(negated.upper, NullableRowAddrMask::BlockList(_))); | ||
| } | ||
|
|
||
| // --- domain-aware evaluation (issue #10960) ----------------------- |
There was a problem hiding this comment.
nitpick: A few comments reference issue numbers or what the code used to do: this one, "Regression test for issue #10960" in filtered_read.rs, "evaluate no longer guarantees that" in MapIndexExec, and the fragment.rs test comment. These go stale. Could they describe the current invariant instead?
There was a problem hiding this comment.
Agreed. Rewrote all four to state the invariant instead:
expression.rstest-section header: dropped the(issue #10960).filtered_read.rs: the test doc now says the scan path consumes an address-domain mask directly (an entry already names its(fragment_id, offset), so routing is arithmetic) and must never reach formask_to_offset_ranges, which costs O(segments) per call — no issue numbers.MapIndexExec: "evaluateanswers in whichever domain its indices used, so finalize here the same wayMaterializeIndexExecdoes" instead of "evaluateno longer guarantees that".fragment.rs: dropped the(#10960).
| /// directly — this never needs a fragment's row-id sequence (unlike legacy | ||
| /// row-id-domain masks), so it avoids opening deletion metadata, row counts, | ||
| /// and data files for non-candidate fragments without any I/O at all. | ||
| fn fragment_metadata_load( |
There was a problem hiding this comment.
praise: Nice. Routing is now pure arithmetic on the address, and the stable-routing and retained-bytes machinery goes away with it.
…ress domain Make row-address the canonical domain for the scalar-index-result pipeline on stable-row-id datasets, instead of eagerly converting every address-domain result (BTree v1+, ZoneMap, BloomFilter) to row-id domain before combining or scanning. That conversion was a pure round trip for a query with no row-id-domain predicate to reconcile with, and its first leg relied on RowIdSequence::get, which is O(segments) per call (see lance-format#10699). - Tag IndexExprResult/NullableIndexExprResult (lance-select) with a MaskDomain (RowAddress/RowId). - ScalarIndexExpr::evaluate_with_options (lance-index) leaves an address-domain leaf as-is; And/Or reconcile mixed domains by converting the row-id side forward via RowIdIndex (cheap, batched) instead of the old reverse direction, which needed a RowIdSequence scan and only supported allow-lists. - filtered_read.rs now consumes an address-domain mask directly (fragment_id/offset is already explicit in the mask), eliminating RowIdSequence::mask_to_offset_ranges from that path entirely. - Every other consumer of the old "always row-id domain" wire contract now explicitly finalizes to whichever domain it needs: MaterializeIndexExec, MapIndexExec (merge-insert), PrefilterUnionExec, CountFromMaskExec, the KNN/FTS vector-search prefilter, and the scanner's take-input/overlay-block plumbing. BREAKING CHANGE: lance_index::scalar::expression::ScalarIndexLoader's row_addr_result_to_row_ids is replaced by row_id_result_to_row_addrs, which converts in the opposite direction. A custom scalar-index loader that overrides it must be updated. IndexExprResult and NullableIndexExprResult also gain a public `domain` field. Fixes lance-format#10960 Co-Authored-By: Claude Sonnet 5 <[email protected]> Co-Authored-By: Claude Opus 5 <[email protected]>
1cab0a8 to
a41ebc8
Compare
|
Rebased onto Rebase. Four conflicts, all from
Verified afterwards: Review items. Fixed, with replies inline: the Answered rather than changed: the typed |
…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]>
Cache stable-row-ID lookups per immutable fragment so append and snapshot changes reuse unchanged work. Lookup mappings and snapshot deletion visibility are charged separately. Sparse per-fragment mappings rebuild when deletions remove at least half of the retained rows; compact range mappings stay reusable, and pruned mappings are reused only when they cover the requested snapshot. Batched sparse lookups use interleaved search while preserving physical addresses, input order, duplicates and deletion visibility. When more than 64 non-range fragments overlap in row-ID space (verified by a 64-fragment stride sample) and the snapshot satisfies cache-capacity (<=75% of `index_cache`) and live-density (>=50% live) gates, a single deletion-free `MergedSourceGroup` is built via bounded streaming parallel scatter (`Vec<AtomicU64>` + collision `overflow`, without retaining duplicate per-fragment copies) and shared across snapshots through a lightweight weak-referenced `SnapshotRowIdRoute` keyed by `(version, e_tag)`. Deletions and incremental appends reuse the same shared group while filtering only hit-fragment deletions and probing the small uncovered delta. Heavily deleted cold snapshots under tight caches (such as `small-cache` at 128 MiB / 91% deleted), disjoint fragments, and compact range fragments bypass group merging and retain the pruned per-fragment path. Persisted formats are unchanged. ### Matched `e91aafecd` vs `main` (`e03f5e2f9`) Measured on a managed Linux VM (`c4-standard-32`, Intel Xeon Platinum 8581C, 32 vCPU, 117 GiB RAM, cgroup v2, swap 0 B, Rust `1.98.1`, `release-with-debug`) against identical immutable datasets in regional GCS (`us-central1`, 100M shuffled/spilled row IDs, 1000 initial fragments, five UInt64 columns, 1000-way fragment span overlap). Both arms use the checked-in `benchmarks/row-id-cache/harness.rs`, identical immutable dataset versions and independently scanned oracles, 1 GiB metadata cache, and 4 GiB index cache (128 MiB for `small-cache`). Values average two fresh processes in reversed arm order. #### End-to-end `take_rows` (lower is better) | Scenario (budget) | `main` (`e03f5e2f9`) | PR head (`e91aafecd`) | `head` vs `main` | | --- | ---: | ---: | --- | | `no-deletes` warm p50 (4 GiB, 32 warm) | 1455.9 ms (cold 14.78 s) | 1655.4 ms (cold **6.79 s**) | **2.18x faster** cold, +13.7% warm (GCS I/O variance on 160k identical reads; resolver is **2.44x faster**) | | `no-deletes` peak RSS | 3.558 GiB | **0.957 GiB** | **3.7x lower** peak RSS | | `small-updates` 7 snaps / 56 takes (8 GiB) | 263.12 s (warm 1801.0 ms) | **99.57 s** (warm **1264.1 ms**) | **2.64x faster** total, **1.42x faster** warm | | `small-updates` peak RSS | 7.465 GiB | **0.931 GiB** | **8.0x lower** peak RSS | | `heavy-deletes` 0–91%, 56 takes (8 GiB) | 159.79 s (warm 1798.7 ms) | **89.16 s** (warm **1225.9 ms**) | **1.79x faster** total, **1.47x faster** warm | | `heavy-deletes` peak RSS | 4.122 GiB | **1.038 GiB** | **4.0x lower** peak RSS | | `small-cache` (128 MiB, 91% del, 32 warm, 4 GiB) | 145.6 ms (cold 4.51 s, 0.804 GiB) | **121.3 ms** (cold **2.23 s**, **0.251 GiB**) | **1.20x faster** warm, **2.03x faster** cold, **3.2x lower** RSS | | `default-compacted` 7 snaps / 56 takes (8 GiB) | **OOM-kill (>8 GiB)** | **63.68 s** (warm **742.7 ms**, **2.039 GiB**) | `main` OOMs; `head` completes cleanly | #### Isolated `resolve_row_ids` (lower is better) | Scenario (budget) | `main` (`e03f5e2f9`, matched 4 GiB) | PR head (`e91aafecd`, matched 4 GiB) | `head` vs `main` | | --- | ---: | ---: | --- | | `no-deletes` (1000-way overlap, 0 del, 32 warm) | cold 9636.9 ms / warm 0.0205 ms (3.560 GiB) | cold **1844.7 ms** / warm **0.0084 ms** (**0.891 GiB**) | **2.44x faster** warm, **5.22x faster** cold, **4.0x lower** RSS | | `small-updates` 7 snaps / 56 calls | **OOM-kill (>4 GiB)** | **2.34 s** / warm **0.1673 ms** (**0.887 GiB**) | `main` OOMs; `head` reuses 1 shared group across all 7 snapshots | | `heavy-deletes` 0–91%, 7 snaps / 56 calls | **OOM-kill (>4 GiB)** | **3.86 s** / warm **0.6503 ms** (**0.921 GiB**) | `main` OOMs; `head` reuses 1 shared group across all 7 snapshots | | `small-cache` (128 MiB, 91% del, 64 IDs, 32 warm) | cold 5277.0 ms / warm 34.50 ms (0.796 GiB) | cold **1937.0 ms** / warm **4.63 ms** (**0.227 GiB**) | **7.44x faster** warm, **2.72x faster** cold, **3.5x lower** RSS | | `default-compacted` 7 snaps / 56 calls | **OOM-kill (>4 GiB)** | **4.22 s** / warm **0.1434 ms** (**1.965 GiB**) | `main` OOMs; `head` completes cleanly | #### Admission, fallback & pruning ablation - **Pruning under cache pressure (prior 3-arm ablation at `2539067ab`):** On `small-cache` (128 MiB index cache, 91% deleted), removing pruning (`head-unpruned`) caused 11.3 GiB of warm cloud reads and degraded warm `take_rows` to 1387.6 ms (8.7x slower than `main`) and warm resolver to 1058.8 ms (31.6x slower than `main`). At `e91aafecd`, the cache-capacity and live-density gates automatically bypass `MergedSourceGroup` on `small-cache`, retaining pruned per-fragment caching (103.5 MiB charged, 0 warm reads, **7.44x faster** warm resolver and **1.20x faster** warm take than `main`). - **Default-compaction lifecycle (`CompactionOptions::default()`):** 1000 mixed-deletion fragments (0/5/9/25/75% deleted) compacted to 72 fragments with 0% deletions, followed by 5 steady update/delete rounds. `head` completes all 56 calls in 4.22 s (0.143 ms warm resolver) and 63.68 s full take while `main` OOM-kills at both 4 GiB and 8 GiB. - **Admission & eviction safety:** `SnapshotRowIdRoute` holds only a `Weak<MergedSourceGroup>` and accesses `MergedRowIdGroupKey` through `index_cache`, so evicted groups are never retained; single-flight per-group locks coalesce concurrent cold builds. Disjoint spilled fragments and compact inline range fragments remain on the per-fragment path without allocating a merged table. Allow memory headroom for cold preparation and coexisting complete/fragment/merged lookups when callers also invoke `get_row_id_index`. ### Validation & CI - Exact-head `e91aafecd` CI passes across all applicable checks (37 succeeded, 4 conditionally skipped, 0 failed): [Rust/Clippy/MSRV/ARM](https://github.com/lance-format/lance/actions/runs/44933829515), [Python](https://github.com/lance-format/lance/actions/runs/44933829441), and [Java 11/17/21/25](https://github.com/lance-format/lance/actions/runs/44933829393). - New unit tests in `rust/lance/src/dataset/rowids/group.rs` verify dense group cross-snapshot reuse (updates, deletes, time-travel), disjoint-fragment bypass, heavy-deletion/small-cache fallback, and `index_cache` eviction release. - Benchmark helper & configs are checked in at [benchmarks/row-id-cache](https://github.com/lance-format/lance/tree/e91aafecdeb12185d88d05350a11a7831b02c72b/benchmarks/row-id-cache). - Follow-ups noted (non-blocking): common metadata-cache deletion key ownership with #8880, and coexistence of complete and fragment representations with #11012.
Summary
Fixes #10960.
Makes row-address the canonical domain for the scalar-index-result pipeline on stable-row-id datasets, instead of eagerly converting every address-domain result (BTree v1+, ZoneMap, BloomFilter) to row-id domain before combining or scanning. That conversion was a pure round trip for a query with no row-id-domain predicate to reconcile with, and its first leg relied on
RowIdSequence::get, which is O(segments) per call (see #10699).IndexExprResult/NullableIndexExprResult(lance-select) with aMaskDomain(RowAddress/RowId).ScalarIndexExpr::evaluate_with_options(lance-index) leaves an address-domain leaf as-is;And/Orreconcile mixed domains by converting the row-id side forward viaRowIdIndex(cheap, batched) instead of the old reverse direction, which needed aRowIdSequencescan and only supported allow-lists.filtered_read.rsnow consumes an address-domain mask directly (fragment_id/offsetis already explicit in the mask), eliminatingRowIdSequence::mask_to_offset_rangesfrom that path entirely.MaterializeIndexExec,MapIndexExec(merge-insert),PrefilterUnionExec,CountFromMaskExec, the KNN/FTS vector-search prefilter, and the scanner's take-input/overlay-block plumbing.Non-goal (per the issue): the
IndexExprResultWireFormaton-the-wire schema/serialization is unchanged.Test plan
cargo test -p lance -p lance-select -p lance-index --lib— 14,081 tests pass, 0 failurescargo clippy -p lance -p lance-select -p lance-index --all-targets -- -D warnings— cleancargo fmt --check— cleantest_and_or_mixes_row_id_and_address_domain_predicatesexercises AND/OR of a row-id-domain (NGram) and address-domain (BTree) predicate on a fragmented, deleted, stable-row-id dataset, asserting against an unindexed baseline (covers both ZoneMap scalar index returns incomplete results on datasets with stable row IDs #7434-style silent drops and the perf: BTREE queries on stable-row-id tables are O(rows × row-id segments) since 14.0 (address-domain translation) #10699-style slow path)test_dense_index_scan_never_consults_row_id_sequenceinfiltered_read.rsasserts zeroRowIdSequence::mask_to_offset_rangescalls for a dense address-domain scan on a stable-row-id dataset🤖 Generated with Claude Code