diff --git a/rust/lancedb/src/dataloader/permutation/builder.rs b/rust/lancedb/src/dataloader/permutation/builder.rs
index 15f8c3cd3..770a956eb 100644
--- a/rust/lancedb/src/dataloader/permutation/builder.rs
+++ b/rust/lancedb/src/dataloader/permutation/builder.rs
@@ -249,10 +249,10 @@ impl PermutationBuilder {
/// Builds the permutation table and stores it in the given database.
pub async fn build(mut self) -> Result
{
- // Remote tables resolve latest independently for each request. Use a
- // separate pinned handle so count, projection, and scan all refer to one
- // snapshot without changing the caller's table checkout state. Native
- // tables return `None` here and retain their existing behavior.
+ // Remote tables resolve latest independently for each request, and a
+ // native handle can refresh or answer a query from a namespace server.
+ // Use a separate pinned handle so count, projection, and scan all refer
+ // to one snapshot without changing the caller's table checkout state.
if let Some(snapshot) = self
.base_table
.base_table()
@@ -396,6 +396,51 @@ mod tests {
use super::*;
+ /// Stands in for a namespace server whose table has advanced past the local
+ /// dataset. A pushed-down query reads this newer row instead of the local
+ /// snapshot.
+ #[derive(Debug, Default)]
+ struct ServerLatestNamespace {
+ query_table_calls: std::sync::atomic::AtomicUsize,
+ latest_row_id: u64,
+ }
+
+ #[async_trait::async_trait]
+ impl lance_namespace::LanceNamespace for ServerLatestNamespace {
+ fn namespace_id(&self) -> String {
+ "server-latest".to_string()
+ }
+
+ async fn query_table(
+ &self,
+ _request: lance_namespace::models::QueryTableRequest,
+ ) -> lance::Result {
+ self.query_table_calls
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ use arrow_array::UInt64Array;
+ use arrow_schema::{DataType, Field, Schema};
+
+ let schema = Arc::new(Schema::new(vec![Field::new(
+ ROW_ID,
+ DataType::UInt64,
+ false,
+ )]));
+ let batch = RecordBatch::try_new(
+ schema.clone(),
+ vec![Arc::new(UInt64Array::from(vec![self.latest_row_id]))],
+ )
+ .unwrap();
+ let mut body = Vec::new();
+ {
+ let mut writer =
+ arrow_ipc::writer::FileWriter::try_new(&mut body, &schema).unwrap();
+ writer.write(&batch).unwrap();
+ writer.finish().unwrap();
+ }
+ Ok(bytes::Bytes::from(body))
+ }
+ }
+
#[tokio::test]
async fn test_permutation_table_only_stores_row_id_and_split_id() {
let temp_dir = tempfile::tempdir().unwrap();
@@ -451,6 +496,140 @@ mod tests {
// Native tables skip the canonicalizing sort; remote does not.
assert!(table.base_table().scan_order_is_deterministic());
+
+ // A main/latest handle may answer from a namespace server, and its
+ // QueryTable request carries no order. The local native scan guarantee
+ // does not extend to that path.
+ let mut pushed_down = table.as_native().unwrap().clone();
+ pushed_down.namespace_client = Some(Arc::new(ServerLatestNamespace::default()));
+ pushed_down
+ .pushdown_operations
+ .insert(crate::connection::NamespaceClientPushdownOperation::QueryTable);
+ let pushed_down: Arc = Arc::new(pushed_down);
+ let pushed_down = Table::from(pushed_down);
+ assert!(!pushed_down.base_table().scan_order_is_deterministic());
+ }
+
+ /// The builder must pin one native snapshot before it counts or scans. A
+ /// namespace-backed latest handle can otherwise count local rows, scan
+ /// server-latest rows, and record the local version as if they agreed.
+ #[tokio::test]
+ async fn test_native_permutation_builder_pins_namespace_pushdown() {
+ use std::sync::atomic::Ordering;
+
+ use arrow_array::{cast::AsArray, types::UInt64Type};
+
+ let temp_dir = tempfile::tempdir().unwrap();
+ let db = connect(temp_dir.path().to_str().unwrap())
+ .execute()
+ .await
+ .unwrap();
+ let data = lance_datagen::gen_batch()
+ .col("col_a", lance_datagen::array::step::())
+ .into_ldb_stream(RowCount::from(10), BatchCount::from(1));
+ let table = db.create_table("base_tbl", data).execute().await.unwrap();
+
+ let namespace = Arc::new(ServerLatestNamespace {
+ latest_row_id: 10,
+ ..Default::default()
+ });
+ let mut native = table.as_native().unwrap().clone();
+ native.namespace_client = Some(namespace.clone());
+ native
+ .pushdown_operations
+ .insert(crate::connection::NamespaceClientPushdownOperation::QueryTable);
+ let native: Arc = Arc::new(native);
+ let table = Table::from(native);
+
+ let permutation = PermutationBuilder::new(table.clone())
+ .build()
+ .await
+ .unwrap();
+
+ assert_eq!(
+ namespace.query_table_calls.load(Ordering::SeqCst),
+ 0,
+ "the builder must read its pinned local snapshot, not server-latest rows"
+ );
+ assert_eq!(permutation.count_rows(None).await.unwrap(), 10);
+
+ let batches: Vec = permutation
+ .query()
+ .execute()
+ .await
+ .unwrap()
+ .try_collect()
+ .await
+ .unwrap();
+ let ids: Vec = batches
+ .iter()
+ .flat_map(|batch| {
+ batch[SRC_ROW_ID_COL]
+ .as_primitive::()
+ .values()
+ .to_vec()
+ })
+ .collect();
+ assert_eq!(ids, (0..10).collect::>());
+
+ let recorded = permutation
+ .schema()
+ .await
+ .unwrap()
+ .metadata
+ .get(BASE_VERSION_CONFIG_KEY)
+ .expect("permutation should record its base version")
+ .parse::()
+ .unwrap();
+ assert_eq!(recorded, table.version().await.unwrap());
+ }
+
+ /// `snapshot_at_current_version` is the builder's one-snapshot hook. With
+ /// read refresh enabled, the caller can advance while the pin stays put.
+ #[tokio::test]
+ async fn test_native_snapshot_pins_count_scan_and_version() {
+ use std::time::Duration;
+
+ use crate::connection::ConnectBuilder;
+
+ let temp_dir = tempfile::tempdir().unwrap();
+ let db = ConnectBuilder::new(temp_dir.path().to_str().unwrap())
+ .read_consistency_interval(Duration::ZERO)
+ .execute()
+ .await
+ .unwrap();
+ let data = lance_datagen::gen_batch()
+ .col("col_a", lance_datagen::array::step::())
+ .into_ldb_stream(RowCount::from(10), BatchCount::from(1));
+ let table = db.create_table("base_tbl", data).execute().await.unwrap();
+
+ let snapshot = table
+ .base_table()
+ .snapshot_at_current_version()
+ .await
+ .unwrap()
+ .expect("native tables should provide an independent pinned handle");
+ let version = snapshot.version().await.unwrap();
+ assert_eq!(snapshot.count_rows(None).await.unwrap(), 10);
+
+ let more_data = lance_datagen::gen_batch()
+ .col("col_a", lance_datagen::array::step::())
+ .into_ldb_stream(RowCount::from(5), BatchCount::from(1));
+ table.add(more_data).execute().await.unwrap();
+ assert!(table.version().await.unwrap() > version);
+
+ assert_eq!(snapshot.version().await.unwrap(), version);
+ assert_eq!(snapshot.count_rows(None).await.unwrap(), 10);
+ let batches: Vec = Table::from(snapshot)
+ .query()
+ .execute()
+ .await
+ .unwrap()
+ .try_collect()
+ .await
+ .unwrap();
+ assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 10);
+ assert_eq!(table.count_rows(None).await.unwrap(), 15);
}
#[cfg(feature = "remote")]
diff --git a/rust/lancedb/src/dataloader/permutation/split.rs b/rust/lancedb/src/dataloader/permutation/split.rs
index b4e5deac1..0fb7f669b 100644
--- a/rust/lancedb/src/dataloader/permutation/split.rs
+++ b/rust/lancedb/src/dataloader/permutation/split.rs
@@ -406,8 +406,8 @@ impl Splitter {
.collect::>();
let row_ids = arrow::compute::concat(&row_id_arrays)?;
// Sample against however many rows this scan actually returned, not the
- // separately computed `num_rows` count checked by `validate` -- that count and
- // this scan are two different queries, not pinned to one snapshot, so a
+ // separately computed `num_rows` count checked by `validate`. `apply` does
+ // not require its caller to pass a count and scan from one snapshot, so a
// concurrent append or delete between them could otherwise push
// `random_range` out of `row_ids`'s real bounds.
let num_eligible_rows = row_ids.len() as u64;
diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs
index 4d663649e..045517968 100644
--- a/rust/lancedb/src/table.rs
+++ b/rust/lancedb/src/table.rs
@@ -4172,10 +4172,18 @@ impl BaseTable for NativeTable {
self
}
- /// Lance scans fragments in order (`Scanner::ordered` defaults to true, and we
- /// never clear it), so repeated identical scans agree.
+ /// Lance scans fragments in order at one dataset version (`Scanner::ordered`
+ /// defaults to true, and we never clear it), so repeated scans of a local
+ /// handle agree. A main/latest handle that may push its query to a namespace
+ /// server does not: the QueryTable request carries no order.
fn scan_order_is_deterministic(&self) -> bool {
- true
+ let may_push_down_namespace_query = self.namespace_client.is_some()
+ && self
+ .pushdown_operations
+ .contains(&NamespaceClientPushdownOperation::QueryTable)
+ && self.dataset.current_branch().is_none()
+ && self.dataset.time_travel_version().is_none();
+ !may_push_down_namespace_query
}
fn name(&self) -> &str {
@@ -4217,6 +4225,14 @@ impl BaseTable for NativeTable {
}))
}
+ async fn snapshot_at_current_version(&self) -> Result