mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
test: lock in that delete keeps table indices (#5168)
`AsyncTable.delete` does not drop indexes. On current main the reported
failure does not reproduce: delete forwards to Lance `dataset.delete`,
and index retention comes from Lance (the retention change in
lance-format/lance#4033, which closed lance-format/lance#3940), not from
recreating indexes after the delete. Nothing in this repo's CI currently
asserts it, so these tests lock that behavior in at the LanceDB level:
- Vector (IVF_FLAT), BTree, and full-text indexes survive deleting a
subset of rows, `delete("true")`, and a later insert. After the partial
delete, `list_indices` and `index_stats` still report indexed rows, and
scalar, full-text, and vector search return the live rows and omit
deleted ones.
- The reported empty-table sequence: `connect_async` to a directory,
create an empty table from a schema, `create_index(column="txt",
config=BTree())` before any rows, add 10 rows, then `delete(where="txt =
'1'")`. `list_indices()` still has one BTree on `txt`, the table has 9
rows, and the same holds after `open_table`.
This is an alternative to the approach in #2471, which saved and
recreated every index inside `delete`. That was declined by a maintainer
because it leaves a window with no indexes, and it is unnecessary now
that Lance keeps them.
Tests only: `rust/lancedb/src/table/delete.rs` and
`python/python/tests/test_table.py`. Both are deterministic (single IVF
partition, exact vectors, distinct FTS tokens) and run in well under a
second.
Refs #2434
## Test plan
- [x] `cargo test --features remote -p lancedb --lib
table::delete::tests::delete_keeps_vector_scalar_and_fts_indices` (5
runs)
- [x] `cargo clippy --features remote -p lancedb --tests -- -D
warnings`, `cargo fmt --all -- --check`
- [x] `pytest` on the two new Python tests (5 runs)
- [x] `ruff format --check .` and `ruff check .` in `python/`
Written with Cursor (Grok).
Co-authored-by: Preston Zhao <195942578+canyang25@users.noreply.github.com>
This commit is contained in:
co-authored by
Preston Zhao
parent
53ae53877d
commit
3e31cd4eab
@@ -23,7 +23,7 @@ from unittest.mock import MagicMock, patch
|
||||
import lancedb
|
||||
from lancedb import table as table_module
|
||||
from lancedb.dependencies import _PANDAS_AVAILABLE
|
||||
from lancedb.index import BTree, FTS, HnswFlat, HnswPq, HnswSq, IvfPq
|
||||
from lancedb.index import BTree, FTS, HnswFlat, HnswPq, HnswSq, IvfFlat, IvfPq
|
||||
import numpy as np
|
||||
import polars as pl
|
||||
import pyarrow as pa
|
||||
@@ -3394,6 +3394,98 @@ async def test_delete_expr_async(mem_db_async: AsyncConnection):
|
||||
assert sorted((await table.to_arrow())["id"].to_pylist()) == [1, 2]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_delete_keeps_indices(mem_db_async: AsyncConnection):
|
||||
table = await mem_db_async.create_table(
|
||||
"indexed_delete",
|
||||
[
|
||||
{
|
||||
"id": row_id,
|
||||
"category": "keep" if row_id < 8 else "drop",
|
||||
"text": f"row{row_id}",
|
||||
"vector": [float(row_id), 0.0, 0.0, 0.0],
|
||||
}
|
||||
for row_id in range(16)
|
||||
],
|
||||
)
|
||||
await table.create_index(
|
||||
"vector", config=IvfFlat(num_partitions=1), name="vector_idx"
|
||||
)
|
||||
await table.create_index("category", config=BTree(), name="category_idx")
|
||||
await table.create_index("text", config=FTS(), name="text_idx")
|
||||
expected = [
|
||||
("category_idx", "BTree"),
|
||||
("text_idx", "FTS"),
|
||||
("vector_idx", "IvfFlat"),
|
||||
]
|
||||
|
||||
async def names():
|
||||
indices = await table.list_indices()
|
||||
return sorted((index.name, index.index_type) for index in indices)
|
||||
|
||||
async def ids_of(query):
|
||||
return sorted((await query.to_arrow())["id"].to_pylist())
|
||||
|
||||
assert (await table.delete("category = 'drop'")).num_deleted_rows == 8
|
||||
assert await names() == expected
|
||||
for index in await table.list_indices():
|
||||
assert index.num_indexed_rows > 0
|
||||
stats = await table.index_stats(index.name)
|
||||
assert stats is not None and stats.num_indexed_rows > 0
|
||||
kept = table.query().where("category = 'keep'").limit(100)
|
||||
assert await ids_of(kept) == list(range(8))
|
||||
assert await ids_of(table.query().nearest_to_text("row0", columns="text")) == [0]
|
||||
assert await ids_of(table.query().nearest_to_text("row8", columns="text")) == []
|
||||
assert await ids_of(table.query().nearest_to([0.0, 0.0, 0.0, 0.0]).limit(1)) == [0]
|
||||
|
||||
assert (await table.delete("true")).num_deleted_rows == 8
|
||||
assert await table.count_rows() == 0
|
||||
assert await names() == expected
|
||||
|
||||
await table.add(
|
||||
[
|
||||
{
|
||||
"id": 20,
|
||||
"category": "fresh",
|
||||
"text": "row20",
|
||||
"vector": [20.0, 0.0, 0.0, 0.0],
|
||||
}
|
||||
]
|
||||
)
|
||||
assert await names() == expected
|
||||
fresh = table.query().where("category = 'fresh'").limit(100)
|
||||
assert await ids_of(fresh) == [20]
|
||||
assert await ids_of(table.query().nearest_to_text("row20", columns="text")) == [20]
|
||||
assert await ids_of(table.query().nearest_to_text("row0", columns="text")) == []
|
||||
nearest = table.query().nearest_to([20.0, 0.0, 0.0, 0.0]).limit(1)
|
||||
assert await ids_of(nearest) == [20]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_delete_keeps_btree_created_before_rows(tmp_path):
|
||||
schema = pa.schema([pa.field("pk", pa.string()), pa.field("txt", pa.string())])
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("test_table", schema=schema)
|
||||
await table.create_index(column="txt", config=BTree())
|
||||
values = [str(row_id) for row_id in range(10)]
|
||||
await table.add(pa.table({"pk": values, "txt": values}))
|
||||
|
||||
await table.delete(where="txt = '1'")
|
||||
|
||||
async def assert_one_btree(opened):
|
||||
assert await opened.count_rows() == 9
|
||||
indices = await opened.list_indices()
|
||||
assert len(indices) == 1
|
||||
index = indices[0]
|
||||
assert index.name == "txt_idx"
|
||||
assert index.index_type == "BTree"
|
||||
assert list(index.columns) == ["txt"]
|
||||
|
||||
await assert_one_btree(table)
|
||||
reopened = await (await lancedb.connect_async(tmp_path)).open_table("test_table")
|
||||
await assert_one_btree(reopened)
|
||||
|
||||
|
||||
def test_update(mem_db: DBConnection):
|
||||
table = mem_db.create_table(
|
||||
"my_table",
|
||||
|
||||
@@ -63,13 +63,20 @@ pub(crate) async fn execute_delete(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::connect;
|
||||
use arrow_array::{Int32Array, RecordBatch, record_batch};
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::query::ExecutableQuery;
|
||||
use arrow_array::{
|
||||
Array, FixedSizeListArray, Float32Array, Int32Array, RecordBatch, StringArray, record_batch,
|
||||
};
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
use futures::TryStreamExt;
|
||||
use lance_index::scalar::FullTextSearchQuery;
|
||||
|
||||
use crate::Table;
|
||||
use crate::connect;
|
||||
use crate::index::vector::IvfFlatIndexBuilder;
|
||||
use crate::index::{Index, IndexType};
|
||||
use crate::query::{ExecutableQuery, QueryBase};
|
||||
#[tokio::test]
|
||||
async fn test_delete_simple() {
|
||||
let conn = connect("memory://").execute().await.unwrap();
|
||||
@@ -299,4 +306,132 @@ mod tests {
|
||||
"Table version must increment after delete_expr operation"
|
||||
);
|
||||
}
|
||||
|
||||
async fn listed(table: &Table) -> Vec<(String, IndexType)> {
|
||||
let mut indices = table.list_indices().await.unwrap();
|
||||
indices.sort_by(|left, right| left.name.cmp(&right.name));
|
||||
indices
|
||||
.into_iter()
|
||||
.map(|index| (index.name, index.index_type))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn add_index(table: &Table, column: &str, index: Index, name: &str) {
|
||||
table
|
||||
.create_index(&[column], index)
|
||||
.name(name.to_string())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn ids(stream: crate::arrow::SendableRecordBatchStream) -> Vec<i32> {
|
||||
let batches = stream.try_collect::<Vec<_>>().await.unwrap();
|
||||
let mut values = Vec::new();
|
||||
for batch in batches {
|
||||
let column = batch.column_by_name("id").unwrap();
|
||||
let array = column.as_any().downcast_ref::<Int32Array>().unwrap();
|
||||
values.extend(array.values().iter().copied());
|
||||
}
|
||||
values.sort_unstable();
|
||||
values
|
||||
}
|
||||
|
||||
async fn filtered(table: &Table, predicate: &str) -> Vec<i32> {
|
||||
let query = table.query().only_if(predicate).limit(100);
|
||||
ids(query.execute().await.unwrap()).await
|
||||
}
|
||||
|
||||
async fn matched(table: &Table, text: &str) -> Vec<i32> {
|
||||
let query = FullTextSearchQuery::new(text.into());
|
||||
let query = query.with_column("text".into()).unwrap();
|
||||
let search = table.query().full_text_search(query).limit(100);
|
||||
ids(search.execute().await.unwrap()).await
|
||||
}
|
||||
|
||||
async fn nearest(table: &Table, id: i32) -> Vec<i32> {
|
||||
let vector = vec![id as f32, 0.0, 0.0, 0.0];
|
||||
let query = table.query().nearest_to(vector).unwrap().limit(1);
|
||||
ids(query.execute().await.unwrap()).await
|
||||
}
|
||||
|
||||
fn rows(ids: &[i32], category_of: impl Fn(i32) -> &'static str) -> RecordBatch {
|
||||
let flat = ids
|
||||
.iter()
|
||||
.flat_map(|id| [*id as f32, 0.0, 0.0, 0.0])
|
||||
.collect::<Vec<_>>();
|
||||
let vector_values = FixedSizeListArray::try_new(
|
||||
Arc::new(Field::new("item", DataType::Float32, true)),
|
||||
4,
|
||||
Arc::new(Float32Array::from(flat)),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let categories: Vec<&str> = ids.iter().copied().map(category_of).collect();
|
||||
let texts: Vec<String> = ids.iter().map(|id| format!("row{id}")).collect();
|
||||
RecordBatch::try_new(
|
||||
Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int32, false),
|
||||
Field::new("category", DataType::Utf8, false),
|
||||
Field::new("text", DataType::Utf8, false),
|
||||
Field::new("vector", vector_values.data_type().clone(), false),
|
||||
])),
|
||||
vec![
|
||||
Arc::new(Int32Array::from(ids.to_vec())),
|
||||
Arc::new(StringArray::from(categories)),
|
||||
Arc::new(StringArray::from(texts)),
|
||||
Arc::new(vector_values),
|
||||
],
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_keeps_vector_scalar_and_fts_indices() {
|
||||
let conn = connect("memory://").execute().await.unwrap();
|
||||
let ids: Vec<i32> = (0..16).collect();
|
||||
let batch = rows(&ids, |id| if id < 8 { "keep" } else { "drop" });
|
||||
let table = conn
|
||||
.create_table("indexed_delete", batch)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let ivf = Index::IvfFlat(IvfFlatIndexBuilder::default().num_partitions(1));
|
||||
let btree = Index::BTree(Default::default());
|
||||
let fts = Index::FTS(Default::default());
|
||||
add_index(&table, "vector", ivf, "vector_idx").await;
|
||||
add_index(&table, "category", btree, "category_idx").await;
|
||||
add_index(&table, "text", fts, "text_idx").await;
|
||||
let expected = vec![
|
||||
("category_idx".to_string(), IndexType::BTree),
|
||||
("text_idx".to_string(), IndexType::FTS),
|
||||
("vector_idx".to_string(), IndexType::IvfFlat),
|
||||
];
|
||||
|
||||
let deleted = table.delete("category = 'drop'").await.unwrap();
|
||||
assert_eq!(deleted.num_deleted_rows, 8);
|
||||
assert_eq!(listed(&table).await, expected);
|
||||
for index in table.list_indices().await.unwrap() {
|
||||
assert!(index.num_indexed_rows.unwrap_or(0) > 0);
|
||||
let stats = table.index_stats(&index.name).await.unwrap().unwrap();
|
||||
assert!(stats.num_indexed_rows > 0);
|
||||
}
|
||||
let kept = (0..8).collect::<Vec<_>>();
|
||||
assert_eq!(filtered(&table, "category = 'keep'").await, kept);
|
||||
assert_eq!(matched(&table, "row0").await, vec![0]);
|
||||
assert!(matched(&table, "row8").await.is_empty());
|
||||
assert_eq!(nearest(&table, 0).await, vec![0]);
|
||||
|
||||
let deleted = table.delete("true").await.unwrap();
|
||||
assert_eq!(deleted.num_deleted_rows, 8);
|
||||
assert_eq!(table.count_rows(None).await.unwrap(), 0);
|
||||
assert_eq!(listed(&table).await, expected);
|
||||
|
||||
table.add(rows(&[20], |_| "fresh")).execute().await.unwrap();
|
||||
assert_eq!(listed(&table).await, expected);
|
||||
assert_eq!(filtered(&table, "category = 'fresh'").await, vec![20]);
|
||||
assert_eq!(matched(&table, "row20").await, vec![20]);
|
||||
assert!(matched(&table, "row0").await.is_empty());
|
||||
assert_eq!(nearest(&table, 20).await, vec![20]);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user