mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
feat(rust): expose progress callbacks for create_index (#4245)
This adds a `.progress()` option to `IndexBuilder` and plumbs it through `create_index` to the lance `CreateIndexBuilder`. There was already a progress callback usable with `table.optimize()` via `OptimizeOptions`, but it was not exposed for `table.create_index()`, although the underlying lance methods support it.
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
|
||||
use arrow_schema::Field;
|
||||
use chrono::{DateTime, Utc};
|
||||
use lance::index::IndexBuildProgress;
|
||||
use lance::index::scalar::IndexDetails;
|
||||
use scalar::FtsIndexBuilder;
|
||||
use serde::Deserialize;
|
||||
@@ -271,6 +272,7 @@ pub struct IndexBuilder {
|
||||
pub(crate) wait_timeout: Option<Duration>,
|
||||
pub(crate) train: bool,
|
||||
pub(crate) name: Option<String>,
|
||||
pub(crate) progress: Option<Arc<dyn IndexBuildProgress>>,
|
||||
}
|
||||
|
||||
impl IndexBuilder {
|
||||
@@ -284,6 +286,7 @@ impl IndexBuilder {
|
||||
train: true,
|
||||
wait_timeout: None,
|
||||
name: None,
|
||||
progress: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -397,6 +400,52 @@ impl IndexBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Progress callback for index building and distributed index finalization.
|
||||
///
|
||||
/// LanceDB Embedded only. Supplying this callback to a LanceDB Enterprise table returns
|
||||
/// [`Error::NotSupported`](crate::Error::NotSupported) when executed. For Enterprise job
|
||||
/// progress, use [`Self::execute_async`] and [`Job::wait_with_progress`] instead.
|
||||
///
|
||||
/// ```
|
||||
/// use std::sync::Arc;
|
||||
/// use async_trait::async_trait;
|
||||
/// use lance::index::IndexBuildProgress;
|
||||
/// use lancedb::{Table, index::Index};
|
||||
///
|
||||
/// #[derive(Debug)]
|
||||
/// struct LogProgress;
|
||||
///
|
||||
/// #[async_trait]
|
||||
/// impl IndexBuildProgress for LogProgress {
|
||||
/// async fn stage_start(&self, stage: &str, total: Option<u64>, unit: &str) -> lance::Result<()> {
|
||||
/// eprintln!("{stage}: started (total: {total:?} {unit})");
|
||||
/// Ok(())
|
||||
/// }
|
||||
///
|
||||
/// async fn stage_progress(&self, stage: &str, completed: u64) -> lance::Result<()> {
|
||||
/// eprintln!("{stage}: {completed} completed");
|
||||
/// Ok(())
|
||||
/// }
|
||||
///
|
||||
/// async fn stage_complete(&self, stage: &str) -> lance::Result<()> {
|
||||
/// eprintln!("{stage}: complete");
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// # async fn example(table: &Table) -> lancedb::Result<()> {
|
||||
/// table.create_index(&["vector"], Index::Auto)
|
||||
/// .progress(Arc::new(LogProgress))
|
||||
/// .execute_async().await?
|
||||
/// .wait().await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn progress(mut self, progress: Arc<dyn IndexBuildProgress>) -> Self {
|
||||
self.progress = Some(progress);
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn execute(self) -> Result<()> {
|
||||
self.parent.clone().create_index(self).await
|
||||
}
|
||||
|
||||
@@ -778,6 +778,12 @@ impl<S: HttpSend> RemoteTable<S> {
|
||||
|
||||
async fn submit_create_index(&self, mut index: IndexBuilder) -> Result<Option<String>> {
|
||||
self.check_mutable().await?;
|
||||
if index.progress.is_some() {
|
||||
return Err(Error::NotSupported {
|
||||
message: "IndexBuilder::progress is only supported for LanceDB Embedded tables. For LanceDB Enterprise, use execute_async() and Job::wait_with_progress()."
|
||||
.into(),
|
||||
});
|
||||
}
|
||||
let mut request = self
|
||||
.client
|
||||
.post(&format!("/v1/table/{}/create_index/", self.identifier));
|
||||
@@ -9452,6 +9458,28 @@ mod tests {
|
||||
assert!(query_index.values().contains(&1));
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::execute(false)]
|
||||
#[case::execute_async(true)]
|
||||
#[tokio::test]
|
||||
async fn test_create_index_progress_not_supported(#[case] background: bool) {
|
||||
let table = Table::new_with_handler("my_table", |_| -> http::Response<String> {
|
||||
panic!("unsupported index progress callbacks must not send requests to the server");
|
||||
});
|
||||
let builder = table
|
||||
.create_index(&["vector"], Index::Auto)
|
||||
.progress(Arc::new(lance::index::NoopIndexBuildProgress));
|
||||
let result = if background {
|
||||
builder.execute_async().await.map(|_| ())
|
||||
} else {
|
||||
builder.execute().await
|
||||
};
|
||||
assert_not_supported_error(
|
||||
result.unwrap_err(),
|
||||
"IndexBuilder::progress is only supported for LanceDB Embedded tables. For LanceDB Enterprise, use execute_async() and Job::wait_with_progress().",
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_create_index() {
|
||||
let cases = [
|
||||
|
||||
@@ -220,6 +220,9 @@ impl NativeTable {
|
||||
if let Some(name) = guarded_name.clone().or(opts.name) {
|
||||
builder = builder.name(name);
|
||||
}
|
||||
if let Some(progress) = opts.progress {
|
||||
builder = builder.progress(progress);
|
||||
}
|
||||
if let Err(error) = builder.await {
|
||||
if let Some(name) = guarded_name {
|
||||
self.dataset.reload().await?;
|
||||
@@ -782,6 +785,111 @@ mod tests {
|
||||
assert_eq!(table.list_indices().await.unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::execute(false)]
|
||||
#[case::execute_async(true)]
|
||||
#[tokio::test]
|
||||
async fn test_create_index_progress(#[case] background: bool) {
|
||||
use async_trait::async_trait;
|
||||
use lance::index::IndexBuildProgress;
|
||||
use lance_core::Result;
|
||||
use std::iter::repeat_with;
|
||||
use std::sync::Mutex;
|
||||
|
||||
let conn = connect("memory://").execute().await.unwrap();
|
||||
|
||||
let dimension = 16;
|
||||
let schema = Arc::new(Schema::new(vec![Field::new(
|
||||
"embeddings",
|
||||
DataType::FixedSizeList(
|
||||
Arc::new(Field::new("item", DataType::Float32, true)),
|
||||
dimension,
|
||||
),
|
||||
false,
|
||||
)]));
|
||||
|
||||
let float_arr = Float32Array::from(
|
||||
repeat_with(rand::random::<f32>)
|
||||
.take(512 * dimension as usize)
|
||||
.collect::<Vec<f32>>(),
|
||||
);
|
||||
|
||||
let vectors = Arc::new(create_fixed_size_list(float_arr, dimension).unwrap());
|
||||
let batch = RecordBatch::try_new(schema.clone(), vec![vectors.clone()]).unwrap();
|
||||
|
||||
let table = conn.create_table("test", batch).execute().await.unwrap();
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum TestProgressCall {
|
||||
Start(String, Option<u64>, String),
|
||||
Progress(String, u64),
|
||||
Complete(String),
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct TestProgress {
|
||||
calls: Mutex<Vec<TestProgressCall>>,
|
||||
}
|
||||
#[async_trait]
|
||||
impl IndexBuildProgress for TestProgress {
|
||||
async fn stage_start(&self, stage: &str, total: Option<u64>, unit: &str) -> Result<()> {
|
||||
self.calls.lock().unwrap().push(TestProgressCall::Start(
|
||||
stage.to_string(),
|
||||
total,
|
||||
unit.to_string(),
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
async fn stage_progress(&self, stage: &str, completed: u64) -> Result<()> {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(TestProgressCall::Progress(stage.to_string(), completed));
|
||||
Ok(())
|
||||
}
|
||||
async fn stage_complete(&self, stage: &str) -> Result<()> {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(TestProgressCall::Complete(stage.to_string()));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
let progress = Arc::new(TestProgress {
|
||||
calls: Mutex::new(Vec::new()),
|
||||
});
|
||||
let builder = table
|
||||
.create_index(&["embeddings"], Index::Auto)
|
||||
.progress(progress.clone());
|
||||
if background {
|
||||
let job = builder.execute_async().await.unwrap();
|
||||
job.wait().await.unwrap();
|
||||
} else {
|
||||
builder.execute().await.unwrap();
|
||||
}
|
||||
|
||||
let calls = progress.calls.lock().unwrap();
|
||||
for stage in [
|
||||
"train_ivf",
|
||||
"train_quantizer",
|
||||
"shuffle",
|
||||
"merge_partitions",
|
||||
] {
|
||||
assert!(
|
||||
calls.iter().any(
|
||||
|call| matches!(call, TestProgressCall::Start(name, _, _) if name == stage)
|
||||
),
|
||||
"expected stage_start for {stage}"
|
||||
);
|
||||
assert!(
|
||||
calls
|
||||
.iter()
|
||||
.any(|call| matches!(call, TestProgressCall::Complete(name) if name == stage)),
|
||||
"expected stage_complete for {stage}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_execute_async_job_waits_for_local_build() {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
|
||||
Reference in New Issue
Block a user