: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): re-land the deltalite footer and commit-snapshot trims (#108283)
Tom Owers812820220b9e
diff --git a/.claude/rules/temporal-workflow-versioning.md b/.claude/rules/temporal-workflow-versioning.mdindex 4900f31a2a02..4acb36ffe2a3 100644--- a/.claude/rules/temporal-workflow-versioning.md+++ b/.claude/rules/temporal-workflow-versioning.md@@ -20,6 +20,12 @@ When adding a new activity or child-workflow start to an existing workflow, gatevalue** (e.g. `enrichment_needed: bool = False` in `create_job_model.py`) — old histories decodethe missing field to the default, so the new command never fires during replay. Only valid whenthe decision comes from recorded history and skipping is acceptable for in-flight runs.+ **Not safe on its own for skipping or removing an existing command.** In a rolling deploy, old+ and new pods share the task queue: a new activity can return "skip" into a history that old+ workflow code wrote with the command still in it. The new code then replays that answer, skips+ the command, and every replay of that execution fails. Put `workflow.patched(...)` in front of+ the field (`if workflow.patched("x") and result.skip_it: ...`) so a history without the marker+ keeps the old command sequence.Never gate workflow commands on values computed inside the workflow body (feature flags, settings,clock, DB reads) — that is itself non-deterministic. Removing/reordering existing commands needsdiff --git a/rust/deltalite/core/examples/upsert_io.rs b/rust/deltalite/core/examples/upsert_io.rsnew file mode 100644index 000000000000..ba4b974a2935--- /dev/null+++ b/rust/deltalite/core/examples/upsert_io.rs@@ -0,0 +1,684 @@+//! Object-store I/O benchmark for the upsert shapes production sees most.+//!+//! Wall clock on a local filesystem does not transfer to S3; the number of GETs, the+//! bytes they fetch, LISTs and PUTs do (each round trip costs tens of ms through the+//! proxy). The `counted://` store below counts them after object_store's range+//! coalescing, so the counts match what the S3 client issues, and can inject a fixed+//! per-request latency so the wall clock becomes a rough S3 proxy too.+//!+//! Scenarios (from the production upsert distribution):+//! median partitioned, 60 partitions x 1 file x 200 rows; 34-row update in one+//! partition (one file probed, ~1 file rewritten)+//! insert unpartitioned, 173 files x 5k rows; 10k-row insert-only batch (the+//! probe-heavy tail: every file's footer and PK column is read)+//! smallbig unpartitioned, 60 files x 20k rows; 34-row update touching 2 files+//! mixed10k unpartitioned, 60 files x 20k rows; 10k-row update spread over all files+//!+//! Usage:+//! cargo run --release -p deltalite-core --example upsert_io -- \+//! --scenario median [--iters 4] [--latency-ms 20] [--probe-concurrency 8] \+//! [--max-parallel-files 4] [--dir /path]+//!+//! `DELTALITE_ADOPT_COMMIT_SNAPSHOT=0` restores the post-commit log refresh, which gives+//! the before/after comparison for the snapshot adoption on one binary.++use std::collections::HashMap;+use std::path::PathBuf;+use std::sync::Arc;+use std::time::Instant;++use arrow_array::{Float64Array, 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 deltalake::writer::{DeltaWriter, RecordBatchWriter};+use deltalite_core::handle::TableHandle;+use deltalite_core::table::MultipartConfig;+use deltalite_core::upsert::UpsertOptions;++mod counted {+ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};+ use std::sync::Arc;+ use std::time::Duration;++ 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::{+ coalesce_ranges, CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload,+ ObjectMeta, ObjectStore, PutMultipartOptions, PutOptions, PutPayload, PutResult,+ RenameOptions, OBJECT_STORE_COALESCE_DEFAULT,+ };++ pub static GETS: AtomicUsize = AtomicUsize::new(0);+ pub static GET_BYTES: AtomicU64 = AtomicU64::new(0);+ pub static LISTS: AtomicUsize = AtomicUsize::new(0);+ pub static WRITES: AtomicUsize = AtomicUsize::new(0);+ pub static PUT_BYTES: AtomicU64 = AtomicU64::new(0);+ pub static LATENCY_MS: AtomicU64 = AtomicU64::new(0);++ #[derive(Clone, Copy, Debug, Default)]+ pub struct Snap {+ pub gets: usize,+ pub get_bytes: u64,+ pub lists: usize,+ pub writes: usize,+ pub put_bytes: u64,+ }++ pub fn snapshot() -> Snap {+ Snap {+ gets: GETS.load(Ordering::Relaxed),+ get_bytes: GET_BYTES.load(Ordering::Relaxed),+ lists: LISTS.load(Ordering::Relaxed),+ writes: WRITES.load(Ordering::Relaxed),+ put_bytes: PUT_BYTES.load(Ordering::Relaxed),+ }+ }++ impl Snap {+ pub fn delta(&self, since: &Snap) -> Snap {+ Snap {+ gets: self.gets - since.gets,+ get_bytes: self.get_bytes - since.get_bytes,+ lists: self.lists - since.lists,+ writes: self.writes - since.writes,+ put_bytes: self.put_bytes - since.put_bytes,+ }+ }+ }++ async fn delay() {+ let ms = LATENCY_MS.load(Ordering::Relaxed);+ if ms > 0 {+ tokio::time::sleep(Duration::from_millis(ms)).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 {+ delay().await;+ 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()+ }++ /// Counts multipart part bytes (one `put_part` per part) and each part as a write.+ #[derive(Debug)]+ struct CountingUpload(Box<dyn MultipartUpload>);++ #[async_trait::async_trait]+ impl MultipartUpload for CountingUpload {+ fn put_part(&mut self, data: PutPayload) -> object_store::UploadPart {+ WRITES.fetch_add(1, Ordering::Relaxed);+ PUT_BYTES.fetch_add(data.content_length() as u64, Ordering::Relaxed);+ self.0.put_part(data)+ }+ async fn complete(&mut self) -> object_store::Result<PutResult> {+ WRITES.fetch_add(1, Ordering::Relaxed);+ delay().await;+ self.0.complete().await+ }+ async fn abort(&mut self) -> object_store::Result<()> {+ self.0.abort().await+ }+ }++ #[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);+ PUT_BYTES.fetch_add(payload.content_length() as u64, Ordering::Relaxed);+ delay().await;+ 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);+ delay().await;+ let inner = self.inner.put_multipart_opts(location, opts).await?;+ Ok(Box::new(CountingUpload(inner)))+ }++ async fn get_opts(+ &self,+ location: &Path,+ options: GetOptions,+ ) -> object_store::Result<GetResult> {+ GETS.fetch_add(1, Ordering::Relaxed);+ delay().await;+ let r = self.inner.get_opts(location, options).await?;+ GET_BYTES.fetch_add(r.range.end - r.range.start, Ordering::Relaxed);+ Ok(r)+ }++ // Count the coalesced requests the S3 store would issue, not the raw ranges.+ async fn get_ranges(+ &self,+ location: &Path,+ ranges: &[std::ops::Range<u64>],+ ) -> object_store::Result<Vec<bytes::Bytes>> {+ coalesce_ranges(+ ranges,+ |r| async move {+ use object_store::ObjectStoreExt;+ self.get_range(location, r).await+ },+ OBJECT_STORE_COALESCE_DEFAULT,+ )+ .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)+ }++ 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);+ delay().await;+ 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));+ }+}++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+enum Scenario {+ Median,+ Insert,+ SmallBig,+ Mixed10k,+}++impl Scenario {+ fn parse(s: &str) -> Self {+ match s {+ "median" => Self::Median,+ "insert" => Self::Insert,+ "smallbig" => Self::SmallBig,+ "mixed10k" => Self::Mixed10k,+ other => panic!("unknown scenario {other}"),+ }+ }+ fn name(self) -> &'static str {+ match self {+ Self::Median => "median",+ Self::Insert => "insert",+ Self::SmallBig => "smallbig",+ Self::Mixed10k => "mixed10k",+ }+ }+ fn partitioned(self) -> bool {+ matches!(self, Self::Median)+ }+ fn files(self) -> usize {+ match self {+ Self::Median => 60,+ Self::Insert => 173,+ Self::SmallBig | Self::Mixed10k => 60,+ }+ }+ fn rows_per_file(self) -> usize {+ match self {+ Self::Median => 200,+ Self::Insert => 5_000,+ Self::SmallBig | Self::Mixed10k => 20_000,+ }+ }+}++struct Args {+ scenario: Scenario,+ iters: usize,+ latency_ms: u64,+ probe_concurrency: usize,+ max_parallel_files: usize,+ dir: Option<PathBuf>,+}++fn parse_args() -> Args {+ let mut args = Args {+ scenario: Scenario::Median,+ iters: 4,+ latency_ms: 0,+ probe_concurrency: 8,+ max_parallel_files: 4,+ 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() {+ "--scenario" => args.scenario = Scenario::parse(&take("--scenario")),+ "--iters" => args.iters = take("--iters").parse().expect("--iters"),+ "--latency-ms" => args.latency_ms = take("--latency-ms").parse().expect("--latency-ms"),+ "--probe-concurrency" => {+ args.probe_concurrency = take("--probe-concurrency")+ .parse()+ .expect("--probe-concurrency")+ }+ "--max-parallel-files" => {+ args.max_parallel_files = take("--max-parallel-files")+ .parse()+ .expect("--max-parallel-files")+ }+ "--dir" => args.dir = Some(PathBuf::from(take("--dir"))),+ other => panic!("unknown flag {other}"),+ }+ }+ args+}++fn arrow_schema(partitioned: bool) -> SchemaRef {+ let mut fields = vec![Field::new("id", DataType::Utf8, true)];+ if partitioned {+ fields.push(Field::new("p", DataType::Utf8, true));+ }+ for i in 0..4 {+ fields.push(Field::new(format!("i{i}"), DataType::Int64, true));+ }+ for i in 0..4 {+ fields.push(Field::new(format!("f{i}"), DataType::Float64, true));+ }+ for i in 0..3 {+ fields.push(Field::new(format!("s{i}"), DataType::Utf8, true));+ }+ fields.push(Field::new(+ "ts",+ DataType::Timestamp(TimeUnit::Microsecond, None),+ true,+ ));+ Arc::new(Schema::new(fields))+}++/// Deterministic UUID-shaped PK, random-looking so min/max stats prune nothing.+fn pk(ns: &str, i: usize) -> String {+ uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, format!("{ns}:{i}").as_bytes()).to_string()+}++/// `rows` rows whose ids are `pk(ns, ids[r])`; `salt` varies payloads so a rewrite+/// really changes bytes.+fn batch(+ schema: &SchemaRef,+ partitioned: bool,+ partition: usize,+ ns: &str,+ ids: &[usize],+ salt: usize,+) -> RecordBatch {+ let n = ids.len();+ let mut cols: Vec<Arc<dyn arrow_array::Array>> = Vec::new();+ cols.push(Arc::new(StringArray::from(+ ids.iter().map(|i| pk(ns, *i)).collect::<Vec<_>>(),+ )));+ if partitioned {+ cols.push(Arc::new(StringArray::from(vec![+ format!("p{partition}");+ n+ ])));+ }+ for c in 0..4u64 {+ cols.push(Arc::new(Int64Array::from(+ ids.iter()+ .map(|i| ((*i as u64).wrapping_mul(0x9E37 + c) ^ salt as u64) as i64 % 1_000_000)+ .collect::<Vec<_>>(),+ )));+ }+ for c in 0..4u64 {+ cols.push(Arc::new(Float64Array::from(+ ids.iter()+ .map(|i| ((*i as u64 * (c + 3) + salt as u64) % 10_007) as f64 / 7.0)+ .collect::<Vec<_>>(),+ )));+ }+ for c in 0..3usize {+ cols.push(Arc::new(StringArray::from(+ ids.iter()+ .map(|i| {+ format!(+ "value-{c}-{:05}-{:06x}",+ (i * 7919 + salt) % 50_000,+ (i * 104729 + c) % 0xFFFFFF+ )+ })+ .collect::<Vec<_>>(),+ )));+ }+ cols.push(Arc::new(TimestampMicrosecondArray::from(+ ids.iter()+ .map(|i| 1_700_000_000_000_000 + (*i as i64) * 1_000 + salt as i64)+ .collect::<Vec<_>>(),+ )));+ RecordBatch::try_new(schema.clone(), cols).expect("batch")+}++async fn create_table(uri: &str, partitioned: bool) -> deltalake::DeltaTable {+ let mut cols = vec![StructField::new("id", KernelType::STRING, true)];+ if partitioned {+ cols.push(StructField::new("p", KernelType::STRING, true));+ }+ for i in 0..4 {+ cols.push(StructField::new(format!("i{i}"), KernelType::LONG, true));+ }+ for i in 0..4 {+ cols.push(StructField::new(format!("f{i}"), KernelType::DOUBLE, true));+ }+ for i in 0..3 {+ cols.push(StructField::new(format!("s{i}"), KernelType::STRING, true));+ }+ cols.push(StructField::new("ts", KernelType::TIMESTAMP_NTZ, true));+ let mut b = CreateBuilder::new()+ .with_location(uri)+ .with_columns(cols)+ .with_configuration_property(deltalake::TableProperty::CheckpointInterval, Some("10"));+ if partitioned {+ b = b.with_partition_columns(vec!["p".to_string()]);+ }+ b.await.expect("create table")+}++/// One file per commit: file `f` holds rows `f*rows_per_file .. (f+1)*rows_per_file`+/// of namespace "base" (partition `f` when partitioned).+async fn build_fixture(uri: &str, sc: Scenario, schema: &SchemaRef) {+ let mut table = create_table(uri, sc.partitioned()).await;+ let mut writer = RecordBatchWriter::for_table(&table).expect("writer");+ for f in 0..sc.files() {+ let ids: Vec<usize> = (f * sc.rows_per_file()..(f + 1) * sc.rows_per_file()).collect();+ let b = batch(schema, sc.partitioned(), f, "base", &ids, 0);+ writer.write(b).await.expect("write");+ writer.flush_and_commit(&mut table).await.expect("commit");+ if (f + 1) % 50 == 0 {+ eprintln!(" fixture: {} / {} files", f + 1, sc.files());+ }+ }+}++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");+ }+ }+}++/// The batch for iteration `i` of a scenario.+fn scenario_batch(sc: Scenario, schema: &SchemaRef, i: usize) -> RecordBatch {+ let rpf = sc.rows_per_file();+ match sc {+ Scenario::Median => {+ let p = i % sc.files();+ let ids: Vec<usize> = (p * rpf..p * rpf + 34).collect();+ batch(schema, true, p, "base", &ids, 1000 + i)+ }+ Scenario::Insert => {+ let ids: Vec<usize> = (i * 10_000..(i + 1) * 10_000).collect();+ batch(schema, false, 0, &format!("new{i}"), &ids, 1000 + i)+ }+ Scenario::SmallBig => {+ // 34 rows in two files, moving along the table each iteration.+ let f0 = (2 * i) % sc.files();+ let f1 = (2 * i + 1) % sc.files();+ let mut ids: Vec<usize> = (f0 * rpf..f0 * rpf + 17).collect();+ ids.extend(f1 * rpf..f1 * rpf + 17);+ batch(schema, false, 0, "base", &ids, 1000 + i)+ }+ Scenario::Mixed10k => {+ let total = sc.files() * rpf;+ let step = total / 10_000;+ let ids: Vec<usize> = (0..10_000).map(|k| (k * step + i) % total).collect();+ batch(schema, false, 0, "base", &ids, 1000 + i)+ }+ }+}++fn ms(from: Instant) -> f64 {+ from.elapsed().as_secs_f64() * 1000.0+}++#[tokio::main]+async fn main() {+ let args = parse_args();+ let sc = args.scenario;+ let schema = arrow_schema(sc.partitioned());++ let dir = args.dir.clone().unwrap_or_else(|| {+ // nosemgrep: rust.lang.security.temp-dir.temp-dir+ std::env::temp_dir().join(format!("deltalite-upsert-io-{}", sc.name()))+ });+ 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 {} at {}", sc.name(), dir.display());+ let started = Instant::now();+ build_fixture(&dir.to_string_lossy(), sc, &schema).await;+ std::fs::write(&marker, b"ok").expect("write marker");+ eprintln!("fixture built in {:.1}s", started.elapsed().as_secs_f64());+ }++ 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);+ counted::register();+ counted::LATENCY_MS.store(args.latency_ms, std::sync::atomic::Ordering::Relaxed);+ let uri = format!("counted://{}", run_dir.to_string_lossy());+ let so: HashMap<String, String> = HashMap::new();++ let opts = UpsertOptions {+ primary_keys: vec!["id".to_string()],+ partition_key: sc.partitioned().then(|| "p".to_string()),+ probe_concurrency: args.probe_concurrency,+ max_parallel_files: args.max_parallel_files,+ ..Default::default()+ };+ println!(+ "upsert_io scenario={} iters={} latency_ms={} probe_concurrency={} max_parallel_files={}",+ sc.name(),+ args.iters,+ args.latency_ms,+ args.probe_concurrency,+ args.max_parallel_files,+ );++ let c0 = counted::snapshot();+ let t = Instant::now();+ let mut handle = TableHandle::open(uri.clone(), so.clone())+ .await+ .expect("open");+ let open_ms = ms(t);+ let d = counted::snapshot().delta(&c0);+ println!(+ "open_handle gets {:4} ({:7.2} MB) lists {:3} writes {:3} wall {:8.1} ms",+ d.gets,+ d.get_bytes as f64 / 1e6,+ d.lists,+ d.writes,+ open_ms+ );+ println!(+ "{:<4} {:>5} {:>9} {:>5} {:>6} {:>9} {:>9} {:>10} {:>7} {:>6} {:>6} {:>6} {:>8}",+ "iter",+ "gets",+ "get_MB",+ "lists",+ "writes",+ "put_MB",+ "wall_ms",+ "rewrite_ms",+ "open_ms",+ "probed",+ "rm",+ "add",+ "copied"+ );+ for i in 0..args.iters {+ let b = scenario_batch(sc, &schema, i);+ let c = counted::snapshot();+ let t = Instant::now();+ let stats = handle+ .upsert(+ vec![b],+ schema.clone(),+ opts.clone(),+ MultipartConfig::default(),+ )+ .await+ .expect("upsert");+ let wall = ms(t);+ let d = counted::snapshot().delta(&c);+ println!(+ "{:<4} {:>5} {:>9.2} {:>5} {:>6} {:>9.2} {:>9.1} {:>10} {:>7} {:>6} {:>6} {:>6} {:>8}",+ i,+ d.gets,+ d.get_bytes as f64 / 1e6,+ d.lists,+ d.writes,+ d.put_bytes as f64 / 1e6,+ wall,+ stats.rewrite_ms,+ stats.open_ms,+ stats.files_probed,+ stats.files_removed,+ stats.files_added,+ stats.rows_copied,+ );+ }+ // A refresh with nothing new to read: what one log refresh costs.+ let c = counted::snapshot();+ let t = Instant::now();+ handle.refresh().await.expect("refresh");+ let d = counted::snapshot().delta(&c);+ println!(+ "refresh_noop gets {:4} ({:7.2} MB) lists {:3} writes {:3} wall {:8.1} ms",+ d.gets,+ d.get_bytes as f64 / 1e6,+ d.lists,+ d.writes,+ ms(t)+ );+}diff --git a/rust/deltalite/core/src/handle.rs b/rust/deltalite/core/src/handle.rsindex 4fa2df5b8453..1b1c7a80fa18 100644--- a/rust/deltalite/core/src/handle.rs+++ b/rust/deltalite/core/src/handle.rs@@ -7,6 +7,8 @@//! 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.+//! After its own commit it does not read the log at all: it adopts the state delta-rs+//! derived for that commit.use std::collections::HashMap;use std::sync::Arc;@@ -19,7 +21,7 @@ use deltalake::DeltaTable;use crate::errors::{Error, Result};use crate::prefetch::CheckpointCache;use crate::table::{open_table_prefetched, wrap_multipart, MultipartConfig};-use crate::upsert::{upsert_cached, RelaxCache, UpsertOptions, UpsertStats};+use crate::upsert::{upsert_cached_with_state, 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@@ -27,6 +29,26 @@ use crate::upsert::{upsert_cached, RelaxCache, UpsertOptions, UpsertStats};/// keep conflicting, so the only fix is to refresh the snapshot and re-plan.const CONFLICT_RETRIES: usize = 5;+/// Kill switch for adopting the commit's own snapshot after an upsert; `0` (or `false`,+/// `off`, `no`) restores the post-commit log refresh. Unset or any other value keeps+/// the adoption on.+pub const ADOPT_COMMIT_SNAPSHOT_ENV: &str = "DELTALITE_ADOPT_COMMIT_SNAPSHOT";++/// Whether the setting `value` of [`ADOPT_COMMIT_SNAPSHOT_ENV`] keeps the adoption on.+pub fn adopt_commit_snapshot_setting(value: Option<&str>) -> bool {+ match value {+ Some(v) => !matches!(+ v.trim().to_ascii_lowercase().as_str(),+ "0" | "false" | "off" | "no"+ ),+ None => true,+ }+}++fn adopt_commit_snapshot_from_env() -> bool {+ adopt_commit_snapshot_setting(std::env::var(ADOPT_COMMIT_SNAPSHOT_ENV).ok().as_deref())+}+/// One live data file as the loaded snapshot records it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct LiveFile {@@ -51,6 +73,7 @@ pub struct TableHandle {/// Checkpoint bytes the table's stores served the last load from; cleared after/// every load so a handle idling between upserts holds only its snapshot.prefetch: Arc<CheckpointCache>,+ adopt_commit_snapshot: bool,initial_open_ms: u64,initial_open_reported: bool,}@@ -67,6 +90,7 @@ impl TableHandle {table,relax_cache: RelaxCache::default(),prefetch,+ adopt_commit_snapshot: adopt_commit_snapshot_from_env(),initial_open_ms: started.elapsed().as_millis() as u64,initial_open_reported: false,})@@ -95,6 +119,17 @@ impl TableHandle {self.initial_open_ms}+ /// Whether an upsert adopts its commit's snapshot instead of refreshing afterwards+ /// (see [`ADOPT_COMMIT_SNAPSHOT_ENV`]).+ pub fn adopt_commit_snapshot(&self) -> bool {+ self.adopt_commit_snapshot+ }++ /// Override the [`ADOPT_COMMIT_SNAPSHOT_ENV`] setting for this handle.+ pub fn set_adopt_commit_snapshot(&mut self, adopt: bool) {+ self.adopt_commit_snapshot = adopt;+ }+/// The table id from the snapshot's metadata action.pub fn table_id(&self) -> Result<String> {Ok(self.table.snapshot()?.metadata().id().to_string())@@ -186,7 +221,7 @@ impl TableHandle {// 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(+ match upsert_cached_with_state(&view,source_batches.clone(),source_schema.clone(),@@ -204,11 +239,19 @@ impl TableHandle {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.+ Ok((mut stats, state)) => {+ // Reads through this handle must observe what was just written. The+ // commit already yielded the resulting state (a relax commit sits+ // under it; a checkpoint written by maintenance describes the same+ // version and the next refresh adopts it), so adopting it costs no+ // I/O. The refresh stays as the kill-switch path.let t = Instant::now();- self.refresh().await?;+ if self.adopt_commit_snapshot {+ self.table.state = Some(state);+ self.prefetch.clear();+ } else {+ self.refresh().await?;+ }open_ms += t.elapsed().as_millis() as u64;stats.open_ms = open_ms;stats.initial_open_ms = self.take_initial_open_ms();@@ -228,3 +271,19 @@ impl TableHandle {self.initial_open_ms}}++#[cfg(test)]+mod tests {+ use super::adopt_commit_snapshot_setting;++ #[test]+ fn adoption_is_on_unless_the_switch_turns_it_off() {+ assert!(adopt_commit_snapshot_setting(None));+ assert!(adopt_commit_snapshot_setting(Some("1")));+ assert!(adopt_commit_snapshot_setting(Some("true")));+ assert!(adopt_commit_snapshot_setting(Some("")));+ for off in ["0", "false", "off", "no", " OFF ", "False"] {+ assert!(!adopt_commit_snapshot_setting(Some(off)), "{off:?}");+ }+ }+}diff --git a/rust/deltalite/core/src/upsert.rs b/rust/deltalite/core/src/upsert.rsindex 5eeef8415119..e34b83efc00c 100644--- a/rust/deltalite/core/src/upsert.rs+++ b/rust/deltalite/core/src/upsert.rs@@ -36,10 +36,12 @@ use deltalake::kernel::{Action, MetadataExt as _, Remove, StructType};use deltalake::protocol::checkpoints::{cleanup_metadata, create_checkpoint};use deltalake::protocol::{DeltaOperation, SaveMode};use deltalake::table::config::TablePropertiesExt;+use deltalake::table::state::DeltaTableState;use deltalake::writer::{DeltaWriter, RecordBatchWriter};use deltalake::{DeltaTable, ObjectStore, PartitionFilter, PartitionValue, Path};use futures::{StreamExt, TryStreamExt};use metrics::{counter, histogram};+use parquet::arrow::arrow_reader::ArrowReaderMetadata;use parquet::arrow::async_reader::ParquetObjectReader;use parquet::arrow::ParquetRecordBatchStreamBuilder;use parquet::arrow::ProjectionMask;@@ -65,6 +67,12 @@ const INITIAL_DECODE_ESTIMATE_BYTES: usize = 4 * 1024 * 1024;/// First-iteration pre-decode reservation for narrow PK-column probe batches.const INITIAL_PROBE_ESTIMATE_BYTES: usize = 256 * 1024;+/// Tail bytes fetched when a data file is opened. Without a hint parquet reads the+/// 8-byte trailer first and the metadata second: two round trips per open. 64 KiB covers+/// the footer of a file with on the order of a hundred columns, and over-fetching on a+/// small file costs bytes, which are cheap, not a round trip, which is not.+const FOOTER_SIZE_HINT: usize = 64 * 1024;+/// Read batch size (in rows) that keeps a decoded batch near `target_bytes`, derived from/// the widest row group's average *uncompressed* bytes/row.///@@ -326,6 +334,9 @@ struct TargetFile {size: u64,stats: Option<String>,remove: Remove,+ /// Footer the probe parsed, handed to the rewrite so a hit file is opened once. Lives+ /// only as long as this partition's rewrite: the reader task consumes it.+ metadata: Option<Arc<ParquetMetaData>>,}/// Which rows of one source batch belong to a partition. Chosen so the common shapes@@ -579,6 +590,22 @@ pub async fn upsert_cached(opts: UpsertOptions,relax_cache: &mut RelaxCache,) -> Result<UpsertStats> {+ upsert_cached_with_state(table, source_batches, source_schema, opts, relax_cache)+ .await+ .map(|(stats, _)| stats)+}++/// [`upsert_cached`] that also returns the table state delta-rs derived for the commit+/// it wrote (what every delta-rs operation returns as its resulting table), so a+/// long-lived handle can adopt it instead of reading the log again. When delta-rs had to+/// retry the commit behind another writer, the state includes that writer's commit.+pub async fn upsert_cached_with_state(+ table: &DeltaTable,+ source_batches: Vec<RecordBatch>,+ source_schema: SchemaRef,+ opts: UpsertOptions,+ relax_cache: &mut RelaxCache,+) -> Result<(UpsertStats, DeltaTableState)> {let started = Instant::now();let strategy = opts.prune_strategy.as_str();let result = upsert_with_relax(table, source_batches, source_schema, opts, relax_cache).await;@@ -586,7 +613,7 @@ pub async fn upsert_cached(// Static label values only -- no per-call allocation (rust/CLAUDE.md).histogram!("deltalite_upsert_duration_seconds").record(started.elapsed().as_secs_f64());match &result {- Ok(stats) => {+ Ok((stats, _)) => {counter!("deltalite_upserts_total", "outcome" => "ok", "prune_strategy" => strategy).increment(1);counter!("deltalite_files_added_total").increment(stats.files_added as u64);@@ -628,12 +655,12 @@ async fn upsert_with_relax(source_schema: SchemaRef,opts: UpsertOptions,relax_cache: &mut RelaxCache,-) -> Result<UpsertStats> {+) -> Result<(UpsertStats, DeltaTableState)> {let relax_started = Instant::now();let relax = columns_needing_relax(table, &source_batches, &source_schema, relax_cache).await?;if relax.is_empty() {let relax_ms = relax_started.elapsed().as_millis() as u64;- let mut stats = upsert_inner(table, source_batches, source_schema, opts).await?;+ let (mut stats, state) = 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@@ -642,19 +669,20 @@ async fn upsert_with_relax(if let Ok(committed) = u64::try_from(stats.version) {relax_cache.advance_own_commit(committed);}- return Ok(stats);+ return Ok((stats, state));}relax_columns_to_nullable(table, &relax).await?;// Re-read the log so the writer (and every schema derived from the table) observes- // the relaxed metadata; the borrowed handle still sees the old snapshot.+ // the relaxed metadata; the borrowed handle still sees the old snapshot. The state+ // the upsert's commit then yields sits on top of the relax commit, so it is complete.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?;+ let (mut stats, state) = upsert_inner(&fresh, source_batches, source_schema, opts).await?;stats.columns_relaxed = relax.len();stats.relax_ms = relax_ms;- Ok(stats)+ Ok((stats, state))}/// Non-nullable table columns that verifiably contain nulls -- in the incoming batch@@ -785,7 +813,7 @@ async fn upsert_inner(mut source_batches: Vec<RecordBatch>,source_schema: SchemaRef,opts: UpsertOptions,-) -> Result<UpsertStats> {+) -> Result<(UpsertStats, DeltaTableState)> {if opts.primary_keys.is_empty() {return Err(Error::Generic("primary_keys must not be empty for an upsert".into(),@@ -1043,7 +1071,7 @@ async fn upsert_inner(commit_ms = stats.commit_ms,"upsert committed");- Ok(stats)+ Ok((stats, finalized.snapshot))}/// Checkpoint and expired-log cleanup after a durable commit, tolerating failure: the@@ -1374,10 +1402,33 @@ async fn list_partition_files(size: v.size() as u64,stats: v.stats(),remove: v.remove_action(true),+ metadata: None,}).collect())}+/// Open a Parquet stream builder for `f`. A footer the probe already parsed is reused+/// without I/O; otherwise the footer is read with [`FOOTER_SIZE_HINT`] so it arrives in+/// one round trip.+async fn open_builder(+ store: &Arc<dyn ObjectStore>,+ f: &TargetFile,+) -> Result<ParquetRecordBatchStreamBuilder<ParquetObjectReader>> {+ let path = Path::parse(&f.path)+ .map_err(|e| Error::Generic(format!("bad data file path {:?}: {e}", f.path)))?;+ let reader = ParquetObjectReader::new(store.clone(), path).with_file_size(f.size);+ if let Some(meta) = &f.metadata {+ let arrow_meta = ArrowReaderMetadata::try_new(meta.clone(), Default::default())?;+ return Ok(ParquetRecordBatchStreamBuilder::new_with_metadata(+ reader, arrow_meta,+ ));+ }+ Ok(+ ParquetRecordBatchStreamBuilder::new(reader.with_footer_size_hint(FOOTER_SIZE_HINT))+ .await?,+ )+}+/// Drop files whose Add-action stats prove they hold no match: min/max disjointness on/// the first PK column, or a PK column that is entirely NULL in the file (SQL NULL never/// matches, so such a file cannot contain a matched row). Both checks are exact@@ -1605,11 +1656,9 @@ async fn probe_file(partition_value: &str,opts: &UpsertOptions,budgets: &Budgets,-) -> Result<bool> {- let path = Path::parse(&f.path)- .map_err(|e| Error::Generic(format!("bad data file path {:?}: {e}", f.path)))?;- let reader = ParquetObjectReader::new(store.clone(), path).with_file_size(f.size);- let builder = ParquetRecordBatchStreamBuilder::new(reader).await?;+) -> Result<(bool, Arc<ParquetMetaData>)> {+ let builder = open_builder(store, f).await?;+ let metadata = builder.metadata().clone();let file_schema = builder.schema().clone();let mut pk_types: Vec<DataType> = Vec::with_capacity(opts.primary_keys.len());@@ -1634,7 +1683,7 @@ async fn probe_file(} else {// The column is physically absent (file predates schema evolution): every// row has NULL for this PK component, and NULL never matches.- return Ok(false);+ return Ok((false, metadata));}}@@ -1649,7 +1698,7 @@ async fn probe_file(partition_value,&pk_types,)?;- return pkset.contains_any_columns(&cols, 1);+ return Ok((pkset.contains_any_columns(&cols, 1)?, metadata));}let mask = ProjectionMask::roots(builder.parquet_schema(), projection);@@ -1686,14 +1735,15 @@ async fn probe_file(let hit = pkset.contains_any_columns(&cols, batch.num_rows())?;drop(permit);if hit {- return Ok(true);+ return Ok((true, metadata));}}- Ok(false)+ Ok((false, metadata))}/// Probe `files` with bounded concurrency, splitting them into (files that contain at-/// least one match, count of files proven match-free). Order is preserved.+/// least one match, count of files proven match-free). Order is preserved. A kept file+/// carries the footer its probe parsed; a skipped file's footer is dropped here.#[allow(clippy::too_many_arguments)]async fn probe_files(store: &Arc<dyn ObjectStore>,@@ -1705,31 +1755,33 @@ async fn probe_files(opts: &UpsertOptions,budgets: &Budgets,) -> Result<(Vec<TargetFile>, usize)> {- let results: Vec<(TargetFile, bool)> = futures::stream::iter(files.into_iter().map(|f| {- let store = store.clone();- async move {- let hit = probe_file(- &store,- &f,- pkset,- table_schema,- partition_col,- partition_value,- opts,- budgets,- )- .await?;- Ok::<_, Error>((f, hit))- }- }))- .buffered(opts.probe_concurrency.max(1))- .try_collect()- .await?;+ let results: Vec<(TargetFile, bool, Arc<ParquetMetaData>)> =+ futures::stream::iter(files.into_iter().map(|f| {+ let store = store.clone();+ async move {+ let (hit, metadata) = probe_file(+ &store,+ &f,+ pkset,+ table_schema,+ partition_col,+ partition_value,+ opts,+ budgets,+ )+ .await?;+ Ok::<_, Error>((f, hit, metadata))+ }+ }))+ .buffered(opts.probe_concurrency.max(1))+ .try_collect()+ .await?;let mut keep = Vec::new();let mut skipped = 0usize;- for (f, hit) in results {+ for (mut f, hit, metadata) in results {if hit {+ f.metadata = Some(metadata);keep.push(f);} else {skipped += 1;@@ -1762,10 +1814,7 @@ async fn filter_file(budgets: Budgets,tx: mpsc::UnboundedSender<(RecordBatch, BudgetPermit)>,) -> Result<FileOutcome> {- let path = Path::parse(&f.path)- .map_err(|e| Error::Generic(format!("bad data file path {:?}: {e}", f.path)))?;- let reader = ParquetObjectReader::new(store, path).with_file_size(f.size);- let builder = ParquetRecordBatchStreamBuilder::new(reader).await?;+ let builder = open_builder(&store, &f).await?;let batch_rows = byte_bounded_batch_rows(builder.metadata(),INITIAL_DECODE_ESTIMATE_BYTES,@@ -2355,6 +2404,7 @@ mod tests {size: 1,stats: stats.map(|s| s.to_string()),remove: Remove::default(),+ metadata: None,}}diff --git a/rust/deltalite/core/tests/handle_and_open.rs b/rust/deltalite/core/tests/handle_and_open.rsindex de7edc49ce76..893ca56bcd90 100644--- a/rust/deltalite/core/tests/handle_and_open.rs+++ b/rust/deltalite/core/tests/handle_and_open.rs@@ -17,7 +17,7 @@ use deltalake::operations::create::CreateBuilder;use deltalake::{DeltaResult, Path, TableProperty};use deltalite_core::handle::TableHandle;use deltalite_core::table::{open_table, open_table_multipart, wrap_multipart, MultipartConfig};-use deltalite_core::upsert::UpsertOptions;+use deltalite_core::upsert::{upsert_cached_with_state, RelaxCache, UpsertOptions};use futures::stream::BoxStream;use object_store::local::LocalFileSystem;use object_store::{@@ -38,10 +38,79 @@ static READS: LazyLock<Mutex<HashMap<String, usize>>> =static CHECKPOINT_GETS: LazyLock<Mutex<HashMap<String, usize>>> =LazyLock::new(|| Mutex::new(HashMap::new()));+/// Every store call in issue order, so a test can ask what happened after a given point+/// (e.g. after the commit PUT). Parquet reads a footer through one `get_opts` and column+/// chunks through `get_ranges`, so the two GET kinds tell footer round trips from data+/// reads.+static OPS: LazyLock<Mutex<Vec<(Op, String)>>> = LazyLock::new(|| Mutex::new(Vec::new()));++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Op {+ Get,+ GetRange,+ Head,+ List,+ Put,+}++impl Op {+ fn is_read(self) -> bool {+ !matches!(self, Op::Put)+ }+}+fn record_read(target: String, n: usize) {*READS.lock().unwrap().entry(target).or_default() += n;}+fn record_op(op: Op, target: &str) {+ OPS.lock().unwrap().push((op, target.to_string()));+}++/// Position in the op log; pass to [`ops_since`] to see only what happened afterwards.+fn ops_len() -> usize {+ OPS.lock().unwrap().len()+}++/// Ops issued since `start` against paths under `root`, in issue order.+fn ops_since(start: usize, root: &str) -> Vec<(Op, String)> {+ OPS.lock()+ .unwrap()+ .iter()+ .skip(start)+ .filter(|(_, path)| path.starts_with(root))+ .cloned()+ .collect()+}++/// The reads issued after the commit JSON for `version` was written: the log reads+/// deltalite spends on observing its own commit.+fn log_reads_after_commit(ops: &[(Op, String)], root: &str, version: i64) -> Vec<(Op, String)> {+ let commit = format!("{root}/_delta_log/{version:020}.json");+ let commit_at = ops+ .iter()+ .position(|(op, path)| *op == Op::Put && *path == commit)+ .unwrap_or_else(|| panic!("no PUT of {commit} in {ops:?}"));+ let log_root = format!("{root}/_delta_log");+ ops[commit_at + 1..]+ .iter()+ .filter(|(op, path)| op.is_read() && path.starts_with(&log_root))+ .cloned()+ .collect()+}++/// Footer GETs (`get_opts`, see [`OPS`]) per data file under `root`.+fn data_file_footer_gets(ops: &[(Op, String)], root: &str) -> HashMap<String, usize> {+ let log_root = format!("{root}/_delta_log");+ let mut out: HashMap<String, usize> = HashMap::new();+ for (op, path) in ops {+ if *op == Op::Get && path.ends_with(".parquet") && !path.starts_with(&log_root) {+ *out.entry(path.clone()).or_default() += 1;+ }+ }+ out+}+/// Reads issued against paths under `root` (an object-store path, no leading slash).fn reads_under(root: &str) -> usize {READS@@ -102,6 +171,7 @@ impl ObjectStore for CountingStore {payload: PutPayload,opts: PutOptions,) -> object_store::Result<PutResult> {+ record_op(Op::Put, location.as_ref());self.inner.put_opts(location, payload, opts).await}@@ -110,6 +180,7 @@ impl ObjectStore for CountingStore {location: &Path,opts: PutMultipartOptions,) -> object_store::Result<Box<dyn MultipartUpload>> {+ record_op(Op::Put, location.as_ref());self.inner.put_multipart_opts(location, opts).await}@@ -119,7 +190,10 @@ impl ObjectStore for CountingStore {options: GetOptions,) -> object_store::Result<GetResult> {record_read(location.to_string(), 1);- if !options.head {+ if options.head {+ record_op(Op::Head, location.as_ref());+ } else {+ record_op(Op::Get, location.as_ref());count_checkpoint_get(location, 1);}self.inner.get_opts(location, options).await@@ -131,6 +205,9 @@ impl ObjectStore for CountingStore {ranges: &[std::ops::Range<u64>],) -> object_store::Result<Vec<bytes::Bytes>> {record_read(location.to_string(), ranges.len());+ for _ in ranges {+ record_op(Op::GetRange, location.as_ref());+ }count_checkpoint_get(location, ranges.len());self.inner.get_ranges(location, ranges).await}@@ -146,6 +223,7 @@ impl ObjectStore for CountingStore {// delta-kernel relies on it, while `LocalFileSystem` yields directory order.fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, object_store::Result<ObjectMeta>> {record_read(prefix_key(prefix), 1);+ record_op(Op::List, &prefix_key(prefix));sorted(self.inner.list(prefix))}@@ -155,11 +233,13 @@ impl ObjectStore for CountingStore {offset: &Path,) -> BoxStream<'static, object_store::Result<ObjectMeta>> {record_read(prefix_key(prefix), 1);+ record_op(Op::List, &prefix_key(prefix));sorted(self.inner.list_with_offset(prefix, offset))}async fn list_with_delimiter(&self, prefix: Option<&Path>) -> object_store::Result<ListResult> {record_read(prefix_key(prefix), 1);+ record_op(Op::List, &prefix_key(prefix));self.inner.list_with_delimiter(prefix).await}@@ -306,6 +386,65 @@ async fn create_seeded_table_with(s}+/// Create an unpartitioned table at `uri` with one live file per key group. The groups+/// must have disjoint key ranges: each upsert's min/max then prunes the earlier files+/// by stats, so they are carried over instead of coalesced into one output file.+async fn create_disjoint_files_table(uri: &str, groups: &[&[&str]]) -> SchemaRef {+ CreateBuilder::new()+ .with_location(uri)+ .with_columns(vec![+ StructField::new("pk", KernelType::STRING, false),+ StructField::new("v", KernelType::LONG, true),+ ])+ .with_configuration_property(TableProperty::CheckpointInterval, Some("100".to_string()))+ .await+ .expect("create table");+ let s = schema(true);+ let mut handle = TableHandle::open(uri.to_string(), HashMap::new())+ .await+ .expect("open for seeding");+ for (i, keys) in groups.iter().enumerate() {+ let vs = keys.iter().map(|_| Some(i as i64)).collect();+ handle+ .upsert(+ vec![batch(&s, keys, vs)],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("seed group");+ }+ assert_eq!(handle.num_files().expect("num_files"), groups.len());+ s+}++/// Sorted live data-file paths of a fresh load: the log's own answer, for comparing+/// against what a handle's adopted state claims.+async fn live_paths_from_the_log(uri: &str) -> Vec<String> {+ let table = open_table(uri, HashMap::new()).await.expect("fresh open");+ let mut paths: Vec<String> = table+ .snapshot()+ .expect("snapshot")+ .log_data()+ .iter()+ .map(|f| f.path().to_string())+ .collect();+ paths.sort();+ paths+}++fn sorted_paths(handle: &TableHandle) -> Vec<String> {+ let mut paths: Vec<String> = handle+ .files()+ .expect("files")+ .into_iter()+ .map(|f| f.path)+ .collect();+ paths.sort();+ paths+}+/// Create a table partitioned on `p` at `uri` with one file in each of two partitions.async fn create_partitioned_table(uri: &str) -> SchemaRef {CreateBuilder::new()@@ -516,8 +655,8 @@ async fn warm_relax_cache_still_relaxes_when_the_batch_carries_nulls() {/// The checkpoint prefetch: a snapshot load must read each checkpoint Parquet file with/// one whole-object GET instead of one ranged GET per footer, metadata and column chunk.-/// Covers both the initial open and the post-commit refresh that adopts a checkpoint the-/// upsert's own maintenance just wrote (through the multipart-wrapped view).+/// Covers both the initial open and the refresh that adopts a checkpoint the previous+/// upsert's own maintenance wrote at the version the handle already holds.#[tokio::test]async fn checkpoint_files_are_read_with_one_get_each() {register_counting_scheme();@@ -539,8 +678,9 @@ async fn checkpoint_files_are_read_with_one_get_each() {);}- // Version 5 sits on the interval boundary: maintenance writes checkpoint 5 and the- // post-commit refresh rebuilds the snapshot from it.+ // Version 5 sits on the interval boundary: maintenance writes checkpoint 5 after the+ // commit whose state the handle adopted, so the next refresh rebuilds the snapshot+ // from that checkpoint (through the multipart-wrapped view's store).let before = checkpoint_gets();let stats = handle.upsert(@@ -552,9 +692,18 @@ async fn checkpoint_files_are_read_with_one_get_each() {.await.expect("boundary upsert");assert_eq!(stats.version, 5);+ let is_checkpoint_5 = |path: &str| path.contains("00000000000000000005.checkpoint");+ assert!(+ !checkpoint_gets_since(&before)+ .keys()+ .any(|p| is_checkpoint_5(p)),+ "adopting the commit state must not read the checkpoint it just wrote"+ );+ let before = checkpoint_gets();+ handle.refresh().await.expect("refresh");let refreshed = checkpoint_gets_since(&before);assert!(- refreshed.keys().any(|p| p.contains("00000000000000000005")),+ refreshed.keys().any(|p| is_checkpoint_5(p)),"the refresh must adopt the new checkpoint (read: {refreshed:?})");for (path, gets) in &refreshed {@@ -694,3 +843,236 @@ async fn files_carry_partition_values() {partitions.sort();assert_eq!(partitions, [Some("x".to_string()), Some("y".to_string())]);}++/// A file the probe found a match in is rewritten with the footer the probe parsed, and+/// that footer arrives in one GET: one footer round trip per hit file for the whole+/// upsert, not two (probe and rewrite each opening the file) times two (trailer, then+/// metadata).+#[tokio::test]+async fn hit_files_are_opened_once_across_probe_and_rewrite() {+ register_counting_scheme();+ let dir = tempfile::tempdir().expect("tempdir");+ let table_dir = dir.path().join("t9");+ let uri = format!("dltest://{}", table_dir.to_string_lossy());+ let root = table_root(&table_dir);+ let s = create_disjoint_files_table(+ &uri,+ &[+ &["a0", "a1", "a2", "a3"],+ &["b0", "b1", "b2", "b3"],+ &["c0", "c1", "c2", "c3"],+ ],+ )+ .await;++ let mut handle = TableHandle::open(uri, HashMap::new())+ .await+ .expect("open handle");+ let hit_files: Vec<String> = handle+ .files()+ .expect("files")+ .into_iter()+ .map(|f| format!("{root}/{}", f.path))+ .collect();+ assert_eq!(hit_files.len(), 3);++ // One key from every file: each is probed, hit, and rewritten.+ let start = ops_len();+ let stats = handle+ .upsert(+ vec![batch(+ &s,+ &["a2", "b2", "c2"],+ vec![Some(7), Some(7), Some(7)],+ )],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("upsert");+ assert_eq!(stats.files_probed, 3);+ assert_eq!(stats.files_removed, 3);++ let footer_gets = data_file_footer_gets(&ops_since(start, &root), &root);+ for path in &hit_files {+ assert_eq!(+ footer_gets.get(path).copied().unwrap_or(0),+ 1,+ "{path}: expected the probe's one footer GET, reused by the rewrite \+ (footer GETs per file: {footer_gets:?})"+ );+ }+}++/// After the commit the handle adopts the state delta-rs derived for it instead of+/// listing the log and reading `_last_checkpoint` again, and that state is the log's+/// truth.+#[tokio::test]+async fn adopting_the_commit_snapshot_skips_the_post_commit_refresh() {+ register_counting_scheme();+ let dir = tempfile::tempdir().expect("tempdir");+ let table_dir = dir.path().join("t10");+ let uri = format!("dltest://{}", table_dir.to_string_lossy());+ let root = table_root(&table_dir);+ let s = create_disjoint_files_table(&uri, &[&["a0", "a1"], &["b0", "b1"]]).await;++ let mut handle = TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open handle");+ assert!(handle.adopt_commit_snapshot(), "adoption is on by default");++ let mut reads_by_mode = Vec::new();+ let mut versions = Vec::new();+ for (adopt, key) in [(true, "a1"), (false, "b1")] {+ handle.set_adopt_commit_snapshot(adopt);+ let start = ops_len();+ let stats = handle+ .upsert(+ vec![batch(&s, &[key], vec![Some(3)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("upsert");+ // Captured before the fresh load below, whose replay must not be counted.+ versions.push(stats.version);+ reads_by_mode.push(log_reads_after_commit(+ &ops_since(start, &root),+ &root,+ stats.version,+ ));+ assert_eq!(handle.version(), stats.version);+ assert_eq!(+ sorted_paths(&handle),+ live_paths_from_the_log(&uri).await,+ "the handle's state must match the log (adopt={adopt})"+ );+ }++ // delta-rs derives the commit's state with one log LIST (plus reads of the commit+ // JSON it just wrote); a post-commit refresh would LIST the log a second time.+ let lists = |reads: &[(Op, String)]| reads.iter().filter(|(op, _)| *op == Op::List).count();+ let (adopted, refreshed) = (&reads_by_mode[0], &reads_by_mode[1]);+ assert_eq!(+ lists(adopted),+ 1,+ "the handle must not refresh after adopting the commit state (reads: {adopted:?})"+ );+ assert!(+ adopted+ .iter()+ .all(|(op, path)| *op == Op::List+ || path.ends_with(&format!("{:020}.json", versions[0]))),+ "after the commit only the commit's own JSON may be read (reads: {adopted:?})"+ );+ assert_eq!(+ lists(refreshed),+ 2,+ "the kill-switch path still refreshes after the commit (reads: {refreshed:?})"+ );+}++/// The adopted state stays a valid base for later refreshes: after a boundary commit+/// (maintenance writes a checkpoint at the adopted version) and an external writer's+/// commit, the next upsert lands on the externally-advanced version and the handle's+/// file list still matches the log.+#[tokio::test]+async fn adopted_snapshot_observes_maintenance_and_external_commits() {+ let dir = tempfile::tempdir().expect("tempdir");+ let uri = dir.path().join("t11").to_string_lossy().to_string();+ let s = create_seeded_table_with(&uri, true, Some(2), 4).await;++ let mut handle = TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open handle");+ let stats = handle+ .upsert(+ vec![batch(&s, &["c"], vec![Some(1)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("boundary upsert");+ assert_eq!(stats.version, 5);+ assert_eq!(handle.version(), 5);+ assert_eq!(sorted_paths(&handle), live_paths_from_the_log(&uri).await);++ let mut other = TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open external handle");+ let stats = other+ .upsert(+ vec![batch(&s, &["d"], vec![Some(2)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("external upsert");+ assert_eq!(stats.version, 6);++ let stats = handle+ .upsert(+ vec![batch(&s, &["c", "d"], vec![Some(3), Some(3)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("upsert after external commit");+ assert_eq!(stats.version, 7);+ assert_eq!(handle.version(), 7);+ assert_eq!(sorted_paths(&handle), live_paths_from_the_log(&uri).await);+}++/// When another writer's commit lands between the snapshot read and the commit and+/// delta-rs retries at the next version, the state returned with the commit includes+/// that writer's file, so a handle adopting it is not behind the log.+#[tokio::test]+async fn commit_state_includes_a_writer_that_landed_first() {+ let dir = tempfile::tempdir().expect("tempdir");+ let uri = dir.path().join("t12").to_string_lossy().to_string();+ let s = create_disjoint_files_table(&uri, &[&["a0", "a1"]]).await;++ let stale = open_table(&uri, HashMap::new()).await.expect("open");+ let v0 = stale.version().expect("loaded");++ // Insert-only, disjoint from every live file: an Add-only commit that delta-rs's+ // conflict checker lets a retried commit land on top of.+ let mut other = TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open external handle");+ other+ .upsert(+ vec![batch(&s, &["m0", "m1"], vec![Some(1), Some(1)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("external upsert");++ let (stats, state) = upsert_cached_with_state(+ &stale,+ vec![batch(&s, &["x0", "x1"], vec![Some(2), Some(2)])],+ s.clone(),+ opts(),+ &mut RelaxCache::default(),+ )+ .await+ .expect("upsert behind the external commit");+ assert_eq!(stats.version, v0 as i64 + 2, "committed after the retry");+ assert_eq!(state.version(), v0 + 2);++ let mut adopted: Vec<String> = state+ .log_data()+ .iter()+ .map(|f| f.path().to_string())+ .collect();+ adopted.sort();+ assert_eq!(adopted.len(), 3, "seed file, external file, own file");+ assert_eq!(adopted, live_paths_from_the_log(&uri).await);+}diff --git a/rust/deltalite/python/README.md b/rust/deltalite/python/README.mdindex b8f88db8261d..a0c83c1f7064 100644--- a/rust/deltalite/python/README.md+++ b/rust/deltalite/python/README.md@@ -183,6 +183,19 @@ disables the prefetch. Cached bytes also reserve space from`DELTALITE_PROCESS_MAX_BUFFERED_BYTES`, so concurrent table opens share theprocess-wide budget. The bytes are released as soon as the load finishes.+**Commit snapshot adoption.** After a successful upsert the handle keeps the+table state delta-rs derived for the commit it just wrote (the same state every+delta-rs operation returns) instead of listing the log and reading that commit+back. The next upsert still refreshes before it plans, so commits from other+writers are observed exactly as before, and a checkpoint the upsert's own+maintenance wrote is adopted on that refresh.+`DELTALITE_ADOPT_COMMIT_SNAPSHOT=0` restores the post-commit refresh.++**Data-file reads.** Every Parquet data file is opened with a 64 KiB footer size+hint, so a footer that fits arrives in one GET instead of two, and a file the+probe found a match in hands its parsed footer to the rewrite, so the file is+not opened a second time.+## Metricsdeltalite emits via the Rust [`metrics`](https://docs.rs/metrics) facade (static