diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index ed7e4bef0..43a40223f 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -210,6 +210,7 @@ pub struct OpenTableBuilder { parent: Arc, request: OpenTableRequest, embedding_registry: Arc, + source_collect_threshold_bytes: usize, branch: Option, version: Option, } @@ -232,11 +233,18 @@ impl OpenTableBuilder { managed_versioning: None, }, embedding_registry, + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, branch: None, version: None, } } + pub(crate) fn with_source_collect_threshold_bytes(mut self, bytes: usize) -> Self { + self.source_collect_threshold_bytes = bytes; + self + } + /// Set the size of the index cache, specified as a number of entries /// /// The default value is 256 @@ -386,7 +394,8 @@ impl OpenTableBuilder { /// Open the table pub async fn execute(self) -> Result { let table = self.parent.open_table(self.request).await?; - let table = Table::new_with_embedding_registry(table, self.parent, self.embedding_registry); + let table = Table::new_with_embedding_registry(table, self.parent, self.embedding_registry) + .with_source_collect_threshold_bytes(self.source_collect_threshold_bytes); // "main" is the default branch, so treat it as no branch. let branch = self.branch.filter(|b| b.as_str() != MAIN_BRANCH); match branch { @@ -412,6 +421,7 @@ impl OpenTableBuilder { pub struct CloneTableBuilder { parent: Arc, request: CloneTableRequest, + source_collect_threshold_bytes: usize, } /// Builder for asynchronously executing a SQL statement on a LanceDB Enterprise database. @@ -530,9 +540,16 @@ impl CloneTableBuilder { Self { parent, request: CloneTableRequest::new(target_table_name, source_uri), + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, } } + pub(crate) fn with_source_collect_threshold_bytes(mut self, bytes: usize) -> Self { + self.source_collect_threshold_bytes = bytes; + self + } + /// Preserve an existing target without reading or cloning the source. /// Defaults to false, which reports a duplicate-name error. /// @@ -584,8 +601,9 @@ impl CloneTableBuilder { /// Execute the clone operation pub async fn execute(self) -> Result
{ let parent = self.parent.clone(); + let threshold = self.source_collect_threshold_bytes; let table = parent.clone_table(self.request).await?; - Ok(Table::new(table, parent)) + Ok(Table::new(table, parent).with_source_collect_threshold_bytes(threshold)) } } @@ -594,6 +612,7 @@ impl CloneTableBuilder { pub struct Connection { internal: Arc, embedding_registry: Arc, + source_collect_threshold_bytes: usize, } impl std::fmt::Display for Connection { @@ -610,9 +629,16 @@ impl Connection { Self { internal, embedding_registry, + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, } } + /// Get the default non-rescannable merge source collection threshold in bytes. + pub fn source_collect_threshold_bytes(&self) -> usize { + self.source_collect_threshold_bytes + } + /// Get the URI of the connection pub fn uri(&self) -> &str { self.internal.uri() @@ -708,6 +734,7 @@ impl Connection { name.into(), initial_data, ) + .with_source_collect_threshold_bytes(self.source_collect_threshold_bytes) } /// Create an empty table with a given schema @@ -741,6 +768,7 @@ impl Connection { name.into(), self.embedding_registry.clone(), ) + .with_source_collect_threshold_bytes(self.source_collect_threshold_bytes) } /// Clone a table in the database @@ -767,6 +795,7 @@ impl Connection { target_table_name.into(), source_uri.into(), ) + .with_source_collect_threshold_bytes(self.source_collect_threshold_bytes) } /// Build and register a Python callable as an immutable Function version @@ -1750,6 +1779,7 @@ pub struct ConnectRequest { pub struct ConnectBuilder { request: ConnectRequest, embedding_registry: Option>, + source_collect_threshold_bytes: usize, #[cfg(feature = "remote")] oauth_config: Option, } @@ -1773,6 +1803,8 @@ impl ConnectBuilder { session: None, }, embedding_registry: None, + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, #[cfg(feature = "remote")] oauth_config: None, } @@ -2017,6 +2049,16 @@ impl ConnectBuilder { self } + /// Set the default non-rescannable merge source collection threshold in bytes. + /// + /// Defaults to 64 MiB. Tables opened or created from this connection inherit + /// this threshold for `merge_insert`, and [`MergeInsertBuilder::source_collect_threshold_bytes`] + /// can override it per operation. + pub fn source_collect_threshold_bytes(mut self, bytes: usize) -> Self { + self.source_collect_threshold_bytes = bytes; + self + } + #[cfg(feature = "remote")] fn apply_env_defaults( env_var_to_remote_storage_option: &[(&str, &str)], @@ -2119,6 +2161,7 @@ impl ConnectBuilder { embedding_registry: self .embedding_registry .unwrap_or_else(|| Arc::new(MemoryRegistry::new())), + source_collect_threshold_bytes: self.source_collect_threshold_bytes, }) } @@ -2143,6 +2186,7 @@ impl ConnectBuilder { embedding_registry: self .embedding_registry .unwrap_or_else(|| Arc::new(MemoryRegistry::new())), + source_collect_threshold_bytes: self.source_collect_threshold_bytes, }) } else { let internal = Arc::new(ListingDatabase::connect_with_options(&self.request).await?); @@ -2151,6 +2195,7 @@ impl ConnectBuilder { embedding_registry: self .embedding_registry .unwrap_or_else(|| Arc::new(MemoryRegistry::new())), + source_collect_threshold_bytes: self.source_collect_threshold_bytes, }) } } @@ -2192,6 +2237,7 @@ pub struct ConnectNamespaceBuilder { read_consistency_interval: Option, embedding_registry: Option>, session: Option>, + source_collect_threshold_bytes: usize, pushdown_operations: HashSet, } @@ -2205,6 +2251,8 @@ impl ConnectNamespaceBuilder { read_consistency_interval: None, embedding_registry: None, session: None, + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, pushdown_operations: HashSet::new(), } } @@ -2283,6 +2331,12 @@ impl ConnectNamespaceBuilder { self } + /// Set the default non-rescannable merge source collection threshold in bytes. + pub fn source_collect_threshold_bytes(mut self, bytes: usize) -> Self { + self.source_collect_threshold_bytes = bytes; + self + } + /// Add operations to push down to the namespace server. /// /// When operations are added, they will be executed on the namespace server @@ -2338,6 +2392,7 @@ impl ConnectNamespaceBuilder { embedding_registry: self .embedding_registry .unwrap_or_else(|| Arc::new(MemoryRegistry::new())), + source_collect_threshold_bytes: self.source_collect_threshold_bytes, }) } } @@ -2370,6 +2425,8 @@ mod test_utils { Self { internal, embedding_registry: Arc::new(MemoryRegistry::new()), + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, } } @@ -2386,6 +2443,8 @@ mod test_utils { Self { internal, embedding_registry: Arc::new(MemoryRegistry::new()), + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, } } } diff --git a/rust/lancedb/src/connection/create_table.rs b/rust/lancedb/src/connection/create_table.rs index 10633adb9..58b28fb8e 100644 --- a/rust/lancedb/src/connection/create_table.rs +++ b/rust/lancedb/src/connection/create_table.rs @@ -20,6 +20,7 @@ pub struct CreateTableBuilder { parent: Arc, embeddings: Vec<(EmbeddingDefinition, Arc)>, embedding_registry: Arc, + source_collect_threshold_bytes: usize, request: CreateTableRequest, } @@ -34,10 +35,17 @@ impl CreateTableBuilder { parent, embeddings: Vec::new(), embedding_registry, + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, request: CreateTableRequest::new(name, data), } } + pub(crate) fn with_source_collect_threshold_bytes(mut self, bytes: usize) -> Self { + self.source_collect_threshold_bytes = bytes; + self + } + /// Set the mode for creating the table /// /// This controls what happens if a table with the given name already exists @@ -228,7 +236,8 @@ impl CreateTableBuilder { parent.create_table(self.request).await?, parent, embedding_registry, - )) + ) + .with_source_collect_threshold_bytes(self.source_collect_threshold_bytes)) } } diff --git a/rust/lancedb/src/data/scannable.rs b/rust/lancedb/src/data/scannable.rs index cfad157b8..b4c06ddbf 100644 --- a/rust/lancedb/src/data/scannable.rs +++ b/rust/lancedb/src/data/scannable.rs @@ -126,6 +126,58 @@ impl Scannable for Vec { } } +pub struct RecordBatchReaderScannable { + reader: Option>, + schema: SchemaRef, +} + +impl RecordBatchReaderScannable { + pub fn new(reader: Box) -> Self { + let schema = RecordBatchReader::schema(reader.as_ref()); + Self { + reader: Some(reader), + schema, + } + } +} + +impl Scannable for RecordBatchReaderScannable { + fn schema(&self) -> SchemaRef { + self.schema.clone() + } + + fn scan_as_stream(&mut self) -> SendableRecordBatchStream { + let schema = self.schema.clone(); + let Some(reader) = self.reader.take() else { + return Box::pin(SimpleRecordBatchStream { + schema, + stream: once(async { + Err(Error::InvalidInput { + message: "Reader has already been consumed".to_string(), + }) + }), + }); + }; + + // Bridge the blocking RecordBatchReader to an async stream via a channel. + let (tx, rx) = tokio::sync::mpsc::channel::>(2); + tokio::task::spawn_blocking(move || { + for batch in reader { + if tx.blocking_send(batch.map_err(Into::into)).is_err() { + break; + } + } + }); + let stream = futures::stream::unfold(rx, |mut rx| async move { + rx.recv().await.map(|batch| (batch, rx)) + }) + .fuse(); + Box::pin(SimpleRecordBatchStream { schema, stream }) + } +} + +// Preserve the existing trait implementation for callers that explicitly use +// `Box` with APIs other than merge_insert. impl Scannable for Box { fn schema(&self) -> SchemaRef { RecordBatchReader::schema(self.as_ref()) @@ -133,34 +185,57 @@ impl Scannable for Box { fn scan_as_stream(&mut self) -> SendableRecordBatchStream { let schema = Scannable::schema(self); + RecordBatchReaderScannable::new(std::mem::replace( + self, + Box::new(RecordBatchIterator::new( + vec![Err(ArrowError::InvalidArgumentError( + "Reader has already been consumed".into(), + ))], + schema, + )), + )) + .scan_as_stream() + } +} - // Swap self with a reader that errors on iteration, so a second call - // produces a clear error instead of silently returning empty data. - let err_reader: Box = Box::new(RecordBatchIterator::new( - vec![Err(ArrowError::InvalidArgumentError( - "Reader has already been consumed".into(), - ))], - schema.clone(), - )); - let reader = std::mem::replace(self, err_reader); +pub trait IntoScannable { + fn into_scannable(self) -> Box; +} - // Bridge the blocking RecordBatchReader to an async stream via a channel. - let (tx, rx) = tokio::sync::mpsc::channel::>(2); - tokio::task::spawn_blocking(move || { - for batch_result in reader { - let result = batch_result.map_err(Into::into); - if tx.blocking_send(result).is_err() { - break; - } - } - }); +impl IntoScannable for RecordBatch { + fn into_scannable(self) -> Box { + Box::new(self) + } +} - let stream = futures::stream::unfold(rx, |mut rx| async move { - rx.recv().await.map(|batch| (batch, rx)) - }) - .fuse(); +impl IntoScannable for Vec { + fn into_scannable(self) -> Box { + Box::new(self) + } +} - Box::pin(SimpleRecordBatchStream { schema, stream }) +impl IntoScannable for SendableRecordBatchStream { + fn into_scannable(self) -> Box { + Box::new(self) + } +} + +impl IntoScannable for Box { + fn into_scannable(self) -> Box { + self + } +} + +impl IntoScannable for Box { + fn into_scannable(self) -> Box { + let reader: Box = self; + Box::new(RecordBatchReaderScannable::new(reader)) + } +} + +impl IntoScannable for Box { + fn into_scannable(self) -> Box { + Box::new(RecordBatchReaderScannable::new(self)) } } @@ -526,7 +601,7 @@ pub(crate) fn estimate_write_partitions( #[cfg(test)] mod tests { use super::*; - use arrow_array::record_batch; + use arrow_array::{RecordBatchIterator, record_batch}; use futures::TryStreamExt; #[tokio::test] @@ -566,6 +641,16 @@ mod tests { assert_eq!(result2[1], batches[1]); } + #[test] + fn test_vec_batch_num_rows() { + let batches = vec![ + record_batch!(("id", Int64, [0, 1])).unwrap(), + record_batch!(("id", Int64, [2, 3, 4])).unwrap(), + ]; + assert_eq!(batches.num_rows(), Some(5)); + assert!(batches.rescannable()); + } + #[tokio::test] async fn test_vec_batch_empty_errors() { let mut empty: Vec = vec![]; @@ -596,6 +681,35 @@ mod tests { assert!(result2.unwrap().is_err()); } + #[tokio::test] + async fn test_record_batch_reader_adapter_preserves_schema_and_errors_once() { + let batch = record_batch!(("id", Int64, [0, 1])).unwrap(); + let schema = batch.schema(); + let reader: Box = Box::new(RecordBatchIterator::new( + vec![Ok(batch.clone())], + schema.clone(), + )); + let mut source = RecordBatchReaderScannable::new(reader); + + assert_eq!(source.schema(), schema); + assert!(!source.rescannable()); + assert_eq!( + source + .scan_as_stream() + .try_collect::>() + .await + .unwrap(), + vec![batch] + ); + + let error = source + .scan_as_stream() + .try_collect::>() + .await + .expect_err("second scan must fail"); + assert!(error.to_string().contains("already been consumed")); + } + #[tokio::test] async fn test_stream_not_rescannable() { let batch = record_batch!(("id", Int64, [0, 1, 2])).unwrap(); @@ -1125,6 +1239,21 @@ mod tests { "expected InvalidInput about missing 'score' column, got: {err:?}" ); } + + #[tokio::test] + async fn test_record_batch_reader_scannable_empty_reader_fused_after_eof() { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let reader: Box = Box::new(RecordBatchIterator::new( + Vec::>::new(), + schema.clone(), + )); + let mut scannable = RecordBatchReaderScannable::new(reader); + assert_eq!(scannable.schema(), schema); + + let mut stream = scannable.scan_as_stream(); + assert!(stream.next().await.is_none()); + assert!(stream.next().await.is_none()); + } } #[cfg(feature = "polars")] diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 87f73e366..9ac6ba7b2 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -1268,7 +1268,12 @@ impl PreparedDeclaration { vec![]; let reader: Box = Box::new(arrow_array::RecordBatchIterator::new(empty, self.schema)); - let mut request = CreateTableRequest::new(name.to_string(), Box::new(reader)); + let mut request = CreateTableRequest::new( + name.to_string(), + Box::new(crate::data::scannable::RecordBatchReaderScannable::new( + reader, + )), + ); request.namespace_path = namespace_path.to_vec(); let table = self.database.clone().create_table(request).await?; let table = Table::new(table, self.database); diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index ba6f951a7..5a45518af 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -3767,7 +3767,9 @@ mod tests { .base_table() .merge_insert( merge, - Box::new(RecordBatchIterator::new(vec![Ok(source)], schema.clone())), + Box::new(crate::data::scannable::RecordBatchReaderScannable::new( + Box::new(RecordBatchIterator::new(vec![Ok(source)], schema.clone())), + )), ) .await .unwrap(); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 1afbd08ea..27ebe7081 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -23,6 +23,8 @@ use super::db::ServerVersion; use super::sql::SqlClient; use super::{ARROW_FILE_CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE, extract_job_id}; use crate::blob::BlobFile; +#[cfg(test)] +use crate::data::scannable::RecordBatchReaderScannable; use crate::data::scannable::{PeekedScannable, Scannable, estimate_write_partitions}; use crate::error::{HttpErrorSource, RemoteErrorMetadata}; use crate::expr::expr_to_sql_string; @@ -70,7 +72,9 @@ use crate::{ TableDefinition, UpdateBuilder, merge::MergeInsertBuilder, }, }; -use arrow_array::{LargeBinaryArray, RecordBatch, RecordBatchReader}; +#[cfg(test)] +use arrow_array::RecordBatchReader; +use arrow_array::{LargeBinaryArray, RecordBatch}; use arrow_ipc::reader::FileReader; use arrow_schema::{DataType, SchemaRef}; use async_trait::async_trait; @@ -4208,7 +4212,7 @@ impl BaseTable for RemoteTable { async fn merge_insert( &self, mut params: MergeInsertBuilder, - new_data: Box, + mut new_data: Box, ) -> Result { params.canonicalize_filters()?; self.check_mutable().await?; @@ -4231,8 +4235,8 @@ impl BaseTable for RemoteTable { // loop can re-execute the plan (and re-stream the body) on each retry. // This mirrors the old `send_streaming(with_retry=true)` path, which // likewise buffered the reader to support retries. - let schema = RecordBatchReader::schema(new_data.as_ref()); - let mut batches = new_data.collect::, _>>()?; + let schema = new_data.schema(); + let mut batches = new_data.scan_as_stream().try_collect::>().await?; // An empty reader still carries a schema. Keep it in an empty batch so // the buffered source remains scannable and can be replayed on retries. if batches.is_empty() { @@ -6787,7 +6791,11 @@ mod tests { let mut merge = table.merge_insert(&["some_col"]); merge.when_matched_update_all(Some(r#"target."A" > 0"#.into())); - let result = table.base_table().merge_insert(merge, data).await.unwrap(); + let result = table + .base_table() + .merge_insert(merge, Box::new(RecordBatchReaderScannable::new(data))) + .await + .unwrap(); assert_eq!(result.version, if old_server { 0 } else { 43 }); if !old_server { @@ -7013,7 +7021,11 @@ mod tests { let mut merge = table.merge_insert(&["shard_key", "id"]); merge.when_matched_update_all(None); merge.when_not_matched_insert_all(); - let result = table.base_table().merge_insert(merge, data).await.unwrap(); + let result = table + .base_table() + .merge_insert(merge, Box::new(RecordBatchReaderScannable::new(data))) + .await + .unwrap(); assert_eq!(result.num_inserted_rows, 3); } @@ -7037,7 +7049,7 @@ mod tests { let merge = table.merge_insert(&["id", "id"]); let err = table .base_table() - .merge_insert(merge, data) + .merge_insert(merge, Box::new(RecordBatchReaderScannable::new(data))) .await .unwrap_err(); assert!( diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 764d5ccc0..d4e37a90d 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -769,7 +769,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn merge_insert( &self, params: MergeInsertBuilder, - new_data: Box, + new_data: Box, ) -> Result; /// Set the unenforced primary key for the table to a single column. /// @@ -1319,6 +1319,7 @@ pub struct Table { inner: Arc, database: Option>, embedding_registry: Arc, + source_collect_threshold_bytes: usize, } #[cfg(all(test, feature = "remote"))] @@ -1344,6 +1345,8 @@ mod test_utils { database: Some(database), // Registry is unused. embedding_registry: Arc::new(MemoryRegistry::new()), + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, } } @@ -1368,6 +1371,8 @@ mod test_utils { database: Some(database), // Registry is unused. embedding_registry: Arc::new(MemoryRegistry::new()), + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, } } @@ -1390,6 +1395,8 @@ mod test_utils { database: Some(database), // Registry is unused. embedding_registry: Arc::new(MemoryRegistry::new()), + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, } } @@ -1414,6 +1421,8 @@ mod test_utils { database: Some(database), // Registry is unused. embedding_registry: Arc::new(MemoryRegistry::new()), + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, } } @@ -1442,6 +1451,8 @@ mod test_utils { database: Some(database), // Registry is unused. embedding_registry: Arc::new(MemoryRegistry::new()), + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, } } } @@ -1459,6 +1470,8 @@ impl From> for Table { inner, database: None, embedding_registry: Arc::new(MemoryRegistry::new()), + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, } } } @@ -1469,6 +1482,8 @@ impl Table { inner, database: Some(database), embedding_registry: Arc::new(MemoryRegistry::new()), + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, } } @@ -1498,9 +1513,21 @@ impl Table { inner, database: Some(database), embedding_registry, + source_collect_threshold_bytes: + crate::table::merge::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, } } + pub(crate) fn with_source_collect_threshold_bytes(mut self, bytes: usize) -> Self { + self.source_collect_threshold_bytes = bytes; + self + } + + /// The default non-rescannable merge source collection threshold in bytes for this table. + pub fn source_collect_threshold_bytes(&self) -> usize { + self.source_collect_threshold_bytes + } + /// Cast as [`NativeTable`], or return None it if is not a [`NativeTable`]. /// /// Warning: This function will be removed soon (features exclusive to NativeTable @@ -1543,6 +1570,7 @@ impl Table { inner: self.inner.query_snapshot().await?, database: self.database.clone(), embedding_registry: self.embedding_registry.clone(), + source_collect_threshold_bytes: self.source_collect_threshold_bytes, }) } @@ -1556,6 +1584,7 @@ impl Table { .await?, database: self.database.clone(), embedding_registry: self.embedding_registry.clone(), + source_collect_threshold_bytes: self.source_collect_threshold_bytes, }) } @@ -2095,6 +2124,7 @@ impl Table { self.inner.clone(), on.iter().map(|s| s.to_string()).collect(), ) + .with_default_source_collect_threshold_bytes(self.source_collect_threshold_bytes) } /// Create a [`Query`] Builder. @@ -3183,6 +3213,7 @@ impl Table { inner, database: self.database.clone(), embedding_registry: self.embedding_registry.clone(), + source_collect_threshold_bytes: self.source_collect_threshold_bytes, }) } @@ -3608,6 +3639,7 @@ impl Table { inner, database: self.database.clone(), embedding_registry: self.embedding_registry.clone(), + source_collect_threshold_bytes: self.source_collect_threshold_bytes, }) } @@ -3630,6 +3662,7 @@ impl Table { inner, database: self.database.clone(), embedding_registry: self.embedding_registry.clone(), + source_collect_threshold_bytes: self.source_collect_threshold_bytes, }) } @@ -5023,10 +5056,10 @@ impl BaseTable for NativeTable { async fn merge_insert( &self, params: MergeInsertBuilder, - new_data: Box, + new_data: Box, ) -> Result { self.dataset.ensure_mutable()?; - let source_schema = arrow_array::RecordBatchReader::schema(&new_data); + let source_schema = new_data.schema(); self.ensure_not_a_view("merge insert into").await?; computed_columns::ensure_not_written( &Schema::from(self.dataset.get().await?.schema()), diff --git a/rust/lancedb/src/table/datafusion/scannable_exec.rs b/rust/lancedb/src/table/datafusion/scannable_exec.rs index dd9f5e681..af1313d95 100644 --- a/rust/lancedb/src/table/datafusion/scannable_exec.rs +++ b/rust/lancedb/src/table/datafusion/scannable_exec.rs @@ -4,12 +4,19 @@ use core::fmt; use std::sync::{Arc, Mutex}; +use async_trait::async_trait; +use datafusion_catalog::{Session, TableProvider}; use datafusion_common::{DataFusionError, Result as DFResult, Statistics, stats::Precision}; use datafusion_execution::{SendableRecordBatchStream, TaskContext}; -use datafusion_physical_expr::{EquivalenceProperties, Partitioning}; +use datafusion_expr::{Expr, TableType}; +use datafusion_physical_expr::{EquivalenceProperties, Partitioning, PhysicalExpr}; +use datafusion_physical_plan::expressions::Column; +use datafusion_physical_plan::projection::ProjectionExec; use datafusion_physical_plan::stream::RecordBatchStreamAdapter; use datafusion_physical_plan::{ - DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties, execution_plan::EmissionType, + DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties, + execution_plan::EmissionType, + statistics::{ChildStats, StatisticsArgs}, }; use futures::TryStreamExt; @@ -18,12 +25,82 @@ use crate::{arrow::SendableRecordBatchStreamExt, data::scannable::Scannable}; pub(crate) struct ScannableExec { // We don't require Scannable to be Sync, so we wrap it in a Mutex to allow safe concurrent access. - source: Mutex>, + source: Arc>>, num_rows: Option, properties: Arc, tracker: Option>, } +/// A DataFusion provider backed by a rescannable [`Scannable`] source. +#[derive(Debug)] +pub(crate) struct ScannableProvider { + source: Arc>>, +} + +impl ScannableProvider { + pub(crate) fn new(source: Box) -> Self { + Self { + source: Arc::new(Mutex::new(source)), + } + } +} + +#[async_trait] +impl TableProvider for ScannableProvider { + fn schema(&self) -> arrow_schema::SchemaRef { + match self.source.lock() { + Ok(source) => source.schema(), + Err(poison) => poison.into_inner().schema(), + } + } + + fn table_type(&self) -> TableType { + TableType::Temporary + } + + async fn scan( + &self, + _state: &dyn Session, + projection: Option<&Vec>, + _filters: &[Expr], + _limit: Option, + ) -> datafusion_common::Result> { + let plan: Arc = { + let source = match self.source.lock() { + Ok(source) => source, + Err(poison) => poison.into_inner(), + }; + Arc::new(ScannableExec::from_shared( + self.source.clone(), + source.schema(), + source.num_rows(), + )) + }; + apply_projection(plan, projection) + } +} + +pub(crate) fn apply_projection( + plan: Arc, + projection: Option<&Vec>, +) -> DFResult> { + let Some(indices) = projection else { + return Ok(plan); + }; + let schema = plan.schema(); + let exprs: Vec<_> = indices + .iter() + .map(|&idx| { + let field = schema.field(idx); + ( + Arc::new(Column::new(field.name(), idx)) as Arc, + field.name().clone(), + ) + }) + .collect(); + Ok(Arc::new(ProjectionExec::try_new(exprs, plan)?)) +} + impl std::fmt::Debug for ScannableExec { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ScannableExec") @@ -45,7 +122,7 @@ impl ScannableExec { ); let num_rows = source.num_rows(); - let source = Mutex::new(source); + let source = Arc::new(Mutex::new(source)); Self { source, num_rows, @@ -53,6 +130,26 @@ impl ScannableExec { tracker, } } + + fn from_shared( + source: Arc>>, + schema: arrow_schema::SchemaRef, + num_rows: Option, + ) -> Self { + let eq_properties = EquivalenceProperties::new(schema); + let properties = PlanProperties::new( + eq_properties, + Partitioning::UnknownPartitioning(1), + EmissionType::Incremental, + datafusion_physical_plan::execution_plan::Boundedness::Bounded, + ); + Self { + num_rows, + source, + properties: Arc::new(properties), + tracker: None, + } + } } impl DisplayAs for ScannableExec { @@ -137,4 +234,311 @@ impl ExecutionPlan for ScannableExec { column_statistics: vec![], })) } + + fn statistics_from_inputs( + &self, + _input_stats: &[Arc], + _args: &StatisticsArgs, + ) -> DFResult> { + Ok(Arc::new(Statistics { + num_rows: self + .num_rows + .map(Precision::Exact) + .unwrap_or(Precision::Absent), + total_byte_size: Precision::Absent, + column_statistics: vec![], + })) + } +} + +/// A DataFusion `TableProvider` wrapper that reports an inexact lower-bound row count. +#[cfg_attr(not(test), allow(dead_code))] +#[derive(Debug)] +pub(crate) struct InexactRowCountProvider { + inner: Arc, + prefix_rows: usize, +} + +#[cfg_attr(not(test), allow(dead_code))] +impl InexactRowCountProvider { + pub(crate) fn new(inner: Arc, prefix_rows: usize) -> Self { + Self { inner, prefix_rows } + } +} + +#[async_trait] +impl TableProvider for InexactRowCountProvider { + fn schema(&self) -> arrow_schema::SchemaRef { + self.inner.schema() + } + + fn table_type(&self) -> TableType { + self.inner.table_type() + } + + async fn scan( + &self, + state: &dyn Session, + projection: Option<&Vec>, + filters: &[Expr], + limit: Option, + ) -> DFResult> { + let plan = self.inner.scan(state, projection, filters, limit).await?; + Ok(Arc::new(InexactRowCountExec::new(plan, self.prefix_rows))) + } +} + +/// An `ExecutionPlan` wrapper that preserves child schema, partitioning, and +/// execution while reporting `Precision::Inexact(prefix_rows)` for `num_rows`. +#[cfg_attr(not(test), allow(dead_code))] +#[derive(Debug)] +pub(crate) struct InexactRowCountExec { + inner: Arc, + prefix_rows: usize, +} + +#[cfg_attr(not(test), allow(dead_code))] +impl InexactRowCountExec { + pub(crate) fn new(inner: Arc, prefix_rows: usize) -> Self { + Self { inner, prefix_rows } + } +} + +impl DisplayAs for InexactRowCountExec { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter<'_>) -> fmt::Result { + write!(f, "InexactRowCountExec: prefix_rows={}", self.prefix_rows) + } +} + +impl ExecutionPlan for InexactRowCountExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> DFResult, + ) -> DFResult { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } + + fn name(&self) -> &str { + "InexactRowCountExec" + } + + fn properties(&self) -> &Arc { + self.inner.properties() + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.inner] + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> DFResult> { + if children.len() != 1 { + return Err(DataFusionError::Internal(format!( + "InexactRowCountExec expected 1 child, got {}", + children.len() + ))); + } + Ok(Arc::new(Self::new( + children.into_iter().next().unwrap(), + self.prefix_rows, + ))) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> DFResult { + self.inner.execute(partition, context) + } + + fn child_stats_requests(&self, partition: Option) -> Vec { + vec![ChildStats::At(partition)] + } + + fn partition_statistics(&self, partition: Option) -> DFResult> { + #[expect(deprecated)] + let mut stats = (*self.inner.partition_statistics(partition)?).clone(); + stats.num_rows = Precision::Inexact(self.prefix_rows); + Ok(Arc::new(stats)) + } + + fn statistics_from_inputs( + &self, + input_stats: &[Arc], + _args: &StatisticsArgs, + ) -> DFResult> { + let mut stats = input_stats + .first() + .map(|s| (**s).clone()) + .unwrap_or_else(|| Statistics::new_unknown(&self.schema())); + stats.num_rows = Precision::Inexact(self.prefix_rows); + Ok(Arc::new(stats)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::record_batch; + use datafusion::execution::context::SessionContext; + use datafusion_catalog::TableProvider; + use datafusion_common::stats::Precision; + use futures::TryStreamExt; + + #[tokio::test] + async fn provider_preserves_schema_statistics_and_repeated_scans() { + let batch = record_batch!(("id", Int64, [1, 2, 3])).unwrap(); + let provider = ScannableProvider::new(Box::new(vec![batch.clone()])); + let ctx = SessionContext::new(); + + assert_eq!(provider.schema(), batch.schema()); + let plan = provider.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!( + datafusion_physical_plan::statistics::StatisticsContext::new() + .compute(&*plan, &StatisticsArgs::new()) + .unwrap() + .num_rows, + Precision::Exact(3) + ); + let first: Vec<_> = plan + .execute(0, ctx.task_ctx()) + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!(first, vec![batch.clone()]); + + let plan = provider.scan(&ctx.state(), None, &[], None).await.unwrap(); + let second: Vec<_> = plan + .execute(0, ctx.task_ctx()) + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!(second, vec![batch]); + } + + #[tokio::test] + async fn provider_preserves_empty_source_schema() { + let schema = Arc::new(arrow_schema::Schema::new(vec![arrow_schema::Field::new( + "id", + arrow_schema::DataType::Int64, + true, + )])); + let source = vec![arrow_array::RecordBatch::new_empty(schema.clone())]; + let provider = ScannableProvider::new(Box::new(source)); + assert_eq!(provider.schema(), schema); + let ctx = SessionContext::new(); + let plan = provider.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!( + datafusion_physical_plan::statistics::StatisticsContext::new() + .compute(&*plan, &StatisticsArgs::new()) + .unwrap() + .num_rows, + Precision::Exact(0) + ); + } + + #[tokio::test] + async fn inexact_row_count_provider_reports_inexact_statistics_and_delegates_execution() { + let batch = record_batch!(("id", Int64, [1, 2, 3, 4, 5])).unwrap(); + let inner = Arc::new(ScannableProvider::new(Box::new(vec![batch.clone()]))); + let provider = InexactRowCountProvider::new(inner, 2); + let ctx = SessionContext::new(); + + assert_eq!(provider.schema(), batch.schema()); + let plan = provider.scan(&ctx.state(), None, &[], None).await.unwrap(); + let stats = datafusion_physical_plan::statistics::StatisticsContext::new() + .compute(&*plan, &StatisticsArgs::new()) + .unwrap(); + assert_eq!(stats.num_rows, Precision::Inexact(2)); + + let rows: Vec<_> = plan + .execute(0, ctx.task_ctx()) + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!(rows, vec![batch]); + } + + #[tokio::test] + async fn provider_applies_projection_preserves_stats_and_rescans() { + let batch = record_batch!(("val", Int64, [10, 20]), ("id", Int64, [1, 2])).unwrap(); + let provider = ScannableProvider::new(Box::new(vec![batch.clone()])); + let ctx = SessionContext::new(); + + // 1. Projection [1] returns only [id] + let proj_id = vec![1]; + for _ in 0..2 { + let plan = provider + .scan(&ctx.state(), Some(&proj_id), &[], None) + .await + .unwrap(); + let plan_schema = plan.schema(); + let field_names: Vec<_> = plan_schema + .fields() + .iter() + .map(|f| f.name().as_str()) + .collect(); + assert_eq!(field_names, vec!["id"]); + let stats = datafusion_physical_plan::statistics::StatisticsContext::new() + .compute(&*plan, &StatisticsArgs::new()) + .unwrap(); + assert_eq!(stats.num_rows, Precision::Exact(2)); + let rows: Vec<_> = plan + .execute(0, ctx.task_ctx()) + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!(rows, vec![record_batch!(("id", Int64, [1, 2])).unwrap()]); + } + + // 2. Reordered projection [1, 0] returns [id, val] + let proj_reordered = vec![1, 0]; + for _ in 0..2 { + let plan = provider + .scan(&ctx.state(), Some(&proj_reordered), &[], None) + .await + .unwrap(); + let plan_schema = plan.schema(); + let field_names: Vec<_> = plan_schema + .fields() + .iter() + .map(|f| f.name().as_str()) + .collect(); + assert_eq!(field_names, vec!["id", "val"]); + let stats = datafusion_physical_plan::statistics::StatisticsContext::new() + .compute(&*plan, &StatisticsArgs::new()) + .unwrap(); + assert_eq!(stats.num_rows, Precision::Exact(2)); + let rows: Vec<_> = plan + .execute(0, ctx.task_ctx()) + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!( + rows, + vec![record_batch!(("id", Int64, [1, 2]), ("val", Int64, [10, 20])).unwrap()] + ); + } + + // 3. Projection None returns complete original schema [val, id] + let plan = provider.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), batch.schema()); + let rows: Vec<_> = plan + .execute(0, ctx.task_ctx()) + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!(rows, vec![batch]); + } } diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 8a72501b6..a7b05ff09 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -5,22 +5,179 @@ use std::collections::HashSet; use std::sync::Arc; use std::time::Duration; -use arrow_array::RecordBatchReader; +use arrow_array::RecordBatch; use arrow_schema::{DataType, Fields}; -use futures::future::Either; -use futures::{FutureExt, TryFutureExt}; +use datafusion_catalog::TableProvider; +use datafusion_physical_plan::stream::RecordBatchStreamAdapter; +use futures::{StreamExt, TryStreamExt}; use lance::dataset::{ MergeInsertBuilder as LanceMergeInsertBuilder, WhenMatched, WhenNotMatchedBySource, }; use lance_datafusion::utils::StreamingWriteSource; use serde::{Deserialize, Serialize}; +use crate::data::scannable::{IntoScannable, Scannable}; use crate::error::{Error, Result}; use super::{BaseTable, NativeTable}; pub(crate) mod lsm; +pub const DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES: usize = 64 * 1024 * 1024; + +enum PreparedMergeSource { + Provider(Arc), + Batches(Vec), + Stream(datafusion_execution::SendableRecordBatchStream), +} + +#[derive(Debug)] +struct MergeCastProvider { + inner: Arc, + table_schema: arrow_schema::SchemaRef, + output_schema: arrow_schema::SchemaRef, +} + +impl MergeCastProvider { + fn try_new( + inner: Arc, + table_schema: arrow_schema::SchemaRef, + ) -> Result { + let source_schema = inner.schema(); + validate_merge_source_fields(source_schema.fields(), table_schema.fields(), "")?; + let empty = Arc::new(datafusion_physical_plan::empty::EmptyExec::new( + source_schema, + )); + let output_schema = + super::datafusion::cast::cast_to_table_schema(empty, &table_schema)?.schema(); + Ok(Self { + inner, + table_schema, + output_schema, + }) + } +} + +#[async_trait::async_trait] +impl TableProvider for MergeCastProvider { + fn schema(&self) -> arrow_schema::SchemaRef { + self.output_schema.clone() + } + + fn table_type(&self) -> datafusion_expr::TableType { + self.inner.table_type() + } + + async fn scan( + &self, + state: &dyn datafusion_catalog::Session, + projection: Option<&Vec>, + filters: &[datafusion_expr::Expr], + limit: Option, + ) -> datafusion_common::Result> { + let plan = self.inner.scan(state, None, filters, limit).await?; + let plan = super::datafusion::cast::cast_to_table_schema(plan, &self.table_schema) + .map_err(|e| datafusion_common::DataFusionError::External(Box::new(e)))?; + super::datafusion::scannable_exec::apply_projection(plan, projection) + } +} + +fn wrap_prepared_source_with_cast( + prepared: PreparedMergeSource, + table_schema: arrow_schema::SchemaRef, +) -> Result { + match prepared { + PreparedMergeSource::Provider(provider) => Ok(PreparedMergeSource::Provider(Arc::new( + MergeCastProvider::try_new(provider, table_schema)?, + ))), + PreparedMergeSource::Batches(batches) => { + let provider = Arc::new(super::datafusion::scannable_exec::ScannableProvider::new( + Box::new(batches), + )); + Ok(PreparedMergeSource::Provider(Arc::new( + MergeCastProvider::try_new(provider, table_schema)?, + ))) + } + PreparedMergeSource::Stream(stream) => { + let plan = Arc::new(lance_datafusion::exec::OneShotExec::new(stream)); + let plan = super::datafusion::cast::cast_to_table_schema(plan, &table_schema)?; + Ok(PreparedMergeSource::Stream( + datafusion_physical_plan::execute_stream( + plan, + Arc::new(datafusion_execution::TaskContext::default()), + )?, + )) + } + } +} + +async fn prepare_merge_source( + mut source: Box, + threshold_bytes: usize, +) -> Result { + if source.rescannable() { + return Ok(PreparedMergeSource::Provider(Arc::new( + super::datafusion::scannable_exec::ScannableProvider::new(source), + ))); + } + + let schema = source.schema(); + let mut stream = source.scan_as_stream(); + let mut prefix = Vec::new(); + let mut bytes = 0usize; + while let Some(batch) = stream.try_next().await? { + bytes = bytes.saturating_add(batch.get_array_memory_size()); + prefix.push(batch); + if bytes > threshold_bytes { + let remaining = stream.map(|batch| { + batch.map_err(|e| datafusion_common::DataFusionError::External(Box::new(e))) + }); + let chained = futures::stream::iter( + prefix + .into_iter() + .map(Ok::), + ) + .chain(remaining); + let stream = Box::pin(RecordBatchStreamAdapter::new(schema, chained)); + return Ok(PreparedMergeSource::Stream(stream)); + } + } + let mut batches = prefix; + if batches.is_empty() { + // Lance's batch provider needs a schema-bearing batch for an empty source. + batches.push(RecordBatch::new_empty(schema)); + } + Ok(PreparedMergeSource::Batches(batches)) +} + +async fn run_with_deadline(deadline: Option, future: F) -> Result +where + F: std::future::Future>, + Error: From, +{ + match deadline { + Some(deadline) => match tokio::time::timeout_at(deadline, future).await { + Ok(result) => result.map_err(Error::from), + Err(_) => Err(Error::Runtime { + message: "merge insert timed out".to_string(), + }), + }, + None => future.await.map_err(Error::from), + } +} + +async fn execute_prepared_merge_source( + job: lance::dataset::MergeInsertJob, + prepared: PreparedMergeSource, + _native_conflict_retries_enabled: bool, +) -> lance::Result<(Arc, lance::dataset::MergeStats)> { + match prepared { + PreparedMergeSource::Provider(provider) => job.execute_provider(provider).await, + PreparedMergeSource::Batches(batches) => job.execute_batches(batches).await, + PreparedMergeSource::Stream(stream) => job.execute(stream).await, + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] pub struct MergeResult { // The commit version associated with the operation. @@ -79,6 +236,7 @@ pub struct MergeInsertBuilder { pub(crate) use_index: bool, pub(crate) use_rte: Option, pub(crate) validate_single_shard: bool, + pub(crate) source_collect_threshold_bytes: usize, } impl MergeInsertBuilder { @@ -96,9 +254,15 @@ impl MergeInsertBuilder { use_index: true, use_rte: None, validate_single_shard: true, + source_collect_threshold_bytes: DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, } } + pub(super) fn with_default_source_collect_threshold_bytes(mut self, bytes: usize) -> Self { + self.source_collect_threshold_bytes = bytes; + self + } + /// Override the remote transport retry budget for this operation. `0` /// disables retries. Ambiguous write results are never replayed. This is /// independent of local transaction conflict retries. @@ -245,16 +409,22 @@ impl MergeInsertBuilder { self } + /// Override the non-rescannable merge source collection threshold. + pub fn source_collect_threshold_bytes(&mut self, bytes: usize) -> &mut Self { + self.source_collect_threshold_bytes = bytes; + self + } + /// Executes the merge insert operation /// /// Returns version and statistics about the merge operation including the number of rows /// inserted, updated, and deleted. - pub async fn execute( - mut self, - new_data: Box, - ) -> Result { + pub async fn execute(mut self, new_data: impl IntoScannable) -> Result { self.canonicalize_filters()?; - self.table.clone().merge_insert(self, new_data).await + self.table + .clone() + .merge_insert(self, new_data.into_scannable()) + .await } pub(crate) fn canonicalize_filters(&mut self) -> Result<()> { @@ -365,7 +535,7 @@ fn validate_merge_source_type(input: &DataType, target: &DataType, path: &str) - pub(crate) async fn execute_merge_insert( table: &NativeTable, mut params: MergeInsertBuilder, - new_data: Box, + new_data: Box, ) -> Result { params.canonicalize_filters()?; let schema = table.schema().await?; @@ -374,29 +544,27 @@ pub(crate) async fn execute_merge_insert( schema.as_ref(), matched_columns.iter().map(String::as_str), )?; - // Normalize blob layouts and JSON extension metadata just as on append. - // Keep arrow.json text labelled until Lance encodes it as JSONB. - let source = if crate::blob::has_blob_columns(&schema) - || schema - .fields() - .iter() - .any(|field| lance_arrow::json::has_json_fields(field)) - { - validate_merge_source_fields(new_data.schema().fields(), schema.fields(), "")?; - let plan = Arc::new(super::datafusion::scannable_exec::ScannableExec::new( - Box::new(new_data), - None, - )); - let plan = super::datafusion::cast::cast_to_table_schema(plan, &schema)?; - datafusion_physical_plan::execute_stream( - plan, - Arc::new(datafusion_execution::TaskContext::default()), - )? - } else { - new_data.into_stream() - }; match lsm::lsm_dispatch_decision(table, ¶ms).await? { lsm::LsmDispatch::Lsm(plan) => { + // Preserve the existing LSM source preprocessing and execution path. + let source = if crate::blob::has_blob_columns(&schema) + || schema + .fields() + .iter() + .any(|field| lance_arrow::json::has_json_fields(field)) + { + validate_merge_source_fields(new_data.schema().fields(), schema.fields(), "")?; + let plan = Arc::new(super::datafusion::scannable_exec::ScannableExec::new( + new_data, None, + )); + let plan = super::datafusion::cast::cast_to_table_schema(plan, &schema)?; + datafusion_physical_plan::execute_stream( + plan, + Arc::new(datafusion_execution::TaskContext::default()), + )? + } else { + new_data.into_stream() + }; let future = lsm::execute_lsm_merge_insert(table, plan, params.validate_single_shard, source); return match params.timeout { @@ -412,8 +580,30 @@ pub(crate) async fn execute_merge_insert( lsm::LsmDispatch::Standard => {} } + let source_schema = new_data.schema(); + let needs_cast = crate::blob::has_blob_columns(&schema) + || schema + .fields() + .iter() + .any(|field| lance_arrow::json::has_json_fields(field)); + if needs_cast { + validate_merge_source_fields(source_schema.fields(), schema.fields(), "")?; + } + let deadline = params + .timeout + .map(|timeout| tokio::time::Instant::now() + timeout); + let prepared = run_with_deadline( + deadline, + prepare_merge_source(new_data, params.source_collect_threshold_bytes), + ) + .await?; + let prepared = if needs_cast { + wrap_prepared_source_with_cast(prepared, schema.clone())? + } else { + prepared + }; + let dataset = table.dataset.get().await?; - let source_schema = source.schema(); let on = params.on.clone(); let mut builder = LanceMergeInsertBuilder::try_new(dataset.clone(), params.on)?; match ( @@ -448,20 +638,28 @@ pub(crate) async fn execute_merge_insert( } builder.use_index(params.use_index); - let future = if let Some(timeout) = params.timeout { - let future = builder.retry_timeout(timeout).try_build()?.execute(source); - Either::Left(tokio::time::timeout(timeout, future).map(|res| match res { - Ok(Ok((new_dataset, stats))) => Ok((new_dataset, stats)), - Ok(Err(e)) => Err(e.into()), - Err(_) => Err(Error::Runtime { + let mut job = builder; + let remaining_timeout = + deadline.map(|deadline| deadline.saturating_duration_since(tokio::time::Instant::now())); + if let Some(remaining) = remaining_timeout { + if remaining.is_zero() { + return Err(Error::Runtime { message: "merge insert timed out".to_string(), - }), - })) - } else { - let job = builder.try_build()?; - Either::Right(job.execute(source).map_err(|e| e.into())) - }; - let (new_dataset, stats) = future.await?; + }); + } + job.retry_timeout(remaining); + } + // `params.retries` only configures remote HTTP transport retries; native + // Lance conflict retries are governed by the Lance builder's conflict retry + // budget and `retry_timeout`. + let native_conflict_retries_enabled = + !matches!(params.timeout, Some(timeout) if timeout.is_zero()); + if !native_conflict_retries_enabled { + job.conflict_retries(0); + } + let job = job.try_build()?; + let execute = execute_prepared_merge_source(job, prepared, native_conflict_retries_enabled); + let (new_dataset, stats) = run_with_deadline(deadline, execute).await?; let mut new_dataset = new_dataset.as_ref().clone(); if let Err(error) = super::freshness::preserve_function_freshness( &mut new_dataset, @@ -498,6 +696,7 @@ mod tests { use std::sync::Arc; use crate::connect; + use crate::query::ExecutableQuery; #[rstest::rstest] #[case(None)] @@ -1059,6 +1258,870 @@ mod tests { ); } } + + #[tokio::test] + async fn connection_source_collect_threshold_defaults_and_propagates() { + assert_eq!( + super::DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES, + 64 * 1024 * 1024 + ); + + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + + let default_conn = connect(uri).execute().await.unwrap(); + assert_eq!( + default_conn.source_collect_threshold_bytes(), + 64 * 1024 * 1024 + ); + let default_table = default_conn + .create_empty_table("default_tbl", schema.clone()) + .execute() + .await + .unwrap(); + assert_eq!( + default_table.source_collect_threshold_bytes(), + 64 * 1024 * 1024 + ); + assert_eq!( + default_table + .merge_insert(&["id"]) + .source_collect_threshold_bytes, + 64 * 1024 * 1024 + ); + + let custom_conn = connect(uri) + .source_collect_threshold_bytes(1024) + .execute() + .await + .unwrap(); + assert_eq!(custom_conn.source_collect_threshold_bytes(), 1024); + + let created = custom_conn + .create_empty_table("custom_tbl", schema) + .execute() + .await + .unwrap(); + assert_eq!(created.source_collect_threshold_bytes(), 1024); + assert_eq!( + created.merge_insert(&["id"]).source_collect_threshold_bytes, + 1024 + ); + + let opened = custom_conn + .open_table("custom_tbl") + .execute() + .await + .unwrap(); + assert_eq!(opened.source_collect_threshold_bytes(), 1024); + assert_eq!( + opened.merge_insert(&["id"]).source_collect_threshold_bytes, + 1024 + ); + + let branched = opened.create_branch("exp", 1).await.unwrap(); + assert_eq!(branched.source_collect_threshold_bytes(), 1024); + let checked_out = opened.checkout_branch("exp", None).await.unwrap(); + assert_eq!(checked_out.source_collect_threshold_bytes(), 1024); + + let mut builder = opened.merge_insert(&["id"]); + builder.source_collect_threshold_bytes(256); + assert_eq!(builder.source_collect_threshold_bytes, 256); + } + + #[tokio::test] + async fn prepare_merge_source_spill_reports_inexact_prefix_statistics_and_replays_all_batches() + { + use futures::TryStreamExt; + + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let b1 = RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![1, 2]))]) + .unwrap(); + let b2 = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(vec![3, 4, 5]))], + ) + .unwrap(); + let b3 = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(vec![6, 7, 8, 9]))], + ) + .unwrap(); + + let threshold = b1.get_array_memory_size(); + let reader: Box = Box::new(RecordBatchIterator::new( + vec![Ok(b1), Ok(b2), Ok(b3)], + schema.clone(), + )); + let prepared = super::prepare_merge_source(Box::new(reader), threshold) + .await + .unwrap(); + + let super::PreparedMergeSource::Stream(stream) = prepared else { + panic!("expected PreparedMergeSource::Stream"); + }; + + assert_eq!(stream.schema(), schema); + let batches: Vec<_> = stream.try_collect().await.unwrap(); + let ids: Vec = batches + .iter() + .flat_map(|batch| { + batch["id"] + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect(); + assert_eq!(ids, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]); + } + + #[rstest::rstest] + #[case(true)] + #[case(false)] + #[tokio::test] + async fn spill_merge_insert_succeeds_with_native_conflict_retries_enabled_and_disabled( + #[case] native_conflict_retries_enabled: bool, + ) { + use futures::TryStreamExt; + use lance::dataset::{MergeInsertBuilder as LanceMergeInsertBuilder, WhenMatched}; + + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("val", DataType::Int32, false), + ])); + let initial = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![1, 2])), + Arc::new(Int32Array::from(vec![10, 20])), + ], + ) + .unwrap(); + let table = conn + .create_table("spill_modes", initial) + .execute() + .await + .unwrap(); + let native = table.as_native().unwrap(); + let dataset = native.dataset.get().await.unwrap(); + + let b1 = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![2, 3])), + Arc::new(Int32Array::from(vec![200, 300])), + ], + ) + .unwrap(); + let b2 = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![4])), + Arc::new(Int32Array::from(vec![400])), + ], + ) + .unwrap(); + let reader: Box = Box::new(RecordBatchIterator::new( + vec![Ok(b1), Ok(b2)], + schema.clone(), + )); + + let prepared = super::prepare_merge_source(Box::new(reader), 1) + .await + .unwrap(); + assert!(matches!(prepared, super::PreparedMergeSource::Stream(_))); + + let mut builder = + LanceMergeInsertBuilder::try_new(dataset, vec!["id".to_string()]).unwrap(); + builder + .when_matched(WhenMatched::UpdateAll) + .when_not_matched(lance::dataset::WhenNotMatched::InsertAll); + if !native_conflict_retries_enabled { + builder.conflict_retries(0); + } + let job = builder.try_build().unwrap(); + + let (new_dataset, stats) = + super::execute_prepared_merge_source(job, prepared, native_conflict_retries_enabled) + .await + .unwrap(); + assert_eq!(stats.num_updated_rows, 1); + assert_eq!(stats.num_inserted_rows, 2); + native.dataset.update(new_dataset.as_ref().clone()); + + let rows: Vec<_> = table + .query() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + let total_rows: usize = rows.iter().map(|b| b.num_rows()).sum(); + assert_eq!(total_rows, 4); + } + + #[tokio::test] + async fn merge_insert_spill_respects_retries_zero_without_disabling_native_execution() { + use futures::TryStreamExt; + + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .source_collect_threshold_bytes(1) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("val", DataType::Int32, false), + ])); + let initial = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![1])), + Arc::new(Int32Array::from(vec![10])), + ], + ) + .unwrap(); + let table = conn + .create_table("spill_retries_zero", initial) + .execute() + .await + .unwrap(); + + let b1 = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![1, 2])), + Arc::new(Int32Array::from(vec![100, 200])), + ], + ) + .unwrap(); + let reader: Box = + Box::new(RecordBatchIterator::new(vec![Ok(b1)], schema)); + + let mut merge = table.merge_insert(&["id"]); + merge + .retries(0) + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let result = merge.execute(reader).await.unwrap(); + assert_eq!(result.num_updated_rows, 1); + assert_eq!(result.num_inserted_rows, 1); + + let rows: Vec<_> = table + .query() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + let total_rows: usize = rows.iter().map(|b| b.num_rows()).sum(); + assert_eq!(total_rows, 2); + } + + #[tokio::test] + async fn merge_cast_provider_casts_on_every_scan_and_preserves_stats_and_schema() { + use datafusion::execution::context::SessionContext; + use datafusion_catalog::TableProvider; + use datafusion_common::stats::Precision; + use datafusion_physical_plan::statistics::{StatisticsArgs, StatisticsContext}; + use futures::TryStreamExt; + + let table_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + lance_arrow::json::json_field("payload", true), + ])); + let source_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("payload", DataType::Utf8, true), + ])); + + let b1 = RecordBatch::try_new( + source_schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![1, 2])), + Arc::new(StringArray::from(vec![r#"{"a":1}"#, r#"{"a":2}"#])), + ], + ) + .unwrap(); + let b2 = RecordBatch::try_new( + source_schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![3])), + Arc::new(StringArray::from(vec![r#"{"a":3}"#])), + ], + ) + .unwrap(); + + let ctx = SessionContext::new(); + + let rescannable = Arc::new( + crate::table::datafusion::scannable_exec::ScannableProvider::new(Box::new(vec![ + b1.clone(), + b2.clone(), + ])), + ); + let cast_provider = + super::MergeCastProvider::try_new(rescannable, table_schema.clone()).unwrap(); + assert!(lance_arrow::json::is_arrow_json_field( + cast_provider.schema().field_with_name("payload").unwrap() + )); + for _ in 0..2 { + let plan = cast_provider + .scan(&ctx.state(), None, &[], None) + .await + .unwrap(); + assert_eq!(plan.schema(), cast_provider.schema()); + let stats = StatisticsContext::new() + .compute(&*plan, &StatisticsArgs::new()) + .unwrap(); + assert_eq!(stats.num_rows, Precision::Exact(3)); + let rows: Vec<_> = plan + .execute(0, ctx.task_ctx()) + .unwrap() + .try_collect() + .await + .unwrap(); + let total: usize = rows.iter().map(|b| b.num_rows()).sum(); + assert_eq!(total, 3); + } + + let reader: Box = Box::new(RecordBatchIterator::new( + vec![Ok(b1.clone()), Ok(b2.clone())], + source_schema.clone(), + )); + let threshold = b1.get_array_memory_size().saturating_sub(1); + let prepared = super::prepare_merge_source(Box::new(reader), threshold) + .await + .unwrap(); + let prepared = + super::wrap_prepared_source_with_cast(prepared, table_schema.clone()).unwrap(); + let super::PreparedMergeSource::Stream(stream) = prepared else { + panic!("expected PreparedMergeSource::Stream"); + }; + assert!(lance_arrow::json::is_arrow_json_field( + stream.schema().field_with_name("payload").unwrap() + )); + let rows: Vec<_> = stream.try_collect().await.unwrap(); + let total: usize = rows.iter().map(|b| b.num_rows()).sum(); + assert_eq!(total, 3); + + let empty_reader: Box = Box::new(RecordBatchIterator::new( + Vec::>::new(), + source_schema, + )); + let empty_prepared = super::prepare_merge_source(Box::new(empty_reader), 1024) + .await + .unwrap(); + let empty_prepared = + super::wrap_prepared_source_with_cast(empty_prepared, table_schema).unwrap(); + let super::PreparedMergeSource::Provider(empty_provider) = empty_prepared else { + panic!("expected PreparedMergeSource::Provider"); + }; + let empty_plan = empty_provider + .scan(&ctx.state(), None, &[], None) + .await + .unwrap(); + let empty_stats = StatisticsContext::new() + .compute(&*empty_plan, &StatisticsArgs::new()) + .unwrap(); + assert_eq!(empty_stats.num_rows, Precision::Exact(0)); + } + + #[tokio::test] + async fn merge_insert_json_and_blob_end_to_end_rescannable_and_spill() { + use futures::TryStreamExt; + + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .source_collect_threshold_bytes(1) + .execute() + .await + .unwrap(); + let table_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + lance_arrow::json::json_field("payload", true), + crate::blob::blob("raw", true), + ])); + let table = conn + .create_empty_table("json_blob_merge", table_schema) + .execute() + .await + .unwrap(); + + let source_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("payload", DataType::Utf8, true), + Field::new("raw", DataType::LargeBinary, true), + ])); + + let b1 = RecordBatch::try_new( + source_schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![1])), + Arc::new(StringArray::from(vec![r#"{"k":1}"#])), + Arc::new(arrow_array::LargeBinaryArray::from(vec![Some( + b"hello".as_slice(), + )])), + ], + ) + .unwrap(); + + let mut merge = table.merge_insert(&["id"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let res = merge.execute(vec![b1]).await.unwrap(); + assert_eq!(res.num_inserted_rows, 1); + + let b2 = RecordBatch::try_new( + source_schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![1, 2])), + Arc::new(StringArray::from(vec![r#"{"k":10}"#, r#"{"k":20}"#])), + Arc::new(arrow_array::LargeBinaryArray::from(vec![ + Some(b"updated".as_slice()), + Some(b"world".as_slice()), + ])), + ], + ) + .unwrap(); + let reader: Box = Box::new(RecordBatchIterator::new( + vec![Ok(b2)], + source_schema.clone(), + )); + let mut merge = table.merge_insert(&["id"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let res = merge.execute(reader).await.unwrap(); + assert_eq!(res.num_updated_rows, 1); + assert_eq!(res.num_inserted_rows, 1); + + let empty_reader: Box = Box::new(RecordBatchIterator::new( + Vec::>::new(), + source_schema, + )); + let mut merge = table.merge_insert(&["id"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let res = merge.execute(empty_reader).await.unwrap(); + assert_eq!(res.num_inserted_rows, 0); + assert_eq!(res.num_updated_rows, 0); + + let rows: Vec<_> = table + .query() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + let total: usize = rows.iter().map(|b| b.num_rows()).sum(); + assert_eq!(total, 2); + } + + #[tokio::test] + async fn gate5360_delete_missing_rescannable_reordered_source() { + use futures::TryStreamExt; + + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + + let target_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("val", DataType::Int32, false), + ])); + let initial = RecordBatch::try_new( + target_schema, + vec![ + Arc::new(Int32Array::from(vec![1, 2])), + Arc::new(Int32Array::from(vec![10, 20])), + ], + ) + .unwrap(); + let table = conn + .create_table("reordered_delete_missing", initial) + .execute() + .await + .unwrap(); + + let source_schema = Arc::new(Schema::new(vec![ + Field::new("val", DataType::Int32, false), + Field::new("id", DataType::Int32, false), + ])); + let source = RecordBatch::try_new( + source_schema, + vec![ + Arc::new(Int32Array::from(vec![10])), + Arc::new(Int32Array::from(vec![1])), + ], + ) + .unwrap(); + + let mut merge = table.merge_insert(&["id"]); + merge.when_not_matched_by_source_delete(None); + let res = merge.execute(vec![source]).await.unwrap(); + assert_eq!(res.num_deleted_rows, 1); + + let rows: Vec<_> = table + .query() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + let ids: Vec = rows + .iter() + .flat_map(|b| { + b["id"] + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect(); + assert_eq!(ids, vec![1]); + assert_eq!(table.count_rows(None).await.unwrap(), 1); + } + + #[tokio::test] + async fn merge_insert_timeout_covers_slow_non_rescannable_source_preparation() { + use std::time::{Duration, Instant}; + + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("val", DataType::Int32, false), + ])); + let initial = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![1])), + Arc::new(Int32Array::from(vec![10])), + ], + ) + .unwrap(); + let table = conn + .create_table("slow_prep_timeout", initial) + .execute() + .await + .unwrap(); + let version_before = table.version().await.unwrap(); + + let slow_schema = schema.clone(); + let stream: crate::arrow::SendableRecordBatchStream = + Box::pin(crate::arrow::SimpleRecordBatchStream { + schema: slow_schema.clone(), + stream: futures::stream::once(async move { + tokio::time::sleep(Duration::from_millis(500)).await; + RecordBatch::try_new( + slow_schema, + vec![ + Arc::new(Int32Array::from(vec![2])), + Arc::new(Int32Array::from(vec![20])), + ], + ) + .map_err(crate::Error::from) + }), + }); + + let start = Instant::now(); + let mut merge = table.merge_insert(&["id"]); + merge + .timeout(Duration::from_millis(80)) + .when_not_matched_insert_all(); + let err = merge.execute(stream).await.unwrap_err(); + let elapsed = start.elapsed(); + + assert!( + matches!(&err, crate::Error::Runtime { message } if message == "merge insert timed out"), + "unexpected error: {err:?}" + ); + assert!( + elapsed < Duration::from_millis(350), + "expected timeout during preparation, took {elapsed:?}" + ); + assert_eq!(table.version().await.unwrap(), version_before); + assert_eq!(table.count_rows(None).await.unwrap(), 1); + } + + #[tokio::test] + async fn merge_insert_timeout_execution_receives_only_remaining_budget_after_preparation() { + use futures::StreamExt; + use std::time::{Duration, Instant}; + + let budget = Duration::from_millis(180); + let deadline = tokio::time::Instant::now() + budget; + let prep_sleep = Duration::from_millis(100); + super::run_with_deadline(Some(deadline), async move { + tokio::time::sleep(prep_sleep).await; + Ok::<_, crate::Error>(()) + }) + .await + .unwrap(); + + let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); + assert!( + remaining < Duration::from_millis(120), + "remaining budget {remaining:?} should reflect elapsed preparation time" + ); + + let exec_start = Instant::now(); + let err = super::run_with_deadline(Some(deadline), async { + tokio::time::sleep(Duration::from_millis(150)).await; + Ok::<_, crate::Error>(()) + }) + .await + .unwrap_err(); + let exec_elapsed = exec_start.elapsed(); + assert!( + matches!(&err, crate::Error::Runtime { message } if message == "merge insert timed out"), + "unexpected error: {err:?}" + ); + assert!( + exec_elapsed < Duration::from_millis(130), + "execution should only get remaining budget (~80ms), took {exec_elapsed:?}" + ); + + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .source_collect_threshold_bytes(1) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("val", DataType::Int32, false), + ])); + let initial = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![1])), + Arc::new(Int32Array::from(vec![10])), + ], + ) + .unwrap(); + let table = conn + .create_table("spill_exec_timeout", initial) + .execute() + .await + .unwrap(); + + let b1 = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![2])), + Arc::new(Int32Array::from(vec![20])), + ], + ) + .unwrap(); + let slow_schema = schema.clone(); + let stream: crate::arrow::SendableRecordBatchStream = + Box::pin(crate::arrow::SimpleRecordBatchStream { + schema, + stream: futures::stream::iter([Ok(b1)]).chain(futures::stream::once(async move { + tokio::time::sleep(Duration::from_millis(400)).await; + RecordBatch::try_new( + slow_schema, + vec![ + Arc::new(Int32Array::from(vec![3])), + Arc::new(Int32Array::from(vec![30])), + ], + ) + .map_err(crate::Error::from) + })), + }); + + let start = Instant::now(); + let mut merge = table.merge_insert(&["id"]); + merge + .timeout(Duration::from_millis(100)) + .when_not_matched_insert_all(); + let err = merge.execute(stream).await.unwrap_err(); + let elapsed = start.elapsed(); + + assert!( + matches!(&err, crate::Error::Runtime { message } if message == "merge insert timed out"), + "unexpected error: {err:?}" + ); + assert!( + elapsed < Duration::from_millis(350), + "expected execution timeout from remaining budget, took {elapsed:?}" + ); + } + + #[tokio::test] + async fn merge_insert_completes_within_configured_timeout() { + use std::time::Duration; + + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("val", DataType::Int32, false), + ])); + let initial = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![1])), + Arc::new(Int32Array::from(vec![10])), + ], + ) + .unwrap(); + let table = conn + .create_table("within_timeout", initial) + .execute() + .await + .unwrap(); + + let source = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![1, 2])), + Arc::new(Int32Array::from(vec![100, 200])), + ], + ) + .unwrap(); + let reader: Box = + Box::new(RecordBatchIterator::new(vec![Ok(source)], schema)); + + let mut merge = table.merge_insert(&["id"]); + merge + .timeout(Duration::from_secs(5)) + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let res = merge.execute(reader).await.unwrap(); + assert_eq!(res.num_updated_rows, 1); + assert_eq!(res.num_inserted_rows, 1); + assert_eq!(table.count_rows(None).await.unwrap(), 2); + } + + #[serial_test::serial] + #[tokio::test] + async fn gate5360_spill_honors_disk_quota() { + struct EnvGuard { + key: &'static str, + prev: Option, + } + impl Drop for EnvGuard { + fn drop(&mut self) { + // SAFETY: serialized via #[serial_test::serial] + unsafe { + match &self.prev { + Some(v) => std::env::set_var(self.key, v), + None => std::env::remove_var(self.key), + } + } + } + } + + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .source_collect_threshold_bytes(1) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("payload", DataType::LargeBinary, false), + ])); + let initial = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![1, 2])), + Arc::new(arrow_array::LargeBinaryArray::from(vec![ + b"a".as_slice(), + b"b".as_slice(), + ])), + ], + ) + .unwrap(); + let table = conn + .create_table("spill_quota", initial) + .execute() + .await + .unwrap(); + + // Exceed both source_collect_threshold_bytes (1 byte) and Lance's 100 MiB + // in-memory replay buffer so source replay must spill to Lance's disk manager. + let chunk = vec![7u8; 2 * 1024 * 1024]; + let make_reader = || -> Box { + let batches = (0..55).map(|i| { + let id = if i == 0 { 1 } else { i + 2 }; + Ok(RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![id])), + Arc::new(arrow_array::LargeBinaryArray::from(vec![chunk.as_slice()])), + ], + ) + .unwrap()) + }); + Box::new(RecordBatchIterator::new( + batches.collect::>(), + schema.clone(), + )) + }; + + let prev = std::env::var_os("LANCE_MAX_TEMP_DIRECTORY_SIZE"); + unsafe { + std::env::set_var("LANCE_MAX_TEMP_DIRECTORY_SIZE", "1"); + } + let guard = EnvGuard { + key: "LANCE_MAX_TEMP_DIRECTORY_SIZE", + prev, + }; + + let mut merge = table.merge_insert(&["id"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let err = merge.execute(make_reader()).await.unwrap_err(); + let err_msg = err.to_string().to_lowercase(); + assert!( + err_msg.contains("limit") + || err_msg.contains("spill") + || err_msg.contains("temp") + || err_msg.contains("disk"), + "expected spill-limit error, got: {err}" + ); + drop(guard); + + let mut merge = table.merge_insert(&["id"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let res = merge.execute(make_reader()).await.unwrap(); + assert_eq!(res.num_updated_rows, 1); + assert_eq!(res.num_inserted_rows, 54); + assert_eq!(table.count_rows(None).await.unwrap(), 56); + } } #[cfg(test)] @@ -1073,6 +2136,7 @@ mod lsm_tests { use crate::connect; use crate::error::Error; + use crate::query::ExecutableQuery; use crate::table::{RTEWriteSpec, Table}; /// A reader of `[id: Int64, value: Int64]` rows; `value` is `0..n`. @@ -1585,7 +2649,7 @@ mod lsm_tests { // --------------------------------------------------------------------- use crate::arrow::SendableRecordBatchStream; - use crate::query::{ExecutableQuery, QueryBase}; + use crate::query::QueryBase; use arrow::array::AsArray; use arrow::datatypes::Int64Type; use futures::TryStreamExt;