Skip to content

feat(index)!: change Inverted (FTS) scalar index to row-address domain - #11018

Merged
westonpace merged 15 commits into
mainfrom
claude/inverted-index-row-address-ece48a
Dec 2, 2026
Merged

westonpace merged 15 commits into
mainfrom
claude/inverted-index-row-address-ece48a

Conversation

@westonpace

@westonpace westonpace commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Summary

Completes the scalar-index row-address migration (#9481 BTree → #9814 Bitmap/LabelList → #9858 NGram/RTree/MinHash LSH, all merged): Inverted (FTS) was the last builtin scalar index type still in the row-id domain. It now stores physical row addresses (fragment_id << 32 | offset) for each document instead of the dataset's logical row id.

Format and domain tracking

  • New INVERTED_ROW_ADDR_DOMAIN_VERSION (4), orthogonal to the posting-list format axis (INVERTED_INDEX_VERSION_V1/V2/V3, tracked via file metadata rather than index_version): a row-address-domain segment can pair with any posting format.

  • index_version(), results_are_row_addrs() and can_follow_stable_row_ids() version-gate on it, matching the earlier migrations.

  • build_scalar_index relabels a fresh build's index_version back down to the legacy posting-format version on a dataset without stable row ids (where row id == row address, so an older reader still reads it correctly) — the same relabeling every other migrated type does.

  • The document identity column in docs.lance is named for its domain: _rowaddr from version 4, _rowid in versions 1–3. This follows MinHash LSH, the only other migrated type that had an identity column literally named _rowid (see docs/src/format/index/scalar/minhash_lsh.md and minhash_lsh/mod.rs, which renames the same way and resolves the name from the file schema on read). The remaining migrated types — BTree ids, Bitmap/LabelList bitmaps, NGram posting_list, RTree id — use domain-neutral column names and had nothing to rename, so no migrated scalar index now leaves a column named _rowid holding addresses.

    The name tracking the version is worth more than tidiness: a reader that ignores index_version finds no such column rather than silently reading one domain's values as the other's. Because build_scalar_index relabels down for older readers, the name is chosen before the file is written, from the version the segment will be committed with — TrainingRequest gains a defaulted set_stable_row_ids hook so only FTS implements it. Rewrites keep their source's version and therefore its column: a loaded DocSet records the name it read and derived builders inherit it, so no merge, remap or consolidation path has to remember. Readers resolve the name from the file's own schema (docs_identity_column), so one reader serves both.

Changes the migration requires

These are hazards the migration introduces and this PR handles — not fixes to pre-existing defects. None of them can fail on the base commit, because before this PR there was no address-domain FTS segment for them to go wrong on; the applicable test is "fails with the hunk reverted on this branch", which is what the coverage below was measured against.

  • append.rs / index/scalar/inverted.rs: the old-data filters used during a segment merge now use the segment's actual domain instead of a hardcoded false. Reverting this fails stale_posting_after_in_place_update_with_stable_row_ids and test_optimize_fts_consolidates_single_row_appends::stable_ids.
  • append.rs: legacy_domain_mismatch forces a full rebuild rather than merging a legacy row-id-domain segment alongside a fresh address-domain one. Pinned by test_optimize_append_rebuilds_stray_legacy_fts_segment_with_stable_row_ids (previously uncovered — reverting it changed nothing in the suite).
  • FTS pushes its deletion/filter/overlay masks straight into the index's own search as a live prefilter, checked against physical postings before any row-id translation — unlike other scalar types, which translate an index's address-domain results into row ids before any mask check (ScalarIndexExec's convention). Forcing only the deletion mask into address domain was not enough: the externally supplied filtered_ids/external_mask and the overlay-staleness block mask follow the same row-id-domain convention and needed the same translation (io/exec/utils.rs's row_id_mask_to_row_addr_domain/translate_treemap_to_row_addr_domain, applied at every FTS prefilter boundary). Reverting it fails 46 tests.
  • create.rs no longer refuses creating a new Inverted index while a live fragment-reuse index exists: that guard assumed Inverted always stored row ids.

Addressed from review

  • Mixed identity domains across columns. A multi-column FTS query merges several named indexes' postings on the stored identifier alone, so rebuilding one column's index after an upgrade left its sibling on the older domain and an AND query silently returned nothing. fts_segments_are_address_domain now resolves the one domain every segment agrees on and errors naming both offenders; the callers already pass every segment a query reads, so the same check covers the cross-column and within-index cases.
  • Row-address segment coverage. Opening a multi-segment FTS index under stable row ids failed outright (segment coverage of row-address hits has no live row ids): open_fts_segment asked for a stable-row-id allow-list unconditionally. SegmentCoverage::allowed_row_mask now serves both restrictions, allowing each covered fragment whole for address-domain hits.
  • Tied-result pagination. Top-k selection ranks ties by the stored identifier, which is now an address, while the plan above sorts by _rowid; paging a tie skipped and repeated rows. Selection cannot be re-keyed — combined_maxscore discovers candidates in ascending stored-id order and its pruning depends on that — so the order is reconciled after selection: searches retain extra candidates, and a tie at the cutoff larger than that margin is completed exactly (the escape hatch the WAND tie certificate already had). Applied to combined fields, both compound paths, Match and Phrase.
  • Spec text stated normatively (reader/writer rules rather than library behaviour); translate_treemap_to_row_addr_domain reports a whole-fragment entry instead of silently passing it through untranslated; the repeated relabel-to-row-id-domain test snippet extracted as utils::test::as_legacy_row_id_segment, documenting that its segment still holds addresses while claiming row ids; comment/nit fixes.

Tests

  • Updated or replaced tests whose premise was "Inverted is the last row-id-domain scalar index type" across append.rs, create.rs, frag_reuse_with_stable_row_ids.rs, dataset/optimize/tests*, dataset/write/update.rs, dataset/mem_wal/index/tests.rs and index/tests/lifecycle.rs.
  • index/tests/lifecycle.rs's test_compaction_survives_an_unsupported_index renamed to test_compaction_drops_coverage_of_an_unsupported_index_it_rewrites: its premise no longer holds for any scalar index type.
  • New: mixed-domain rejection (cross-column and within-index), docs.lance identity column asserted for both domains and across a merge, tie pagination within and beyond the re-rank margin and across four query shapes, translate_treemap_to_row_addr_domain unit tests, and a Python compat test InvertedRowAddressDomainIndex mirroring NgramRowAddressDomainIndex.

Known gaps

  • Compaction's eager-remap vs. unreadable-index gap. plan_groups_with_budget's unreadable_coverage hold-back only runs without stable row ids; under stable row ids it relies on supports_eager_remap, a type-level capability check that does not account for a specific index instance being unreadable. Predates this PR and affects every address-domain scalar type — it was only ever hidden because Inverted was the last type that could dodge it in tests. Flagged as a follow-up.
  • Tie ordering is reconciled above the collectors, in each exec. Teaching the collectors to retain ties at the k-th score in one pass would remove both the retained margin and the exact-completion replay.
  • build_prefilter / build_prefilter_restricted_to_fragments still have _in_domain siblings. Collapsing them needs the overlay-block translation made lazy first, since the merged function would otherwise be async while three vector execute() bodies are sync.

Test plan

  • Rebased onto main (was 11 commits behind; picked up cd45844c9, which fixes the HnswQueryParams compile error that was failing clippy/builds/MSRV)
  • cargo test -p lance --lib — 11459 passed, 1 failed (test_only_proven_address_indices_are_compatible::case_10_rtree_address_domain, which also fails on origin/main; unrelated to this PR)
  • cargo test -p lance-index --lib — 4185 passed
  • cargo clippy -p lance -p lance-index --lib --tests and cargo fmt clean
  • Full CI green (41/41 excluding the format-spec vote) as of 01da7a07e
  • CI for the identity-column rename (99d810578, 87935eb6e) — still running
  • Python compat suite — relies on CI. Schema-driven reading should let an existing version-4 fixture written before the rename still open, but that is reasoning rather than evidence; worth watching that job specifically.

🤖 Generated with Claude Code

@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 repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

@github-actions github-actions Bot added A-python Python bindings A-index Vector index, linalg, tokenizer A-format On-disk format: protos and format spec docs format-change A change to the format spec, which requires a vote. Remove if minor (e.g. fixing typo). enhancement New feature or request breaking-change labels Nov 12, 2026
@github-actions

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Important

Format specification vote

This PR modifies the Lance format specification, so it requires 3 binding +1 votes from PMC members (excluding the proposer), at least one of them on the latest commit, and a minimum 72-hour voting period, weekends excluded, before it can merge. Vote by approving this PR (+1) or requesting changes (−1, a veto). See the voting process.

Approvals carry over across pushes, so a rebase or a typo fix does not send everyone back to re-vote. Whoever approves the latest commit is vouching that nothing substantive has changed since the earlier approvals; if something has, ask for fresh votes.

Status: ❌ Blocked — vetoed by @wjones127

Approvals none (0/3)
Latest commit approved by none — one PMC member must approve the latest commit
Vetoes @wjones127
Voting period elapsed — ended Tue 2026-11-17 22:32 UTC (14:32 PST)

Updated automatically by the format-spec vote gate, which re-checks every 15 minutes — just voted? Re-check now (press Run workflow; leave the input blank to re-check every open format PR). A PMC member may apply the format-waived label to waive the vote for a trivial edit (typo, wording, formatting).

Base automatically changed from claude/youthful-heisenberg-xazxmj to main November 12, 2026 22:33
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Nov 12, 2026
@westonpace
westonpace force-pushed the claude/inverted-index-row-address-ece48a branch from 9db3e56 to 83e249c Compare November 13, 2026 14:46
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Nov 13, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Nov 13, 2026
@westonpace
westonpace force-pushed the claude/inverted-index-row-address-ece48a branch from 83e249c to 517d53c Compare November 13, 2026 18:00
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Nov 13, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Nov 13, 2026

@wjones127 wjones127 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.

Thanks for finishing this off. Moving Inverted onto row addresses is the last piece of the migration, and the version gating and Python compat test follow the earlier PRs closely, which made this much easier to review. The coverage drop for newer-build indices on compaction is an expected trade-off we accepted for this transition, so no concerns there.

Blocking:

  • Tests for the two fixes. The prefilter-domain fix and the merge old-data-filter fix each need a test that fails on the base commit.
  • Mixed-domain indexes. The query paths trust the first segment's domain. Please check that all segments agree when opening, and error if they don't.
  • Untranslated fallback. translate_treemap_to_row_addr_domain should error instead of passing a row-id mask through.
  • +1 to both gatekeeper findings, which still look open at this head: mixed domains across columns in combined-fields/cross-column queries and tie-breaking before top-k translation.

Non-blocking: how this composes with #11012 (which I'm merging, so this will need a rebase), spec wording and the _rowid column name, the cold-query lookup cost, and a few cleanups inline.

/// is vanishingly unlikely to appear in a row-id-domain mask (it would
/// require 2^32 contiguous ids), so it is left untranslated rather than
/// failing the query.
pub(crate) async fn translate_treemap_to_row_addr_domain(

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.

issue(blocking): The description calls out two real bugs fixed here, but I can't find a test that fails without either fix:

  1. Prefilter domain: on a stable-row-id dataset with at least two fragments, run an FTS query with a scalar filter (plus a deletion) that matches a row in fragment 1. Without this translation, the row-id-domain filter and the address-domain postings disagree.
  2. The append.rs merge using the segment's own domain for its old-data filter (the stale posting after an in-place update).

For the translation itself, a small unit test of translate_treemap_to_row_addr_domain on an in-memory stable-row-id dataset would pin it cheaply: allow-list and block-list, rows in fragment > 0, and a row moved by an update. This is resolved when each fix has a test that fails on the base commit.

Comment thread rust/lance/src/io/exec/fts/segments.rs Outdated
dataset: &Dataset,
segments: &[IndexMetadata],
) -> bool {
!dataset.manifest.uses_stable_row_ids()

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.

question(blocking): The prefilter domain, the SegmentCoverage domain, and fts_row_addr_to_row_id all take the first segment's domain as the whole index's domain (here, and again in inverted.rs). A committed index shouldn't mix legacy and v4 segments, but the only guard is legacy_domain_mismatch in optimize_indices. commit_existing_index_segments doesn't check, and a writer with a bug could produce one.

Could fts_segments_are_address_domain check that every segment agrees and return an error if not? Then a mixed index fails loudly when it's opened instead of returning wrong rows. To unblock: that check plus a test that commits a mixed index and asserts the query errors.

dataset: &Dataset,
treemap: &RowAddrTreeMap,
) -> Result<RowAddrTreeMap> {
let Some(row_ids) = treemap.row_addrs() else {

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.

issue(blocking): If any entry is Full, row_addrs() returns None and this returns the whole treemap untranslated, including every Partial entry it could have translated. The caller then ANDs a row-id-domain mask into an address-domain one and silently filters the wrong rows. A Full entry in a row-id-domain mask means 2³² contiguous ids, which in practice means a fragment-shaped mask was mislabeled, so that's a bug we'd want to hear about. Could this return an error instead? To unblock: that branch errors.

Separately, this reads confusingly because the row ids live in a RowAddrTreeMap, so row_addrs() yields ids. The typed-domain follow-up from #11012 would fix that, so nothing to do here beyond the error.

/// by convention) is translated into the same address domain so ANDing it
/// into the deletion mask compares like with like, and so is `overlay_block`.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn build_prefilter_in_domain(

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.

question(non-blocking): How does this fit with #11012? There, SelectionVectorToPrefilter takes ScalarIndexExec's address-domain mask and finalizes it to row ids:

pub(crate) struct SelectionVectorToPrefilter {
stream: SendableRecordBatchStream,
dataset: Arc<Dataset>,
// The wire format carries no domain bit, so the producer's identity decides
// how to interpret it: `ScalarIndexExec` always emits row-address domain
// (needs converting, see below), but `PrefilterUnionExec` already finalizes
// its own combined result to row-id domain before serializing (to match its
// `missing` branch) — converting its output again would corrupt it, treating
// genuine row ids as if they were addresses.
already_row_id_domain: bool,
}

This PR then translates that same mask back into addresses for FTS. So an FTS query with an indexed filter goes address -> row id -> address, which is exactly the round trip #11012 is removing. Could FTS ask prefilter_mask_future for its mask in address domain directly, instead of translating it afterward? Both PRs also change prefilter_mask_future, so one of them will need rebasing onto the other either way.

Comment thread docs/src/format/index/scalar/fts.md Outdated
An FTS index may contain multiple partitions. Each partition has its own set of token, document, and posting list files, prefixed with the partition ID (e.g. `part_0_tokens.lance`, `part_0_docs.lance`, `part_0_invert.lance`). The `metadata.lance` file lists all partition IDs in the index. At query time, every partition must be searched and the results combined to produce the final ranked output. Fewer partitions generally means better query performance, since each partition requires its own token dictionary lookup and posting list scan. The number of partitions is controlled by the training configuration -- specifically `LANCE_FTS_TARGET_SIZE` determines how large each merged partition can grow (see [Training Process](#training-process) for details).

From format version 4 onward, a segment stores a physical row address (`fragment_id << 32 | offset`) in `docs.lance._rowid` instead of the dataset's logical row id. A segment persisted before version 4 stores a row id there instead. The current implementation supports format versions 1 through 3; format version 4 is specified here but is not yet implemented.
From format version 4 (`INVERTED_ROW_ADDR_DOMAIN_VERSION`) onward, a segment stores a physical row address (`fragment_id << 32 | offset`) in `docs.lance._rowid` instead of the dataset's logical row id. A segment persisted before version 4 stores a row id there instead. This version is independent of the posting-list format below (tracked separately via file metadata, not `index_version`): a row-address-domain segment can pair with any posting format.

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.

suggestion: Since this is the spec, could we state it as rules for implementations rather than describe what the library does? In particular, readers need to know they must pick the domain from index_version, and writers need to know when a v1-3 label is still allowed.

Suggested change
From format version 4 (`INVERTED_ROW_ADDR_DOMAIN_VERSION`) onward, a segment stores a physical row address (`fragment_id << 32 | offset`) in `docs.lance._rowid` instead of the dataset's logical row id. A segment persisted before version 4 stores a row id there instead. This version is independent of the posting-list format below (tracked separately via file metadata, not `index_version`): a row-address-domain segment can pair with any posting format.
From format version 4 (`INVERTED_ROW_ADDR_DOMAIN_VERSION`) onward, `docs.lance._rowid` holds the document's physical row address (`fragment_id << 32 | offset`). In versions 1 through 3 it holds the dataset's row id. Readers must interpret `_rowid` according to the segment's `index_version`. Writers may label a segment with version 1 through 3 only on a dataset without stable row ids, where row ids and row addresses are equal. A reader that supports version 4 must also support every capability of version 3. The posting-list format is recorded separately and must not be inferred from `index_version`.

.iter()
.map(|fragment| fragment.id as u32)
.collect::<Vec<_>>();
let lookup = live_row_addr_to_row_id_lookup(dataset, fragment_ids).await?;

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.

question(non-blocking): This builds the address → row-id lookup from every fragment in the dataset, loading each one's row-id sequence and deletion vector (live_row_addr_to_row_id_lookup), even when the query returns 10 rows. Repeat queries hit the cache, but a cold query pays O(fragments) I/O to translate a handful of results. Could we translate only the final top-k addresses with row_addrs_to_row_ids (or restrict the lookup to the fragments those addresses touch)? Fine as a follow-up.

/// by convention) is translated into the same address domain so ANDing it
/// into the deletion mask compares like with like, and so is `overlay_block`.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn build_prefilter_in_domain(

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.

suggestion: build_prefilter_in_domain(..., false) does the same thing as build_prefilter, and the same goes for the _restricted_to_fragments pair and the two DatasetPreFilter constructors. Could we collapse each pair into one function that takes the domain? Then FTS callers choose a domain explicitly, and there's one path to maintain.

.execute_uncommitted()
.await
.unwrap();
let legacy_segment = IndexMetadata {

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.

suggestion: This relabel-to-v0 snippet and its comment show up about nine times across the tests. Could it be one helper, e.g. commit_as_legacy_row_id_segment? Also, the segment it commits still holds addresses while claiming to be row-id domain. That's fine for guard and rejection tests, but a test that queries through it would get wrong answers. A doc note on the helper would keep someone from reaching for it there.

Comment thread rust/lance/src/index/scalar/inverted.rs Outdated
/// marks row-address-domain segments; it is independent of the posting-list
/// format, which every such segment already carries explicitly in
/// `details.posting_format_version` (see `InvertedIndexPlugin::train_inverted_index`),
/// so the fallback below never needs to synthesize one for it.

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.

nitpick: This says the fallback never needs to synthesize a posting format for v4, but 3 | 4 => 3 below does exactly that. Either drop the 4 arm or reword the comment to say why v4 falls back to V3.

Comment thread rust/lance/src/index/create.rs Outdated
let indices = load_all_indices(self.dataset).await?;
// These always store row ids, so refuse them before training.
// Vector indices always store row ids, so refuse them before training.
// Inverted used to as well, but it now trains in row-address domain

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.

nitpick: I'd drop the history in lines 245-248. The PR records it, and the comment only needs to say why vector indices are refused.

@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Nov 16, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added K-changes Latest Gatekeeper recommendation requests changes. and removed K-changes Latest Gatekeeper recommendation requests changes. labels Nov 16, 2026
@westonpace
westonpace force-pushed the claude/inverted-index-row-address-ece48a branch from 517d53c to a1a668e Compare November 23, 2026 19:30
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Nov 23, 2026
@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

❌ 1 Tests Failed:

Tests completed Failed Passed Skipped
11737 1 11736 0
View the full list of 1 ❄️ flaky test(s)
lance::hybrid_udtf::hybrid_field_path_payload::case_2_backtick

Flake rate in main: 100.00% (Passed 0 times, Failed 1 times)

Stack Traces | 0.672s run time
thread 'hybrid_field_path_payload::case_2_backtick' (94232) panicked at .../lance/tests/hybrid_udtf.rs:1059:9:
assertion `left == right` failed: hybrid projection="a`b": RecordBatch { schema: Schema { fields: [Field { name: "a`b", data_type: Int32, nullable: true }], metadata: {} }, columns: [PrimitiveArray<Int32>
[
  null,
  null,
  null,
]], row_count: 3 }
  left: 3
 right: 0
stack backtrace:
   0: __rustc::rust_begin_unwind
             at .../std/src/panicking.rs:679:5
   1: core::panicking::panic_fmt
             at .../core/src/panicking.rs:80:14
   2: core::panicking::assert_failed_inner
             at .../core/src/panicking.rs:434:23
   3: core::panicking::assert_failed::<usize, usize>
             at .../core/src/panicking.rs:394:5
   4: {async_fn#0}
             at ./tests/hybrid_udtf.rs:1059:9
   5: {async_block#0}
             at ./tests/hybrid_udtf.rs:1029:1
   6: poll<&mut dyn core::future::future::Future<Output=()>>
             at .../src/future/future.rs:133:9
   7: {closure#0}<core::pin::Pin<&mut dyn core::future::future::Future<Output=()>>>
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../scheduler/current_thread/mod.rs:830:70
   8: with_budget<core::task::poll::Poll<()>, tokio::runtime::scheduler::current_thread::{impl#9}::block_on::{closure#0}::{closure#0}::{closure_env#0}<core::pin::Pin<&mut dyn core::future::future::Future<Output=()>>>>
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../task/coop/mod.rs:167:5
   9: budget<core::task::poll::Poll<()>, tokio::runtime::scheduler::current_thread::{impl#9}::block_on::{closure#0}::{closure#0}::{closure_env#0}<core::pin::Pin<&mut dyn core::future::future::Future<Output=()>>>>
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../task/coop/mod.rs:133:5
  10: {closure#0}<core::pin::Pin<&mut dyn core::future::future::Future<Output=()>>>
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../scheduler/current_thread/mod.rs:830:25
  11: <tokio::runtime::scheduler::current_thread::Context>::enter::<core::task::poll::Poll<()>, <tokio::runtime::scheduler::current_thread::CoreGuard>::block_on<core::pin::Pin<&mut dyn core::future::future::Future<Output = ()>>>::{closure#0}::{closure#0}>
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../scheduler/current_thread/mod.rs:486:19
  12: <tokio::runtime::scheduler::current_thread::CoreGuard>::block_on::<core::pin::Pin<&mut dyn core::future::future::Future<Output = ()>>>::{closure#0}
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../scheduler/current_thread/mod.rs:829:44
  13: <tokio::runtime::scheduler::current_thread::CoreGuard>::enter::<<tokio::runtime::scheduler::current_thread::CoreGuard>::block_on<core::pin::Pin<&mut dyn core::future::future::Future<Output = ()>>>::{closure#0}, core::option::Option<()>>::{closure#0}
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../scheduler/current_thread/mod.rs:906:68
  14: <tokio::runtime::context::scoped::Scoped<tokio::runtime::scheduler::Context>>::set::<<tokio::runtime::scheduler::current_thread::CoreGuard>::enter<<tokio::runtime::scheduler::current_thread::CoreGuard>::block_on<core::pin::Pin<&mut dyn core::future::future::Future<Output = ()>>>::{closure#0}, core::option::Option<()>>::{closure#0}, (alloc::boxed::Box<tokio::runtime::scheduler::current_thread::Core>, core::option::Option<()>)>
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../runtime/context/scoped.rs:40:9
  15: tokio::runtime::context::set_scheduler::<(alloc::boxed::Box<tokio::runtime::scheduler::current_thread::Core>, core::option::Option<()>), <tokio::runtime::scheduler::current_thread::CoreGuard>::enter<<tokio::runtime::scheduler::current_thread::CoreGuard>::block_on<core::pin::Pin<&mut dyn core::future::future::Future<Output = ()>>>::{closure#0}, core::option::Option<()>>::{closure#0}>::{closure#0}
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../src/runtime/context.rs:186:38
  16: try_with<tokio::runtime::context::Context, tokio::runtime::context::set_scheduler::{closure_env#0}<(alloc::boxed::Box<tokio::runtime::scheduler::current_thread::Core, alloc::alloc::Global>, core::option::Option<()>), tokio::runtime::scheduler::current_thread::{impl#9}::enter::{closure_env#0}<tokio::runtime::scheduler::current_thread::{impl#9}::block_on::{closure_env#0}<core::pin::Pin<&mut dyn core::future::future::Future<Output=()>>>, core::option::Option<()>>>, (alloc::boxed::Box<tokio::runtime::scheduler::current_thread::Core, alloc::alloc::Global>, core::option::Option<()>)>
             at .../src/thread/local.rs:463:12
  17: <std::thread::local::LocalKey<tokio::runtime::context::Context>>::with::<tokio::runtime::context::set_scheduler<(alloc::boxed::Box<tokio::runtime::scheduler::current_thread::Core>, core::option::Option<()>), <tokio::runtime::scheduler::current_thread::CoreGuard>::enter<<tokio::runtime::scheduler::current_thread::CoreGuard>::block_on<core::pin::Pin<&mut dyn core::future::future::Future<Output = ()>>>::{closure#0}, core::option::Option<()>>::{closure#0}>::{closure#0}, (alloc::boxed::Box<tokio::runtime::scheduler::current_thread::Core>, core::option::Option<()>)>
             at .../src/thread/local.rs:427:20
  18: tokio::runtime::context::set_scheduler::<(alloc::boxed::Box<tokio::runtime::scheduler::current_thread::Core>, core::option::Option<()>), <tokio::runtime::scheduler::current_thread::CoreGuard>::enter<<tokio::runtime::scheduler::current_thread::CoreGuard>::block_on<core::pin::Pin<&mut dyn core::future::future::Future<Output = ()>>>::{closure#0}, core::option::Option<()>>::{closure#0}>
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../src/runtime/context.rs:186:17
  19: <tokio::runtime::scheduler::current_thread::CoreGuard>::enter::<<tokio::runtime::scheduler::current_thread::CoreGuard>::block_on<core::pin::Pin<&mut dyn core::future::future::Future<Output = ()>>>::{closure#0}, core::option::Option<()>>
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../scheduler/current_thread/mod.rs:906:27
  20: <tokio::runtime::scheduler::current_thread::CoreGuard>::block_on::<core::pin::Pin<&mut dyn core::future::future::Future<Output = ()>>>
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../scheduler/current_thread/mod.rs:819:24
  21: {closure#0}<core::pin::Pin<&mut dyn core::future::future::Future<Output=()>>>
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../scheduler/current_thread/mod.rs:216:33
  22: tokio::runtime::context::runtime::enter_runtime::<<tokio::runtime::scheduler::current_thread::CurrentThread>::block_on<core::pin::Pin<&mut dyn core::future::future::Future<Output = ()>>>::{closure#0}, ()>
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../runtime/context/runtime.rs:65:16
  23: block_on<core::pin::Pin<&mut dyn core::future::future::Future<Output=()>>>
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../scheduler/current_thread/mod.rs:204:9
  24: <tokio::runtime::runtime::Runtime>::block_on_inner::<core::pin::Pin<&mut dyn core::future::future::Future<Output = ()>>>
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../src/runtime/runtime.rs:379:52
  25: block_on<core::pin::Pin<&mut dyn core::future::future::Future<Output=()>>>
             at .................................................../home/runner/.cargo.................................................../registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54..../src/runtime/runtime.rs:348:18
  26: case_2_backtick
             at ./tests/hybrid_udtf.rs:1029:1
  27: hybrid_udtf::hybrid_field_path_payload::case_2_backtick::{closure#0}
             at ./tests/hybrid_udtf.rs:1029:10
  28: <hybrid_udtf::hybrid_field_path_payload::case_2_backtick::{closure#0} as core::ops::function::FnOnce<()>>::call_once
             at .../src/ops/function.rs:250:5
  29: <fn() -> core::result::Result<(), alloc::string::String> as core::ops::function::FnOnce<()>>::call_once
             at .../src/ops/function.rs:250:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

To view more test analytics, go to the Test Analytics Dashboard
📋 Got 3 mins? Take this short survey to help us improve Test Analytics.

lance-gatekeeper[bot]

This comment was marked as outdated.

lance-gatekeeper[bot]

This comment was marked as outdated.

@wjones127 wjones127 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.

Thanks for working through all of these. Everything that blocked last time is addressed. The translation and the merge filter each have tests now, and the row_addr_domain_tests unit tests are what I had in mind. Mixed domains error at open, both within an index and across columns. Whole-fragment masks error on stable-row-id tables. The tie-pagination findings are resolved. Renaming the v4 column to _rowaddr to match the spec is a nice change too.

Blocking: the identity column and the format version are set independently on the write path. As a result, train_inverted_index can produce a v4 segment with a _rowid column (see inline). I'd like the column derived from the version, so a mismatch can't be written.

Non-blocking:

  • The reader accepts either identity column regardless of version, despite the doc saying it's checked.
  • The v4 posting-format fallback, the stale_rows translation condition, and one first-segment holdover in open_fts_segments.
  • thought: A reminder for the docs follow-up: main's fts.md says version 4 "is specified here but is not yet implemented", and its prose puts v4 addresses in docs.lance._rowid while the table says _rowaddr. Both are wrong once this merges, so it'd be good to get that PR into the same release.

I didn't re-review the tie-completion paths in compound/match/phrase in detail, since #11489 removes them.

Comment thread rust/lance-index/src/scalar/inverted.rs Outdated
// this back to the legacy row-id-domain version (via
// `relabel_as_row_id_domain`) on a dataset without stable row
// ids, where a row id and a row address are the same value.
index_version: INVERTED_ROW_ADDR_DOMAIN_VERSION,

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.

issue(blocking): This always returns version 4, but the identity column comes from a separate argument, and train_inverted_index still passes ROW_ID. So the public entry point now produces a v4 segment with a _rowid column, which the spec allows only in v1-3. The in-tree caller is the legacy reindex in remap.rs. That path looks broken already, since it requests neither a row id nor a row address column:

let training_data = load_training_data(
dataset,
&field_path,
&TrainingCriteria::new(TrainingOrdering::None),
None,
true, // Legacy reindexing should always train
None,
TrainingScanOptions::default(),
)
.await?;
InvertedIndexPlugin::train_inverted_index(
training_data,
&new_store,
inverted_index.params().clone(),
None,
Arc::new(NoopIndexBuildProgress),
)
.await?

The batch-remap bug the gatekeeper found had the same shape: column and version decided in different places. What if the column were derived from the version instead of passed alongside it? For example, decide the target version once before training and have the builder take that. Then with_identity_column, the != ROW_ID adoption heuristic in InnerBuilder's merge, and most of set_stable_row_ids go away. These are new public signatures, so now is the cheap time to change them.

This is resolved when a v4 segment can no longer be written with _rowid, for example because the column is derived from the version. I'd also like a test that goes through train_inverted_index.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done in 9c48e7e — took the suggestion: the version is now the single input and the column is derived from it.

train_inverted_index_at_version(..., index_version) derives the column through InvertedIndexPlugin::identity_column_for_version, refuses a version this build does not write for the given params, and stamps what it was given. train_inverted_index is that at INVERTED_ROW_ADDR_DOMAIN_VERSION, so the public entry point can no longer produce v4 + _rowid. The training request carries index_version instead of a column, so set_stable_row_ids settles it before training — which means relabel_as_row_id_domain and its branch in build_scalar_index are gone, as is with_identity_column on InvertedIndexBuilder (now at_index_version).

InnerBuilder::merge_from no longer adopts whichever side looked non-default; it errors on a mismatch. Both builders default to the row-address domain, matching every other default in this PR.

You were right about remap.rs, and the same fix found a second one:

  • remap.rs's legacy reindex requested neither a row id nor a row address, so the rebuilt segment had no identity column at all. It now scans _rowaddr and picks its version the way build_scalar_index does.
  • mem-WAL flush had its own copy of the legacy-version rule and wrote the column from an unrelated default. With the builder's default flipped these disagreed, and the new load-time check (your other comment) caught it. Both now come from one flushed_index_version.

Test through train_inverted_index is train_names_the_identity_column_for_its_version in index/tests/lifecycle.rs: trains at the default and at the legacy version, then reads the column off the written docs.lance rather than off the loaded index, whose own name would agree either way. train_rejects_a_version_it_does_not_write covers the refusal.

///
/// The domain carried here is the one the *manifest* declares through
/// `index_version`, which the segment's own `docs.lance` identity column is
/// then checked against. Defaulting it to row addresses -- what every build

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.

issue(non-blocking): This says the docs.lance identity column is checked against the manifest's domain, but I can't find that check. docs_identity_column takes whichever of _rowaddr/_rowid the file has, regardless of results_are_row_addresses. That leniency is why the batch-remap bug (a v4 segment written with _rowid) only showed up in a schema assertion.

Could load error when the column disagrees with the declared domain? Then the rename guards this reader too, not just other implementations. One catch: as_legacy_row_id_segment relabels a segment that has _rowaddr, so the FTS tests that use it would need a real legacy file.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You're right, there was no such check — the doc described what I'd intended, not what the code did. Implemented in 9c48e7e, and the doc now matches.

PartitionDocuments resolves its identity column once at load and keeps it (the three read paths that each re-derived it now share that one value), PartitionDocumentStore exposes it, and InvertedIndex::load rejects any partition whose column contradicts the declared domain.

It immediately earned its keep: mem-WAL flush was writing _rowaddr into segments it committed at a legacy version, which nothing would have reported before.

And yes, the fixtures needed real legacy files. crate::utils::test::rewrite_fts_docs_to_row_id_column rewrites a segment's docs.lance to name _rowid, and as_legacy_row_id_fts_segment wraps it with the relabel plus a refresh of the recorded file sizes. The combined-fields legacy_row_id_segment helper (which already remapped contents) calls the rewrite too. One wrinkle worth knowing if you hit it: the rewrite has to go through a cache-free store, since a store that has already read those files serves the old schema back.

as_legacy_row_id_segment keeps its relabel-only behaviour for the other index types, where the two domains really do share a layout.

// fresh build now produces (see `INVERTED_ROW_ADDR_DOMAIN_VERSION`).
let column_stale_rows = match stale_rows.get(slot).filter(|rows| !rows.is_empty()) {
Some(rows)
if !dataset.manifest.uses_stable_row_ids()

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.

question(non-blocking): Why translate when stable row ids are off? Without them, this calls translate_treemap_to_row_addr_domain directly. That skips the no-stable-row-ids short-circuit you added in row_id_mask_to_row_addr_domain for Xuanwo's whole-fragment case, so a stale set with a whole-fragment entry would error here. I couldn't tell whether stale_rows can hold one. This also picks the domain from indices.first() rather than the one resolved for the query. If #11489 replaces this block, fine to leave it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch — fixed in 9c48e7e rather than left to #11489.

The !uses_stable_row_ids() arm was wrong twice over: there the two domains coincide so the translation is a no-op, and running it anyway routes through translate_treemap_to_row_addr_domain, which rejects a whole-fragment entry as a mislabelled mask. I couldn't prove stale_rows never holds one either, which is reason enough not to depend on it. The condition now matches row_id_mask_to_row_addr_domain: translate only under stable row ids.

On the domain source: per-column is deliberate, since bm25_row_stats_for_terms compares each column's stale set against that column's own index — on a multi-column query those are different indexes. A query whose columns disagree is rejected further down, where their segments resolve together. I've said that in the comment.

Comment thread rust/lance/src/index/scalar/inverted.rs Outdated
0 | 1 => 1,
2 => 2,
3 => 3,
3 | 4 => 3,

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.

suggestion: The doc above says V3 is the only posting format a v4 segment is ever written with. But format.rs says a v4 segment can pair with any posting format, and training with V1/V2 params on a stable-row-id dataset does produce one:

// Version 4: `docs.lance`'s identity column holds physical row addresses
// instead of row ids. Independent of the posting-list format above (still
// read from file metadata, not from this version): a V4 segment can pair
// with any posting format, since training always scans row addresses now
// and this version is only overridden back to one of V1-V3 on a dataset
// without stable row ids, where a row id and a row address are the same
// value. See `ngram_index_version`/`BTREE_ROW_ADDR_DOMAIN_VERSION` for the
// same pattern on other scalar index types.

Every v4 writer records posting_format_version, so I'd make a v4 segment without it an error instead of guessing V3. Once v4 ships, a lenient fallback is something readers have to keep supporting.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed, and the doc was simply wrong — format.rs is right that any posting format pairs with v4. Fixed in 9c48e7e: normalize_inverted_details now errors on a v4 segment with no posting_format_version instead of guessing V3, and the doc says why rather than claiming V3 is the only pairing.

Two fixtures had to become coherent with that: the mem-WAL metadata test now supplies the field for its v4 cases (and covers V1/V2/V3 all pairing with 4, plus the new rejection), and the unavailable-tokenizer test's "no manifest tokenizer" details keep posting_format_version — that test is about a missing tokenizer, not missing format metadata.

// disagree fails loudly rather than answering from two numbering systems
// at once.
fts_segments_are_address_domain(dataset, segments)?;
let row_domain = match segments.first() {

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.

question(non-blocking): fts_segments_are_address_domain already returns the resolved domain. Why re-read segments.first() here? With stable row ids they agree, because the check errors first. Without stable row ids they don't: the helper returns true, but first() is usually a relabelled legacy segment and gives RowId. If RowId is intended there, a short comment would help.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

RowId is intended, and the comment is now there (9c48e7e).

The two are answering different questions. fts_segments_are_address_domain says whether the results need translating, and returns true for everything once stable row ids are off. row_domain says how to read the identifiers a segment stores, which is what its index_version declares. They agree wherever it matters: under stable row ids the check has already rejected any disagreement, and without them a row id and a row address are the same value, so coverage resolves identically either way.

/// Row ids 0..4 lie in fragments 0 and 1, so the second fragment's ids and
/// addresses disagree. Translating has to move exactly those.
#[tokio::test]
async fn translates_row_ids_in_every_fragment() {

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.

praise: Thanks for these. Allow and block lists, a second fragment, and a row moved by an update are the cases I was hoping for.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks! Those were the cases that kept catching me while writing the translation, so they seemed worth pinning.

lance-gatekeeper[bot]

This comment was marked as outdated.

lance-gatekeeper[bot]

This comment was marked as outdated.

lance-gatekeeper[bot]

This comment was marked as outdated.

@Xuanwo

Xuanwo commented Dec 1, 2026

Copy link
Copy Markdown
Member

(AI-generated review comment)

On an unbounded, unordered Match leaf, MatchQueryExec copies every document score into a Vec<f32> and sorts it. With requested_limit == None, cutoff_tie_unresolved always returns false, so the vector and its worst-case O(n log n) sort have no effect on the result. Score collection and sort

Could you check that a cutoff is possible before collecting the scores? Both limits must be present, requested > 0, documents.len() >= searched, and documents.len() > requested. Bounded searches that reach the widened cap would still check for ties and replay when needed.

lance-gatekeeper[bot]

This comment was marked as outdated.

@westonpace

Copy link
Copy Markdown
Member Author

@Xuanwo good catch, and you're right about the shape of it — fixed in 00ac034.

The collect-and-sort is now gated on cutoff_may_be_tied(count, requested, searched), the count-only half of the preconditions: both limits present, requested > 0, count >= searched, count > requested. cutoff_tie_unresolved calls the same function rather than repeating the test, so the gate cannot drift from the check it guards — this PR has twice been bitten by a predicate living in two places, so that seemed worth doing properly.

Two notes beyond what you flagged:

The waste was worse than one sort. On an unbounded search documents is the entire match set, so it was an O(n) allocation plus an O(n log n) sort at exactly the point where n is largest — which compounds the materialization cost tracked in #11456 rather than being independent of it. The same gate now also covers the phrase path in phrase.rs, which allocated the score vector unconditionally for the same always-false check.

Bounded searches that reach the widened cap are unaffected: they still sort, check, and replay. The sort itself has to stay — unordered_results (#11669) lets a leaf skip its final sort, and cutoff_tie_unresolved reads scores positionally, so taking them in search order would make the check read arbitrary positions.

Tests in io::exec::fts::segments: test_cutoff_may_be_tied_admits_everything_the_full_check_resolves sweeps every shape of (count, requested, searched) and asserts cutoff_tie_unresolved implies cutoff_may_be_tied, with a guard against the implication holding vacuously; test_cutoff_may_be_tied_is_false_without_a_bound pins the case you reported.

For context on how much to invest here: #11489 removes this machinery entirely by keeping the whole execution path in the row-address domain, so the plan ranks on the identifier selection already ranks on and no tie ever needs holding. I kept the fix minimal for that reason rather than restructuring around it.

lance-gatekeeper[bot]

This comment was marked as outdated.

@westonpace

Copy link
Copy Markdown
Member Author

Review keeps going back and forth. Much of the review is about things that are obsoleted by #11489

Should I just fold that PR into this one? Or can we move this one forward and move on to the next one? I feel like I'm spinning my wheels a little.

@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 with a non-blocking risk.

For the scope question, I recommend moving #11018 forward and keeping #11489 as a separate follow-up. It is stacked on this head and proposes carrying row addresses through final sorting; it can be assessed after #11018 lands. The cutoff and maintenance fixes remain verified. No blocking issue found, and no further changes are requested for this revision.

The author-accepted resource trade-off remains: broad searches or large cutoff ties can materialize all matches, so CPU and memory can scale with the full match set despite small result limits. Selective prefilters reduce that working set. Same-version deterministic pagination remains required; tie order across compaction for unpinned readers is unspecified.

For stable-ID tables, serialized ScalarIndexQuery batches carry row addresses; direct native prefilter handoffs, PrefilterUnionExec batches, FilteredRowIds, external masks and overlay masks carry logical row IDs. FTS translates logical inputs to its stored domain and emits logical row IDs. Mixed-version distributed execution remains unverified; #11456 tracks documenting and testing that boundary.

@Xuanwo

Xuanwo commented Dec 2, 2026

Copy link
Copy Markdown
Member

Review keeps going back and forth. Much of the review is about things that are obsoleted by #11489

Should I just fold that PR into this one? Or can we move this one forward and move on to the next one? I feel like I'm spinning my wheels a little.

I believe we can just move forward!

westonpace and others added 15 commits December 2, 2026 11:04
Stacked on #9858 (NGram/RTree/MinHash LSH), stacked on #9814 (Bitmap/LabelList),
stacked on #9481 (BTree). This completes the scalar-index migration: Inverted
was the last builtin scalar index type still in the row-id domain, and now
stores physical row addresses (fragment_id << 32 | offset) in docs.lance's
identity column (still named `_rowid`) instead of row ids.

- New INVERTED_ROW_ADDR_DOMAIN_VERSION (4), orthogonal to the posting-list
  format axis (tracked separately via file metadata, not index_version).
- index_version()/results_are_row_addrs()/can_follow_stable_row_ids() gate on
  it; build_scalar_index relabels a fresh build back to the legacy version on
  a non-stable-row-id dataset, matching every other migrated type.
- append.rs/scalar/inverted.rs: old-data filters and legacy-domain-mismatch
  rebuild now use the segment's own domain instead of a hardcoded row-id
  assumption, fixing a real bug where a stale posting after an in-place
  update under stable row ids leaked through a merge.
- FTS's own deletion/filter/overlay masks (DatasetPreFilter, IndexVisibility)
  are checked directly against an address-domain index's own stored
  addresses, before any row-id translation -- they now translate the
  row-id-domain conventions every other mask follows into that same domain
  instead of silently comparing unrelated numeric spaces.
- create.rs no longer refuses creating an Inverted index under a live
  fragment reuse index: it applies to Inverted like every other scalar type
  now.
- Updated or replaced tests that assumed Inverted was "the last row-id-domain
  index" across append.rs, create.rs, frag_reuse_with_stable_row_ids.rs,
  dataset/optimize/tests, dataset/write/update.rs, and index/tests/lifecycle.rs,
  largely via the manual legacy-segment-relabel pattern already used for the
  prior migrations. Added an Inverted case to a few other-type-parametrized
  tests confirming it now behaves like every other address-domain index.
- New Python compat test InvertedRowAddressDomainIndex; format docs updated.

Known gap: a latent gap in compaction's eager-remap-vs-unreadable-index path
(planning.rs's `unreadable_coverage` hold-back only applies without stable
row ids) was exposed by this migration removing the last index type that
could dodge it, but predates this PR and affects every address-domain index
type, not just Inverted -- flagged separately for follow-up.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Y3hhWk6pkpoQgZywMu49WT
A multi-column FTS query (`combined_fields`, a cross-column compound)
merges several *named indexes*' postings on the stored identifier alone.
Since Inverted moved to the row-address domain, that identifier only means
the same thing in every column if every column's index was built since the
migration. Rebuilding one column's index after an upgrade leaves its
sibling on the older domain, and then one column's row id `2` and the
other's row address `1 << 32` for the same row score as two unrelated
documents: an AND query silently returns nothing.

`fts_segments_are_address_domain` took the first segment's domain as the
whole query's, so nothing noticed. It now resolves the one domain every
segment agrees on and errors naming both offenders otherwise. The callers
already pass every segment the query reads -- `all_segments` and
`selected_segments` span all target columns -- so the same check covers
the cross-column case and the within-index one. `open_fts_segments`
applies it too, the chokepoint every indexed FTS path funnels through.

`fts_row_addr_to_row_id` now takes that resolved domain instead of
re-deriving one from a representative index, so the domain the results are
translated out of cannot drift from the one the postings and masks were
read in.

Within one named index this mix is already refused at write time
(`manifest_build`'s per-name check, and `optimize_indices`'
`legacy_domain_mismatch`); the read-side check covers a manifest written
by another implementation. Across named indexes nothing refuses it at
write time and nothing could -- rebuilding one column is a legitimate
commit on its own, and only a query spanning both makes the pair wrong --
so rejecting it at read time is the only place it can be caught.

No check runs without stable row ids, where a row id and a row address are
the same number and `build_scalar_index` deliberately relabels fresh
builds down to a legacy version.

Co-Authored-By: Claude Opus 5 <[email protected]>
Opening a multi-segment FTS index under stable row ids failed outright with
"segment coverage of row-address hits has no live row ids".

`SegmentCoverage::resolve` gives a row-address-domain index
`Restriction::Fragments` -- a hit must lie in a fragment the segment still
covers -- while a row-id-domain one gets `Restriction::LiveRowIds`.
`open_fts_segment` asked for the latter unconditionally via `live_rows`,
which errors for anything else. The filtering paths (`restrict`,
`restrict_lookup`) already handled both through `AllowedRows`; only FTS,
which hands the restriction to the segment's own search to apply while it
scores, was still row-id only.

`allowed_row_mask` now serves that shape for both restrictions, allowing
each covered fragment whole for row-address hits. A fragment is one entry
with no per-row bitmap, so a coverage spanning the whole table costs one
small entry per fragment rather than one per row -- the reason the per-row
path walks hits instead of coverage does not apply to building the mask.

This only surfaced once Inverted moved to the row-address domain, since
before that every FTS segment resolved to `LiveRowIds`. It accounted for 97
of the 98 failures `cargo test -p lance --lib` showed on this branch; the
suite is now at parity with the base commit (11408 passed, 1 pre-existing
unrelated RTree failure).

Co-Authored-By: Claude Opus 5 <[email protected]>
Addresses the review's "I can't find a test that fails without either
fix". Measured each fix by reverting it on this branch and running the
suite, rather than assuming:

- Prefilter domain translation (`utils.rs`): already covered -- 46 tests
  fail with `translate_filter_in_domain`/`translate_overlay_block_in_domain`
  neutered.
- Old-data filter domain (`append.rs`, `false` -> `idx.results_are_row_addrs()`):
  already covered -- `stale_posting_after_in_place_update_with_stable_row_ids`
  and `test_optimize_fts_consolidates_single_row_appends::stable_ids` both
  fail when it is put back.
- `legacy_domain_mismatch` (`append.rs`): genuinely uncovered. Reverting it
  changed nothing in the suite. Pinned here by
  `test_optimize_append_rebuilds_stray_legacy_fts_segment_with_stable_row_ids`,
  the FTS counterpart of the existing BTree/NGram
  `test_optimize_append_rebuilds_stray_legacy_segment_with_stable_row_ids`:
  append-mode optimize selects no old segments to merge, so without the
  check a stray row-id-domain segment is left beside a fresh
  address-domain delta. Its consequence is a hard failure rather than
  corruption -- `manifest_build`'s per-name guard rejects the commit, so
  optimize errors -- which the test now pins.

Also adds the requested direct unit tests for
`translate_treemap_to_row_addr_domain` (`row_addr_domain_tests`): rows in
fragments past the first, allow-list and block-list shapes, a row moved by
an update, and ids that no longer resolve.

Note none of these can fail on the *base* commit: before Inverted moved to
the row-address domain there was no address-domain FTS segment, so
`results_are_row_addrs()` was always false for Inverted and the hardcoded
`false` was correct. These are hazards the migration introduces and this PR
handles, not fixes to pre-existing defects, so "fails on the base commit"
is unsatisfiable for them; "fails with the hunk reverted on this branch" is
the criterion that applies, and is what was measured above.

Co-Authored-By: Claude Opus 5 <[email protected]>
… tests

- `translate_treemap_to_row_addr_domain` now reports a whole-fragment entry
  instead of returning the treemap untranslated. In a row-id-domain mask
  such an entry would mean 2^32 contiguous row ids, so it really means an
  address-domain mask was mislabelled upstream; passing it through handed
  the caller a mask it then ANDed into an address-domain one, and silently
  dropped the translation of every `Partial` entry beside it. Nothing in
  the suite produces one, confirming it was unreachable-by-design rather
  than relied upon.

- FTS format spec: state the domain rule normatively -- what readers must
  do with `_rowid`, when writers may still label a segment 1-3, that a
  version-4 reader must support everything version 3 does, and that the
  posting format is recorded separately and must not be inferred from
  `index_version`.

- Extract the repeated relabel-to-row-id-domain snippet (12 copies across
  5 files) as `utils::test::as_legacy_row_id_segment`, and say once, on the
  helper, what the comment used to say at each site -- including the part
  that was never written down: the segment it returns still stores row
  addresses while claiming row ids, so it is right for testing that the
  system detects the domain and wrong for testing what a query through it
  returns.

- `normalize_inverted_details`: the comment claimed the fallback never
  synthesizes a posting format for version 4 while the arm below it mapped
  `3 | 4 => 3`. Keep the arm -- a segment arriving without the field should
  be read, not rejected -- and say why.

- `create.rs`: drop the note about what Inverted used to do; the comment
  only needs to say why vector indices are refused.

Co-Authored-By: Claude Opus 5 <[email protected]>
Paging one row at a time through three equal-scoring rows returned
`[1, 1, 2]` instead of `[0, 1, 2]`, with no writes between pages.

Top-k selection ranks ties by the identifier the index stores, and that is
now a row address. It cannot do otherwise: `combined_maxscore` discovers
candidates in ascending stored-id order (`.min()` over the cursor heads),
and its pruning is sound only because a candidate tying the threshold
arrives after, and so loses to, every incumbent. Re-keying the heap on
translated row ids -- the obvious fix -- would break that invariant, since
candidates would still arrive in address order.

So the ordering is reconciled after selection instead. An update moves a
row's address without moving its row id, so selection keeps the lowest
*address* among ties while the plan above sorts by `_rowid`; with a tight
limit the row the plan would have ranked first was never returned at all,
and paging repeated its neighbour. Each search whose results will be
translated now retains `FTS_TIE_RERANK_BUDGET` extra candidates, so a tie
group at the cutoff is held whole rather than cut at an arbitrary address,
and `finalize_row_ids_and_scores` orders the survivors by
`(score DESC, row_id ASC)` before applying the real limit.

The widening is what fixes the paginated case -- the plan's own sort then
sees the whole tie group -- and the re-rank covers the fully covered plan
that returns this search's output directly, with no `SortExec` above it.
Both only engage when results are actually translated (stable row ids plus
an address-domain index), so a query needing no translation is unchanged.
Like `WAND_TIE_COMPLETION_BUDGET`, the budget bounds how large a tie group
can be and still resolve exactly.

Applied to every FTS path that translates after a bounded top-k: combined
fields, and the three compound paths.

Co-Authored-By: Claude Opus 5 <[email protected]>
A fixed re-rank margin is not enough on its own. With 131 identically
scoring rows the tie at the top-k cutoff exceeds `FTS_TIE_RERANK_BUDGET`,
so the retained candidates were still cut at an arbitrary address and the
one-row pages returned `[1, 2, 2]` instead of `[0, 1, 2]`. Equal scores
across many short documents are an ordinary FTS case, and retrying the same
pages cannot recover the discarded row.

`cutoff_tie_unresolved` now detects it: the search filled its widened cap
*and* the score at the requested cutoff still equals the last score
retained, so rows beyond the cap may tie the cutoff too and which of them
belong in the top-k cannot be decided from what came back. The search is
then completed exactly -- the same escape hatch the WAND tie certificate
takes when its own completion budget is exhausted, which this previously
lacked.

Applied to combined fields, the hybrid compound path and the cross-column
compound path, each of which issues one search that can simply be reissued.
`CompoundQueryExec` cannot: the branch structure below it consumes its
prefilter and candidate set, so it searches exhaustively when results will
be translated and lets `finalize_row_ids_and_scores` apply the limit.
Teaching the collectors to retain ties at the k-th score in one pass would
remove both that and the other paths' second search; this keeps the fix
inside the exec layer.

Co-Authored-By: Claude Opus 5 <[email protected]>
…rase

Two gaps in the previous commit's exact-completion fallback.

`cross_column_compound_search` rejects an unbounded limit outright
("cross-column compound FTS requires a bounded result limit"), so replaying
with `limit: None` turned a large cutoff tie from a wrong answer into a
failed query: a title/body MUST query with `limit=1` over 131 equal-scoring
rows errored on its first page. The replay now bounds itself by
`exhaustive_limit` -- every row the dataset physically stores, read from the
manifest with no per-fragment I/O -- which no result set can exceed. A
legacy fragment that does not record its row count falls back to no bound
rather than to an undercount that would truncate the tie again. The other
collectors take `params.limit.unwrap_or(usize::MAX)` and were unaffected.

The Match and Phrase paths never widened their limit at all, so a bare
Match over the same 131-row tie still paged `[1, 2, 2]`. They translate
through `scored_documents_batch`, which dropped unresolvable rows but never
restored `_rowid` order or applied a limit. It now re-ranks and truncates
like `finalize_row_ids_and_scores`, and both paths widen, detect an
unresolved cutoff tie, and complete it exactly -- `PreparedMatch` carries
its own params, so the Match replay rebuilds it around an exact copy.

Covered by `test_fts_large_tie_pagination_across_query_shapes`, which runs
the cross-column, single-column-boolean and bare-Match shapes; the
bare-Match case is what surfaced the second gap.

Co-Authored-By: Claude Opus 5 <[email protected]>
Addresses the review's point that `docs.lance._rowid` holding row addresses
is easy for another implementation to misread, and that with no reader
implementing version 4 yet this is the last cheap moment to pick the name.

From `INVERTED_ROW_ADDR_DOMAIN_VERSION` the column is `_rowaddr`; versions
1 through 3 keep `_rowid`. The name now tracks `index_version`, which is
worth more than the tidiness: a reader that ignores the version finds no
such column instead of silently reading one domain's values as the other's,
turning the exact foot-gun behind three of this PR's bugs into a loud
failure.

The constraint that made this more than a rename is that
`build_scalar_index` relabels a fresh build down to a legacy version on a
dataset without stable row ids, so an older reader can still read it -- and
that reader looks for `_rowid`. The name therefore has to be chosen before
the file is written, from the version the segment will end up committed
with. `TrainingRequest` grows a defaulted `set_stable_row_ids` hook so only
FTS has to care; `build_scalar_index` calls it, and the name is threaded to
`DocSet::to_batch`.

Rewrites keep their source segment's version, so they keep its column: a
loaded `DocSet` records the name it read, `into_builder` inherits it, and
`to_builder` sets it from the opened index -- so no merge, remap or
consolidation path has to remember. MemWAL FTS commits legacy versions and
keeps `_rowid` unchanged.

Readers resolve the name from the file's own schema rather than the index
version (`docs_identity_column`), so one reader serves both and an existing
version-4 fixture written before this change still opens.

`test_fts_docs_identity_column_matches_index_version` asserts the column
actually written, for both domains and across a merge. That assertion is
what makes the threading verifiable: with schema-driven reading, a build
path that was never told which name to write would otherwise still work and
quietly violate the spec -- it caught two such paths (append/consolidation
and partition-derived builders) that reading alone did not.

Co-Authored-By: Claude Opus 5 <[email protected]>
The posting-list description still resolved document IDs through
`docs.lance._rowid`, which names only the pre-version-4 column after the
rename. Refer to the identity column instead of one of its two names.

Co-Authored-By: Claude Opus 5 <[email protected]>
Spec changes require the format vote, and this PR does not need one: main's
`fts.md` already specifies format version 4's document identity column as
`_rowaddr` (the Document File Schema table lists `_rowid` for version <= 3
and `_rowaddr` for version >= 4). The code now writes that column, so the
implementation matches the published spec rather than amending it.

This drops every `fts.md` edit on the branch, including the original
commit's -- which had rewritten the table into a single `_rowid` column and
so contradicted what was already voted.

Two inaccuracies are left standing in the restored text, neither introduced
here and neither a format change:

- The prose says the address lives in `docs.lance._rowid` while the table
  below it says `_rowaddr` for version 4. The table is what the code
  implements. This contradiction is pre-existing on main.
- "format version 4 is specified here but is not yet implemented" is false
  once this PR lands.

Both want a follow-up docs PR that can take the vote on its own.

Co-Authored-By: Claude Opus 5 <[email protected]>
All three were introduced by this PR's own earlier commits; each test below
was confirmed to fail with its fix reverted.

- A whole-fragment (`Full`) allow or block mask failed FTS queries on a
  dataset *without* stable row ids. `fts_segments_are_address_domain`
  reports address domain there because the two domains coincide, which sent
  valid masks through `translate_treemap_to_row_addr_domain` -- added last
  round to report a `Full` entry as a mislabelled mask. Where a row id and a
  row address are the same number there is nothing to translate and nothing
  to mislabel, so the mask is now returned untouched. The report still
  stands on stable-row-id datasets, where the domains can actually differ.

- `HybridCompoundQueryExec` truncated to the widened tie-rerank bound rather
  than the limit the caller asked for, so a mixed indexed/residual plan with
  no outer scanner limit returned up to the whole margin past `k` (a `k = 1`
  query returned 6 rows).

- `DocSet::load_with_remapping` resolved the identity column but dropped it
  on the returned set, so a batch-remapped merge wrote `_rowid` while still
  committing `index_version` 4. Only the reader's name resolution hid it;
  a reader selecting the specified v4 `_rowaddr` column could not read the
  rewritten file. It now records the detected name as `load` does.

Reported by @Xuanwo (items 1-3) and the gatekeeper (item 3).

Co-Authored-By: Claude Opus 5 <[email protected]>
Review: the new `results_are_row_addresses` parameter on
`InvertedIndex::load` forced `, true` onto ~85 call sites that only wanted
the behaviour a fresh index already has, which both bloated the diff and
left a bare bool to interpret at each site.

`load`/`load_with_remapping` now return `InvertedIndexLoad`, awaited
directly (via `IntoFuture`), so those call sites go back to their
pre-migration three-argument form. The domain is named only where it is not
the default:

- `.in_legacy_row_id_domain()` for a segment persisted before
  `INVERTED_ROW_ADDR_DOMAIN_VERSION`, whose identity column holds row ids.
- `.in_domain_of_version(index_version)` for the two plugin entry points,
  which resolve the domain from the manifest's declared version.

Note the method is named for the row-*id* domain rather than the row-address
one suggested in review: the default already is row addresses, so the opt-out
is the legacy side.

No behaviour change -- every former `true` is the new default and every
former `false` is the explicit legacy call.

Co-Authored-By: Claude Opus 5 <[email protected]>
… trains at

Review (Will): `train_inverted_index` always stamped
`INVERTED_ROW_ADDR_DOMAIN_VERSION` while taking the document identity column
as a separate argument that still defaulted to `_rowid`, so the public entry
point could write a v4 segment with a legacy column -- a layout the format
does not allow, and the same shape as the batch-remap bug found earlier:
column and version decided in two places.

The version is now the single input. `train_inverted_index_at_version` takes
it, derives the column through `identity_column_for_version`, refuses a
version this build does not write for the given params, and stamps what it
was given; `train_inverted_index` is that at the row-address domain. The
training request carries the version rather than the column, so
`set_stable_row_ids` settles it before training instead of
`build_scalar_index` relabelling afterwards -- `relabel_as_row_id_domain` and
its branch there are gone. `InnerBuilder::merge_from` now rejects a column
mismatch instead of adopting whichever side looked non-default, and both
builders default to the row-address domain like every other default in this
PR.

Two callers were writing segments nothing could read back:
- remap.rs's legacy FTS reindex asked for neither a row id nor a row address,
  so the rebuilt segment had no identity column at all. It now scans row
  addresses and picks its version the way `build_scalar_index` does.
- mem-WAL flush computed the legacy version with its own copy of the rule and
  wrote the column from an unrelated default. Both now come from
  `flushed_index_version`.

Also from the same review:
- `InvertedIndex::load` rejects a segment whose `docs.lance` column
  contradicts the domain the manifest declares, instead of reading the wrong
  numbering system; the doc that claimed this check existed is now true.
  Fixtures that faked a legacy segment by relabelling alone get real legacy
  files via `as_legacy_row_id_fts_segment`.
- `normalize_inverted_details` errors on a v4 segment with no
  `posting_format_version` rather than guessing V3: from v4 the two axes are
  independent, V1 and V2 pair with it, and every writer records the field.
- The FTS `stale_rows` translation no longer runs without stable row ids,
  where the domains coincide and translating would reject a legitimate
  whole-fragment entry.
- Documented why `open_fts_segments` reads the domain from the segment rather
  than from the check that precedes it.

Co-Authored-By: Claude Opus 5 <[email protected]>
…dresses

Gatekeeper found that giving remap.rs's legacy reindex its missing identity
column let the path complete without making its output valid: the rebuild
rescans the dataset as it stands *before* the rewrite commits, so its
postings hold addresses the commit is about to retire, while the commit
replaces the index's coverage with the destination fragments. Eager
compaction then succeeded and the same query went from matches to none, with
no error -- worse than the panic the missing column used to cause.

The scan now runs through the same old-to-new address map the in-place remap
path applies (materializing a batch translator the way `remap_streaming`
does), dropping the rows it deletes, so the rebuilt segment lands in the
committed snapshot's address space.

Covered by `test_legacy_fts_index_survives_eager_compaction`, which is the
gatekeeper's reproducer over the checked-in 0.27.0 fixture: it reports 0 rows
before this change and 2 after.

Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-format On-disk format: protos and format spec docs A-index Vector index, linalg, tokenizer A-python Python bindings breaking-change enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants