Repository navigation
Conversation
📝 WalkthroughWalkthroughThe inverted-index search paths now preserve deterministic top-k results for equal BM25 scores. Boundary ties are retained during WAND and BM25 collection, deferred row IDs are resolved before final sorting, and results use score-descending then row_id-ascending ordering. ChangesDeterministic top-k ranking
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Query as WAND search
participant Collector as TopKCollector
participant Merge as BM25 merge
participant Results as Final candidates
Query->>Collector: insert scored documents
Collector->>Collector: retain k-th-score boundary ties
Collector->>Merge: materialize heap and deferred ties
Merge->>Results: resolve row_ids and sort deterministically
Results->>Query: return top-k candidates
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
6badd5f to
a7f155e
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
Note
Quiet mode is enabled, so only the most important comments were posted inline. Other review comments are grouped below.
🟡 Other comments (1)
rust/lance-index/src/scalar/inverted/index.rs-11628-11662 (1)
11628-11662: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winUse a masked non-flat predicate for this filtered FTS test.
bm25_searchpasses the prefilter’s OR result back intodocs_for_wand(...), and the relevant existing test shows an OR with an allow-list can still return!has_row_ids()before the outer deferredCandidateAddr::Pending(doc_id)resolver fixes candidates. Becausetest_fts_topk_tied_scores_stable_prefix_filteredalso usesOperator::Or, its “forces the real row_id / full-key eviction path” claim is not guaranteed by the current setup. Use a masked non-flat predicate such asOperator::Andwith an all-rows allow-list so this test matchestest_fts_topk_tied_scores_stable_prefix_unsorted_row_idswithout relying on path-coverage assumptions.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rust/lance-index/src/scalar/inverted/index.rs` around lines 11628 - 11662, Update test_fts_topk_tied_scores_stable_prefix_filtered to use a masked non-flat prefilter, such as Operator::And combined with the all-rows AllowListFilter, instead of the current Operator::Or setup. Match the predicate construction used by test_fts_topk_tied_scores_stable_prefix_unsorted_row_ids, while preserving the existing top3/top5 assertions and stable row_id ordering.
🧹 Nitpick comments (4)
rust/lance-index/src/scalar/inverted/index.rs (3)
11539-11560: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAdd
#[cfg_attr(coverage, coverage(off))]to this test-utility impl.The other test doubles in this file (
DocsRowIdReadCounter,DocsRowIdCountingReader,DocsRowIdCountingStore) carry it. As per coding guidelines: "disable coverage for test utilities with#[cfg_attr(coverage, coverage(off))]".♻️ Proposed change
+ #[cfg_attr(coverage, coverage(off))] #[async_trait::async_trait] impl PreFilter for AllowListFilter {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rust/lance-index/src/scalar/inverted/index.rs` around lines 11539 - 11560, Add #[cfg_attr(coverage, coverage(off))] to the AllowListFilter PreFilter implementation, matching the existing test utilities DocsRowIdReadCounter, DocsRowIdCountingReader, and DocsRowIdCountingStore. Do not alter the implementation methods or behavior.Source: Coding guidelines
1232-1232: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueRow-id resolution is IO-bound; consider
self.store.io_parallelism()for the fan-out.
resolve_row_idsreads the docs file's ROW_ID column, and every other IO fan-out in this file (aggregate_corpus_stats,df_for_term, partition loading) is bounded byself.store.io_parallelism(). Using the compute-intensive CPU count here is inconsistent and does not track store IO capacity.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rust/lance-index/src/scalar/inverted/index.rs` at line 1232, Update the fan-out in resolve_row_ids to use self.store.io_parallelism() instead of get_num_compute_intensive_cpus(). Keep the existing buffer_unordered behavior and ensure the concurrency limit follows the store’s IO capacity, consistent with the other IO-bound paths.
938-962: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winReplace the bare
.unwrap()s on the heap peeks/pops with.expect("reason")(or return an error).Lines 942, 952, 954 panic if the invariant ever breaks. The analogous collector in
wand.rs(TopKCollector::take_worst) returnsError::internalfor exactly this case, so the two merge paths are inconsistent. As per coding guidelines: "Never use.unwrap(),.expect(),panic!(), orassert!()in library code for fallible operations" and "Avoid bare.unwrap(); ... If unavoidable, use.expect(\"reason\")."♻️ Minimal fix using `expect`
- let kth = candidates.peek().unwrap().0.score; + let kth = candidates + .peek() + .expect("heap is full, so it holds at least one candidate") + .0 + .score; match candidate.score.cmp(&kth) { // Below the k-th score: never competitive. std::cmp::Ordering::Less => {} // Tied at the k-th score: a potential winner once row_ids are // resolved, so keep it in the boundary band. std::cmp::Ordering::Equal => overflow.push(candidate), // Strictly better on score: it enters the heap. Whether the // displaced candidate stays a boundary tie depends on the new k-th. std::cmp::Ordering::Greater => { - let Reverse(displaced) = candidates.pop().unwrap(); + let Reverse(displaced) = + candidates.pop().expect("heap is full, so pop yields the k-th"); candidates.push(Reverse(candidate)); - let new_kth = candidates.peek().unwrap().0.score; + let new_kth = candidates + .peek() + .expect("a candidate was just pushed") + .0 + .score;🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rust/lance-index/src/scalar/inverted/index.rs` around lines 938 - 962, Replace the bare unwrap calls in the candidate heap handling around candidates.peek() and candidates.pop() with descriptive expect messages, or propagate an appropriate internal error consistent with wand.rs TopKCollector::take_worst. Preserve the existing heap-selection and overflow behavior while making invariant failures explicit rather than using bare unwraps.Source: Coding guidelines
rust/lance-index/src/scalar/inverted/wand.rs (1)
4413-4487: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winGood collector coverage; add a direct unit test for
admit_ties_flooredge inputs.The tie-admission scheme rests on
admit_ties_floor, but its documented edge behavior (0.0, negative, and NaN inputs relative to thethreshold > 0.0guards) is only covered indirectly. A three-linerstestlocks the contract in place. As per coding guidelines: "Every bugfix and feature must have corresponding tests" and "Userstestfor Rust parameterized tests, use readable#[case::{name}(...)]names".💚 Proposed test
#[rstest] #[case::positive(1.0)] #[case::small(f32::MIN_POSITIVE)] fn test_admit_ties_floor_admits_kth_score_ties(#[case] kth: f32) { let floor = admit_ties_floor(kth); assert!(floor < kth, "floor {floor} must sit below the k-th score {kth}"); assert!(kth > floor, "a doc tied at the k-th score must pass `score > threshold`"); } #[rstest] #[case::zero(0.0)] #[case::negative(-1.0)] fn test_admit_ties_floor_keeps_non_positive_read_as_no_threshold(#[case] kth: f32) { assert!(!(admit_ties_floor(kth) > 0.0)); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rust/lance-index/src/scalar/inverted/wand.rs` around lines 4413 - 4487, Add direct rstest coverage for the admit_ties_floor function, using readable named cases for positive values (including f32::MIN_POSITIVE), zero, and negative input. Assert positive inputs produce a floor below the k-th score, and zero or negative inputs do not produce a positive threshold; place the tests alongside the existing TopKCollector tests.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@rust/lance-index/src/scalar/inverted/index.rs`:
- Around line 1226-1239: Update the deferred row-ID resolution flow around
resolve_row_ids and the subsequent entries.into_iter().zip(row_ids) loop to
validate that every requested doc_id produced a row ID before assigning results.
Detect any short resolution instead of allowing zip to truncate and preserve the
placeholder, then return an appropriate error consistent with the existing
resolve_deferred_candidates guard.
---
Other comments:
In `@rust/lance-index/src/scalar/inverted/index.rs`:
- Around line 11628-11662: Update
test_fts_topk_tied_scores_stable_prefix_filtered to use a masked non-flat
prefilter, such as Operator::And combined with the all-rows AllowListFilter,
instead of the current Operator::Or setup. Match the predicate construction used
by test_fts_topk_tied_scores_stable_prefix_unsorted_row_ids, while preserving
the existing top3/top5 assertions and stable row_id ordering.
---
Nitpick comments:
In `@rust/lance-index/src/scalar/inverted/index.rs`:
- Around line 11539-11560: Add #[cfg_attr(coverage, coverage(off))] to the
AllowListFilter PreFilter implementation, matching the existing test utilities
DocsRowIdReadCounter, DocsRowIdCountingReader, and DocsRowIdCountingStore. Do
not alter the implementation methods or behavior.
- Line 1232: Update the fan-out in resolve_row_ids to use
self.store.io_parallelism() instead of get_num_compute_intensive_cpus(). Keep
the existing buffer_unordered behavior and ensure the concurrency limit follows
the store’s IO capacity, consistent with the other IO-bound paths.
- Around line 938-962: Replace the bare unwrap calls in the candidate heap
handling around candidates.peek() and candidates.pop() with descriptive expect
messages, or propagate an appropriate internal error consistent with wand.rs
TopKCollector::take_worst. Preserve the existing heap-selection and overflow
behavior while making invariant failures explicit rather than using bare
unwraps.
In `@rust/lance-index/src/scalar/inverted/wand.rs`:
- Around line 4413-4487: Add direct rstest coverage for the admit_ties_floor
function, using readable named cases for positive values (including
f32::MIN_POSITIVE), zero, and negative input. Assert positive inputs produce a
floor below the k-th score, and zero or negative inputs do not produce a
positive threshold; place the tests alongside the existing TopKCollector tests.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: QUIET
Plan: Pro Plus
Run ID: 07a492b0-2bd6-43ee-9af1-781768a51473
📒 Files selected for processing (3)
rust/lance-index/src/scalar/inverted/builder.rsrust/lance-index/src/scalar/inverted/index.rsrust/lance-index/src/scalar/inverted/wand.rs
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
rust/lance-index/src/scalar/inverted/wand.rs (1)
160-195: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winNaN-score guard is unreachable while the heap is still filling up.
The NaN check at lines 191-195 only executes once the heap is full (
self.heap.len() == self.limit). The earlier "heap not yet full" fast path (lines 178-184) pushesdocunconditionally, before the NaN check runs. So a NaN-scored candidate is accepted into the top-k while the collector is still filling, but rejected once it reaches capacity — inconsistent with the stated intent ("A NaN custom-scorer score is never competitive; drop it"). This can let an uncompetitive/invalid document occupy a top-k slot (and, in deferred mode, be treated as tied at whatever the eventual k-th score becomes).🐛 Proposed fix: move the NaN check before the not-yet-full fast path
) -> Result<bool> { if self.limit == 0 { return Ok(false); } + // A NaN custom-scorer score is never competitive; drop it before it can enter the + // heap while still filling (the full-heap branch below already excludes it). + if doc.score.0.is_nan() { + return Ok(false); + } if self.heap.len() > self.limit { return Err(Error::internal(format!( "FTS top-k heap length {} exceeds limit {}", self.heap.len(), self.limit ))); } // Heap not yet full: everything is competitive. if self.heap.len() < self.limit { let slot = self.frequency_slots.push(pairs)?; self.heap .push(Reverse((doc, doc_length, posting_doc_id, slot))); return Ok(true); } let Some(worst) = self.heap.peek().map(|entry| entry.0.0.clone()) else { return Err(Error::internal( "FTS top-k heap is empty while its nonzero limit is reached", )); }; - // A NaN custom-scorer score is never competitive; drop it (also keeps NaN out of the - // `total_cmp` key, matching the pre-tiebreak collector). - if doc.score.0.is_nan() { - return Ok(false); - }None of the new tests (
test_top_k_collector_deferred_tiebreak_retains_boundary_ties,test_top_k_collector_full_key_eviction_by_row_id,test_top_k_collector_reuses_frequency_slots) exercise a NaN insert while the heap is belowlimit, so this regressed silently. Worth adding a regression test alongside the fix.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rust/lance-index/src/scalar/inverted/wand.rs` around lines 160 - 195, Move the NaN-score guard in insert before the heap-not-full fast path so doc.score.0.is_nan() always returns Ok(false), including while the heap is filling. Preserve the existing limit and capacity checks, and add a regression test covering insertion of a NaN-scored document when the heap length is below limit.
♻️ Duplicate comments (1)
rust/lance-index/src/scalar/inverted/index.rs (1)
1234-1257: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
debug_assert_eq!still lets a shortresolve_row_idsreturn silently corrupt results in release builds.This is the same risk flagged in a prior review (
resolve_row_idsreturning fewer row_ids than requested leaves the placeholderrow_id = 0set at line 1230, via theziptruncating silently). The fix replaces the earlier no-check code withdebug_assert_eq!, butdebug_assert!compiles out in release builds, so in production a length mismatch still produces a wrong-row (0) result with no error — exactly the scenario the prior review asked to guard against with an explicitErr.As per coding guidelines: "Do not silently guard against impossible conditions; use
debug_assert!, return an explicit error, or remove the check" and "Preferdebug_assert!overassert!for non-safety invariants; reserveassert!for conditions preventing data corruption" — a silently-wrong row_id returned to the caller is exactly a data-corruption outcome, so this invariant belongs behind an explicitResultcheck (orassert!), notdebug_assert!.🛡️ Proposed fix
for (entries, row_ids) in batches { - // `resolve_row_ids` maps one row_id per requested doc_id, so the lengths always match; - // the assert documents that invariant (a short return would otherwise leave placeholder - // row 0 via the `zip` below). - debug_assert_eq!(entries.len(), row_ids.len()); + if entries.len() != row_ids.len() { + return Err(Error::internal(format!( + "resolve_row_ids returned {} row_ids for {} deferred doc_ids", + row_ids.len(), + entries.len() + ))); + } for ((pos, _), row_id) in entries.into_iter().zip(row_ids) { resolved[pos].1 = row_id; } }As per coding guidelines: "Do not silently guard against impossible conditions; use
debug_assert!, return an explicit error, or remove the check." Based on a past review comment on this exact code (resolve_row_idstruncation viazip), which proposed the same explicit-error fix that was not fully applied here.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rust/lance-index/src/scalar/inverted/index.rs` around lines 1234 - 1257, Replace the `debug_assert_eq!` in the deferred row-resolution loop with an explicit error check that returns an error when `entries.len()` and `row_ids.len()` differ, before the `zip` iteration. Preserve normal resolution for matching lengths and ensure release builds cannot leave placeholder row IDs after `resolve_row_ids` truncates the mismatch.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@rust/lance-index/src/scalar/inverted/wand.rs`:
- Around line 160-195: Move the NaN-score guard in insert before the
heap-not-full fast path so doc.score.0.is_nan() always returns Ok(false),
including while the heap is filling. Preserve the existing limit and capacity
checks, and add a regression test covering insertion of a NaN-scored document
when the heap length is below limit.
---
Duplicate comments:
In `@rust/lance-index/src/scalar/inverted/index.rs`:
- Around line 1234-1257: Replace the `debug_assert_eq!` in the deferred
row-resolution loop with an explicit error check that returns an error when
`entries.len()` and `row_ids.len()` differ, before the `zip` iteration. Preserve
normal resolution for matching lengths and ensure release builds cannot leave
placeholder row IDs after `resolve_row_ids` truncates the mismatch.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: QUIET
Plan: Pro Plus
Run ID: 7f896b81-bab5-4b14-be10-8e898b1ce3d4
📒 Files selected for processing (2)
rust/lance-index/src/scalar/inverted/index.rsrust/lance-index/src/scalar/inverted/wand.rs
83d8f99 to
3ce7d38
Compare
03cbcb6 to
eb66f95
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Xuanwo
left a comment
There was a problem hiding this comment.
Thank you @sbrunk for working on this!
This branch currently conflicts with main, where the FTS search and segment-merge paths have since been refactored. From reading current main source, two porting requirements need to be covered when refreshing the branch:
- In
rust/lance-index/src/scalar/inverted/wand/maxscore.rs, MaxScore checksTopKCollector::rejects_score(rust/lance-index/src/scalar/inverted/wand/collector.rs), which rejects candidates tied with the k-th score before they reach the collector. - In
rust/lance/src/io/exec/fts/segments.rs,search_prepared_segmentsmerges segment results using a score-only comparison and needs to preserve the chosen tiebreak across partitions and segments while keepinglimit = 0valid.
Once refreshed on current main, coverage for matching equal-score rows across segments (including the prepared path) verifying that concatenated pages agree with a larger-query prefix and that limit = 0 remains valid would confirm stable pagination end to end.
eb66f95 to
e17dc28
Compare
|
I rebased the branch onto current Review comments addressed
BenchmarksApple M3, Standard
Corpus with many ties (1M docs, all containing
Probable causeLowering the WAND threshold one ULP below the k-th score lets every tie through. That stops blocks whose best possible score equals the k-th score from being skipped, so every tied document gets scored and, for phrases, position-checked. On cold queries the tie band also overflows its buffer, and the partition is searched a second time with row addresses loaded. A broad term with many ties is exactly the target case for this PR, so we have a regression exactly for the queries the PR is meant to fix. A few ideas how to improve
Open question: for cold modern partitions, knowing the order means either loading addresses or recording a "built in row order, never remapped" flag in the index metadata. The flag is cheaper but changes the stable format. |
Xuanwo
left a comment
There was a problem hiding this comment.
Thanks @sbrunk for rebasing onto main, fixing the obsolete score-band overflow flag, and sharing the tied-corpus benchmarks.
Beyond the inline note on element tie-band truncation, the broad tied-corpus regression (your measurement of warm single-term latency rising from 17.6 µs to 15.1 ms) needs to be addressed before merge:
- Preserve equality pruning whenever remaining final row keys provably cannot beat the current k-th entry, while keeping exact results.
- Re-benchmark warm and cold paths on both ordered and unordered row IDs once that pruning is in place.
- On the cross-partition idea, a publishing partition's minimum row ID alone does not bound the global k-th entry, so sibling partitions would need a sound bound before switching to strict pruning.
Xuanwo
left a comment
There was a problem hiding this comment.
One additional Dataset-level follow-up on e17dc28 (with MaxScore enabled):
When two text rows ("common filler filler filler", "common") are indexed and a third "common" row is appended unindexed, running MatchQuery("common") on text with boost = 0.0 (all zero scores) returns row IDs [0, 1] for LIMIT 2, while LIMIT 1 OFFSET 0 and LIMIT 1 OFFSET 1 together return [1, 1]. Could we preserve the final (score, row_id) order across indexed and unindexed rows for this case and add a page-concatenation regression test?
For context on other Dataset-level checks on the same head: reversed segments, LIMIT 0, and the ordinary Dataset-written 130-element fixture all pass (the reverse-coordinate failure in my inline comment above reproduces at the index level).
e17dc28 to
169abc5
Compare
There was a problem hiding this comment.
❌ Gate recommendation: request changes.
The zero-boost case and rank-1–4 element selection are fixed. The existing element-band finding remains for deeper coordinates, and the score-transform finding remains for positive boosts that collapse scores. The new LSM element merge also disagrees with its source cutoffs.
Keep the order-aware fast path, but make the changed candidate-selection and merge paths use the same complete order, including full element paths and final boosted scores. Use an exact fallback where that order cannot be evaluated before truncation; sorting the survivors cannot recover discarded winners.
| }]; | ||
| if let Some((idx, _)) = merged.schema().column_with_name(DOC_INDEX_COL) { | ||
| sort_expr.push(PhysicalSortExpr { | ||
| expr: Arc::new(Column::new(DOC_INDEX_COL, idx)), |
There was a problem hiding this comment.
The merge now orders equal scores by _doc_index, but a memtable still truncates by (score DESC, row_position ASC, doc_index ASC). Consequently, even a single memtable can return a different first hit when the limit changes: with rows id=1, tags=["other", "beta"] and id=2, tags=["beta", "other"], LIMIT 1 returns (1, [1]), whereas LIMIT 2 starts with (2, [0]). Both scores are 0.49191087. This breaks the stable-prefix contract and can duplicate or skip hits when paging ordinary tied element searches.
Carry one complete tie key, including row identity, through source cutoffs and the merge, or defer truncation until that order is available. Sorting by coordinate after the row-first cutoff cannot recover the discarded winner.
Reproducer
Extend this file's new element_document_score_ties_break_on_doc_index test. In its hits helper, replace the match constructor with:
MatchQuery::new("beta".to_string()).with_operator(
lance_index::scalar::inverted::query::Operator::And,
)Keep schema.clone() in the test's first LsmFtsSearchPlanner::new(...) call, then append:
let batch = arrow::compute::concat_batches(
&schema,
&[
element_tags_batch(&schema, 1, &["other", "beta"]),
element_tags_batch(&schema, 2, &["beta", "other"]),
],
)
.unwrap();
let active = element_memtable(&schema, batch, 1);
let collector = LsmDataSourceCollector::without_base_table(
format!("{}/single", tmp.path().display()),
vec![],
)
.with_in_memory_memtables(
uuid::Uuid::new_v4(),
InMemoryMemTables {
active,
frozen: vec![],
},
);
let planner = LsmFtsSearchPlanner::new(
collector, vec!["id".to_string()], schema,
);
let top_two = hits(&planner, Some(2), &projection).await;
let top_one = hits(&planner, Some(1), &projection).await;
assert_eq!(top_one, top_two[..1], "single memtable must preserve prefix");Run:
cargo test --profile ci -p lance element_document_score_ties_break_on_doc_index --lib -- --nocaptureOn 7ff133d, the final assertion fails with left: [(1, 1, 0.49191087)], right: [(2, 0, 0.49191087)]. Using AND exercises the row-first source cutoff independently of the OR heap selection.
The rebased prepared-segment merge uses the shared ranked collector, with reversed-segment and zero-limit coverage. 7ff133d
Xuanwo
left a comment
There was a problem hiding this comment.
The reversed-coordinate and zero-boost pagination regressions now pass. A positive-boost OR query still drops the wrong tied row in FtsMemIndex before the final sort.
I tested one flushed partition with alpha filler filler at row positions 0 and 1 and alpha at position 2. Searching for alpha with OR, boost 2.0, and the tail excluded returned [2, 0, 1] without a limit. Rows 0 and 1 had bit-identical scores. With limit=2, the same query returned [2, 1].
TopK::offer rejects a later equal-score candidate even when its key is better. When a higher score arrives, the reversed heap can also evict the smaller of two tied keys. Please use the final tie order for admission and eviction, and prune an equal score only when its key cannot win. A regression comparing the limited result with the exhaustive prefix, with candidates offered in both orders, covers both cases. Gatekeeper's AND example separately exercises the ordering between a memtable cutoff and the final merge.
`ScoredDoc::cmp` compares score, then row_id, then doc_index. The segment merge, the cross-partition merge and the scanner use that comparator. `TopKCollector::insert()` rejects a NaN score, so a custom scorer cannot take the top of a result. A tie group reads the same at any limit.
A WAND walk visits documents in DocId order. Where a partition's row addresses are resident and ascend with DocId, `TopKCollector::insert()` rejects a document tied at the k-th score and leaves the score threshold at the raw k-th score. Where the addresses are not resident, `insert()` keeps the tied documents in a band of at most `limit + SCORE_FLOOR_BUFFER`. The merge ranks that band once the row addresses are read.
`insert()` retains a boundary tie like any other candidate and sets `aborted` once the retained band reaches `limit + SCORE_FLOOR_BUFFER`. A retry pays off where the corpus ties at the k-th score throughout. The ascending-address rejection stays inside the rank-tie branch. Above the branch it rejects every candidate once the heap is full, and the k-th score stops improving.
- The collector's mode enum is `TieOrdering`; `TieHandling` stays with the compound path. - The wand and compound paths share `SCORE_FLOOR_BUFFER`. - `TopKKey` and `TopKRankKey` derive order from `Reverse` fields. - `retain_displaced()` covers both heap eviction sites. - `Wand` reads `TopKCollector::aborted`, so `score_floor_overflow` is gone. - `push_top_k_document` in lance-index serves the segment merge and the search candidates path. - `load_modern_partition` takes `ModernScoringContext`.
Element-granular FTS returns one hit per list element. The elements of one row share a row address, so the collector's tie key could not separate them: it kept them in a band capped at `limit + SCORE_FLOOR_BUFFER`, and a full band settled the group on the posting DocId. DocId matches `doc_index` only when elements were appended in coordinate order, so a row whose elements are stored with `doc_index` descending returned the wrong winner and its top-k was not an ordered prefix of its top-k at a larger limit. `WandDocuments::tie_order` returns the row address and a packed coordinate key. `ElementCoordinateKey` holds ranks 0-1 and ranks 2-3, one u64 each, so u64 order equals comparing rank by rank. The key comes from a resident projection of the partition's coordinate columns, attached when the walk has resident row addresses and `coordinate_rank <= 4`. Those columns are the ones the cross-partition merge already reads: the projection reuses the cached entry, and the read sits after the visibility and posting checks. A partition deeper than that gets no key. Its ties stay retained, the band cap applies, and `band_truncated` reports a group that the DocId proxy settled. The collector records whether the key covers every rank of the partition, so a debug build catches a tie ranked outside the ranks it covers.
…ex score The index collector ranks hits by its own BM25 score and, with a limit pushed into the leaf, cuts its top-k there. `MatchQueryExec` multiplies the emitted scores by `MatchQuery::boost` afterwards. A boost of 0.0 maps every hit onto 0.0, so the cut was made in an order the plan never returns: `LIMIT 2` gave [0, 1] while one-row pages gave [1, 1], repeating one row and dropping another. A scan with an offset and no limit has the same shape with any boost, because no candidate budget reaches the leaves and each leaf emits its own order. - `match_leaf_params` withholds the pushed limit unless the boost is positive. Such a leaf collects every hit and the plan sorts them into the final score space. `validate_fts_query_contract` admits no other non-positive boost. - `combine_fts_leaf_plans` re-sorts an indexed-only leaf when the scan has a fetch, and `Scanner::fts_page_order` sorts the source when the scan skips rows without one. A scan with neither a limit nor an offset, and a scan with `order_by`, keep the leaf order: the first is not paged, and the second is re-sorted and paged by the caller's ordering. - Memtable search ranks with the boost applied and orders hits by score, row position and document coordinate before truncating. The hit list comes from a `HashMap`, so the score-only comparator picked the truncated top-k by `HashMap` order, which the merge upstream cannot reproduce. - The LSM element merge breaks score ties on `_doc_index`. Its `_rowid` key is dropped: the canonical FTS schema fills that column with a typed NULL, so the key compared NULL to NULL and would have ordered real NULL rows last. A leaf without a pushed limit collects every match. Within one memtable that is bounded by `max_memtable_rows`, 100_000 by default. An offset scan with no limit sorts the whole source.
7ff133d to
22656a4
Compare
The heap evicted the best key of a tied score band, so a better-keyed equal-score candidate was rejected and a limit kept the worse half of every tie. Entries now order score ascending and key descending. Block-max, the MaxScore prefix bound and the candidate probe now prune strictly: partitions are not walked in key order, so the k-th score can come from a candidate with a worse key, and an equal bound can still hold a row that wins on key. The whole-tail bound still prunes on equality: it is scored last, over newer row positions only. When every block bound equals the k-th score, block-max skipping is lost.
The packed coordinate key covers four doc_index ranks; past that the collector fell back to posting DocId, which is not part of the result order, and a row dropped there cannot come back when the merge sorts the survivors. It now also compares the partition's coordinate columns for the deeper ranks, so DocId only splits candidates already identical on score, row id and coordinates. Coordinate columns are now projected for element partitions of any rank.
A boost of 0.0 puts every hit at score 0.0, so the leaf's own BM25 score ranks nothing. Dropping the pushed limit, as the previous fix did, let the leaf walk and materialize its whole corpus. The leaf now keeps its limit and selects on the tie order instead. Over an index of 262144 documents at LIMIT 10 the index search falls from 296 ms and 262144 candidates to 9.7 ms and 10. Element partitions and compound queries still walk unbounded.
There was a problem hiding this comment.
❌ Gate recommendation: request changes.
Deep-coordinate selection is fixed. The positive score-collapse and MemWAL cutoff/merge failures remain; both can omit or repeat results when the limit changes.
Keep the order-aware fast path, but apply the same complete final order before candidate cutoffs and across source merges. Rank in the final boosted-score space and use a consistent full tie key; where that order is unavailable, use an exact fallback before truncation.
Please mark this PR with the breaking-change label: lance_index::scalar::inverted::query::FtsSearchParams adds the public constant_score field, so Rust callers constructing it with struct literals must initialize that field.
Problem
Lance resolved equal BM25 scores by encounter and pruning order, which varies with
kand with the order partitions finish. So the top-k at a small limit was not an ordered prefix of the top-k at a larger limit, and paging a broad tied term (many documents sharing tf and document length, so identical BM25) duplicated and skipped rows across pages.Lucene avoids this with a secondary sort
(score DESC, docId ASC). This PR brings the same guarantee to the plain FTS path:supports_compound_scorerreturns false for a top-levelMatch/Phrase, so the common query runsMatchQueryExec/PhraseQueryExec→bm25_search→wand::TopKCollector, which was score-only.Result order is
(score DESC, row_id ASC, doc_index ASC), wheredoc_indexapplies to list-element granularity. The collector, the cross-partition merge, the cross-segment merge and the indexed/flat union sort all use that key.Change
Ordered key.
ScoredDoc::cmpcompares score, then row id, thendoc_index. The collector's rank key and the plan-levelSortExec(fts_score_sort_exprs) carry the same key, with_doc_indexappended for element plans.Order-aware pruning. The collector ranks ties when it can prove its order key matches the final order, and retains documents on equal keys otherwise. A walk whose partition holds resident, strictly increasing row addresses ranks ties and keeps the WAND floor at the raw k-th score: a tied top-10 walk scores 128 documents out of 8,192, and that test fails at 8,192 scored if the branch is removed (
test_ascending_row_addresses_prune_a_tied_walk_at_the_raw_kth_score). Any other walk lowers the floor by one ULP, so score-only prune tests keep documents tied at the k-th score rather than dropping them. Both tie bands are bounded atlimit + SCORE_FLOOR_BUFFER(128). The pruning kernels are untouched.Deferred addresses. A partition whose band fills is retried once with a row-address projection, so its ties rank instead of being retained.
Wand::score_floor_overflowdrives the retry, which runs in parallel with bounded fan-out. An earlier revision lowered the score floor for every partition instead; that is what cost tie-heavy searches their pruning.Element coordinates. The elements of one row share a row address, so ranking their ties needs the element coordinate.
WandDocuments::tie_orderreturns the row address and a packeddoc_indexkey,ElementCoordinateKey, covering coordinate ranks 0-3, read from the partition's coordinate columns. Element ties are then ranked during the walk and the element band stays empty. A partition withcoordinate_rank >= 5gets no key: its ties stay retained, the cap applies, and the collector reportsband_truncated, marking a group that the posting DocId settled. That report is adebug!line; there is no metric for it.Cut in the final score space. The index collector ranks by its own BM25 score, while
MatchQueryExecmultiplies emitted scores byMatchQuery::boostafterwards, so a boost of 0.0 makes the cut in an order the plan never returns.match_leaf_paramswithholds the pushed leaf limit unless the boost is positive. Memtable search ranks with the boost applied and orders hits by score, row position and document coordinate before truncating; its hit list comes from aHashMap, so the score-only comparator picked the truncated top-k by hash order. The LSM element merge breaks score ties on_doc_index.Scanner::fts_page_ordersorts an FTS source when the scan skips rows without a fetch, which is the same problem at any boost.Row ids
ScoredDoc.row_idholds a document key: a row address for legacy indexes, a dense per-partitionDocIdfor modern ones. Address order matches DocId order only for un-remapped partitions, so ranking keys on the resolved row address.Correctness within a dataset version does not depend on stable row ids; the key needs to be unique and comparable, which holds for both legacy row addresses and stable row ids. Stable row ids additionally keep the order stable across compaction. This matches Lucene, whose
docIdtiebreak is deterministic within a searcher version but not stable across segment merges.Performance
Two corpora, 1M documents each: a Zipf corpus (what
cargo bench --bench invertedbuilds) and a tie-dense corpus where half the documents share the top score, in a single partition, cold and warm caches. Bench binaries built up front, sides alternating across 3 rounds with a separateCRITERION_HOMEper round and side, Apple M3 Max. Run-to-run spread in these rounds was under 1%, so the ratios are readable. Absolute levels differ from the earlier runs in this thread; read ratios.invert_search(1000000)invert_phrase_search(1000000)tie_term_coldtie_or_coldtie_and_coldtie_phrase_coldtie_term_warmtie_or_warmtie_and_warmtie_phrase_warminvert_indexingandinvert_indexing_with_positionswere measured on an earlier revision of this branch: median ratios 0.96 and 1.00 against the same base, with 13-15% run-to-run spread. The build path only gained a comparison inScoredDoc::cmp._rowidcolumn read, about 0.9 ms on this corpus, plus re-walking the partition. OR, AND and phrase cold cases land at 1.10-1.17x, and warm cases are flat or slightly faster. A candidate patch reuses the first walk's posting lists for the retry and removes about a third of the single-term cost, but it holds that partition's postings and visibility across the retry and can retain a query's whole posting footprint, so it is left out pending a decision on that memory bound.LIMIT 10went from 632 ms to about 4 s; a 100k-row memtable atLIMIT 10went from 327 us to 13.2 ms. Zero boost is opt-in; the Python default is 1.0. Applying the boost before the indexed cut would keep pruning and needs the boost threaded intoSearchOptionsand the memtable search.Limits
coordinate_rank >= 5: ties past the band cap settle on the posting DocId. Reported bydebug!, not by a metric.coordinate_rankcomes fromlist_depthand has no cap.(_score, _doc_index)across memtable arms keep union-partition order, because the canonical FTS schema fills_rowidwith a typed NULL.Tests
cargo test -p lance-index --lib4267 passed (3 ignored),cargo test -p lance --lib11232 passed (9 ignored),cargo check --workspace --tests --benchesclean.doc_index, end to end and through the indexed/flat union, includingdoc_indexdescending against DocId past the band cap, and nested lists at coordinate ranks 2, 3 and 4. The rank-5 test pins exact order inside the cap and states the boundary.doc_indexwhen row addresses are not resident.admit_ties_floorat zero, negative and NaN._doc_index.with_limit, which makes segment truncation externally reachable.