← Back to Pull requests

test(index): add a fragment reuse contract harness across index types #10639

Merged
wjones127 merged 4 files (913 lines) on Nov 04, 2026 02:34 UTC
View on GitHub
wjones127 wjones127 commented on Nov 02, 2026 20:49 UTC
Author

Summary

Adds a contract test for the fragment reuse index (FRI): whatever history it records, an indexed query must return exactly the rows a query computed from the table's current contents returns. It is the guard for the upcoming consolidation of FRI logic into one module.

for index in [BTree, Bitmap, ZoneMap, BloomFilter, LabelList, NGram, Inverted, IVF_FLAT]
  for history in [v0, tagged ordered compaction, tagged stable partition]
    build -> partial delete -> whole-fragment delete
    -> staged segment merge committed after a concurrent delete/append/index
    -> rewrite -> append + delete -> in-place update -> chained rewrite
    -> eager compaction over the pending history
    -> optimize_indices -> remap -> trim
    after every step: indexed results == oracle, through a warm handle and a cold session

The oracle scans the table and evaluates each query in Rust, never consulting an index or the history. A second short scenario follows OSS-2763 (deferred then eager compaction). Maintenance steps may refuse with InvalidInput/NotSupported; returning wrong or missing rows fails.

Evidence

  • Reverting the prefilter change of #10325 fails the IVF_FLAT cases at the staged-merge step (no rows instead of the 5 nearest).

  • Disabling the eager-remap refusal from #10507 fails the BTree and Inverted cases of the OSS-2763 scenario (v = 13 returns nothing; FTS returns only the appended row).

  • The tagged full-text-search cases fail today and are ignored pending #10623, which this harness found.
  • All 30 cases run in under a second.

    Merge Risk

    Door: two-way; tests only.
    Blast Radius: none.

    🤖 Generated with Claude Code

    Diff: 913 lines (+913 / -0) across 4 files Reviewer: zhangyue19921010 Review duration: 1785m
    All Vouch review confidence checks passed
    Residual risk 0.08 = Change Risk (0.47) × (1 − Review Confidence (0.84)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.47 · 913 lines diff across 4 files
    0.47
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.84 · 4 substantive comment(s)
    0.84
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    83%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    9 items
    github-actions[bot] github-actions[bot] commented on Nov 02, 2026 20:49 UTC
    Bot

    ACTION NEEDED
    Lance follows the Conventional Commits specification for release automation.

    The PR title and description are used as the merge commit message. Please update your PR title and description to match the specification.

    For details on the error please inspect the "PR Title Check" action.

    claude[bot] claude[bot] commented on Nov 03, 2026 00:29 UTC
    Reviewer

    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.

    <sub>Tip: disable this comment in your organization's Code Review settings.</sub>

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on Nov 03, 2026 00:38 UTC
    Reviewer

    ✅ Gate recommendation: approve.

    The independent oracle is a useful guard for the fragment-reuse refactor. The two ignored tagged full-text cases reproduce the existing empty-coverage failure tracked in #10623.

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on Nov 03, 2026 01:53 UTC
    Reviewer

    ✅ Gate recommendation: approve.

    The live-row model now checks data preservation as well as indexed query results through warm and cold handles. The two ignored tagged full-text cases continue to reproduce the pre-existing empty-coverage failure tracked in #10623.

    zhangyue19921010 zhangyue19921010 commented on code on Nov 03, 2026 02:55 UTC
    Code Review
    rust/lance/src/dataset/optimize/tests/frag_reuse_contract/index_kind.rs:1
    @@ -0,0 +1,285 @@
    +// SPDX-License-Identifier: Apache-2.0
    +// SPDX-FileCopyrightText: Copyright The Lance Authors
    +
    +//! What each index type is built on and asked, and the rows it is asked about.
    +
    +use std::collections::BTreeSet;
    +use std::sync::Arc;
    +
    +use arrow_array::builder::{ListBuilder, StringBuilder};
    +use arrow_array::cast::AsArray;
    +use arrow_array::types::{Float32Type, Int32Type};
    +use arrow_array::{FixedSizeListArray, Float32Array, Int32Array, RecordBatch, StringArray};
    +use arrow_schema::{DataType, Field, Schema};
    +use lance_arrow::FixedSizeListArrayExt;
    +use lance_index::IndexParams;
    +use lance_index::IndexType;
    +use lance_index::scalar::{
    +    BuiltinIndexType, FullTextSearchQuery, InvertedIndexParams, ScalarIndexParams,
    +};
    +use lance_linalg::distance::MetricType;
    +
    +use crate::index::vector::VectorIndexParams;
    +use crate::{Dataset, Result};
    +
    +const DIM: i32 = 4;
    +const IVF_PARTITIONS: usize = 2;
    +/// Added to `v` by an in-place update, so updated rows answer different
    +/// queries than they did when the index was built.
    +const UPDATED: i32 = 1000;
    +
    +#[derive(Debug, Clone, Copy)]
    +pub(super) enum Query {
    +    Filter(&'static str, fn(&Row) -> bool),
    +    FullText(&'static str),
    +    /// `k` close to the live row count makes a candidate the prefilter
    +    /// should have excluded show up as a missing row.
    +    Nearest {
    +        target: f32,
    +        k: usize,
    +    },
    +}
    +
    +impl Query {
    +    /// The `i` of every row in `rows` the query should return, computed
    +    /// without an index.
    +    pub(super) fn expected<'a>(self, rows: impl IntoIterator<Item = &'a Row>) -> BTreeSet<i32> {
    +        let rows = rows.into_iter();
    +        match self {
    +            Self::Filter(_, predicate) => {
    +                rows.filter(|row| predicate(row)).map(|row| row.i).collect()
    +            }
    +            Self::FullText(token) => rows
    +                .filter(|row| row.text.split_whitespace().any(|word| word == token))
    +                .map(|row| row.i)
    +                .collect(),
    +            Self::Nearest { target, k } => {
    +                let mut by_distance: Vec<(f32, i32)> = rows
    +                    .map(|row| {
    +                        let distance = (row.vec[0] - target).powi(2)
    +                            + row.vec[1..].iter().map(|v| v * v).sum::<f32>();
    +                        (distance, row.i)
    +                    })
    +                    .collect();
    +                by_distance.sort_by(|a, b| a.0.total_cmp(&b.0));
    +                by_distance.into_iter().take(k).map(|(_, i)| i).collect()
    +            }
    +        }
    +    }
    +
    +    /// The `i` of every row `dataset` returns for the query, through its index.
    +    pub(super) async fn run(self, dataset: &Dataset) -> Result<BTreeSet<i32>> {
    +        let mut scanner = dataset.scan();
    +        match self {
    +            Self::Filter(filter, _) => {
    +                scanner.filter(filter)?;
    +            }
    +            Self::FullText(token) => {
    +                scanner.full_text_search(FullTextSearchQuery::new(token.to_string()))?;
    +            }
    +            Self::Nearest { target, k } => {
    +                let mut vector = vec![0.0f32; DIM as usize];
    +                vector[0] = target;
    +                scanner
    +                    .nearest("vec", &Float32Array::from(vector), k)?
    +                    .minimum_nprobes(IVF_PARTITIONS);
    +            }
    +        }
    +        scanner.project(&["i"])?;
    +        let batch = scanner.try_into_batch().await?;

    nit: Could we assert that the expected index segment is used at checkpoints where it should still have coverage? MAYBE If FRI accidentally drops that coverage, a flat scan can return the same rows and pass the result check.

    zhangyue19921010 zhangyue19921010 approved these changes on Nov 03, 2026 02:55 UTC
    Approved Reviewer

    Approved these changes.

    wjones127 wjones127 commented on code on Nov 03, 2026 17:22 UTC
    Code Review
    rust/lance/src/dataset/optimize/tests/frag_reuse_contract/index_kind.rs:1
    @@ -0,0 +1,285 @@
    +// SPDX-License-Identifier: Apache-2.0
    +// SPDX-FileCopyrightText: Copyright The Lance Authors
    +
    +//! What each index type is built on and asked, and the rows it is asked about.
    +
    +use std::collections::BTreeSet;
    +use std::sync::Arc;
    +
    +use arrow_array::builder::{ListBuilder, StringBuilder};
    +use arrow_array::cast::AsArray;
    +use arrow_array::types::{Float32Type, Int32Type};
    +use arrow_array::{FixedSizeListArray, Float32Array, Int32Array, RecordBatch, StringArray};
    +use arrow_schema::{DataType, Field, Schema};
    +use lance_arrow::FixedSizeListArrayExt;
    +use lance_index::IndexParams;
    +use lance_index::IndexType;
    +use lance_index::scalar::{
    +    BuiltinIndexType, FullTextSearchQuery, InvertedIndexParams, ScalarIndexParams,
    +};
    +use lance_linalg::distance::MetricType;
    +
    +use crate::index::vector::VectorIndexParams;
    +use crate::{Dataset, Result};
    +
    +const DIM: i32 = 4;
    +const IVF_PARTITIONS: usize = 2;
    +/// Added to `v` by an in-place update, so updated rows answer different
    +/// queries than they did when the index was built.
    +const UPDATED: i32 = 1000;
    +
    +#[derive(Debug, Clone, Copy)]
    +pub(super) enum Query {
    +    Filter(&'static str, fn(&Row) -> bool),
    +    FullText(&'static str),
    +    /// `k` close to the live row count makes a candidate the prefilter
    +    /// should have excluded show up as a missing row.
    +    Nearest {
    +        target: f32,
    +        k: usize,
    +    },
    +}
    +
    +impl Query {
    +    /// The `i` of every row in `rows` the query should return, computed
    +    /// without an index.
    +    pub(super) fn expected<'a>(self, rows: impl IntoIterator<Item = &'a Row>) -> BTreeSet<i32> {
    +        let rows = rows.into_iter();
    +        match self {
    +            Self::Filter(_, predicate) => {
    +                rows.filter(|row| predicate(row)).map(|row| row.i).collect()
    +            }
    +            Self::FullText(token) => rows
    +                .filter(|row| row.text.split_whitespace().any(|word| word == token))
    +                .map(|row| row.i)
    +                .collect(),
    +            Self::Nearest { target, k } => {
    +                let mut by_distance: Vec<(f32, i32)> = rows
    +                    .map(|row| {
    +                        let distance = (row.vec[0] - target).powi(2)
    +                            + row.vec[1..].iter().map(|v| v * v).sum::<f32>();
    +                        (distance, row.i)
    +                    })
    +                    .collect();
    +                by_distance.sort_by(|a, b| a.0.total_cmp(&b.0));
    +                by_distance.into_iter().take(k).map(|(_, i)| i).collect()
    +            }
    +        }
    +    }
    +
    +    /// The `i` of every row `dataset` returns for the query, through its index.
    +    pub(super) async fn run(self, dataset: &Dataset) -> Result<BTreeSet<i32>> {
    +        let mut scanner = dataset.scan();
    +        match self {
    +            Self::Filter(filter, _) => {
    +                scanner.filter(filter)?;
    +            }
    +            Self::FullText(token) => {
    +                scanner.full_text_search(FullTextSearchQuery::new(token.to_string()))?;
    +            }
    +            Self::Nearest { target, k } => {
    +                let mut vector = vec![0.0f32; DIM as usize];
    +                vector[0] = target;
    +                scanner
    +                    .nearest("vec", &Float32Array::from(vector), k)?
    +                    .minimum_nprobes(IVF_PARTITIONS);
    +            }
    +        }
    +        scanner.project(&["i"])?;
    +        let batch = scanner.try_into_batch().await?;

    That's a good idea. I'll see if I can modify the tests to detect that.

    zhangyue19921010 zhangyue19921010 commented on Nov 04, 2026 02:34 UTC
    Contributor

    Nice change! Merging :)

    Assignees
    wjones127 wjones127
    Labels
    risk: low confidence: 84.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 47.4% (MEDIUM) · Higher = larger blast radius
    47.4%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 84.0% · Lower = rushed or shallow review
    84.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.6% · Safe to merge
    7.6%