:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(data-warehouse): stop re-opening the delta table on every deltalite upsert (#106992)
Tom Owers30789ac8fcc6
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex e0bccc980a1d..49bc03aea90b 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -3925,15 +3925,17 @@ dependencies = ["object_store","parquet","serde_json",+ "tempfile","thiserror 2.0.18","tokio","tracing",+ "url","uuid",][[package]]name = "deltalite-python"-version = "0.1.7"+version = "0.1.8"dependencies = ["arrow","arrow-array",diff --git a/rust/deltalite/core/Cargo.toml b/rust/deltalite/core/Cargo.tomlindex 68fa13c7a950..d7302d980bc9 100644--- a/rust/deltalite/core/Cargo.toml+++ b/rust/deltalite/core/Cargo.toml@@ -53,3 +53,8 @@ thiserror = { workspace = true }tokio = { workspace = true }tracing = { workspace = true }uuid = { workspace = true }++[dev-dependencies]+# For the commit_overhead example (counted:// store registration) and table-fixture tests.+tempfile = "3"+url = { workspace = true }diff --git a/rust/deltalite/core/examples/commit_overhead.rs b/rust/deltalite/core/examples/commit_overhead.rsnew file mode 100644index 000000000000..5186bae226b5--- /dev/null+++ b/rust/deltalite/core/examples/commit_overhead.rs@@ -0,0 +1,554 @@+//! Per-commit overhead benchmark for the deltalite upsert path.+//!+//! Reproduces the production V3-loader call pattern: a Delta table with a deep commit+//! log (checkpoints at the table's `checkpoint_interval`, tombstone-heavy history) takes+//! repeated small upserts, and each iteration mirrors the exact orchestration of one+//! Python `DeltaLiteTable.open(...).upsert(...)` call so the open/replay overhead around+//! plan/rewrite/commit becomes visible per phase.+//!+//! Runs against the local filesystem, which UNDERSTATES the win on S3: a full log+//! replay here is cheap syscalls, while in production each replay is a LIST plus many+//! sequential GETs. Treat the numbers as a lower bound on the production improvement+//! and the replay *counts* as the transferable fact.+//!+//! Usage:+//! cargo run --release -p deltalite-core --example commit_overhead -- \+//! [--versions 1200] [--iters 40] [--rows 50] [--partitions 8] \+//! [--non-nullable-pk] [--reuse-handle] [--dir /path/to/fixture]+//!+//! The fixture table is cached in `--dir` (or a temp dir keyed by the parameters) and+//! reused across runs, so only the first run pays the table-building cost.++use std::collections::HashMap;+use std::path::PathBuf;+use std::sync::Arc;+use std::time::Instant;++use arrow_array::{Int64Array, RecordBatch, StringArray, TimestampMicrosecondArray};+use arrow_schema::{DataType, Field, Schema, SchemaRef, TimeUnit};+use deltalake::kernel::{DataType as KernelType, StructField};+use deltalake::operations::create::CreateBuilder;+use deltalite_core::handle::TableHandle;+use deltalite_core::table::{open_table_multipart, MultipartConfig};+use deltalite_core::upsert::{upsert, UpsertOptions};++/// Wall-clock on a local filesystem is noisy; the number of object-store operations is+/// not, and it is the quantity S3 latency multiplies in production. This store counts+/// reads (GET/HEAD/LIST) and writes per phase; it is registered under a `counted://`+/// scheme through delta-rs's factory registries so every open/replay in the run goes+/// through it.+mod counted {+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::sync::Arc;++ use deltalake::logstore::{+ default_logstore, logstore_factories, object_store_factories, LogStore, LogStoreFactory,+ ObjectStoreFactory, StorageConfig,+ };+ use deltalake::{DeltaResult, Path};+ use futures::stream::BoxStream;+ use object_store::local::LocalFileSystem;+ use object_store::{+ CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore,+ PutMultipartOptions, PutOptions, PutPayload, PutResult, RenameOptions,+ };++ pub static GETS: AtomicUsize = AtomicUsize::new(0);+ pub static LISTS: AtomicUsize = AtomicUsize::new(0);+ pub static WRITES: AtomicUsize = AtomicUsize::new(0);++ /// (gets, lists, writes) since process start.+ pub fn snapshot() -> (usize, usize, usize) {+ (+ GETS.load(Ordering::Relaxed),+ LISTS.load(Ordering::Relaxed),+ WRITES.load(Ordering::Relaxed),+ )+ }++ fn sorted(+ stream: BoxStream<'static, object_store::Result<ObjectMeta>>,+ ) -> BoxStream<'static, object_store::Result<ObjectMeta>> {+ use futures::{StreamExt, TryStreamExt};+ futures::stream::once(async move {+ let mut items: Vec<ObjectMeta> = stream.try_collect().await?;+ items.sort_by(|a, b| a.location.cmp(&b.location));+ Ok::<_, object_store::Error>(futures::stream::iter(items.into_iter().map(Ok)))+ })+ .try_flatten()+ .boxed()+ }++ #[derive(Debug)]+ struct CountingStore {+ inner: Arc<dyn ObjectStore>,+ }++ impl std::fmt::Display for CountingStore {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "CountingStore({})", self.inner)+ }+ }++ #[async_trait::async_trait]+ impl ObjectStore for CountingStore {+ async fn put_opts(+ &self,+ location: &Path,+ payload: PutPayload,+ opts: PutOptions,+ ) -> object_store::Result<PutResult> {+ WRITES.fetch_add(1, Ordering::Relaxed);+ self.inner.put_opts(location, payload, opts).await+ }++ async fn put_multipart_opts(+ &self,+ location: &Path,+ opts: PutMultipartOptions,+ ) -> object_store::Result<Box<dyn MultipartUpload>> {+ WRITES.fetch_add(1, Ordering::Relaxed);+ self.inner.put_multipart_opts(location, opts).await+ }++ async fn get_opts(+ &self,+ location: &Path,+ options: GetOptions,+ ) -> object_store::Result<GetResult> {+ GETS.fetch_add(1, Ordering::Relaxed);+ self.inner.get_opts(location, options).await+ }++ async fn get_ranges(+ &self,+ location: &Path,+ ranges: &[std::ops::Range<u64>],+ ) -> object_store::Result<Vec<bytes::Bytes>> {+ GETS.fetch_add(ranges.len(), Ordering::Relaxed);+ self.inner.get_ranges(location, ranges).await+ }++ fn delete_stream(+ &self,+ locations: BoxStream<'static, object_store::Result<Path>>,+ ) -> BoxStream<'static, object_store::Result<Path>> {+ WRITES.fetch_add(1, Ordering::Relaxed);+ self.inner.delete_stream(locations)+ }++ // Listings are sorted before they are returned: cloud stores list keys+ // lexicographically and delta-kernel relies on that, but `LocalFileSystem`+ // yields directory order.+ fn list(+ &self,+ prefix: Option<&Path>,+ ) -> BoxStream<'static, object_store::Result<ObjectMeta>> {+ LISTS.fetch_add(1, Ordering::Relaxed);+ sorted(self.inner.list(prefix))+ }++ fn list_with_offset(+ &self,+ prefix: Option<&Path>,+ offset: &Path,+ ) -> BoxStream<'static, object_store::Result<ObjectMeta>> {+ LISTS.fetch_add(1, Ordering::Relaxed);+ sorted(self.inner.list_with_offset(prefix, offset))+ }++ async fn list_with_delimiter(+ &self,+ prefix: Option<&Path>,+ ) -> object_store::Result<ListResult> {+ LISTS.fetch_add(1, Ordering::Relaxed);+ self.inner.list_with_delimiter(prefix).await+ }++ async fn copy_opts(+ &self,+ from: &Path,+ to: &Path,+ options: CopyOptions,+ ) -> object_store::Result<()> {+ WRITES.fetch_add(1, Ordering::Relaxed);+ self.inner.copy_opts(from, to, options).await+ }++ async fn rename_opts(+ &self,+ from: &Path,+ to: &Path,+ options: RenameOptions,+ ) -> object_store::Result<()> {+ WRITES.fetch_add(1, Ordering::Relaxed);+ self.inner.rename_opts(from, to, options).await+ }+ }++ #[derive(Debug, Default)]+ struct Factory;++ impl ObjectStoreFactory for Factory {+ fn parse_url_opts(+ &self,+ url: &url::Url,+ _config: &StorageConfig,+ ) -> DeltaResult<(Arc<dyn ObjectStore>, Path)> {+ let store = CountingStore {+ inner: Arc::new(LocalFileSystem::new()),+ };+ Ok((Arc::new(store), Path::from_url_path(url.path())?))+ }+ }++ impl LogStoreFactory for Factory {+ fn with_options(+ &self,+ prefixed_store: Arc<dyn ObjectStore>,+ root_store: Arc<dyn ObjectStore>,+ location: &url::Url,+ options: &StorageConfig,+ ) -> DeltaResult<Arc<dyn LogStore>> {+ Ok(default_logstore(+ prefixed_store,+ root_store,+ location,+ options,+ ))+ }+ }++ pub fn register() {+ let scheme = url::Url::parse("counted://").expect("static url");+ object_store_factories().insert(scheme.clone(), Arc::new(Factory));+ logstore_factories().insert(scheme, Arc::new(Factory));+ }+}++struct Args {+ versions: usize,+ iters: usize,+ rows: usize,+ partitions: usize,+ non_nullable_pk: bool,+ reuse_handle: bool,+ dir: Option<PathBuf>,+}++fn parse_args() -> Args {+ let mut args = Args {+ versions: 1200,+ iters: 40,+ rows: 50,+ partitions: 8,+ non_nullable_pk: false,+ reuse_handle: false,+ dir: None,+ };+ // nosemgrep: rust.lang.security.args.args+ let mut it = std::env::args().skip(1);+ while let Some(flag) = it.next() {+ let mut take = |name: &str| it.next().unwrap_or_else(|| panic!("{name} needs a value"));+ match flag.as_str() {+ "--versions" => args.versions = take("--versions").parse().expect("--versions"),+ "--iters" => args.iters = take("--iters").parse().expect("--iters"),+ "--rows" => args.rows = take("--rows").parse().expect("--rows"),+ "--partitions" => args.partitions = take("--partitions").parse().expect("--partitions"),+ "--non-nullable-pk" => args.non_nullable_pk = true,+ "--reuse-handle" => args.reuse_handle = true,+ "--dir" => args.dir = Some(PathBuf::from(take("--dir"))),+ other => panic!("unknown flag {other}"),+ }+ }+ args+}++fn arrow_schema(non_nullable_pk: bool) -> SchemaRef {+ Arc::new(Schema::new(vec![+ Field::new("pk", DataType::Utf8, !non_nullable_pk),+ Field::new("p", DataType::Utf8, true),+ Field::new("v", DataType::Int64, true),+ Field::new("ts", DataType::Timestamp(TimeUnit::Microsecond, None), true),+ Field::new("payload", DataType::Utf8, true),+ ]))+}++/// Deterministic UUID-shaped PK: random-looking (so min/max stats prune nothing, like+/// production UUID keys) but stable per (partition, row) so upserts hit existing rows.+fn pk(partition: usize, row: usize) -> String {+ let ns = uuid::Uuid::NAMESPACE_OID;+ uuid::Uuid::new_v5(&ns, format!("{partition}:{row}").as_bytes()).to_string()+}++/// One batch of `rows` rows for `partition`, all updates of the fixture's fixed PKs.+/// `salt` varies the payload so every commit really rewrites bytes.+fn batch(schema: &SchemaRef, partition: usize, rows: usize, salt: usize) -> RecordBatch {+ let pks: Vec<String> = (0..rows).map(|r| pk(partition, r)).collect();+ let parts: Vec<String> = (0..rows).map(|_| format!("p{partition}")).collect();+ let vs: Vec<i64> = (0..rows).map(|r| (salt * 1000 + r) as i64).collect();+ let ts: Vec<i64> = (0..rows)+ .map(|r| 1_700_000_000_000_000 + (salt * rows + r) as i64)+ .collect();+ let payload: Vec<String> = (0..rows)+ .map(|r| format!("{}-{}", pk(partition, r), "x".repeat(180 + (salt + r) % 40)))+ .collect();+ RecordBatch::try_new(+ schema.clone(),+ vec![+ Arc::new(StringArray::from(pks)),+ Arc::new(StringArray::from(parts)),+ Arc::new(Int64Array::from(vs)),+ Arc::new(TimestampMicrosecondArray::from(ts)),+ Arc::new(StringArray::from(payload)),+ ],+ )+ .expect("batch construction")+}++fn opts() -> UpsertOptions {+ UpsertOptions {+ primary_keys: vec!["pk".to_string()],+ partition_key: Some("p".to_string()),+ ..Default::default()+ }+}++async fn create_table(uri: &str, non_nullable_pk: bool) {+ let cols = vec![+ StructField::new("pk", KernelType::STRING, !non_nullable_pk),+ StructField::new("p", KernelType::STRING, true),+ StructField::new("v", KernelType::LONG, true),+ StructField::new("ts", KernelType::TIMESTAMP_NTZ, true),+ StructField::new("payload", KernelType::STRING, true),+ ];+ CreateBuilder::new()+ .with_location(uri)+ .with_columns(cols)+ .with_partition_columns(vec!["p".to_string()])+ .await+ .expect("create table");+}++/// Build `versions` commits: commit i updates partition `i % partitions` wholesale, so+/// the log grows deep (with tombstones and periodic checkpoints) while live files stay+/// at ~1 per partition -- matching production's files_probed p50 of 1.+async fn build_fixture(uri: &str, args: &Args, schema: &SchemaRef) {+ create_table(uri, args.non_nullable_pk).await;+ let so: HashMap<String, String> = HashMap::new();+ for i in 0..args.versions {+ let table = open_table_multipart(uri, so.clone(), MultipartConfig::default())+ .await+ .expect("open for fixture");+ let p = i % args.partitions;+ let b = batch(schema, p, args.rows, i);+ upsert(&table, vec![b], schema.clone(), opts())+ .await+ .expect("fixture upsert");+ if (i + 1) % 200 == 0 {+ eprintln!(" fixture: {} / {} commits", i + 1, args.versions);+ }+ }+}++fn copy_tree(src: &std::path::Path, dst: &std::path::Path) {+ std::fs::create_dir_all(dst).expect("mkdir copy target");+ for entry in std::fs::read_dir(src).expect("read fixture dir") {+ let entry = entry.expect("dir entry");+ let to = dst.join(entry.file_name());+ if entry.file_type().expect("file type").is_dir() {+ copy_tree(&entry.path(), &to);+ } else {+ std::fs::copy(entry.path(), &to).expect("copy fixture file");+ }+ }+}++fn ms(from: Instant) -> f64 {+ from.elapsed().as_secs_f64() * 1000.0+}++fn stat(label: &str, xs: &[f64]) {+ let mut sorted = xs.to_vec();+ sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());+ let avg = xs.iter().sum::<f64>() / xs.len() as f64;+ let p50 = sorted[xs.len() / 2];+ let p95 = sorted[(((xs.len() as f64) * 0.95) as usize).min(xs.len() - 1)];+ println!("{label:<16} avg {avg:8.1} p50 {p50:8.1} p95 {p95:8.1}");+}++#[tokio::main]+async fn main() {+ let args = parse_args();+ let schema = arrow_schema(args.non_nullable_pk);++ // Benchmark-only fixture cache keyed by run parameters; not a security-sensitive+ // temp file, so a predictable name under the system temp dir is intentional here.+ let dir = args.dir.clone().unwrap_or_else(|| {+ // nosemgrep: rust.lang.security.temp-dir.temp-dir+ std::env::temp_dir().join(format!(+ "deltalite-commit-overhead-v{}-r{}-p{}-nn{}",+ args.versions, args.rows, args.partitions, args.non_nullable_pk as u8+ ))+ });+ let marker = dir.join(".fixture-complete");++ if !marker.exists() {+ if dir.exists() {+ std::fs::remove_dir_all(&dir).expect("clear partial fixture");+ }+ std::fs::create_dir_all(&dir).expect("mkdir fixture");+ eprintln!(+ "building fixture: {} commits at {}",+ args.versions,+ dir.display()+ );+ let started = Instant::now();+ build_fixture(&dir.to_string_lossy(), &args, &schema).await;+ std::fs::write(&marker, b"ok").expect("write marker");+ eprintln!("fixture built in {:.1}s", started.elapsed().as_secs_f64());+ } else {+ eprintln!("reusing fixture at {}", dir.display());+ }++ // Measure against a clone so the pristine fixture never grows: the measured upserts+ // would otherwise move the table's distance from its last checkpoint between runs,+ // and replay cost with it, making before/after comparisons unfair.+ let run_dir = dir.with_file_name(format!(+ "{}-run",+ dir.file_name().unwrap().to_string_lossy()+ ));+ if run_dir.exists() {+ std::fs::remove_dir_all(&run_dir).expect("clear run dir");+ }+ copy_tree(&dir, &run_dir);+ // Route the measured runs through the counting store so per-phase I/O op counts+ // come out alongside the (noisier) wall-clock numbers.+ counted::register();+ let uri = format!("counted://{}", run_dir.to_string_lossy());++ let so: HashMap<String, String> = HashMap::new();+ let multipart = MultipartConfig::default();++ let (+ mut t_open,+ mut t_refresh,+ mut t_plan,+ mut t_rewrite,+ mut t_commit,+ mut t_maint,+ mut t_total,+ ) = (vec![], vec![], vec![], vec![], vec![], vec![], vec![]);+ let mut t_relax: Vec<f64> = vec![];+ let mut probed = 0usize;+ // Per-phase I/O op deltas: (gets, lists, writes) for open/upsert per iteration.+ let mut io = [(0usize, 0usize, 0usize); 2];+ let track = |slot: &mut (usize, usize, usize), before: (usize, usize, usize)| {+ let now = counted::snapshot();+ slot.0 += now.0 - before.0;+ slot.1 += now.1 - before.1;+ slot.2 += now.2 - before.2;+ now+ };++ // `--reuse-handle` models a caller that keeps the handle across batches (the+ // production writer currently opens a fresh one per batch).+ let mut kept_handle: Option<TableHandle> = if args.reuse_handle {+ Some(+ TableHandle::open(uri.clone(), so.clone())+ .await+ .expect("open kept handle"),+ )+ } else {+ None+ };++ for i in 0..args.iters {+ let salt = args.versions + i + 1;+ let p = i % args.partitions;+ let b = batch(&schema, p, args.rows, salt);+ let total_started = Instant::now();+ let mut c = counted::snapshot();++ // Phase 1: what `DeltaLiteTable.open` does in production (fresh handle per+ // batch), unless the kept-handle mode amortises it away.+ let t = Instant::now();+ let mut handle = match kept_handle.take() {+ Some(h) => h,+ None => TableHandle::open(uri.clone(), so.clone())+ .await+ .expect("open handle"),+ };+ t_open.push(ms(t));+ c = track(&mut io[0], c);++ // Phase 2: the whole upsert entrypoint (refresh + retry loop + core upsert ++ // post-commit refresh), exactly what the Python binding runs.+ let stats = handle+ .upsert(vec![b], schema.clone(), opts(), multipart)+ .await+ .expect("bench upsert");+ t_refresh.push(stats.open_ms as f64);+ t_plan.push(stats.plan_ms as f64);+ t_rewrite.push(stats.rewrite_ms as f64);+ t_commit.push(stats.commit_ms as f64);+ t_maint.push(stats.maintenance_ms as f64);+ t_relax.push(stats.relax_ms as f64);+ probed += stats.files_probed;+ track(&mut io[1], c);++ if args.reuse_handle {+ kept_handle = Some(handle);+ }+ t_total.push(ms(total_started));+ }++ println!(+ "\ncommit_overhead: versions={} iters={} rows={} partitions={} non_nullable_pk={} reuse_handle={} (filesystem; understates S3)",+ args.versions, args.iters, args.rows, args.partitions, args.non_nullable_pk, args.reuse_handle+ );+ println!(+ "files_probed avg {:.1}\n",+ probed as f64 / args.iters as f64+ );+ stat("open_handle_ms", &t_open);+ stat("open_ms", &t_refresh);+ stat("relax_ms", &t_relax);+ stat("plan_ms", &t_plan);+ stat("rewrite_ms", &t_rewrite);+ stat("commit_ms", &t_commit);+ stat("maintenance_ms", &t_maint);+ stat("total_ms", &t_total);+ let named: f64 = [+ &t_open, &t_refresh, &t_relax, &t_plan, &t_rewrite, &t_commit, &t_maint,+ ]+ .iter()+ .map(|v| v.iter().sum::<f64>() / v.len() as f64)+ .sum();+ let total_avg = t_total.iter().sum::<f64>() / t_total.len() as f64;+ println!(+ "residual_ms avg {:8.1} (total minus named phases)",+ total_avg - named+ );++ println!("\nI/O ops per iteration (deterministic; what S3 latency multiplies):");+ let n = args.iters as f64;+ for (label, (g, l, w)) in ["open_handle", "handle_upsert"].iter().zip(io.iter()) {+ println!(+ "{label:<16} gets {:7.1} lists {:6.1} writes {:6.1}",+ *g as f64 / n,+ *l as f64 / n,+ *w as f64 / n+ );+ }+ let (tg, tl, tw) = io+ .iter()+ .fold((0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2));+ println!(+ "{:<16} gets {:7.1} lists {:6.1} writes {:6.1}",+ "TOTAL",+ tg as f64 / n,+ tl as f64 / n,+ tw as f64 / n+ );+}diff --git a/rust/deltalite/core/src/handle.rs b/rust/deltalite/core/src/handle.rsnew file mode 100644index 000000000000..f04faf48cbd4--- /dev/null+++ b/rust/deltalite/core/src/handle.rs@@ -0,0 +1,140 @@+//! A long-lived handle on one Delta table, owning the open/refresh orchestration+//! around [`crate::upsert::upsert_cached`].+//!+//! Production measured ~81% of an upsert's wall-clock outside plan/rewrite/commit, and+//! the cause was full Delta-log replays: the previous binding-level orchestration+//! re-opened the table from scratch once per conflict-retry attempt and once more after+//! the commit, each a checkpoint read plus every commit since. This handle loads the+//! snapshot once at open and afterwards only applies newer commits incrementally+//! (`update_incremental`), which is one log LIST plus the handful of new commit JSONs.++use std::collections::HashMap;+use std::time::Instant;++use arrow_array::RecordBatch;+use arrow_schema::SchemaRef;+use deltalake::DeltaTable;++use crate::errors::{Error, Result};+use crate::table::{open_table, wrap_multipart, MultipartConfig};+use crate::upsert::{upsert_cached, RelaxCache, UpsertOptions, UpsertStats};++/// Conflict-retry budget for one upsert call. A concurrent writer can make delta-rs+/// reject the commit with a "must rerun" conflict (it read data another transaction+/// deleted); delta-rs's own commit retries re-attempt the SAME, now-stale actions and+/// keep conflicting, so the only fix is to refresh the snapshot and re-plan.+const CONFLICT_RETRIES: usize = 5;++/// A loaded Delta table plus the per-table caches that make repeated small upserts+/// cheap: the snapshot (refreshed incrementally, never rebuilt) and the relax memo.+pub struct TableHandle {+ uri: String,+ storage_options: HashMap<String, String>,+ table: DeltaTable,+ relax_cache: RelaxCache,+}++impl TableHandle {+ /// Open an existing Delta table (one full snapshot load).+ pub async fn open(uri: String, storage_options: HashMap<String, String>) -> Result<Self> {+ let table = open_table(&uri, storage_options.clone()).await?;+ Ok(Self {+ uri,+ storage_options,+ table,+ relax_cache: RelaxCache::default(),+ })+ }++ /// The table URI this handle was opened on.+ pub fn uri(&self) -> &str {+ &self.uri+ }++ /// The loaded table, for read paths (schema, files, history).+ pub fn table(&self) -> &DeltaTable {+ &self.table+ }++ /// The table version this handle currently observes (-1 before any load).+ pub fn version(&self) -> i64 {+ self.table+ .version()+ .and_then(|v| i64::try_from(v).ok())+ .unwrap_or(-1)+ }++ /// Bring the snapshot up to date with commits made elsewhere. Incremental (applies+ /// only commits newer than the loaded version); falls back to a full re-open when+ /// the incremental path fails -- e.g. the table was deleted and recreated at a+ /// lower version, which is not reachable forward from the loaded state.+ pub async fn refresh(&mut self) -> Result<()> {+ if self.table.update_incremental(None).await.is_ok() {+ return Ok(());+ }+ self.table = open_table(&self.uri, self.storage_options.clone()).await?;+ // The old snapshot is gone; nothing the relax memo verified can be trusted.+ self.relax_cache = RelaxCache::default();+ Ok(())+ }++ /// Run one upsert, retrying data conflicts against a refreshed snapshot.+ ///+ /// Only data conflicts are retried. A concurrent schema/protocol change surfaces as+ /// `Error::Unsupported` (see core `errors.rs`), not `Conflict`, and so breaks+ /// straight out to the caller's MERGE fallback -- re-planning a blind rewrite+ /// against changed metadata could null-pad a newly-added column.+ pub async fn upsert(+ &mut self,+ source_batches: Vec<RecordBatch>,+ source_schema: SchemaRef,+ opts: UpsertOptions,+ multipart: MultipartConfig,+ ) -> Result<UpsertStats> {+ let mut open_ms = 0u64;++ // Observe commits made elsewhere since this handle last looked, so the first+ // attempt plans against current state (the previous per-call full re-open gave+ // the same guarantee at a full log-replay's cost).+ let t = Instant::now();+ self.refresh().await?;+ open_ms += t.elapsed().as_millis() as u64;++ let mut attempt = 0usize;+ loop {+ // A per-attempt view over the shared snapshot: cloning state is in-memory,+ // wrapping the store is free, and the handle keeps its own table untouched+ // for the refreshes below.+ let view = wrap_multipart(self.table.clone(), multipart);+ match upsert_cached(+ &view,+ source_batches.clone(),+ source_schema.clone(),+ opts.clone(),+ &mut self.relax_cache,+ )+ .await+ {+ Err(Error::Conflict(_)) if attempt < CONFLICT_RETRIES => {+ attempt += 1;+ // Short linear backoff so two upserts racing a hot table don't+ // live-lock re-reading each other's in-flight commit.+ tokio::time::sleep(std::time::Duration::from_millis(50 * attempt as u64)).await;+ let t = Instant::now();+ self.refresh().await?;+ open_ms += t.elapsed().as_millis() as u64;+ }+ Ok(mut stats) => {+ // Pick up our own commit (and any relax/maintenance commits), so+ // reads through this handle observe what was just written.+ let t = Instant::now();+ self.refresh().await?;+ open_ms += t.elapsed().as_millis() as u64;+ stats.open_ms = open_ms;+ return Ok(stats);+ }+ Err(e) => return Err(e),+ }+ }+ }+}diff --git a/rust/deltalite/core/src/lib.rs b/rust/deltalite/core/src/lib.rsindex b8cd7817ade3..a3c4a0ea1e59 100644--- a/rust/deltalite/core/src/lib.rs+++ b/rust/deltalite/core/src/lib.rs@@ -29,6 +29,7 @@//! crate (built with maturin, imported as `deltalite`).pub mod errors;+pub mod handle;pub mod limits;pub mod pkset;pub mod schema;@@ -37,6 +38,7 @@ pub mod table;pub mod upsert;pub use errors::{Error, Result};+pub use handle::TableHandle;pub use limits::ProcessLimits;-pub use table::{open_table, open_table_multipart, MultipartConfig};-pub use upsert::{upsert, PruneStrategy, UpsertOptions, UpsertStats};+pub use table::{open_table, open_table_multipart, wrap_multipart, MultipartConfig};+pub use upsert::{upsert, upsert_cached, PruneStrategy, RelaxCache, UpsertOptions, UpsertStats};diff --git a/rust/deltalite/core/src/table.rs b/rust/deltalite/core/src/table.rsindex 47daf8cb55ce..404e60de96a5 100644--- a/rust/deltalite/core/src/table.rs+++ b/rust/deltalite/core/src/table.rs@@ -63,8 +63,16 @@ pub async fn open_table_multipart(multipart: MultipartConfig,) -> Result<DeltaTable> {let table = open_table(uri, storage_options).await?;+ Ok(wrap_multipart(table, multipart))+}++/// Re-home an already-loaded table onto the multipart-aware store wrapper, without I/O.+/// The loaded snapshot moves across as-is: the wrapper changes how large data-file+/// `put`s are performed, never what the log contains, so replaying the log under the+/// wrapped store would rebuild an identical snapshot at a full log-replay's cost.+pub fn wrap_multipart(table: DeltaTable, multipart: MultipartConfig) -> DeltaTable {if multipart.threshold == 0 {- return Ok(table);+ return table;}let wrapped = Arc::new(MultipartLogStore::new(table.log_store(),@@ -72,6 +80,6 @@ pub async fn open_table_multipart(multipart.part_size,));let mut wrapped_table = DeltaTable::new(wrapped, Default::default());- wrapped_table.load().await.map_err(Error::from)?;- Ok(wrapped_table)+ wrapped_table.state = table.state;+ wrapped_table}diff --git a/rust/deltalite/core/src/upsert.rs b/rust/deltalite/core/src/upsert.rsindex 93d9b624ead9..64c86968b881 100644--- a/rust/deltalite/core/src/upsert.rs+++ b/rust/deltalite/core/src/upsert.rs@@ -251,6 +251,68 @@ pub struct UpsertStats {/// Non-nullable columns relaxed to nullable before this upsert because the table's/// data (or this batch) already contains nulls in them.pub columns_relaxed: usize,+ /// Wall-clock ms spent opening/refreshing the table snapshot around the upsert+ /// (initial refresh, conflict-retry refreshes, post-commit refresh). Set by+ /// [`crate::handle::TableHandle::upsert`]; 0 when the core `upsert` runs directly.+ pub open_ms: u64,+ /// Wall-clock ms spent importing the caller's source data into Arrow batches. Set+ /// by the language binding that owns the import; 0 when unset.+ pub ingest_ms: u64,+ /// Wall-clock ms spent deciding (and, rarely, performing) nullability relaxation+ /// before the upsert proper.+ pub relax_ms: u64,+ /// Wall-clock ms spent on post-commit checkpoint/log-cleanup maintenance. Non-zero+ /// only on checkpoint-boundary commits.+ pub maintenance_ms: u64,+}++/// Per-table memo for the file-stats scan in [`columns_needing_relax`], which otherwise+/// JSON-parses every live Add action's stats on every upsert even though relaxation is+/// almost never needed. A column verified clean stays trusted while the table advances+/// only through this cache's own upserts: their source batches were verified null-free+/// for that column (or it would have been relaxed) and their rewrites only copy rows+/// out of verified-clean files. A commit this cache did not witness (a concurrent+/// writer, a delta-rs commit-retry interleave) leaves the table on a version the cache+/// never advanced to, so the next upsert rescans.+#[derive(Debug, Default)]+pub struct RelaxCache {+ /// Table version the clean set was verified against.+ version: Option<u64>,+ /// Non-nullable columns whose live files showed no positive evidence of nulls.+ clean: HashSet<String>,+}++impl RelaxCache {+ /// True when `column` was verified clean at `version`. Drops the memo first when it+ /// was verified against a different version.+ fn is_verified_clean(&mut self, version: u64, column: &str) -> bool {+ if self.version != Some(version) {+ self.version = None;+ self.clean.clear();+ return false;+ }+ self.clean.contains(column)+ }++ /// Record that `columns` showed no evidence of nulls in the table's files at+ /// `version`.+ fn record_clean(&mut self, version: u64, columns: impl IntoIterator<Item = String>) {+ if self.version != Some(version) {+ self.clean.clear();+ }+ self.version = Some(version);+ self.clean.extend(columns);+ }++ /// Carry the clean set forward onto the version this cache's own upsert just+ /// committed. Valid only when the commit landed directly on the verified version+ /// (`committed == verified + 1`): a bigger jump means another writer's actions are+ /// part of the new version, so the memo stays behind and the next upsert rescans.+ fn advance_own_commit(&mut self, committed: u64) {+ if self.version.is_some_and(|v| committed == v + 1) {+ self.version = Some(committed);+ }+ }}/// A file selected for rewrite, with the metadata needed to tombstone it.@@ -476,6 +538,25 @@ impl Budgets {/// insert, unmatched target rows survive verbatim, and SQL NULL semantics apply to the/// primary keys (a NULL component never matches). The whole batch lands in ONE commit/// carrying `opts.commit_metadata` in flat `commitInfo`.+pub async fn upsert(+ table: &DeltaTable,+ source_batches: Vec<RecordBatch>,+ source_schema: SchemaRef,+ opts: UpsertOptions,+) -> Result<UpsertStats> {+ upsert_cached(+ table,+ source_batches,+ source_schema,+ opts,+ &mut RelaxCache::default(),+ )+ .await+}++/// [`upsert`] with a caller-held [`RelaxCache`], so repeated upserts through one handle+/// skip the per-file relax scan when the table has only advanced through their own+/// commits.#[instrument(level = "info",skip_all,@@ -486,15 +567,16 @@ impl Budgets {version = tracing::field::Empty,))]-pub async fn upsert(+pub async fn upsert_cached(table: &DeltaTable,source_batches: Vec<RecordBatch>,source_schema: SchemaRef,opts: UpsertOptions,+ relax_cache: &mut RelaxCache,) -> Result<UpsertStats> {let started = Instant::now();let strategy = opts.prune_strategy.as_str();- let result = upsert_with_relax(table, source_batches, source_schema, opts).await;+ let result = upsert_with_relax(table, source_batches, source_schema, opts, relax_cache).await;// Static label values only -- no per-call allocation (rust/CLAUDE.md).histogram!("deltalite_upsert_duration_seconds").record(started.elapsed().as_secs_f64());@@ -540,10 +622,22 @@ async fn upsert_with_relax(source_batches: Vec<RecordBatch>,source_schema: SchemaRef,opts: UpsertOptions,+ relax_cache: &mut RelaxCache,) -> Result<UpsertStats> {- let relax = columns_needing_relax(table, &source_batches, &source_schema).await?;+ let relax_started = Instant::now();+ let relax = columns_needing_relax(table, &source_batches, &source_schema, relax_cache).await?;if relax.is_empty() {- return upsert_inner(table, source_batches, source_schema, opts).await;+ let relax_ms = relax_started.elapsed().as_millis() as u64;+ let mut stats = upsert_inner(table, source_batches, source_schema, opts).await?;+ stats.relax_ms = relax_ms;+ // Our own commit added no nulls to the verified-clean columns (the source was+ // checked above; existing rows only move between files), so the memo may follow+ // it. `advance_own_commit` refuses any commit that did not land directly on the+ // verified version, which is what protects against interleaved writers.+ if let Ok(committed) = u64::try_from(stats.version) {+ relax_cache.advance_own_commit(committed);+ }+ return Ok(stats);}relax_columns_to_nullable(table, &relax).await?;@@ -551,8 +645,10 @@ async fn upsert_with_relax(// the relaxed metadata; the borrowed handle still sees the old snapshot.let mut fresh = table.clone();fresh.update_incremental(None).await?;+ let relax_ms = relax_started.elapsed().as_millis() as u64;let mut stats = upsert_inner(&fresh, source_batches, source_schema, opts).await?;stats.columns_relaxed = relax.len();+ stats.relax_ms = relax_ms;Ok(stats)}@@ -564,6 +660,7 @@ async fn columns_needing_relax(table: &DeltaTable,source_batches: &[RecordBatch],source_schema: &Schema,+ cache: &mut RelaxCache,) -> Result<Vec<String>> {let snapshot = table.snapshot()?;let non_nullable: Vec<String> = snapshot@@ -576,6 +673,9 @@ async fn columns_needing_relax(return Ok(vec![]);}+ // The source-side check always runs -- it is O(columns) and each batch is new+ // evidence. Only the file-stats scan below is memoized.+ let version = snapshot.version();let mut relax: Vec<String> = Vec::new();let mut unresolved: Vec<String> = Vec::new();for name in non_nullable {@@ -587,7 +687,7 @@ async fn columns_needing_relax(.any(|b| b.column(idx).null_count() > 0){relax.push(name);- } else {+ } else if !cache.is_verified_clean(version, &name) {unresolved.push(name);}}@@ -624,6 +724,9 @@ async fn columns_needing_relax(}}}+ // Whatever survived the scan showed no evidence of nulls at this version; the+ // next upsert through the same cache skips scanning these columns.+ cache.record_clean(version, unresolved);}relax.sort();@@ -910,7 +1013,9 @@ async fn upsert_inner(let commit_ms = commit_started.elapsed().as_millis() as u64;if (finalized.version() + 1) % checkpoint_interval == 0 {+ let maintenance_started = Instant::now();best_effort_log_maintenance(table, finalized.version(), cleanup_enabled).await;+ stats.maintenance_ms = maintenance_started.elapsed().as_millis() as u64;}stats.plan_ms = plan_ms;@@ -1958,6 +2063,46 @@ mod tests {assert_eq!(PruneStrategy::default(), PruneStrategy::Probe);}+ // ---- RelaxCache ------------------------------------------------------------------++ #[test]+ fn relax_cache_skips_only_columns_verified_at_the_same_version() {+ let mut cache = RelaxCache::default();+ assert!(!cache.is_verified_clean(7, "a"));++ cache.record_clean(7, vec!["a".to_string(), "b".to_string()]);+ assert!(cache.is_verified_clean(7, "a"));+ assert!(cache.is_verified_clean(7, "b"));+ assert!(!cache.is_verified_clean(7, "c"));++ // A different version drops the memo entirely (an unwitnessed writer may have+ // added null-bearing files), including for previously-clean columns.+ assert!(!cache.is_verified_clean(9, "a"));+ assert!(!cache.is_verified_clean(7, "a"));+ }++ #[test]+ fn relax_cache_advances_only_across_its_own_adjacent_commit() {+ let mut cache = RelaxCache::default();+ cache.record_clean(7, vec!["a".to_string()]);++ // Own commit directly on the verified version: memo follows.+ cache.advance_own_commit(8);+ assert!(cache.is_verified_clean(8, "a"));++ // A jump (delta-rs commit retry slotted another writer's commit underneath):+ // memo stays behind, so the next upsert at 11 rescans.+ cache.advance_own_commit(11);+ assert!(!cache.is_verified_clean(11, "a"));+ }++ #[test]+ fn relax_cache_advance_without_verification_stays_empty() {+ let mut cache = RelaxCache::default();+ cache.advance_own_commit(1);+ assert!(!cache.is_verified_clean(1, "a"));+ }+// ---- target_file_size resolution -------------------------------------------------#[test]diff --git a/rust/deltalite/core/tests/handle_and_open.rs b/rust/deltalite/core/tests/handle_and_open.rsnew file mode 100644index 000000000000..d85ea666b979--- /dev/null+++ b/rust/deltalite/core/tests/handle_and_open.rs@@ -0,0 +1,396 @@+//! Integration tests for the open/refresh path: the single-load guarantee of+//! `open_table_multipart`, snapshot preservation in `wrap_multipart`, and the+//! `TableHandle` upsert orchestration (incremental refresh, relax with a warm cache).++use std::collections::HashMap;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;++use arrow_array::{Int64Array, RecordBatch, StringArray};+use arrow_schema::{DataType, Field, Schema, SchemaRef};+use deltalake::kernel::{DataType as KernelType, StructField};+use deltalake::logstore::{+ default_logstore, logstore_factories, object_store_factories, LogStore, LogStoreFactory,+ ObjectStoreFactory, StorageConfig,+};+use deltalake::operations::create::CreateBuilder;+use deltalake::{DeltaResult, Path};+use deltalite_core::handle::TableHandle;+use deltalite_core::table::{open_table, open_table_multipart, wrap_multipart, MultipartConfig};+use deltalite_core::upsert::UpsertOptions;+use futures::stream::BoxStream;+use object_store::local::LocalFileSystem;+use object_store::{+ CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore,+ PutMultipartOptions, PutOptions, PutPayload, PutResult, RenameOptions,+};++// ---- read-counting store, registered as its own URL scheme ------------------------++static READS: AtomicUsize = AtomicUsize::new(0);++fn reads() -> usize {+ READS.load(Ordering::SeqCst)+}++#[derive(Debug)]+struct CountingStore {+ inner: Arc<dyn ObjectStore>,+}++impl std::fmt::Display for CountingStore {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "CountingStore({})", self.inner)+ }+}++#[async_trait::async_trait]+impl ObjectStore for CountingStore {+ async fn put_opts(+ &self,+ location: &Path,+ payload: PutPayload,+ opts: PutOptions,+ ) -> object_store::Result<PutResult> {+ self.inner.put_opts(location, payload, opts).await+ }++ async fn put_multipart_opts(+ &self,+ location: &Path,+ opts: PutMultipartOptions,+ ) -> object_store::Result<Box<dyn MultipartUpload>> {+ self.inner.put_multipart_opts(location, opts).await+ }++ async fn get_opts(+ &self,+ location: &Path,+ options: GetOptions,+ ) -> object_store::Result<GetResult> {+ READS.fetch_add(1, Ordering::SeqCst);+ self.inner.get_opts(location, options).await+ }++ async fn get_ranges(+ &self,+ location: &Path,+ ranges: &[std::ops::Range<u64>],+ ) -> object_store::Result<Vec<bytes::Bytes>> {+ READS.fetch_add(ranges.len(), Ordering::SeqCst);+ self.inner.get_ranges(location, ranges).await+ }++ fn delete_stream(+ &self,+ locations: BoxStream<'static, object_store::Result<Path>>,+ ) -> BoxStream<'static, object_store::Result<Path>> {+ self.inner.delete_stream(locations)+ }++ // Sorted before returning: cloud stores list keys lexicographically and+ // delta-kernel relies on it, while `LocalFileSystem` yields directory order.+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, object_store::Result<ObjectMeta>> {+ READS.fetch_add(1, Ordering::SeqCst);+ sorted(self.inner.list(prefix))+ }++ fn list_with_offset(+ &self,+ prefix: Option<&Path>,+ offset: &Path,+ ) -> BoxStream<'static, object_store::Result<ObjectMeta>> {+ READS.fetch_add(1, Ordering::SeqCst);+ sorted(self.inner.list_with_offset(prefix, offset))+ }++ async fn list_with_delimiter(&self, prefix: Option<&Path>) -> object_store::Result<ListResult> {+ READS.fetch_add(1, Ordering::SeqCst);+ self.inner.list_with_delimiter(prefix).await+ }++ async fn copy_opts(+ &self,+ from: &Path,+ to: &Path,+ options: CopyOptions,+ ) -> object_store::Result<()> {+ self.inner.copy_opts(from, to, options).await+ }++ async fn rename_opts(+ &self,+ from: &Path,+ to: &Path,+ options: RenameOptions,+ ) -> object_store::Result<()> {+ self.inner.rename_opts(from, to, options).await+ }+}++fn sorted(+ stream: BoxStream<'static, object_store::Result<ObjectMeta>>,+) -> BoxStream<'static, object_store::Result<ObjectMeta>> {+ use futures::{StreamExt, TryStreamExt};+ futures::stream::once(async move {+ let mut items: Vec<ObjectMeta> = stream.try_collect().await?;+ items.sort_by(|a, b| a.location.cmp(&b.location));+ Ok::<_, object_store::Error>(futures::stream::iter(items.into_iter().map(Ok)))+ })+ .try_flatten()+ .boxed()+}++#[derive(Debug, Default)]+struct Factory;++impl ObjectStoreFactory for Factory {+ fn parse_url_opts(+ &self,+ url: &url::Url,+ _config: &StorageConfig,+ ) -> DeltaResult<(Arc<dyn ObjectStore>, Path)> {+ let store = CountingStore {+ inner: Arc::new(LocalFileSystem::new()),+ };+ Ok((Arc::new(store), Path::from_url_path(url.path())?))+ }+}++impl LogStoreFactory for Factory {+ fn with_options(+ &self,+ prefixed_store: Arc<dyn ObjectStore>,+ root_store: Arc<dyn ObjectStore>,+ location: &url::Url,+ options: &StorageConfig,+ ) -> DeltaResult<Arc<dyn LogStore>> {+ Ok(default_logstore(+ prefixed_store,+ root_store,+ location,+ options,+ ))+ }+}++fn register_counting_scheme() {+ let scheme = url::Url::parse("dltest://").expect("static url");+ object_store_factories().insert(scheme.clone(), Arc::new(Factory));+ logstore_factories().insert(scheme, Arc::new(Factory));+}++// ---- fixtures ----------------------------------------------------------------------++fn schema(v_nullable: bool) -> SchemaRef {+ Arc::new(Schema::new(vec![+ Field::new("pk", DataType::Utf8, false),+ Field::new("v", DataType::Int64, v_nullable),+ ]))+}++fn batch(schema: &SchemaRef, pks: &[&str], vs: Vec<Option<i64>>) -> RecordBatch {+ RecordBatch::try_new(+ schema.clone(),+ vec![+ Arc::new(StringArray::from(pks.to_vec())),+ Arc::new(Int64Array::from(vs)),+ ],+ )+ .expect("test batch")+}++fn opts() -> UpsertOptions {+ UpsertOptions {+ primary_keys: vec!["pk".to_string()],+ ..Default::default()+ }+}++/// Create an unpartitioned table at `uri` with a non-nullable `pk` and a `v` column of+/// the given nullability, then seed it with a few commits so opening has log to replay.+async fn create_seeded_table(uri: &str, v_nullable: bool) -> SchemaRef {+ CreateBuilder::new()+ .with_location(uri)+ .with_columns(vec![+ StructField::new("pk", KernelType::STRING, false),+ StructField::new("v", KernelType::LONG, v_nullable),+ ])+ .await+ .expect("create table");++ let s = schema(v_nullable);+ for i in 0..3 {+ let mut handle = TableHandle::open(uri.to_string(), HashMap::new())+ .await+ .expect("open for seeding");+ let b = batch(&s, &["a", "b"], vec![Some(i), Some(i + 1)]);+ handle+ .upsert(vec![b], s.clone(), opts(), MultipartConfig::default())+ .await+ .expect("seed upsert");+ }+ s+}++// ---- tests -------------------------------------------------------------------------++/// Pins the double-load fix: opening through the multipart wrapper must cost the same+/// storage reads as a plain open, not twice as many. Serial with the other counting+/// test via the shared atomic; each measurement is deltas around one call, and the+/// tests run in one process where no other code touches the `dltest://` scheme.+#[tokio::test]+async fn open_table_multipart_replays_the_log_once() {+ register_counting_scheme();+ let dir = tempfile::tempdir().expect("tempdir");+ let uri = format!("dltest://{}", dir.path().join("t1").to_string_lossy());+ create_seeded_table(&uri, true).await;++ let before_plain = reads();+ let plain = open_table(&uri, HashMap::new()).await.expect("plain open");+ let plain_reads = reads() - before_plain;++ let before_multipart = reads();+ let multipart = open_table_multipart(&uri, HashMap::new(), MultipartConfig::default())+ .await+ .expect("multipart open");+ let multipart_reads = reads() - before_multipart;++ assert_eq!(plain.version(), multipart.version());+ assert!(plain.version().is_some(), "open must load the snapshot");+ assert_eq!(+ multipart_reads, plain_reads,+ "the multipart open must not replay the log a second time \+ (multipart {multipart_reads} reads vs plain {plain_reads})"+ );+}++#[tokio::test]+async fn wrap_multipart_carries_the_loaded_snapshot_without_io() {+ let dir = tempfile::tempdir().expect("tempdir");+ let uri = dir.path().join("t2").to_string_lossy().to_string();+ create_seeded_table(&uri, true).await;++ let table = open_table(&uri, HashMap::new()).await.expect("open");+ let version = table.version();+ let wrapped = wrap_multipart(table, MultipartConfig::default());+ assert_eq!(wrapped.version(), version);+ assert!(+ wrapped.snapshot().is_ok(),+ "the wrapped table must be usable without another load"+ );+}++/// One handle across several upserts: every commit must land on the version the+/// previous one produced, and an external writer's commit must be observed by the next+/// upsert through the incremental refresh (previously guaranteed by a full re-open).+#[tokio::test]+async fn handle_upserts_observe_own_and_external_commits() {+ let dir = tempfile::tempdir().expect("tempdir");+ let uri = dir.path().join("t3").to_string_lossy().to_string();+ let s = create_seeded_table(&uri, true).await;++ let mut handle = TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open handle");+ let v0 = handle.version();++ let stats = handle+ .upsert(+ vec![batch(&s, &["a", "c"], vec![Some(10), Some(11)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("first upsert");+ assert_eq!(stats.version, v0 + 1);+ assert_eq!(handle.version(), v0 + 1, "handle observes its own commit");++ // Another writer commits behind this handle's back.+ let mut other = TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open external handle");+ other+ .upsert(+ vec![batch(&s, &["d"], vec![Some(12)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("external upsert");++ let stats = handle+ .upsert(+ vec![batch(&s, &["a"], vec![Some(13)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("second upsert");+ assert_eq!(+ stats.version,+ v0 + 3,+ "the upsert must plan against the externally-advanced version"+ );+}++/// The relax memo must never swallow a genuinely-needed relaxation: after upserts that+/// verify the non-nullable column clean (warming the cache), a batch that carries a+/// null in it still relaxes the column and commits the nulls.+#[tokio::test]+async fn warm_relax_cache_still_relaxes_when_the_batch_carries_nulls() {+ let dir = tempfile::tempdir().expect("tempdir");+ let uri = dir.path().join("t4").to_string_lossy().to_string();+ let s = create_seeded_table(&uri, false).await;++ let mut handle = TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open handle");++ // Two clean upserts through one handle: the second runs with a warm memo.+ for i in 0..2 {+ let stats = handle+ .upsert(+ vec![batch(&s, &["a"], vec![Some(20 + i)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("clean upsert");+ assert_eq!(stats.columns_relaxed, 0);+ }++ // Now the batch carries a null in the non-nullable column: the source-side check+ // (which the memo never bypasses) must relax `v` and the write must succeed.+ let nullable_schema = schema(true);+ let stats = handle+ .upsert(+ vec![batch(&nullable_schema, &["e"], vec![None])],+ nullable_schema.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("null-carrying upsert");+ assert_eq!(stats.columns_relaxed, 1, "the column must relax");++ // The relaxed schema is durable: a fresh handle sees `v` nullable and takes more+ // nulls without relaxing again.+ let mut fresh = TableHandle::open(uri, HashMap::new())+ .await+ .expect("fresh handle");+ let stats = fresh+ .upsert(+ vec![batch(&nullable_schema, &["f"], vec![None])],+ nullable_schema,+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("post-relax upsert");+ assert_eq!(stats.columns_relaxed, 0);+}diff --git a/rust/deltalite/python/Cargo.toml b/rust/deltalite/python/Cargo.tomlindex 1d0fd1f2ae95..8e14c1734b09 100644--- a/rust/deltalite/python/Cargo.toml+++ b/rust/deltalite/python/Cargo.toml@@ -1,7 +1,7 @@[package]name = "deltalite-python"# Mirrors pyproject.toml in this directory (always identical); bump both together.-version = "0.1.7"+version = "0.1.8"edition = "2021"# CI compiles with this exact toolchain; cargo's MSRV-aware resolver uses it to# avoid picking dependency versions CI cannot build (aws-* crates move MSRV often).diff --git a/rust/deltalite/python/README.md b/rust/deltalite/python/README.mdindex 2d46b9b5875b..2099ae8775ea 100644--- a/rust/deltalite/python/README.md+++ b/rust/deltalite/python/README.md@@ -100,7 +100,7 @@ rejected (raising `DeltaLiteError`) rather than silently double-inserted.| `DeltaLiteTable.is_deltatable(uri, storage_options=None)` | `True` if a Delta table exists at `uri`. || `.upsert(data, primary_keys, partition_key=None, **opts)` | Insert-or-replace `data` by key. Returns `UpsertStats`. See knobs below. || `.version()` | Current table version (`int`). |-| `.reload()` | Reload the table state from the log. |+| `.reload()` | Bring the table state up to date with the log (incremental; falls back to a full re-open). || `.schema_arrow()` | Table schema as a pyarrow `Schema`. || `.partition_columns()` | Partition column names (`list[str]`). || `.file_uris()` | URIs of the table's active data files. |@@ -111,9 +111,13 @@ rejected (raising `DeltaLiteError`) rather than silently double-inserted.Returned by `upsert`. Counts: `version`, `partitions_touched`, `files_added`,`files_removed`, `files_carried_over`, `files_probed`, `rows_updated`,`rows_inserted`, `rows_copied`, `source_rows`, `null_pk_rows`. Per-phase-wall-clock timings (milliseconds): `plan_ms` (listing + pruning files),-`rewrite_ms` (reading + rewriting the touched partitions), `commit_ms`-(committing to the Delta log).+wall-clock timings (milliseconds): `ingest_ms` (importing the pyarrow source),+`open_ms` (snapshot refreshes around the upsert), `relax_ms` (nullability-relax+check), `plan_ms` (listing + pruning files), `rewrite_ms` (reading + rewriting+the touched partitions), `commit_ms` (committing to the Delta log),+`maintenance_ms` (checkpoint/log cleanup, non-zero only on checkpoint-boundary+commits). `columns_relaxed` counts non-nullable columns flipped to nullable+before the write.### Exceptionsdiff --git a/rust/deltalite/python/pyproject.toml b/rust/deltalite/python/pyproject.tomlindex 57e8a207d186..5492d46a5c3f 100644--- a/rust/deltalite/python/pyproject.toml+++ b/rust/deltalite/python/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "maturin"[project]name = "deltalite"# Mirrors `rust/deltalite/python/Cargo.toml` (always identical); bump both together.-version = "0.1.7"+version = "0.1.8"description = "Streaming partition upsert for Delta tables, replacing delta-rs SQL MERGE"readme = "README.md"requires-python = ">=3.12"diff --git a/rust/deltalite/python/src/lib.rs b/rust/deltalite/python/src/lib.rsindex 3e61a783109d..1821644a1f2d 100644--- a/rust/deltalite/python/src/lib.rs+++ b/rust/deltalite/python/src/lib.rs@@ -12,11 +12,11 @@ use arrow::pyarrow::{FromPyArrow, ToPyArrow};use arrow_array::{new_empty_array, Array, RecordBatch};use arrow_schema::SchemaRef;use deltalake::writer::RecordBatchWriter;-use deltalake::DeltaTable;use deltalite_core::errors::Error;+use deltalite_core::handle::TableHandle;use deltalite_core::limits::ProcessLimits;use deltalite_core::schema::import_column;-use deltalite_core::table::{open_table, open_table_multipart, MultipartConfig};+use deltalite_core::table::{open_table, MultipartConfig};use deltalite_core::upsert::{PruneStrategy, UpsertOptions};use pyo3::create_exception;use pyo3::exceptions::PyException;@@ -169,6 +169,14 @@ pub struct UpsertStats {pub commit_ms: u64,#[pyo3(get)]pub columns_relaxed: usize,+ #[pyo3(get)]+ pub open_ms: u64,+ #[pyo3(get)]+ pub ingest_ms: u64,+ #[pyo3(get)]+ pub relax_ms: u64,+ #[pyo3(get)]+ pub maintenance_ms: u64,}#[pymethods]@@ -209,6 +217,10 @@ impl From<deltalite_core::upsert::UpsertStats> for UpsertStats {rewrite_ms: s.rewrite_ms,commit_ms: s.commit_ms,columns_relaxed: s.columns_relaxed,+ open_ms: s.open_ms,+ ingest_ms: s.ingest_ms,+ relax_ms: s.relax_ms,+ maintenance_ms: s.maintenance_ms,}}}@@ -218,9 +230,7 @@ impl From<deltalite_core::upsert::UpsertStats> for UpsertStats {/// `deltalake` package -- both address the same `_delta_log`.#[pyclass(module = "deltalite")]pub struct DeltaLiteTable {- uri: String,- storage_options: HashMap<String, String>,- table: DeltaTable,+ handle: TableHandle,}#[pymethods]@@ -234,15 +244,10 @@ impl DeltaLiteTable {storage_options: Option<HashMap<String, String>>,) -> PyResult<Self> {let so = storage_options.unwrap_or_default();- let so2 = so.clone();- let table = py- .detach(|| runtime().block_on(open_table(&uri, so2)))+ let handle = py+ .detach(|| runtime().block_on(TableHandle::open(uri, so))).map_err(to_py_err)?;- Ok(Self {- uri,- storage_options: so,- table,- })+ Ok(Self { handle })}/// Whether `uri` points at a loadable Delta table.@@ -261,25 +266,22 @@ impl DeltaLiteTable {/// The table version this handle currently observes (-1 before any load).fn version(&self) -> i64 {- self.table- .version()- .and_then(|v| i64::try_from(v).ok())- .unwrap_or(-1)+ self.handle.version()}- /// Re-read the log so this handle observes commits made elsewhere.+ /// Re-read the log so this handle observes commits made elsewhere. Incremental --+ /// only commits newer than the loaded version are read -- with a full re-open+ /// fallback when the log is not reachable forward from the loaded state.fn reload(&mut self, py: Python<'_>) -> PyResult<()> {- let uri = self.uri.clone();- let so = self.storage_options.clone();- self.table = py- .detach(|| runtime().block_on(open_table(&uri, so)))+ let handle = &mut self.handle;+ py.detach(|| runtime().block_on(handle.refresh())).map_err(to_py_err)?;Ok(())}/// The table's Arrow schema, as the write path will expect it.fn schema_arrow(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {- let schema = RecordBatchWriter::for_table(&self.table)+ let schema = RecordBatchWriter::for_table(self.handle.table()).map_err(|e| to_py_err(Error::from(e)))?.arrow_schema();Ok(schema.to_pyarrow(py)?.into())@@ -287,14 +289,19 @@ impl DeltaLiteTable {/// The table's partition columns (possibly empty).fn partition_columns(&self) -> PyResult<Vec<String>> {- let snapshot = self.table.snapshot().map_err(|e| to_py_err(e.into()))?;+ let snapshot = self+ .handle+ .table()+ .snapshot()+ .map_err(|e| to_py_err(e.into()))?;Ok(snapshot.metadata().partition_columns().to_vec())}/// URIs of the live data files.fn file_uris(&self) -> PyResult<Vec<String>> {Ok(self- .table+ .handle+ .table().get_file_uris().map_err(|e| to_py_err(e.into()))?.collect::<Vec<_>>())@@ -359,7 +366,9 @@ impl DeltaLiteTable {) -> PyResult<UpsertStats> {// Import while holding the GIL (it reads a Python object), then release it for// all the I/O.+ let ingest_started = std::time::Instant::now();let (schema, batches) = read_pyarrow(data)?;+ let ingest_ms = ingest_started.elapsed().as_millis() as u64;let prune_strategy = match prune_strategy.as_deref() {Some(s) => s.parse::<PruneStrategy>().map_err(to_py_err)?,@@ -390,59 +399,22 @@ impl DeltaLiteTable {};let multipart = MultipartConfig::resolve(multipart_threshold, multipart_part_size);- let uri = self.uri.clone();- let so = self.storage_options.clone();+ // Conflict retries, snapshot refreshes and the post-commit reload all live in+ // `TableHandle::upsert` (shared with the Rust benchmarks); the handle refreshes+ // incrementally instead of re-replaying the whole log per attempt.+ let handle = &mut self.handle;let stats = py- .detach(|| {- runtime().block_on(async move {- // A concurrent writer can make delta-rs reject the commit with a- // "must rerun" conflict (it read data another transaction deleted).- // delta-rs's own commit retries re-attempt the SAME, now-stale actions and- // keep conflicting; the only fix is to re-read the table and re-plan. So on- // a Conflict we re-open a fresh snapshot and re-run the whole upsert a few- // times before giving up -- after which the caller falls back to the MERGE.- // Re-opening each attempt also gives every try a fresh snapshot, so a- // retried batch never plans against stale state.- //- // Only data conflicts are retried. A concurrent schema/protocol change- // surfaces as Error::Unsupported (see core `errors.rs`), not Conflict, and so- // breaks straight out to the MERGE fallback -- re-planning a blind rewrite- // against changed metadata could null-pad a newly-added column.- const CONFLICT_RETRIES: usize = 5;- let mut attempt = 0usize;- loop {- let table = open_table_multipart(&uri, so.clone(), multipart).await?;- match deltalite_core::upsert::upsert(- &table,- batches.clone(),- schema.clone(),- opts.clone(),- )- .await- {- Err(Error::Conflict(_)) if attempt < CONFLICT_RETRIES => {- attempt += 1;- // Short linear backoff so two upserts racing a hot table don't- // live-lock re-reading each other's in-flight commit.- tokio::time::sleep(std::time::Duration::from_millis(- 50 * attempt as u64,- ))- .await;- }- other => break other,- }- }- })- })+ .detach(|| runtime().block_on(handle.upsert(batches, schema, opts, multipart))).map_err(to_py_err)?;- self.reload(py)?;- Ok(stats.into())+ let mut stats: UpsertStats = stats.into();+ stats.ingest_ms = ingest_ms;+ Ok(stats)}/// Commit metadata of the most recent `limit` commits, oldest first.fn history(&self, py: Python<'_>, limit: usize) -> PyResult<Py<PyAny>> {- let table = self.table.clone();+ let table = self.handle.table().clone();let infos = py.detach(|| {runtime().block_on(async move {