feat: add Scannable-based merge insert with spill support and retry-safe execution (#5360)

Addresses part 1 of #4505 

Refactor merge-insert to accept Scannable sources while preserving
RecordBatchReader compatibility, introduce ScannableProvider and
retry-aware source execution, and add configurable 64 MiB source
collection thresholds with spill-based routing for large non-rescannable
inputs. Preserve row-count statistics using inexact prefix estimates,
apply JSON/blob casting per scan, and propagate threshold configuration
through connections and tables. Add regression tests covering source
routing, spill replay, retry behavior, statistics, configuration, and
JSON/blob casting while preserving existing LSM/MemWAL and FirstSeen
behavior.

---------

Co-authored-by: Xuanwo <github@xuanwo.io>
This commit is contained in:
somil jain
2026-12-02 22:35:12 +00:00
committed by GitHub
co-authored by Xuanwo
parent 74503e13f6
commit 614f8c3201
9 changed files with 1806 additions and 89 deletions
+61 -2
View File
@@ -210,6 +210,7 @@ pub struct OpenTableBuilder {
parent: Arc<dyn Database>,
request: OpenTableRequest,
embedding_registry: Arc<dyn EmbeddingRegistry>,
source_collect_threshold_bytes: usize,
branch: Option<String>,
version: Option<u64>,
}
@@ -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<Table> {
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<dyn Database>,
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<Table> {
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<dyn Database>,
embedding_registry: Arc<dyn EmbeddingRegistry>,
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<Arc<dyn EmbeddingRegistry>>,
source_collect_threshold_bytes: usize,
#[cfg(feature = "remote")]
oauth_config: Option<crate::remote::OAuthConfig>,
}
@@ -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<std::time::Duration>,
embedding_registry: Option<Arc<dyn EmbeddingRegistry>>,
session: Option<Arc<lance::session::Session>>,
source_collect_threshold_bytes: usize,
pushdown_operations: HashSet<NamespaceClientPushdownOperation>,
}
@@ -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,
}
}
}
+10 -1
View File
@@ -20,6 +20,7 @@ pub struct CreateTableBuilder {
parent: Arc<dyn Database>,
embeddings: Vec<(EmbeddingDefinition, Arc<dyn EmbeddingFunction>)>,
embedding_registry: Arc<dyn EmbeddingRegistry>,
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))
}
}
+154 -25
View File
@@ -126,6 +126,58 @@ impl Scannable for Vec<RecordBatch> {
}
}
pub struct RecordBatchReaderScannable {
reader: Option<Box<dyn RecordBatchReader + Send>>,
schema: SchemaRef,
}
impl RecordBatchReaderScannable {
pub fn new(reader: Box<dyn RecordBatchReader + Send>) -> 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::<crate::Result<RecordBatch>>(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<dyn RecordBatchReader + Send>` with APIs other than merge_insert.
impl Scannable for Box<dyn RecordBatchReader + Send> {
fn schema(&self) -> SchemaRef {
RecordBatchReader::schema(self.as_ref())
@@ -133,34 +185,57 @@ impl Scannable for Box<dyn RecordBatchReader + Send> {
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<dyn RecordBatchReader + Send> = 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<dyn Scannable>;
}
// Bridge the blocking RecordBatchReader to an async stream via a channel.
let (tx, rx) = tokio::sync::mpsc::channel::<crate::Result<RecordBatch>>(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<dyn Scannable> {
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<RecordBatch> {
fn into_scannable(self) -> Box<dyn Scannable> {
Box::new(self)
}
}
Box::pin(SimpleRecordBatchStream { schema, stream })
impl IntoScannable for SendableRecordBatchStream {
fn into_scannable(self) -> Box<dyn Scannable> {
Box::new(self)
}
}
impl IntoScannable for Box<dyn Scannable> {
fn into_scannable(self) -> Box<dyn Scannable> {
self
}
}
impl<R: RecordBatchReader + Send + 'static> IntoScannable for Box<R> {
fn into_scannable(self) -> Box<dyn Scannable> {
let reader: Box<dyn RecordBatchReader + Send> = self;
Box::new(RecordBatchReaderScannable::new(reader))
}
}
impl IntoScannable for Box<dyn RecordBatchReader + Send> {
fn into_scannable(self) -> Box<dyn Scannable> {
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<RecordBatch> = 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<dyn RecordBatchReader + Send> = 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::<Vec<_>>()
.await
.unwrap(),
vec![batch]
);
let error = source
.scan_as_stream()
.try_collect::<Vec<_>>()
.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<dyn RecordBatchReader + Send> = Box::new(RecordBatchIterator::new(
Vec::<std::result::Result<RecordBatch, ArrowError>>::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")]
+6 -1
View File
@@ -1268,7 +1268,12 @@ impl PreparedDeclaration {
vec![];
let reader: Box<dyn arrow_array::RecordBatchReader + Send> =
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);
+3 -1
View File
@@ -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();
+19 -7
View File
@@ -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<S: HttpSend> BaseTable for RemoteTable<S> {
async fn merge_insert(
&self,
mut params: MergeInsertBuilder,
new_data: Box<dyn RecordBatchReader + Send>,
mut new_data: Box<dyn Scannable>,
) -> Result<MergeResult> {
params.canonicalize_filters()?;
self.check_mutable().await?;
@@ -4231,8 +4235,8 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
// 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::<std::result::Result<Vec<_>, _>>()?;
let schema = new_data.schema();
let mut batches = new_data.scan_as_stream().try_collect::<Vec<_>>().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!(
+36 -3
View File
@@ -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<dyn RecordBatchReader + Send>,
new_data: Box<dyn Scannable>,
) -> Result<MergeResult>;
/// Set the unenforced primary key for the table to a single column.
///
@@ -1319,6 +1319,7 @@ pub struct Table {
inner: Arc<dyn BaseTable>,
database: Option<Arc<dyn Database>>,
embedding_registry: Arc<dyn EmbeddingRegistry>,
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<Arc<dyn BaseTable>> 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<dyn RecordBatchReader + Send>,
new_data: Box<dyn Scannable>,
) -> Result<MergeResult> {
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()),
@@ -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<Box<dyn Scannable>>,
source: Arc<Mutex<Box<dyn Scannable>>>,
num_rows: Option<usize>,
properties: Arc<PlanProperties>,
tracker: Option<Arc<WriteProgressTracker>>,
}
/// A DataFusion provider backed by a rescannable [`Scannable`] source.
#[derive(Debug)]
pub(crate) struct ScannableProvider {
source: Arc<Mutex<Box<dyn Scannable>>>,
}
impl ScannableProvider {
pub(crate) fn new(source: Box<dyn Scannable>) -> 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<usize>>,
_filters: &[Expr],
_limit: Option<usize>,
) -> datafusion_common::Result<Arc<dyn ExecutionPlan>> {
let plan: Arc<dyn ExecutionPlan> = {
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<dyn ExecutionPlan>,
projection: Option<&Vec<usize>>,
) -> DFResult<Arc<dyn ExecutionPlan>> {
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<dyn PhysicalExpr>,
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<Mutex<Box<dyn Scannable>>>,
schema: arrow_schema::SchemaRef,
num_rows: Option<usize>,
) -> 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<Statistics>],
_args: &StatisticsArgs,
) -> DFResult<Arc<Statistics>> {
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<dyn TableProvider>,
prefix_rows: usize,
}
#[cfg_attr(not(test), allow(dead_code))]
impl InexactRowCountProvider {
pub(crate) fn new(inner: Arc<dyn TableProvider>, 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<usize>>,
filters: &[Expr],
limit: Option<usize>,
) -> DFResult<Arc<dyn ExecutionPlan>> {
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<dyn ExecutionPlan>,
prefix_rows: usize,
}
#[cfg_attr(not(test), allow(dead_code))]
impl InexactRowCountExec {
pub(crate) fn new(inner: Arc<dyn ExecutionPlan>, 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<dyn datafusion_physical_expr::PhysicalExpr>,
) -> DFResult<datafusion_common::tree_node::TreeNodeRecursion>,
) -> DFResult<datafusion_common::tree_node::TreeNodeRecursion> {
Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue)
}
fn name(&self) -> &str {
"InexactRowCountExec"
}
fn properties(&self) -> &Arc<PlanProperties> {
self.inner.properties()
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.inner]
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> DFResult<Arc<dyn ExecutionPlan>> {
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<TaskContext>,
) -> DFResult<SendableRecordBatchStream> {
self.inner.execute(partition, context)
}
fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
vec![ChildStats::At(partition)]
}
fn partition_statistics(&self, partition: Option<usize>) -> DFResult<Arc<Statistics>> {
#[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<Statistics>],
_args: &StatisticsArgs,
) -> DFResult<Arc<Statistics>> {
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]);
}
}
File diff suppressed because it is too large Load Diff