fix: pin native permutation builds to one snapshot (#5126)

## Problem

`PermutationBuilder` pinned backends that returned a snapshot handle,
but `NativeTable` returned `None`. A namespace-backed latest handle
could count and record the local table version while its row-id scan was
pushed to a server that returned newer rows. A native handle with read
refresh enabled could also advance between the version read, count, and
scan. The result was a permutation whose recorded version, row count,
and row ids did not describe one snapshot.

## Fix

- Return an independent pinned native handle from
`NativeTable::snapshot_at_current_version()`, so one build's version,
count, and scan share a dataset.
- Report `scan_order_is_deterministic()` false when a main/latest native
handle may push queries to a namespace server, whose `QueryTable`
request carries no order. Local scans remain deterministic at a fixed
version.

Refs OSS-3109

The query `scan_in_order` API and Python dispatch remain a separate
slice.
This commit is contained in:
Xuanwo
2026-11-20 20:36:29 +08:00
committed by GitHub
parent 56638a9e71
commit f460c34bdd
3 changed files with 204 additions and 9 deletions
@@ -249,10 +249,10 @@ impl PermutationBuilder {
/// Builds the permutation table and stores it in the given database.
pub async fn build(mut self) -> Result<Table> {
// 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<bytes::Bytes> {
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<dyn crate::table::BaseTable> = 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::<Int32Type>())
.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<dyn crate::table::BaseTable> = 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<RecordBatch> = permutation
.query()
.execute()
.await
.unwrap()
.try_collect()
.await
.unwrap();
let ids: Vec<u64> = batches
.iter()
.flat_map(|batch| {
batch[SRC_ROW_ID_COL]
.as_primitive::<UInt64Type>()
.values()
.to_vec()
})
.collect();
assert_eq!(ids, (0..10).collect::<Vec<_>>());
let recorded = permutation
.schema()
.await
.unwrap()
.metadata
.get(BASE_VERSION_CONFIG_KEY)
.expect("permutation should record its base version")
.parse::<u64>()
.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::<Int32Type>())
.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::<Int32Type>())
.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<RecordBatch> = Table::from(snapshot)
.query()
.execute()
.await
.unwrap()
.try_collect()
.await
.unwrap();
assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 10);
assert_eq!(table.count_rows(None).await.unwrap(), 15);
}
#[cfg(feature = "remote")]
@@ -406,8 +406,8 @@ impl Splitter {
.collect::<Vec<_>>();
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;
+19 -3
View File
@@ -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<Option<Arc<dyn BaseTable>>> {
// A native handle can advance between requests when read consistency
// refreshes, and a namespace-backed handle can answer a query from a
// different snapshot than the local count/version. Hand the caller an
// independent time-travel handle so one build sees one dataset.
Ok(Some(self.checkout_current().await?))
}
async fn checkout(&self, version: u64) -> Result<()> {
self.dataset.as_time_travel(version).await
}