: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(deltalite): cut log listings and small reads on open, refresh and commit (#113107)
Tom Owers7fe76618ec3b
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex f837f4a0c0f0..30376345ee8e 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -3973,7 +3973,7 @@ dependencies = [[[package]]name = "deltalite-python"-version = "0.1.10"+version = "0.1.11"dependencies = ["arrow","arrow-array",diff --git a/rust/deltalite/README.md b/rust/deltalite/README.mdindex d64aba2271a7..e5f3eb33d3ed 100644--- a/rust/deltalite/README.md+++ b/rust/deltalite/README.md@@ -124,6 +124,11 @@ budgets): `DELTALITE_PROCESS_MAX_PARALLEL_PARTITIONS` (8),`DELTALITE_PROCESS_MAX_FETCH_BYTES` (256 MiB), `DELTALITE_MAX_SOURCE_BYTES`,`DELTALITE_MULTIPART_THRESHOLD_BYTES`, `DELTALITE_MULTIPART_PART_SIZE_BYTES`.+Kill switches for the request savings on the log and on small files (set to `0`+to restore the earlier requests): `DELTALITE_PROBE_REFRESH`,+`DELTALITE_OPTIMISTIC_COMMIT_VERSION`, `DELTALITE_COMMIT_JSON_CACHE`,+`DELTALITE_SMALL_FILE_SINGLE_GET`. See `python/README.md`, "Log requests".+`DeltaLiteTable.compact` takes the same budget knobs plus its own (see`python/README.md`, "Compaction"); it shares the process-global limits withevery upsert in the process.diff --git a/rust/deltalite/core/examples/upsert_io.rs b/rust/deltalite/core/examples/upsert_io.rsindex ba4b974a2935..8bbe14f06d79 100644--- a/rust/deltalite/core/examples/upsert_io.rs+++ b/rust/deltalite/core/examples/upsert_io.rs@@ -13,6 +13,16 @@//! 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+//! tail23 as median, but 73 partitions and a checkpoint every 25 commits, so the log+//! holds 23 commits after the last checkpoint (the longest tail production sees)+//! nockpt as median, with no checkpoint at all (60 commits to replay)+//! manysmall unpartitioned, 300 files x 200 rows; 50-row insert-only batch (every small+//! file is probed)+//! hourly partitioned, 2000 partitions x 1 file x 50 rows; 30-row update across 3+//! partitions+//!+//! `--cold` opens a new handle for every upsert, which is what the loader does for most+//! batches. `--compact` runs one compaction after the upserts.//!//! Usage://! cargo run --release -p deltalite-core --example upsert_io -- \@@ -55,15 +65,32 @@ mod counted {};pub static GETS: AtomicUsize = AtomicUsize::new(0);+ pub static HEADS: 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);+ pub static TRACE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);++ fn trace(op: &str, what: impl std::fmt::Display) {+ if TRACE.load(Ordering::Relaxed) {+ eprintln!(" [io] {op:<5} {what}");+ }+ }++ /// The last two path segments, enough to tell a log entry from a data file.+ fn tail(p: &Path) -> String {+ let s = p.as_ref();+ let mut parts: Vec<&str> = s.rsplit('/').take(2).collect();+ parts.reverse();+ parts.join("/")+ }#[derive(Clone, Copy, Debug, Default)]pub struct Snap {pub gets: usize,+ pub heads: usize,pub get_bytes: u64,pub lists: usize,pub writes: usize,@@ -73,6 +100,7 @@ mod counted {pub fn snapshot() -> Snap {Snap {gets: GETS.load(Ordering::Relaxed),+ heads: HEADS.load(Ordering::Relaxed),get_bytes: GET_BYTES.load(Ordering::Relaxed),lists: LISTS.load(Ordering::Relaxed),writes: WRITES.load(Ordering::Relaxed),@@ -84,6 +112,7 @@ mod counted {pub fn delta(&self, since: &Snap) -> Snap {Snap {gets: self.gets - since.gets,+ heads: self.heads - since.heads,get_bytes: self.get_bytes - since.get_bytes,lists: self.lists - since.lists,writes: self.writes - since.writes,@@ -155,6 +184,7 @@ mod counted {) -> object_store::Result<PutResult> {WRITES.fetch_add(1, Ordering::Relaxed);PUT_BYTES.fetch_add(payload.content_length() as u64, Ordering::Relaxed);+ trace("PUT", format!("{} {:?}", tail(location), opts.mode));delay().await;self.inner.put_opts(location, payload, opts).await}@@ -175,10 +205,21 @@ mod counted {location: &Path,options: GetOptions,) -> object_store::Result<GetResult> {- GETS.fetch_add(1, Ordering::Relaxed);+ if options.head {+ HEADS.fetch_add(1, Ordering::Relaxed);+ } else {+ GETS.fetch_add(1, Ordering::Relaxed);+ }+ trace(+ if options.head { "HEAD" } else { "GET" },+ format!("{} {:?}", tail(location), options.range),+ );delay().await;+ let head = options.head;let r = self.inner.get_opts(location, options).await?;- GET_BYTES.fetch_add(r.range.end - r.range.start, Ordering::Relaxed);+ if !head {+ GET_BYTES.fetch_add(r.range.end - r.range.start, Ordering::Relaxed);+ }Ok(r)}@@ -212,6 +253,7 @@ mod counted {prefix: Option<&Path>,) -> BoxStream<'static, object_store::Result<ObjectMeta>> {LISTS.fetch_add(1, Ordering::Relaxed);+ trace("LIST", format!("{:?}", prefix.map(tail)));sorted(self.inner.list(prefix))}@@ -221,6 +263,10 @@ mod counted {offset: &Path,) -> BoxStream<'static, object_store::Result<ObjectMeta>> {LISTS.fetch_add(1, Ordering::Relaxed);+ trace(+ "LIST",+ format!("{:?} offset {}", prefix.map(tail), tail(offset)),+ );sorted(self.inner.list_with_offset(prefix, offset))}@@ -229,6 +275,7 @@ mod counted {prefix: Option<&Path>,) -> object_store::Result<ListResult> {LISTS.fetch_add(1, Ordering::Relaxed);+ trace("LIST", format!("{:?} delimiter", prefix.map(tail)));delay().await;self.inner.list_with_delimiter(prefix).await}@@ -300,6 +347,10 @@ enum Scenario {Insert,SmallBig,Mixed10k,+ Tail23,+ NoCkpt,+ ManySmall,+ Hourly,}impl Scenario {@@ -309,6 +360,10 @@ impl Scenario {"insert" => Self::Insert,"smallbig" => Self::SmallBig,"mixed10k" => Self::Mixed10k,+ "tail23" => Self::Tail23,+ "nockpt" => Self::NoCkpt,+ "manysmall" => Self::ManySmall,+ "hourly" => Self::Hourly,other => panic!("unknown scenario {other}"),}}@@ -318,21 +373,47 @@ impl Scenario {Self::Insert => "insert",Self::SmallBig => "smallbig",Self::Mixed10k => "mixed10k",+ Self::Tail23 => "tail23",+ Self::NoCkpt => "nockpt",+ Self::ManySmall => "manysmall",+ Self::Hourly => "hourly",}}fn partitioned(self) -> bool {- matches!(self, Self::Median)+ matches!(+ self,+ Self::Median | Self::Tail23 | Self::NoCkpt | Self::Hourly+ )+ }+ fn checkpoint_interval(self) -> &'static str {+ match self {+ Self::Tail23 => "25",+ Self::NoCkpt => "100000",+ _ => "10",+ }+ }+ /// Files written per fixture commit.+ fn files_per_commit(self) -> usize {+ match self {+ Self::Hourly => 40,+ Self::ManySmall => 4,+ _ => 1,+ }}fn files(self) -> usize {match self {- Self::Median => 60,+ Self::Median | Self::NoCkpt => 60,+ Self::Tail23 => 73,Self::Insert => 173,Self::SmallBig | Self::Mixed10k => 60,+ Self::ManySmall => 300,+ Self::Hourly => 2000,}}fn rows_per_file(self) -> usize {match self {- Self::Median => 200,+ Self::Median | Self::Tail23 | Self::NoCkpt | Self::ManySmall => 200,+ Self::Hourly => 50,Self::Insert => 5_000,Self::SmallBig | Self::Mixed10k => 20_000,}@@ -346,6 +427,8 @@ struct Args {probe_concurrency: usize,max_parallel_files: usize,dir: Option<PathBuf>,+ cold: bool,+ compact: bool,}fn parse_args() -> Args {@@ -356,10 +439,20 @@ fn parse_args() -> Args {probe_concurrency: 8,max_parallel_files: 4,dir: None,+ cold: false,+ compact: false,};// nosemgrep: rust.lang.security.args.argslet mut it = std::env::args().skip(1);while let Some(flag) = it.next() {+ if flag == "--cold" {+ args.cold = true;+ continue;+ }+ if flag == "--compact" {+ args.compact = true;+ continue;+ }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")),@@ -465,7 +558,7 @@ fn batch(RecordBatch::try_new(schema.clone(), cols).expect("batch")}-async fn create_table(uri: &str, partitioned: bool) -> deltalake::DeltaTable {+async fn create_table(uri: &str, partitioned: bool, interval: &str) -> deltalake::DeltaTable {let mut cols = vec![StructField::new("id", KernelType::STRING, true)];if partitioned {cols.push(StructField::new("p", KernelType::STRING, true));@@ -483,7 +576,7 @@ async fn create_table(uri: &str, partitioned: bool) -> deltalake::DeltaTable {let mut b = CreateBuilder::new().with_location(uri).with_columns(cols)- .with_configuration_property(deltalake::TableProperty::CheckpointInterval, Some("10"));+ .with_configuration_property(deltalake::TableProperty::CheckpointInterval, Some(interval));if partitioned {b = b.with_partition_columns(vec!["p".to_string()]);}@@ -493,13 +586,24 @@ async fn create_table(uri: &str, partitioned: bool) -> deltalake::DeltaTable {/// 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 table = create_table(uri, sc.partitioned(), sc.checkpoint_interval()).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 sc.partitioned() {+ if (f + 1) % sc.files_per_commit() == 0 || f + 1 == sc.files() {+ writer.flush_and_commit(&mut table).await.expect("commit");+ }+ } else {+ // One file per flush; several flushes per commit.+ if (f + 1) % sc.files_per_commit() == 0 || f + 1 == sc.files() {+ writer.flush_and_commit(&mut table).await.expect("commit");+ } else {+ writer.flush().await.expect("flush");+ }+ }if (f + 1) % 50 == 0 {eprintln!(" fixture: {} / {} files", f + 1, sc.files());}@@ -523,7 +627,22 @@ fn copy_tree(src: &std::path::Path, dst: &std::path::Path) {fn scenario_batch(sc: Scenario, schema: &SchemaRef, i: usize) -> RecordBatch {let rpf = sc.rows_per_file();match sc {- Scenario::Median => {+ Scenario::ManySmall => {+ let ids: Vec<usize> = (i * 50..(i + 1) * 50).collect();+ batch(schema, false, 0, &format!("new{i}"), &ids, 1000 + i)+ }+ Scenario::Hourly => {+ // 10 rows in each of 3 partitions. One batch per partition, concatenated.+ let parts: Vec<RecordBatch> = (0..3)+ .map(|k| {+ let p = (i * 3 + k) % sc.files();+ let ids: Vec<usize> = (p * rpf..p * rpf + 10).collect();+ batch(schema, true, p, "base", &ids, 1000 + i)+ })+ .collect();+ arrow_select::concat::concat_batches(schema, &parts).expect("concat")+ }+ Scenario::Median | Scenario::Tail23 | Scenario::NoCkpt => {let p = i % sc.files();let ids: Vec<usize> = (p * rpf..p * rpf + 34).collect();batch(schema, true, p, "base", &ids, 1000 + i)@@ -586,6 +705,10 @@ async fn main() {copy_tree(&dir, &run_dir);counted::register();counted::LATENCY_MS.store(args.latency_ms, std::sync::atomic::Ordering::Relaxed);+ counted::TRACE.store(+ std::env::var("UPSERT_IO_TRACE").is_ok(),+ std::sync::atomic::Ordering::Relaxed,+ );let uri = format!("counted://{}", run_dir.to_string_lossy());let so: HashMap<String, String> = HashMap::new();@@ -613,9 +736,10 @@ async fn main() {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",+ "open_handle gets {:4} ({:7.2} MB) heads {:3} lists {:3} writes {:3} wall {:8.1} ms",d.gets,d.get_bytes as f64 / 1e6,+ d.heads,d.lists,d.writes,open_ms@@ -636,10 +760,17 @@ async fn main() {"add","copied");+ let run_started = Instant::now();+ let run_c0 = counted::snapshot();for i in 0..args.iters {let b = scenario_batch(sc, &schema, i);let c = counted::snapshot();let t = Instant::now();+ if args.cold {+ handle = TableHandle::open(uri.clone(), so.clone())+ .await+ .expect("open");+ }let stats = handle.upsert(vec![b],@@ -668,6 +799,39 @@ async fn main() {stats.rows_copied,);}+ let d = counted::snapshot().delta(&run_c0);+ println!(+ "total{} gets {:5} ({:8.2} MB) heads {:3} lists {:4} writes {:4} wall {:9.1} ms",+ if args.cold { " (cold)" } else { " " },+ d.gets,+ d.get_bytes as f64 / 1e6,+ d.heads,+ d.lists,+ d.writes,+ ms(run_started)+ );+ if args.compact {+ let c = counted::snapshot();+ let t = Instant::now();+ let stats = handle+ .compact(+ deltalite_core::CompactOptions::default(),+ MultipartConfig::default(),+ )+ .await+ .expect("compact");+ let d = counted::snapshot().delta(&c);+ println!(+ "compact gets {:4} ({:7.2} MB) heads {:3} lists {:3} writes {:3} wall {:8.1} ms {:?}",+ d.gets,+ d.get_bytes as f64 / 1e6,+ d.heads,+ d.lists,+ d.writes,+ ms(t),+ stats+ );+ }// A refresh with nothing new to read: what one log refresh costs.let c = counted::snapshot();let t = Instant::now();diff --git a/rust/deltalite/core/src/compact.rs b/rust/deltalite/core/src/compact.rsindex 8b1653f34576..df304f83bb2a 100644--- a/rust/deltalite/core/src/compact.rs+++ b/rust/deltalite/core/src/compact.rs@@ -463,12 +463,16 @@ async fn read_bin(metadata: None,};let _file = ctx.limits.acquire_file().await?;- let builder = open_builder(&ctx.store, &target).await?;+ let (builder, held_fetch) = open_builder(&ctx.store, &target, &ctx.budgets).await?;let bytes_per_row = decoded_bytes_per_row(builder.metadata());- let _fetch = ctx- .budgets- .acquire_fetch(max_row_group_fetch_bytes(builder.metadata(), None))- .await?;+ let _fetch = match held_fetch {+ Some(fetch) => fetch,+ None => {+ ctx.budgets+ .acquire_fetch(max_row_group_fetch_bytes(builder.metadata(), None))+ .await?+ }+ };let batch_rows = byte_bounded_batch_rows(builder.metadata(),ctx.decode_batch_bytes,diff --git a/rust/deltalite/core/src/handle.rs b/rust/deltalite/core/src/handle.rsindex 335f3e3d7277..42745698c692 100644--- a/rust/deltalite/core/src/handle.rs+++ b/rust/deltalite/core/src/handle.rs@@ -9,18 +9,30 @@//! (`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.+//!+//! A refresh first asks whether there is anything to apply, with the log probe (see+//! [`crate::logprobe`]): one GET and one HEAD, issued together, in place of the LIST.+//! The probe is used only while it is proof. The handle lists the log when it has no+//! commit file to identify the table by, when the last LIST is older than the trust+//! window, and after its own commit on a checkpoint boundary. When the probe finds that+//! the table was replaced, the handle loads the table again.use std::collections::HashMap;use std::sync::Arc;-use std::time::Instant;+use std::time::{Duration, Instant};use arrow_array::RecordBatch;use arrow_schema::SchemaRef;+use deltalake::table::config::TablePropertiesExt as _;use deltalake::DeltaTable;+use metrics::counter;use crate::errors::{Error, Result};+use crate::limits::{env_switch, switch_setting};+use crate::logprobe::{check_anchor, commit_path, probe_log, trust_window, LogAnchor, LogProbe};use crate::prefetch::CheckpointCache;-use crate::table::{open_table_prefetched, wrap_multipart, MultipartConfig};+use crate::store::{CommitProbe, OPTIMISTIC_COMMIT_VERSION_ENV};+use crate::table::{open_table_prefetched, wrap_multipart_view, MultipartConfig};use crate::upsert::{upsert_cached_with_state, RelaxCache, UpsertOptions, UpsertStats};/// Conflict-retry budget for one upsert call. A concurrent writer can make delta-rs@@ -36,15 +48,13 @@ 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,- }+ switch_setting(value)}+/// Kill switch for the refresh that probes the log before it lists it; `0` restores the+/// LIST on every refresh.+pub const PROBE_REFRESH_ENV: &str = "DELTALITE_PROBE_REFRESH";+fn adopt_commit_snapshot_from_env() -> bool {adopt_commit_snapshot_setting(std::env::var(ADOPT_COMMIT_SNAPSHOT_ENV).ok().as_deref())}@@ -74,6 +84,16 @@ pub struct TableHandle {/// every load so a handle idling between upserts holds only its snapshot.prefetch: Arc<CheckpointCache>,adopt_commit_snapshot: bool,+ probe_refresh: bool,+ probe_commit: bool,+ /// A commit file that the last load or LIST-based refresh read. `None` when it read+ /// none, or the store gives no ETag; the handle then lists the log as before.+ anchor: Option<LogAnchor>,+ /// When the last load or LIST of the log started.+ listed_at: Instant,+ /// Set when this handle's own commit landed on a checkpoint boundary: the next+ /// refresh lists the log, so the snapshot moves onto the new checkpoint.+ list_on_next_refresh: bool,initial_open_ms: u64,initial_open_reported: bool,}@@ -83,6 +103,7 @@ impl TableHandle {pub async fn open(uri: String, storage_options: HashMap<String, String>) -> Result<Self> {let started = Instant::now();let (table, prefetch) = open_table_prefetched(&uri, storage_options.clone()).await?;+ let anchor = prefetch.take_anchor();prefetch.clear();Ok(Self {uri,@@ -91,6 +112,11 @@ impl TableHandle {relax_cache: RelaxCache::default(),prefetch,adopt_commit_snapshot: adopt_commit_snapshot_from_env(),+ probe_refresh: env_switch(PROBE_REFRESH_ENV),+ probe_commit: env_switch(OPTIMISTIC_COMMIT_VERSION_ENV),+ anchor,+ listed_at: started,+ list_on_next_refresh: false,initial_open_ms: started.elapsed().as_millis() as u64,initial_open_reported: false,})@@ -130,6 +156,16 @@ impl TableHandle {self.adopt_commit_snapshot = adopt;}+ /// Override the [`PROBE_REFRESH_ENV`] setting for this handle.+ pub fn set_probe_refresh(&mut self, probe: bool) {+ self.probe_refresh = probe;+ }++ /// Override the [`OPTIMISTIC_COMMIT_VERSION_ENV`] setting for this handle.+ pub fn set_probe_commit(&mut self, probe: bool) {+ self.probe_commit = probe;+ }+/// The table id from the snapshot's metadata action.pub fn table_id(&self) -> Result<String> {Ok(self.table.snapshot()?.metadata().id().to_string())@@ -176,23 +212,121 @@ impl TableHandle {/// 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.+ /// the incremental path fails or the table at this path is no longer the table that+ /// was loaded (it was deleted and created again).pub async fn refresh(&mut self) -> Result<()> {- if self.table.update_incremental(None).await.is_ok() {- self.prefetch.clear();- return Ok(());+ let result = self.refresh_snapshot().await;+ self.prefetch.clear();+ result+ }++ async fn refresh_snapshot(&mut self) -> Result<()> {+ let must_list = std::mem::take(&mut self.list_on_next_refresh);+ let anchor = self.anchor.clone().filter(|_| self.probe_refresh);+ let Some(anchor) = anchor else {+ counter!("deltalite_refresh_probe_total", "outcome" => "no_anchor").increment(1);+ return self.refresh_by_listing(None).await;+ };+ if must_list || self.trust_remaining().is_none() {+ counter!("deltalite_refresh_probe_total", "outcome" => "listed").increment(1);+ return self.refresh_by_listing(Some(&anchor)).await;+ }+ let outcome = self.probe(&anchor).await;+ counter!("deltalite_refresh_probe_total", "outcome" => outcome.label()).increment(1);+ match outcome {+ LogProbe::Current => Ok(()),+ LogProbe::Replaced => self.reload().await,+ // The probe checked the anchor, and its GET of the next commit is in the+ // load cache, so the LIST-based refresh does not fetch that commit again.+ LogProbe::NewCommits | LogProbe::Unknown => self.refresh_by_listing(None).await,}+ }++ async fn probe(&self, anchor: &LogAnchor) -> LogProbe {+ let Some(version) = self.table.version() else {+ return LogProbe::Unknown;+ };+ let log_store = self.table.log_store();+ let Some(next) = commit_path(log_store.as_ref(), version + 1) else {+ return LogProbe::Unknown;+ };+ probe_log(&log_store.root_object_store(None), &next, anchor).await+ }++ /// The LIST-based refresh. With `identity`, a HEAD of that commit file runs beside+ /// the LIST, because a LIST after the loaded version cannot see that the table was+ /// replaced by one with fewer versions.+ async fn refresh_by_listing(&mut self, identity: Option<&LogAnchor>) -> Result<()> {+ let started = Instant::now();+ let (identity, updated) = match identity {+ Some(anchor) => {+ let store = self.table.log_store().root_object_store(None);+ tokio::join!(+ check_anchor(&store, anchor),+ self.table.update_incremental(None)+ )+ }+ None => (LogProbe::Current, self.table.update_incremental(None).await),+ };+ if identity == LogProbe::Replaced || updated.is_err() {+ return self.reload().await;+ }+ self.listed_at = started;+ if let Some(anchor) = self.prefetch.take_anchor() {+ self.anchor = Some(anchor);+ }+ Ok(())+ }++ /// Load the table again from nothing.+ async fn reload(&mut self) -> Result<()> {+ let started = Instant::now();let (table, prefetch) =open_table_prefetched(&self.uri, self.storage_options.clone()).await?;+ self.anchor = prefetch.take_anchor();prefetch.clear();self.table = table;self.prefetch = prefetch;+ self.listed_at = started;// The old snapshot is gone; nothing the relax memo verified can be trusted.self.relax_cache = RelaxCache::default();Ok(())}+ /// How much longer a 404 for the next commit file proves that the commit was never+ /// written, or `None` when log cleanup could have removed it since the last LIST.+ fn trust_remaining(&self) -> Option<Duration> {+ let retention = self+ .table+ .snapshot()+ .ok()?+ .table_config()+ .log_retention_duration();+ trust_window(retention)+ .checked_sub(self.listed_at.elapsed())+ .filter(|left| !left.is_zero())+ }++ /// The probe that a commit through a view of this table may use in place of the+ /// LIST before its put. `None` restores the LIST.+ fn commit_probe(&self) -> Option<CommitProbe> {+ if !self.probe_commit {+ return None;+ }+ let anchor = self.anchor.clone()?;+ let deadline = Instant::now().checked_add(self.trust_remaining()?)?;+ Some(CommitProbe::new(anchor, deadline))+ }++ /// Whether the loaded version is one that post-commit maintenance checkpoints.+ fn on_checkpoint_boundary(&self) -> bool {+ let Ok(snapshot) = self.table.snapshot() else {+ return true;+ };+ let interval = snapshot.table_config().checkpoint_interval().get();+ (snapshot.version() + 1) % interval == 0+ }+/// Run one upsert, retrying data conflicts against a refreshed snapshot.////// Only data conflicts are retried. A concurrent schema/protocol change surfaces as@@ -205,6 +339,21 @@ impl TableHandle {source_schema: SchemaRef,opts: UpsertOptions,multipart: MultipartConfig,+ ) -> Result<UpsertStats> {+ let result = self+ .upsert_with_retries(source_batches, source_schema, opts, multipart)+ .await;+ // The views share this handle's load cache; no exit may leave log bytes in it.+ self.prefetch.clear();+ result+ }++ async fn upsert_with_retries(+ &mut self,+ source_batches: Vec<RecordBatch>,+ source_schema: SchemaRef,+ opts: UpsertOptions,+ multipart: MultipartConfig,) -> Result<UpsertStats> {let mut open_ms = 0u64;@@ -220,7 +369,7 @@ impl TableHandle {// 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);+ let view = wrap_multipart_view(self.table.clone(), multipart, self.commit_probe());match upsert_cached_with_state(&view,source_batches.clone(),@@ -249,6 +398,7 @@ impl TableHandle {if self.adopt_commit_snapshot {self.table.state = Some(state);self.prefetch.clear();+ self.list_on_next_refresh = self.on_checkpoint_boundary();} else {self.refresh().await?;}@@ -270,12 +420,13 @@ impl TableHandle {multipart: MultipartConfig,) -> Result<crate::compact::CompactStats> {self.refresh().await?;- let view = wrap_multipart(self.table.clone(), multipart);- let (stats, state) = crate::compact::compact(&view, opts).await?;+ let view = wrap_multipart_view(self.table.clone(), multipart, self.commit_probe());+ let result = crate::compact::compact(&view, opts).await;+ self.prefetch.clear();+ let (stats, state) = result?;if let Some(state) = state {if self.adopt_commit_snapshot {self.table.state = Some(state);- self.prefetch.clear();} else {self.refresh().await?;}diff --git a/rust/deltalite/core/src/lib.rs b/rust/deltalite/core/src/lib.rsindex 914aa6efa04e..15f93945c8ae 100644--- a/rust/deltalite/core/src/lib.rs+++ b/rust/deltalite/core/src/lib.rs@@ -33,9 +33,11 @@ pub mod compact;pub mod errors;pub mod handle;pub mod limits;+mod logprobe;pub mod pkset;pub mod prefetch;pub mod schema;+mod smallfile;mod stats;pub mod store;pub mod table;diff --git a/rust/deltalite/core/src/limits.rs b/rust/deltalite/core/src/limits.rsindex de2db10cf123..9a699f067810 100644--- a/rust/deltalite/core/src/limits.rs+++ b/rust/deltalite/core/src/limits.rs@@ -74,6 +74,23 @@ pub(crate) fn env_usize(name: &str, default: usize) -> usize {}}+/// Whether the setting `value` of an on/off kill switch keeps the feature on: `0`,+/// `false`, `off` and `no` turn it off; unset or any other value keeps it on.+pub(crate) fn switch_setting(value: Option<&str>) -> bool {+ match value {+ Some(v) => !matches!(+ v.trim().to_ascii_lowercase().as_str(),+ "0" | "false" | "off" | "no"+ ),+ None => true,+ }+}++/// [`switch_setting`] of the environment variable `name`.+pub(crate) fn env_switch(name: &str) -> bool {+ switch_setting(std::env::var(name).ok().as_deref())+}+impl ProcessLimits {/// Build limits with explicit capacities and the default fetch budget. Zero/// capacities are clamped to 1 (a zero-permit semaphore would deadlock every upsertdiff --git a/rust/deltalite/core/src/logprobe.rs b/rust/deltalite/core/src/logprobe.rsnew file mode 100644index 000000000000..eaafaa1121ff--- /dev/null+++ b/rust/deltalite/core/src/logprobe.rs@@ -0,0 +1,225 @@+//! A check that the loaded snapshot is current, without a LIST of `_delta_log/`.+//!+//! Two requests, issued together, replace the listing:+//!+//! - a GET of the commit file after the loaded version. Delta versions are contiguous+//! and a commit file is never written twice, so a 404 for `version + 1` proves that+//! no newer version exists.+//! - a HEAD of a commit file that the last load read (the [`LogAnchor`]). A table that+//! was deleted and created again also answers 404 for `version + 1`, but its log+//! holds other objects, so the anchor is absent or has another ETag.+//!+//! The 404 is proof only while log cleanup cannot have removed `version + 1`. Cleanup+//! removes a commit file when it is older than the table's log retention, so the caller+//! must stop trusting the probe long before that time has passed since it last listed+//! the log (see [`trust_window`]).+//!+//! The probe depends on a store that answers a GET or HEAD with the current state of the+//! object: S3 (strongly consistent for reads after a write or a delete), the local file+//! system and the in-memory store. A store or a cache in front of it that can answer 404+//! for an object that exists must run with `DELTALITE_PROBE_REFRESH=0`.++use std::sync::Arc;+use std::time::Duration;++use chrono::{DateTime, Utc};+use deltalake::logstore::LogStore;+use object_store::path::Path;+use object_store::{ObjectMeta, ObjectStore, ObjectStoreExt};++/// The longest time the probe is trusted after the last LIST of the log.+pub(crate) const MAX_TRUST_WINDOW: Duration = Duration::from_secs(600);++/// How long after a LIST the probe is proof, for a table with log retention `retention`.+/// Half the retention leaves a margin for clock differences between the writers, and+/// [`MAX_TRUST_WINDOW`] bounds the time that an error in this argument can stay hidden.+pub(crate) fn trust_window(retention: Duration) -> Duration {+ (retention / 2).min(MAX_TRUST_WINDOW)+}++/// The identity of one commit file as the store reported it on a read.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct LogAnchor {+ pub(crate) version: u64,+ pub(crate) path: Path,+ pub(crate) e_tag: String,+ pub(crate) last_modified: DateTime<Utc>,+}++impl LogAnchor {+ /// The anchor for the commit file that `meta` describes. `None` when the path is not+ /// a commit file or the store gives no ETag, because then nothing identifies the+ /// object.+ pub(crate) fn from_meta(meta: &ObjectMeta) -> Option<Self> {+ Some(Self {+ version: commit_version(&meta.location)?,+ path: meta.location.clone(),+ e_tag: meta.e_tag.clone()?,+ last_modified: meta.last_modified,+ })+ }++ fn matches(&self, meta: &ObjectMeta) -> bool {+ meta.e_tag.as_deref() == Some(self.e_tag.as_str())+ && meta.last_modified == self.last_modified+ }+}++/// What the probe found.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum LogProbe {+ /// The table is the one that was loaded and it has no newer version.+ Current,+ /// The table is the one that was loaded and it has a newer version.+ NewCommits,+ /// The anchor is gone or is another object: the table was replaced, or cleanup+ /// removed the anchor. The loaded snapshot must not be used.+ Replaced,+ /// A request failed. The caller must use the LIST.+ Unknown,+}++impl LogProbe {+ /// Static metric label.+ pub(crate) fn label(self) -> &'static str {+ match self {+ LogProbe::Current => "current",+ LogProbe::NewCommits => "new_commits",+ LogProbe::Replaced => "replaced",+ LogProbe::Unknown => "unknown",+ }+ }+}++/// Whether the table still holds the object that `anchor` describes.+pub(crate) async fn check_anchor(store: &Arc<dyn ObjectStore>, anchor: &LogAnchor) -> LogProbe {+ match store.head(&anchor.path).await {+ Ok(meta) if anchor.matches(&meta) => LogProbe::Current,+ Ok(_) | Err(object_store::Error::NotFound { .. }) => LogProbe::Replaced,+ Err(_) => LogProbe::Unknown,+ }+}++/// GET `next_commit` (the commit file after the loaded version) and check `anchor`, in+/// one round trip.+pub(crate) async fn probe_log(+ store: &Arc<dyn ObjectStore>,+ next_commit: &Path,+ anchor: &LogAnchor,+) -> LogProbe {+ let (next, identity) = tokio::join!(store.get(next_commit), check_anchor(store, anchor));+ match (identity, next) {+ (LogProbe::Current, Err(object_store::Error::NotFound { .. })) => LogProbe::Current,+ (LogProbe::Current, Ok(_)) => LogProbe::NewCommits,+ (LogProbe::Current, Err(_)) => LogProbe::Unknown,+ (other, _) => other,+ }+}++/// The store path of the commit file for `version` under `log_store`'s log root.+pub(crate) fn commit_path(log_store: &dyn LogStore, version: u64) -> Option<Path> {+ let root = Path::from_url_path(log_store.root_url().path()).ok()?;+ Some(root.join("_delta_log").join(format!("{version:020}.json")))+}++/// The version that a commit file path names: `_delta_log/<20 digits>.json`.+pub(crate) fn commit_version(location: &Path) -> Option<u64> {+ let in_log = location.parts().any(|part| part.as_ref() == "_delta_log");+ let name = location.filename()?;+ let digits = name.strip_suffix(".json")?;+ if !in_log || digits.len() != 20 || !digits.bytes().all(|b| b.is_ascii_digit()) {+ return None;+ }+ digits.parse().ok()+}++#[cfg(test)]+mod tests {+ use bytes::Bytes;+ use object_store::memory::InMemory;+ use object_store::PutPayload;++ use super::*;++ const ANCHOR: &str = "t/_delta_log/00000000000000000004.json";+ const NEXT: &str = "t/_delta_log/00000000000000000006.json";++ async fn put(store: &Arc<dyn ObjectStore>, path: &str, body: &'static str) {+ store+ .put(&Path::from(path), PutPayload::from_bytes(Bytes::from(body)))+ .await+ .unwrap();+ }++ async fn anchored() -> (Arc<dyn ObjectStore>, LogAnchor) {+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());+ put(&store, ANCHOR, "four").await;+ let meta = store.head(&Path::from(ANCHOR)).await.unwrap();+ (store, LogAnchor::from_meta(&meta).unwrap())+ }++ async fn probe(store: &Arc<dyn ObjectStore>, anchor: &LogAnchor) -> LogProbe {+ probe_log(store, &Path::from(NEXT), anchor).await+ }++ #[test]+ fn only_commit_files_have_a_version() {+ for (path, version) in [+ ("t/_delta_log/00000000000000000004.json", Some(4)),+ ("_delta_log/00000000000000012345.json", Some(12345)),+ ("t/_delta_log/00000000000000000004.checkpoint.parquet", None),+ ("t/_delta_log/_last_checkpoint", None),+ ("t/_delta_log/0000000000000000004.json", None),+ ("t/_delta_log/0000000000000000000a.json", None),+ ("t/p=1/00000000000000000004.json", None),+ ] {+ assert_eq!(commit_version(&Path::from(path)), version, "{path}");+ }+ }++ #[test]+ fn an_object_without_an_etag_is_no_anchor() {+ let meta = ObjectMeta {+ location: Path::from(ANCHOR),+ last_modified: Utc::now(),+ size: 4,+ e_tag: None,+ version: None,+ };+ assert_eq!(LogAnchor::from_meta(&meta), None);+ }++ #[test]+ fn the_trust_window_follows_a_short_retention() {+ let day = Duration::from_secs(86_400);+ assert_eq!(trust_window(30 * day), MAX_TRUST_WINDOW);+ assert_eq!(+ trust_window(Duration::from_secs(60)),+ Duration::from_secs(30)+ );+ assert_eq!(trust_window(Duration::ZERO), Duration::ZERO);+ }++ #[tokio::test]+ async fn an_untouched_log_is_current_until_the_next_commit_exists() {+ let (store, anchor) = anchored().await;+ assert_eq!(probe(&store, &anchor).await, LogProbe::Current);+ put(&store, NEXT, "six").await;+ assert_eq!(probe(&store, &anchor).await, LogProbe::NewCommits);+ }++ #[tokio::test]+ async fn a_deleted_or_rewritten_anchor_is_a_replaced_table() {+ let (store, anchor) = anchored().await;+ put(&store, ANCHOR, "another table").await;+ assert_eq!(probe(&store, &anchor).await, LogProbe::Replaced);+ put(&store, NEXT, "six").await;+ assert_eq!(+ probe(&store, &anchor).await,+ LogProbe::Replaced,+ "a newer commit of another table must not look like progress"+ );+ store.delete(&Path::from(ANCHOR)).await.unwrap();+ assert_eq!(check_anchor(&store, &anchor).await, LogProbe::Replaced);+ }+}diff --git a/rust/deltalite/core/src/prefetch.rs b/rust/deltalite/core/src/prefetch.rsindex 0513a56c400e..5f9ecbbf3c59 100644--- a/rust/deltalite/core/src/prefetch.rs+++ b/rust/deltalite/core/src/prefetch.rs@@ -1,4 +1,5 @@-//! Whole-object prefetch for Delta checkpoint Parquet files.+//! Whole-object prefetch for Delta checkpoint Parquet files, and a per-load memory of+//! commit JSON files.//!//! A snapshot load reads the latest checkpoint through the kernel's Parquet reader, which//! issues one ranged GET for the footer, one for the metadata and one per column chunk it@@ -15,9 +16,22 @@//! limit also bounds the aggregate cache for one load, while the process-wide byte budget//! bounds concurrent loads. [`crate::handle::TableHandle`] clears the cache after every//! open and refresh so a long-lived handle does not pin checkpoint bytes between upserts.+//!+//! The same cache holds the commit JSON files of one load. The kernel reads each commit+//! after the checkpoint two times, and the update after a commit reads the commit that+//! this process wrote a moment before; both second reads are served from memory. A commit+//! file is written with a create-only put by every writer and is never written again, so+//! the copy is exact for as long as the table at this path is the same table. The cache+//! therefore lives for one operation of one handle: the handle clears it when the+//! operation ends, a table that is opened again gets a new cache, and a table opened+//! without a handle stops caching commits when its load ends. The commit entries are+//! bounded by [`MAX_CACHED_COMMITS`], [`MAX_CACHED_COMMIT_BYTES`] and+//! [`MAX_CACHED_COMMIT_FILE_BYTES`], and their bytes count against the same two budgets+//! as the checkpoint bytes. A commit that does not fit is read as before.use std::collections::HashMap;use std::ops::Range;+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};use async_trait::async_trait;@@ -36,7 +50,8 @@ use tokio::sync::{OnceCell, OwnedSemaphorePermit, Semaphore};use tracing::debug;use uuid::Uuid;-use crate::limits::ProcessLimits;+use crate::limits::{env_switch, ProcessLimits};+use crate::logprobe::{commit_path, commit_version, LogAnchor};/// Largest checkpoint object fetched whole by default. A checkpoint this size describes/// a table with hundreds of thousands of live files, whose snapshot the kernel holds in@@ -56,6 +71,19 @@ pub fn is_checkpoint_file(location: &Path) -> bool {in_log && name.ends_with(".parquet") && name.contains(".checkpoint.")}+/// Kill switch for the commit JSON memory; `0` restores one GET for each read of a+/// commit file.+pub const COMMIT_JSON_CACHE_ENV: &str = "DELTALITE_COMMIT_JSON_CACHE";++/// Most commit files held at one time. A log tail is as long as the table's checkpoint+/// interval at most, so only a table without a checkpoint has more.+pub const MAX_CACHED_COMMITS: usize = 256;+/// Most commit bytes held at one time.+pub const MAX_CACHED_COMMIT_BYTES: u64 = 8 * 1024 * 1024;+/// Largest commit file held. A larger commit keeps its stream, so it is never in memory+/// as one buffer.+pub const MAX_CACHED_COMMIT_FILE_BYTES: u64 = 1024 * 1024;+#[derive(Debug, Clone)]enum Fetched {Cached {@@ -75,11 +103,22 @@ enum Fetched {/// an occupied budget falls back to range reads so multipart loads cannot deadlock.#[derive(Debug)]pub struct CheckpointCache {+ cache_commits: AtomicBool,max_bytes: u64,budget: Arc<Semaphore>,budget_kb: u32,process_limits: Arc<ProcessLimits>,- entries: Mutex<HashMap<Path, Arc<OnceCell<Fetched>>>>,+ entries: Mutex<Entries>,+ /// The newest commit file that a read through this cache returned.+ anchor: Mutex<Option<LogAnchor>>,+}++#[derive(Debug, Default)]+struct Entries {+ cells: HashMap<Path, Arc<OnceCell<Fetched>>>,+ /// Commit files with a cell, and the bytes admitted for them.+ commits: usize,+ commit_bytes: u64,}impl CheckpointCache {@@ -92,11 +131,13 @@ impl CheckpointCache {fn with_process_limits(max_bytes: u64, process_limits: Arc<ProcessLimits>) -> Self {let budget_kb = max_bytes.div_ceil(1024).clamp(1, u32::MAX as u64) as u32;Self {+ cache_commits: AtomicBool::new(max_bytes > 0 && env_switch(COMMIT_JSON_CACHE_ENV)),max_bytes,budget: Arc::new(Semaphore::new(budget_kb as usize)),budget_kb,process_limits,- entries: Mutex::new(HashMap::new()),+ entries: Mutex::new(Entries::default()),+ anchor: Mutex::new(None),}}@@ -124,12 +165,13 @@ impl CheckpointCache {/// Drop every cached object.pub fn clear(&self) {- self.lock().clear();+ *self.lock() = Entries::default();}/// Bytes currently held (for observability and tests).pub fn cached_bytes(&self) -> u64 {self.lock()+ .cells.values().filter_map(|cell| match cell.get() {Some(Fetched::Cached { bytes, .. }) => Some(bytes.len() as u64),@@ -138,7 +180,103 @@ impl CheckpointCache {.sum()}- fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<Path, Arc<OnceCell<Fetched>>>> {+ /// Number of commit files with an entry (for observability and tests).+ pub fn cached_commits(&self) -> usize {+ self.lock().commits+ }++ /// Whether commit JSON files are served from this cache.+ pub fn caches_commits(&self) -> bool {+ self.cache_commits.load(Ordering::Relaxed)+ }++ /// Stop holding commit files, for a table that no handle clears after each+ /// operation. Entries already held stay until [`CheckpointCache::clear`].+ pub fn stop_caching_commits(&self) {+ self.cache_commits.store(false, Ordering::Relaxed);+ }++ /// Take the identity of the newest commit file read through this cache since the+ /// last call.+ pub(crate) fn take_anchor(&self) -> Option<LogAnchor> {+ self.anchor+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .take()+ }++ fn note_commit(&self, meta: &ObjectMeta) {+ let Some(seen) = LogAnchor::from_meta(meta) else {+ return;+ };+ let mut anchor = self+ .anchor+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ if anchor.as_ref().is_none_or(|a| a.version <= seen.version) {+ *anchor = Some(seen);+ }+ }++ /// Store the bytes of a commit this process wrote, so the update after the commit+ /// reads them from memory. The create-only put succeeded, so the object holds+ /// exactly these bytes.+ pub(crate) fn seed(&self, location: Path, bytes: Bytes) {+ if !self.caches_commits() {+ return;+ }+ let Some(cell) = self.commit_cell(&location) else {+ return;+ };+ let Some((_cache_permit, _process_permit)) = self.admit_commit(bytes.len() as u64) else {+ return;+ };+ let meta = ObjectMeta {+ location,+ last_modified: chrono::Utc::now(),+ size: bytes.len() as u64,+ e_tag: None,+ version: None,+ };+ drop(cell.set(Fetched::Cached {+ meta,+ bytes,+ _cache_permit,+ _process_permit,+ }));+ }++ /// The cell for a commit file, or `None` when [`MAX_CACHED_COMMITS`] files have one.+ fn commit_cell(&self, location: &Path) -> Option<Arc<OnceCell<Fetched>>> {+ let mut entries = self.lock();+ if let Some(cell) = entries.cells.get(location) {+ return Some(cell.clone());+ }+ if entries.commits >= MAX_CACHED_COMMITS {+ return None;+ }+ entries.commits += 1;+ Some(entries.cells.entry(location.clone()).or_default().clone())+ }++ /// Reserve room for `bytes` of one commit file under every bound, without waiting.+ fn admit_commit(+ &self,+ bytes: u64,+ ) -> Option<(Arc<OwnedSemaphorePermit>, Arc<OwnedSemaphorePermit>)> {+ if bytes > MAX_CACHED_COMMIT_FILE_BYTES {+ return None;+ }+ let permits = self.try_reserve(bytes)?;+ let mut entries = self.lock();+ if entries.commit_bytes + bytes > MAX_CACHED_COMMIT_BYTES {+ return None;+ }+ entries.commit_bytes += bytes;+ Some(permits)+ }++ fn lock(&self) -> std::sync::MutexGuard<'_, Entries> {// A poisoned map only means another reader panicked mid-insert; the entries are// plain values, so continuing is safe.self.entries@@ -147,7 +285,11 @@ impl CheckpointCache {}fn cell(&self, location: &Path) -> Arc<OnceCell<Fetched>> {- self.lock().entry(location.clone()).or_default().clone()+ self.lock()+ .cells+ .entry(location.clone())+ .or_default()+ .clone()}/// Record that `location` is too large without touching the store. A ranged read@@ -239,9 +381,8 @@ impl CheckpointPrefetchStore {/// Only plain reads are served from memory; HEAD and preconditioned or versioned/// reads carry semantics the cached copy cannot honour.- fn serves(&self, location: &Path, options: &GetOptions) -> bool {- is_checkpoint_file(location)- && !options.head+ fn plain(options: &GetOptions) -> bool {+ !options.head&& options.if_match.is_none()&& options.if_none_match.is_none()&& options.if_modified_since.is_none()@@ -249,6 +390,65 @@ impl CheckpointPrefetchStore {&& options.version.is_none()}+ fn serves(&self, location: &Path, options: &GetOptions) -> bool {+ is_checkpoint_file(location) && Self::plain(options)+ }++ fn whole(meta: ObjectMeta, bytes: Bytes) -> GetResult {+ let range = 0..bytes.len() as u64;+ GetResult {+ payload: GetResultPayload::Stream(+ futures::stream::once(async move { Ok(bytes) }).boxed(),+ ),+ meta,+ range,+ attributes: Attributes::default(),+ }+ }++ /// A whole read of a commit file: from memory when this load read or wrote it+ /// before, else one GET whose bytes are kept when they fit the bounds.+ async fn get_commit(&self, location: &Path) -> object_store::Result<GetResult> {+ let Some(cell) = self.cache.commit_cell(location) else {+ return self.get_commit_uncached(location).await;+ };+ // The GET of the caller that found the cell empty. When its bytes are not kept,+ // that caller still gets the response, so no request is made twice.+ let mut unkept: Option<GetResult> = None;+ let fetched = cell+ .get_or_try_init(|| async {+ let result = self.inner.get_opts(location, GetOptions::default()).await?;+ self.cache.note_commit(&result.meta);+ let Some((_cache_permit, _process_permit)) =+ self.cache.admit_commit(result.meta.size)+ else {+ unkept = Some(result);+ return Ok::<_, object_store::Error>(Fetched::TooLarge);+ };+ let meta = result.meta.clone();+ let bytes = result.bytes().await?;+ Ok(Fetched::Cached {+ meta,+ bytes,+ _cache_permit,+ _process_permit,+ })+ })+ .await?+ .clone();+ match (fetched, unkept) {+ (Fetched::Cached { meta, bytes, .. }, _) => Ok(Self::whole(meta, bytes)),+ (Fetched::TooLarge, Some(result)) => Ok(result),+ (Fetched::TooLarge, None) => self.get_commit_uncached(location).await,+ }+ }++ async fn get_commit_uncached(&self, location: &Path) -> object_store::Result<GetResult> {+ let result = self.inner.get_opts(location, GetOptions::default()).await?;+ self.cache.note_commit(&result.meta);+ Ok(result)+ }+fn resolve(range: Option<&GetRange>, len: u64) -> Range<u64> {match range {None => 0..len,@@ -298,6 +498,13 @@ impl ObjectStore for CheckpointPrefetchStore {location: &Path,options: GetOptions,) -> object_store::Result<GetResult> {+ if commit_version(location).is_some() && Self::plain(&options) && options.range.is_none() {+ return if self.cache.caches_commits() {+ self.get_commit(location).await+ } else {+ self.get_commit_uncached(location).await+ };+ }if !self.serves(location, &options) {return self.inner.get_opts(location, options).await;}@@ -437,9 +644,18 @@ impl LogStore for CheckpointPrefetchLogStore {commit_or_bytes: CommitOrBytes,operation_id: Uuid,) -> Result<(), TransactionError> {+ // `Bytes` is reference counted: this is the buffer that is put, not a copy.+ let written = match &commit_or_bytes {+ CommitOrBytes::LogBytes(bytes) if self.cache.caches_commits() => Some(bytes.clone()),+ _ => None,+ };self.inner.write_commit_entry(version, commit_or_bytes, operation_id)- .await+ .await?;+ if let (Some(bytes), Some(path)) = (written, commit_path(self.inner.as_ref(), version)) {+ self.cache.seed(path, bytes);+ }+ Ok(())}async fn abort_commit_entry(@@ -818,4 +1034,143 @@ mod tests {assert_eq!(gets(&counting), 2, "every range passes straight through");assert_eq!(store.cache.cached_bytes(), 0);}++ fn commit(version: u64) -> Path {+ Path::from(format!("bucket/table/_delta_log/{version:020}.json"))+ }++ async fn commit_fixture(sizes: &[usize]) -> (Arc<Counting>, CheckpointPrefetchStore) {+ let counting = Arc::new(Counting {+ inner: InMemory::new(),+ gets: AtomicUsize::new(0),+ });+ for (version, size) in sizes.iter().enumerate() {+ counting+ .put(&commit(version as u64), PutPayload::from_bytes(body(*size)))+ .await+ .unwrap();+ }+ let store = CheckpointPrefetchStore::new(+ counting.clone(),+ Arc::new(CheckpointCache::new(u64::MAX)),+ );+ (counting, store)+ }++ async fn read_all(store: &CheckpointPrefetchStore, sizes: &[usize]) {+ for (version, size) in sizes.iter().enumerate() {+ let got = store.get(&commit(version as u64)).await.unwrap();+ assert_eq!(got.bytes().await.unwrap(), body(*size), "commit {version}");+ }+ }++ #[tokio::test]+ async fn the_second_read_of_a_commit_is_from_memory_until_the_cache_is_cleared() {+ let (counting, store) = commit_fixture(&[100, 200]).await;++ read_all(&store, &[100, 200]).await;+ read_all(&store, &[100, 200]).await;+ assert_eq!(gets(&counting), 2);+ assert_eq!(store.cache.cached_commits(), 2);+ assert_eq!(store.cache.cached_bytes(), 300);++ store.cache.clear();+ assert_eq!(store.cache.cached_commits(), 0);+ read_all(&store, &[100, 200]).await;+ assert_eq!(gets(&counting), 4);++ store.cache.stop_caching_commits();+ store.cache.clear();+ read_all(&store, &[100, 200]).await;+ read_all(&store, &[100, 200]).await;+ assert_eq!(+ gets(&counting),+ 8,+ "one GET for each read when the cache is off"+ );+ assert_eq!(store.cache.cached_bytes(), 0);+ }++ #[tokio::test]+ async fn the_commit_cache_holds_a_bounded_number_of_files() {+ let sizes = vec![10usize; MAX_CACHED_COMMITS + 5];+ let (counting, store) = commit_fixture(&sizes).await;++ read_all(&store, &sizes).await;+ read_all(&store, &sizes).await;++ assert_eq!(store.cache.cached_commits(), MAX_CACHED_COMMITS);+ assert_eq!(+ gets(&counting),+ sizes.len() + 5,+ "a file past the bound is read as before, and never more than two times"+ );+ }++ #[tokio::test]+ async fn the_commit_cache_holds_a_bounded_number_of_bytes() {+ let file = MAX_CACHED_COMMIT_FILE_BYTES as usize;+ let fit = (MAX_CACHED_COMMIT_BYTES / MAX_CACHED_COMMIT_FILE_BYTES) as usize;+ let mut sizes = vec![file; fit + 2];+ sizes.push(file + 1);+ let (counting, store) = commit_fixture(&sizes).await;++ read_all(&store, &sizes).await;+ assert_eq!(+ gets(&counting),+ sizes.len(),+ "a file that is not kept costs one GET"+ );+ assert_eq!(store.cache.cached_bytes(), MAX_CACHED_COMMIT_BYTES);++ read_all(&store, &sizes).await;+ assert_eq!(gets(&counting), sizes.len() + 3);+ assert_eq!(store.cache.cached_bytes(), MAX_CACHED_COMMIT_BYTES);+ }++ #[tokio::test]+ async fn a_missing_commit_is_not_remembered() {+ let (counting, store) = commit_fixture(&[10]).await;+ let next = commit(1);++ let missing = store.get(&next).await;+ assert!(matches!(missing, Err(object_store::Error::NotFound { .. })));+ counting+ .put(&next, PutPayload::from_bytes(body(20)))+ .await+ .unwrap();++ let got = store.get(&next).await.unwrap().bytes().await.unwrap();+ assert_eq!(got, body(20));+ }++ #[tokio::test]+ async fn a_written_commit_is_read_from_memory_and_gives_no_anchor() {+ let (counting, store) = commit_fixture(&[10]).await;+ store.cache.seed(commit(1), body(30));++ let got = store.get(&commit(1)).await.unwrap().bytes().await.unwrap();+ assert_eq!(got, body(30));+ assert_eq!(gets(&counting), 0);+ assert_eq!(store.cache.take_anchor(), None);+ }++ #[tokio::test]+ async fn the_anchor_is_the_newest_commit_read_with_or_without_the_cache() {+ for cached in [true, false] {+ let (counting, store) = commit_fixture(&[10, 20, 30]).await;+ if !cached {+ store.cache.stop_caching_commits();+ }+ for version in [2, 0, 1] {+ store.get(&commit(version)).await.unwrap();+ }+ let head = counting.head(&commit(2)).await.unwrap();++ let anchor = store.cache.take_anchor().expect("anchor");+ assert_eq!(anchor.version, 2, "cached={cached}");+ assert_eq!(Some(anchor.e_tag), head.e_tag);+ assert_eq!(store.cache.take_anchor(), None, "taken once");+ }+ }}diff --git a/rust/deltalite/core/src/smallfile.rs b/rust/deltalite/core/src/smallfile.rsnew file mode 100644index 000000000000..6d5d51200e1e--- /dev/null+++ b/rust/deltalite/core/src/smallfile.rs@@ -0,0 +1,252 @@+//! One-request reads of small data files.+//!+//! A data file is opened with a read of its last `FOOTER_SIZE_HINT` bytes. For a file no+//! larger than the hint, that read already returns the whole file, and the range read+//! that follows (the PK columns for the probe, every column for a rewrite or a+//! compaction) fetches bytes that the process had a moment before.+//! [`fetch_small_file`] makes the one request explicit and [`SmallFileStore`] serves the+//! reader of that file from the same bytes.+//!+//! The file size comes from the Add action in the Delta log, never from a HEAD. The+//! bytes belong to one reader and are dropped with it. That reader takes its fetch+//! permit for the whole file before the request, so the bytes are inside the fetch+//! budget from the first one, and the row groups that the reader decodes are slices of+//! the same buffer. Data files are immutable (a new file gets a new name), so the bytes+//! cannot be stale.++use std::ops::Range;+use std::sync::Arc;++use async_trait::async_trait;+use bytes::Bytes;+use futures::stream::{BoxStream, StreamExt};+use object_store::path::Path;+use object_store::{+ Attributes, GetOptions, GetRange, GetResult, GetResultPayload, ListResult, MultipartUpload,+ ObjectMeta, ObjectStore, PutMultipartOptions, PutOptions, PutPayload, PutResult,+};++/// Kill switch; `0` restores the footer read and the range reads.+pub const SMALL_FILE_SINGLE_GET_ENV: &str = "DELTALITE_SMALL_FILE_SINGLE_GET";++/// A small data file held in memory: its bytes and the object metadata of the read.+#[derive(Debug, Clone)]+pub(crate) struct SmallFile {+ meta: ObjectMeta,+ bytes: Bytes,+}++/// Whether a file of `size` bytes is read in one request, given the footer read size.+pub(crate) fn reads_whole(size: u64, footer_hint: u64) -> bool {+ size > 0 && size <= footer_hint && crate::limits::env_switch(SMALL_FILE_SINGLE_GET_ENV)+}++/// Read all of `path` in one request. `size` is the size that the Delta log records;+/// `None` when the object does not hold exactly that many bytes, and the caller then+/// opens the file by ranges as before.+pub(crate) async fn fetch_small_file(+ store: &Arc<dyn ObjectStore>,+ path: &Path,+ size: u64,+) -> object_store::Result<Option<SmallFile>> {+ let options = GetOptions {+ range: Some(GetRange::Bounded(0..size)),+ ..Default::default()+ };+ let result = store.get_opts(path, options).await?;+ let meta = result.meta.clone();+ if meta.size != size {+ return Ok(None);+ }+ let bytes = result.bytes().await?;+ Ok((bytes.len() as u64 == size).then_some(SmallFile { meta, bytes }))+}++/// Serves plain reads of one path from memory and delegates everything else.+#[derive(Debug)]+pub(crate) struct SmallFileStore {+ inner: Arc<dyn ObjectStore>,+ path: Path,+ file: SmallFile,+}++impl SmallFileStore {+ pub(crate) fn new(inner: Arc<dyn ObjectStore>, path: Path, file: SmallFile) -> Self {+ Self { inner, path, file }+ }++ fn clamp(&self, range: &Range<u64>) -> Range<u64> {+ let len = self.file.bytes.len() as u64;+ let start = range.start.min(len);+ start..range.end.min(len).max(start)+ }++ fn slice(&self, range: &Range<u64>) -> Bytes {+ self.file+ .bytes+ .slice(range.start as usize..range.end as usize)+ }+}++impl std::fmt::Display for SmallFileStore {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "SmallFileStore({})", self.inner)+ }+}++#[async_trait]+impl ObjectStore for SmallFileStore {+ 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> {+ let plain = !options.head+ && options.if_match.is_none()+ && options.if_none_match.is_none()+ && options.if_modified_since.is_none()+ && options.if_unmodified_since.is_none()+ && options.version.is_none();+ if location != &self.path || !plain {+ return self.inner.get_opts(location, options).await;+ }+ let len = self.file.bytes.len() as u64;+ let range = match options.range.as_ref() {+ None => 0..len,+ Some(GetRange::Bounded(r)) => self.clamp(r),+ Some(GetRange::Offset(offset)) => (*offset).min(len)..len,+ Some(GetRange::Suffix(n)) => len.saturating_sub(*n)..len,+ };+ let slice = self.slice(&range);+ Ok(GetResult {+ payload: GetResultPayload::Stream(+ futures::stream::once(async move { Ok(slice) }).boxed(),+ ),+ meta: self.file.meta.clone(),+ range,+ attributes: Attributes::default(),+ })+ }++ async fn get_ranges(+ &self,+ location: &Path,+ ranges: &[Range<u64>],+ ) -> object_store::Result<Vec<Bytes>> {+ if location != &self.path {+ return self.inner.get_ranges(location, ranges).await;+ }+ Ok(ranges.iter().map(|r| self.slice(&self.clamp(r))).collect())+ }++ fn delete_stream(+ &self,+ locations: BoxStream<'static, object_store::Result<Path>>,+ ) -> BoxStream<'static, object_store::Result<Path>> {+ self.inner.delete_stream(locations)+ }++ fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, object_store::Result<ObjectMeta>> {+ self.inner.list(prefix)+ }++ fn list_with_offset(+ &self,+ prefix: Option<&Path>,+ offset: &Path,+ ) -> BoxStream<'static, object_store::Result<ObjectMeta>> {+ self.inner.list_with_offset(prefix, offset)+ }++ async fn list_with_delimiter(&self, prefix: Option<&Path>) -> object_store::Result<ListResult> {+ self.inner.list_with_delimiter(prefix).await+ }++ async fn copy_opts(+ &self,+ from: &Path,+ to: &Path,+ options: object_store::CopyOptions,+ ) -> object_store::Result<()> {+ self.inner.copy_opts(from, to, options).await+ }++ async fn rename_opts(+ &self,+ from: &Path,+ to: &Path,+ options: object_store::RenameOptions,+ ) -> object_store::Result<()> {+ self.inner.rename_opts(from, to, options).await+ }+}++#[cfg(test)]+mod tests {+ use object_store::memory::InMemory;+ use object_store::ObjectStoreExt;++ use super::*;++ #[tokio::test]+ async fn a_file_is_read_whole_only_when_the_log_size_is_the_object_size() {+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());+ let path = Path::from("t/part-0.parquet");+ let body = Bytes::from_static(b"0123456789");+ store+ .put(&path, PutPayload::from_bytes(body.clone()))+ .await+ .unwrap();++ let file = fetch_small_file(&store, &path, 10).await.unwrap();+ assert_eq!(file.map(|f| f.bytes), Some(body));+ for wrong in [4, 11] {+ let file = fetch_small_file(&store, &path, wrong).await.unwrap();+ assert!(file.is_none(), "log size {wrong}");+ }+ }++ #[tokio::test]+ async fn reads_of_the_held_file_make_no_request() {+ let inner: Arc<dyn ObjectStore> = Arc::new(InMemory::new());+ let path = Path::from("t/part-0.parquet");+ let body = Bytes::from_static(b"0123456789");+ inner+ .put(&path, PutPayload::from_bytes(body.clone()))+ .await+ .unwrap();+ let file = fetch_small_file(&inner, &path, 10).await.unwrap().unwrap();+ inner.delete(&path).await.unwrap();+ let store = SmallFileStore::new(inner, path.clone(), file);++ assert_eq!(+ store.get_range(&path, 2..5).await.unwrap(),+ body.slice(2..5)+ );+ let ranges = store.get_ranges(&path, &[0..1, 8..10]).await.unwrap();+ assert_eq!(ranges, vec![body.slice(0..1), body.slice(8..10)]);+ let suffix = GetOptions {+ range: Some(GetRange::Suffix(4)),+ ..Default::default()+ };+ let tail = store.get_opts(&path, suffix).await.unwrap();+ assert_eq!(tail.bytes().await.unwrap(), body.slice(6..10));+ }+}diff --git a/rust/deltalite/core/src/store.rs b/rust/deltalite/core/src/store.rsindex dc0070554932..e3896782de04 100644--- a/rust/deltalite/core/src/store.rs+++ b/rust/deltalite/core/src/store.rs@@ -16,14 +16,20 @@//! `write_commit_entry` (delegated verbatim to the inner log store, preserving the//! conditional-put `If-None-Match` behaviour), and any `put_opts` with a non-Overwrite//! mode or a preconditioned option set is forwarded unmodified.+//!+//! [`MultipartLogStore`] can also answer the question that delta-rs asks before each+//! commit put ("what is the latest version?") without a LIST of the log; see+//! [`CommitProbe`].-use std::sync::Arc;+use std::sync::{Arc, Mutex};+use std::time::Instant;use async_trait::async_trait;use bytes::Bytes;use deltalake::kernel::transaction::TransactionError;use deltalake::logstore::{CommitOrBytes, LogStore, LogStoreConfig};use futures::stream::{BoxStream, StreamExt};+use metrics::counter;use object_store::path::Path;use object_store::{GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, ObjectStoreExt,@@ -31,6 +37,8 @@ use object_store::{};use uuid::Uuid;+use crate::logprobe::{commit_path, probe_log, LogAnchor, LogProbe};+/// Default size above which a single `put` becomes a multipart upload.pub const DEFAULT_MULTIPART_THRESHOLD: usize = 64 * 1024 * 1024;/// Part size for multipart uploads. Must be >= 5 MiB for S3; 16 MiB balances request@@ -227,6 +235,85 @@ pub struct MultipartLogStore {inner: Arc<dyn LogStore>,threshold: usize,part_size: usize,+ commit_probe: Option<CommitProbe>,+}++/// Kill switch for the commit that probes the log in place of the LIST before the+/// commit put; `0` restores the LIST.+pub const OPTIMISTIC_COMMIT_VERSION_ENV: &str = "DELTALITE_OPTIMISTIC_COMMIT_VERSION";++/// The name of the delta-rs log store that commits with a create-only put.+const CONDITIONAL_PUT_LOG_STORE: &str = "DefaultLogStore";++/// Answers `get_latest_version(v)` for a snapshot at `v` with the log probe (see+/// [`crate::logprobe`]) in place of the LIST.+///+/// delta-rs lists the log before each commit put to learn the latest version. The LIST+/// proves two things: the commit file of `v` is there, and no later one is. The probe+/// proves the same two things with one GET and one HEAD, issued together: the next+/// commit file answers 404, and a commit file of the loaded table is unchanged. The+/// create-only put of `v + 1` stays the conflict check, as before.+///+/// The probe answers the first question for each `v` only. When delta-rs asks again for+/// the same `v`, its put lost a race, so that call and every later one use the LIST and+/// the conflict checks as before. The probe is also not used when the table was replaced+/// (the commit fails as a conflict, and the caller loads the table again), when a+/// request fails, or after `deadline`.+pub(crate) struct CommitProbe {+ anchor: LogAnchor,+ /// The end of the time in which a 404 for the next commit file is proof.+ deadline: Instant,+ state: Mutex<CommitProbeState>,+}++#[derive(Default)]+struct CommitProbeState {+ /// The last start version answered by the probe.+ answered: Option<u64>,+ /// Set when a call fell back to the LIST: the commit is contended.+ listing: bool,+}++impl CommitProbe {+ pub(crate) fn new(anchor: LogAnchor, deadline: Instant) -> Self {+ Self {+ anchor,+ deadline,+ state: Mutex::new(CommitProbeState::default()),+ }+ }++ fn state(&self) -> std::sync::MutexGuard<'_, CommitProbeState> {+ self.state.lock().unwrap_or_else(|p| p.into_inner())+ }++ /// Whether the probe may answer for `start_version`. A refusal is permanent.+ fn begin(&self, start_version: u64) -> bool {+ let mut state = self.state();+ if state.listing || state.answered == Some(start_version) || Instant::now() >= self.deadline+ {+ state.listing = true;+ return false;+ }+ state.answered = Some(start_version);+ true+ }++ fn use_listing(&self) {+ self.state().listing = true;+ }+}++fn replaced_table_error(version: u64) -> deltalake::DeltaTableError {+ deltalake::DeltaTableError::Transaction {+ source: TransactionError::LogStoreError {+ msg: format!(+ "the table was replaced or its log was cleaned up after version {version} \+ was loaded; the commit was not written"+ ),+ source: "the log file that identifies the loaded table has changed".into(),+ },+ }}impl MultipartLogStore {@@ -236,8 +323,19 @@ impl MultipartLogStore {inner,threshold,part_size,+ commit_probe: None,}}++ /// Let `probe` answer the version question before a commit put. Ignored for a log+ /// store that does not commit with a create-only put (for example the DynamoDB+ /// lock store), which keeps its own `get_latest_version`.+ pub(crate) fn with_commit_probe(mut self, probe: CommitProbe) -> Self {+ if self.inner.name() == CONDITIONAL_PUT_LOG_STORE {+ self.commit_probe = Some(probe);+ }+ self+ }}impl std::fmt::Debug for MultipartLogStore {@@ -290,7 +388,28 @@ impl LogStore for MultipartLogStore {}async fn get_latest_version(&self, start_version: u64) -> deltalake::DeltaResult<u64> {- self.inner.get_latest_version(start_version).await+ let Some(probe) = &self.commit_probe else {+ return self.inner.get_latest_version(start_version).await;+ };+ if !probe.begin(start_version) {+ return self.inner.get_latest_version(start_version).await;+ }+ let outcome = match commit_path(self.inner.as_ref(), start_version + 1) {+ Some(next) => {+ let store = self.inner.root_object_store(None);+ probe_log(&store, &next, &probe.anchor).await+ }+ None => LogProbe::Unknown,+ };+ counter!("deltalite_commit_probe_total", "outcome" => outcome.label()).increment(1);+ match outcome {+ LogProbe::Current => Ok(start_version),+ LogProbe::Replaced => Err(replaced_table_error(start_version)),+ LogProbe::NewCommits | LogProbe::Unknown => {+ probe.use_listing();+ self.inner.get_latest_version(start_version).await+ }+ }}fn object_store(&self, operation_id: Option<Uuid>) -> Arc<dyn ObjectStore> {@@ -383,4 +502,147 @@ mod tests {let total: usize = parts.iter().map(|p| p.content_length()).sum();assert_eq!(total, 12 * 1024 * 1024);}++ /// A log store over an in-memory object store that counts the LIST-based version+ /// questions it answers.+ struct FakeLogStore {+ name: &'static str,+ store: Arc<dyn ObjectStore>,+ config: LogStoreConfig,+ latest: u64,+ listings: std::sync::atomic::AtomicUsize,+ }++ #[async_trait]+ impl LogStore for FakeLogStore {+ fn name(&self) -> String {+ self.name.to_string()+ }+ async fn read_commit_entry(&self, _: u64) -> deltalake::DeltaResult<Option<Bytes>> {+ Ok(None)+ }+ async fn write_commit_entry(+ &self,+ _: u64,+ _: CommitOrBytes,+ _: Uuid,+ ) -> Result<(), TransactionError> {+ Ok(())+ }+ async fn abort_commit_entry(+ &self,+ _: u64,+ _: CommitOrBytes,+ _: Uuid,+ ) -> Result<(), TransactionError> {+ Ok(())+ }+ async fn get_latest_version(&self, _: u64) -> deltalake::DeltaResult<u64> {+ self.listings+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ Ok(self.latest)+ }+ fn object_store(&self, _: Option<Uuid>) -> Arc<dyn ObjectStore> {+ self.store.clone()+ }+ fn root_object_store(&self, _: Option<Uuid>) -> Arc<dyn ObjectStore> {+ self.store.clone()+ }+ fn config(&self) -> &LogStoreConfig {+ &self.config+ }+ }++ fn commit_file(version: u64) -> Path {+ Path::from(format!("bucket/t/_delta_log/{version:020}.json"))+ }++ /// A log with commits `0..=5` behind a store named `name`, and the probe for it.+ async fn probed_store(+ name: &'static str,+ deadline: Instant,+ ) -> (Arc<FakeLogStore>, MultipartLogStore) {+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());+ for version in 0..=5 {+ store+ .put(&commit_file(version), payload_of(10))+ .await+ .unwrap();+ }+ let anchor = LogAnchor::from_meta(&store.head(&commit_file(3)).await.unwrap()).unwrap();+ let location = url::Url::parse("memory:///bucket/t").unwrap();+ let fake = Arc::new(FakeLogStore {+ name,+ store,+ config: LogStoreConfig::new(&location, Default::default()),+ latest: 9,+ listings: Default::default(),+ });+ let wrapped = MultipartLogStore::new(fake.clone(), 0, 0)+ .with_commit_probe(CommitProbe::new(anchor, deadline));+ (fake, wrapped)+ }++ fn listings(fake: &FakeLogStore) -> usize {+ fake.listings.load(std::sync::atomic::Ordering::SeqCst)+ }++ fn soon() -> Instant {+ Instant::now() + std::time::Duration::from_secs(60)+ }++ #[tokio::test]+ async fn the_probe_answers_once_for_each_version_and_then_the_listing_does() {+ let (fake, store) = probed_store(CONDITIONAL_PUT_LOG_STORE, soon()).await;++ assert_eq!(store.get_latest_version(5).await.unwrap(), 5);+ assert_eq!(+ listings(&fake),+ 0,+ "no LIST while the next commit is absent"+ );++ // delta-rs asks again for the same version when its put lost a race.+ assert_eq!(store.get_latest_version(5).await.unwrap(), 9);+ assert_eq!(store.get_latest_version(9).await.unwrap(), 9);+ assert_eq!(listings(&fake), 2, "a contended commit stays on the LIST");+ }++ #[tokio::test]+ async fn a_commit_that_exists_sends_the_question_to_the_listing() {+ let (fake, store) = probed_store(CONDITIONAL_PUT_LOG_STORE, soon()).await;+ assert_eq!(store.get_latest_version(4).await.unwrap(), 9);+ assert_eq!(listings(&fake), 1);+ }++ #[tokio::test]+ async fn a_log_store_without_a_create_only_put_keeps_its_listing() {+ let (fake, store) = probed_store("S3DynamoDbLogStore", soon()).await;+ assert_eq!(store.get_latest_version(5).await.unwrap(), 9);+ assert_eq!(listings(&fake), 1);+ }++ #[tokio::test]+ async fn the_probe_is_not_used_after_its_deadline() {+ let (fake, store) = probed_store(CONDITIONAL_PUT_LOG_STORE, Instant::now()).await;+ assert_eq!(store.get_latest_version(5).await.unwrap(), 9);+ assert_eq!(listings(&fake), 1);+ }++ #[tokio::test]+ async fn a_replaced_table_fails_the_commit_as_a_conflict() {+ let (fake, store) = probed_store(CONDITIONAL_PUT_LOG_STORE, soon()).await;+ fake.store+ .put(&commit_file(3), payload_of(11))+ .await+ .unwrap();++ let err = store.get_latest_version(5).await.unwrap_err();+ assert_eq!(listings(&fake), 0);+ let mapped: crate::errors::Error = err.into();+ assert!(+ matches!(mapped, crate::errors::Error::Conflict(_)),+ "{mapped:?}"+ );+ }}diff --git a/rust/deltalite/core/src/table.rs b/rust/deltalite/core/src/table.rsindex 3ace258b13fa..c4bb28f280a9 100644--- a/rust/deltalite/core/src/table.rs+++ b/rust/deltalite/core/src/table.rs@@ -7,7 +7,7 @@ use deltalake::{DeltaTable, DeltaTableBuilder};use crate::errors::{Error, Result};use crate::prefetch::{CheckpointCache, CheckpointPrefetchLogStore};-use crate::store::MultipartLogStore;+use crate::store::{CommitProbe, MultipartLogStore};/// How data-file uploads are performed.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -52,6 +52,9 @@ impl MultipartConfig {/// than a plain load once it is open.pub async fn open_table(uri: &str, storage_options: HashMap<String, String>) -> Result<DeltaTable> {let (table, prefetch) = open_table_prefetched(uri, storage_options).await?;+ // Nothing clears the cache after later operations on this table, so it must not+ // collect the commit files that they read and write.+ prefetch.stop_caching_commits();prefetch.clear();Ok(table)}@@ -107,3 +110,25 @@ pub fn wrap_multipart(table: DeltaTable, multipart: MultipartConfig) -> DeltaTabwrapped_table.state = table.state;wrapped_table}++/// [`wrap_multipart`] for a handle's view of its table. `commit_probe` lets a commit+/// through the view skip the LIST before the commit put (see [`CommitProbe`]). Always+/// wraps; a zero threshold keeps every upload a single put.+pub(crate) fn wrap_multipart_view(+ table: DeltaTable,+ multipart: MultipartConfig,+ commit_probe: Option<CommitProbe>,+) -> DeltaTable {+ let threshold = if multipart.threshold == 0 {+ usize::MAX+ } else {+ multipart.threshold+ };+ let mut wrapped = MultipartLogStore::new(table.log_store(), threshold, multipart.part_size);+ if let Some(probe) = commit_probe {+ wrapped = wrapped.with_commit_probe(probe);+ }+ let mut wrapped_table = DeltaTable::new(Arc::new(wrapped), Default::default());+ wrapped_table.state = table.state;+ wrapped_table+}diff --git a/rust/deltalite/core/src/upsert.rs b/rust/deltalite/core/src/upsert.rsindex 0ac59d5a89b0..63d652324a1d 100644--- a/rust/deltalite/core/src/upsert.rs+++ b/rust/deltalite/core/src/upsert.rs@@ -61,6 +61,7 @@ use crate::limits::{};use crate::pkset::PkSet;use crate::schema::{cast_to_schema, unknown_columns};+use crate::smallfile::{fetch_small_file, reads_whole, SmallFileStore};use crate::writer::StreamingWriter;/// One logical group of work: a partition value (or the whole table when unpartitioned).@@ -1638,23 +1639,50 @@ fn target_file(v: &LogicalFileView) -> TargetFile {/// 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.+///+/// A file no larger than the hint is read whole in one request (see+/// `crate::smallfile`). The fetch permit for those bytes is taken before the request and+/// returned with the builder; it is the reader's one fetch permit for this file, so the+/// caller must not take another.pub(crate) async fn open_builder(store: &Arc<dyn ObjectStore>,f: &TargetFile,-) -> Result<ParquetRecordBatchStreamBuilder<ParquetObjectReader>> {+ budgets: &Budgets,+) -> Result<(+ ParquetRecordBatchStreamBuilder<ParquetObjectReader>,+ Option<FetchPermit>,+)> {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 reader = ParquetObjectReader::new(store.clone(), path).with_file_size(f.size);let arrow_meta = ArrowReaderMetadata::try_new(meta.clone(), Default::default())?;- return Ok(ParquetRecordBatchStreamBuilder::new_with_metadata(- reader, arrow_meta,+ return Ok((+ ParquetRecordBatchStreamBuilder::new_with_metadata(reader, arrow_meta),+ None,));}- Ok(+ if reads_whole(f.size, FOOTER_SIZE_HINT as u64) {+ let fetch = budgets.acquire_fetch(f.size as usize).await?;+ if let Some(file) = fetch_small_file(store, &path, f.size).await? {+ let store: Arc<dyn ObjectStore> =+ Arc::new(SmallFileStore::new(store.clone(), path.clone(), file));+ let reader = ParquetObjectReader::new(store, path).with_file_size(f.size);+ return Ok((+ ParquetRecordBatchStreamBuilder::new(+ reader.with_footer_size_hint(FOOTER_SIZE_HINT),+ )+ .await?,+ Some(fetch),+ ));+ }+ }+ let reader = ParquetObjectReader::new(store.clone(), path).with_file_size(f.size);+ Ok((ParquetRecordBatchStreamBuilder::new(reader.with_footer_size_hint(FOOTER_SIZE_HINT)).await?,- )+ None,+ ))}/// Drop files whose Add-action stats prove they hold no match: min/max disjointness on@@ -1885,7 +1913,7 @@ async fn probe_file(opts: &UpsertOptions,budgets: &Budgets,) -> Result<(bool, Arc<ParquetMetaData>)> {- let builder = open_builder(store, f).await?;+ let (builder, held_fetch) = open_builder(store, f, budgets).await?;let metadata = builder.metadata().clone();let file_schema = builder.schema().clone();@@ -1930,12 +1958,17 @@ async fn probe_file(}// Fetch budget before any data is fetched; held until the stream is gone.- let fetch = budgets- .acquire_fetch(max_row_group_fetch_bytes(- builder.metadata(),- Some(&projection),- ))- .await?;+ let fetch = match held_fetch {+ Some(fetch) => fetch,+ None => {+ budgets+ .acquire_fetch(max_row_group_fetch_bytes(+ builder.metadata(),+ Some(&projection),+ ))+ .await?+ }+ };let mask = ProjectionMask::roots(builder.parquet_schema(), projection);let batch_rows = byte_bounded_batch_rows(builder.metadata(),@@ -2055,12 +2088,17 @@ async fn filter_file(budgets: Budgets,tx: mpsc::UnboundedSender<(RecordBatch, BudgetPermit)>,) -> Result<FileOutcome> {- let builder = open_builder(&store, &f).await?;+ let (builder, held_fetch) = open_builder(&store, &f, &budgets).await?;// Reserve the compressed bytes the reader will hold before it fetches any data.// Taken once per file and before any decode budget (see `Budgets::acquire_fetch`).- let fetch = budgets- .acquire_fetch(max_row_group_fetch_bytes(builder.metadata(), None))- .await?;+ let fetch = match held_fetch {+ Some(fetch) => fetch,+ None => {+ budgets+ .acquire_fetch(max_row_group_fetch_bytes(builder.metadata(), None))+ .await?+ }+ };let batch_rows = byte_bounded_batch_rows(builder.metadata(),INITIAL_DECODE_ESTIMATE_BYTES,@@ -2639,6 +2677,45 @@ mod tests {assert!(matches!(err, Error::SchemaMismatch(_)), "{err}");}+ // ---- small files ------------------------------------------------------------------++ #[tokio::test]+ async fn a_small_file_is_fetched_only_under_its_fetch_permit() {+ let batch = int_batch(&[1, 2, 3]);+ let mut encoded = Vec::new();+ let mut writer =+ parquet::arrow::ArrowWriter::try_new(&mut encoded, batch.schema(), None).unwrap();+ writer.write(&batch).unwrap();+ writer.close().unwrap();+ let store: Arc<dyn ObjectStore> = Arc::new(object_store::memory::InMemory::new());+ let file = TargetFile {+ size: encoded.len() as u64,+ ..target_file(None)+ };+ object_store::ObjectStoreExt::put(+ store.as_ref(),+ &Path::from(file.path.as_str()),+ encoded.into(),+ )+ .await+ .unwrap();+ let limits = Arc::new(ProcessLimits::with_fetch(1, 1, 1 << 20, 1 << 20));+ let budgets = Budgets::new(1 << 20, 8 * 1024, limits);++ let whole_budget = budgets.acquire_fetch(usize::MAX).await.unwrap();+ let blocked = tokio::time::timeout(+ std::time::Duration::from_millis(50),+ open_builder(&store, &file, &budgets),+ )+ .await;+ assert!(blocked.is_err(), "the open must wait for the fetch budget");++ drop(whole_budget);+ let (builder, fetch) = open_builder(&store, &file, &budgets).await.unwrap();+ assert!(fetch.is_some(), "the reader holds the permit for the file");+ assert_eq!(builder.metadata().file_metadata().num_rows(), 3);+ }+// ---- stats-based pruning ---------------------------------------------------------fn target_file(stats: Option<&str>) -> TargetFile {diff --git a/rust/deltalite/core/tests/handle_and_open.rs b/rust/deltalite/core/tests/handle_and_open.rsindex cbea07e2e9f1..337a8ce38215 100644--- a/rust/deltalite/core/tests/handle_and_open.rs+++ b/rust/deltalite/core/tests/handle_and_open.rs@@ -59,6 +59,41 @@ impl Op {}}+/// Work to run before the first matching PUT under a table root, so a test can make+/// another writer land at an exact point of an upsert.+type Hook = Box<dyn FnOnce() -> futures::future::BoxFuture<'static, ()> + Send>;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum PutKind {+ DataFile,+ Commit,+}++static PUT_HOOKS: LazyLock<Mutex<Vec<(String, PutKind, Hook)>>> =+ LazyLock::new(|| Mutex::new(Vec::new()));++fn before_first_put(root: &str, kind: PutKind, hook: Hook) {+ PUT_HOOKS+ .lock()+ .unwrap()+ .push((root.to_string(), kind, hook));+}++fn take_put_hook(location: &str) -> Option<Hook> {+ let kind = if !location.contains("/_delta_log/") {+ PutKind::DataFile+ } else if location.ends_with(".json") {+ PutKind::Commit+ } else {+ return None;+ };+ let mut hooks = PUT_HOOKS.lock().unwrap();+ let at = hooks+ .iter()+ .position(|(root, k, _)| *k == kind && location.starts_with(root.as_str()))?;+ Some(hooks.remove(at).2)+}+fn record_read(target: String, n: usize) {*READS.lock().unwrap().entry(target).or_default() += n;}@@ -171,6 +206,9 @@ impl ObjectStore for CountingStore {payload: PutPayload,opts: PutOptions,) -> object_store::Result<PutResult> {+ if let Some(hook) = take_put_hook(location.as_ref()) {+ hook().await;+ }record_op(Op::Put, location.as_ref());self.inner.put_opts(location, payload, opts).await}@@ -1076,3 +1114,375 @@ async fn commit_state_includes_a_writer_that_landed_first() {assert_eq!(adopted.len(), 3, "seed file, external file, own file");assert_eq!(adopted, live_paths_from_the_log(&uri).await);}++// ---- log probe, commit probe, small files -------------------------------------------++fn count(ops: &[(Op, String)], op: Op, suffix: &str) -> usize {+ ops.iter()+ .filter(|(o, path)| *o == op && path.ends_with(suffix))+ .count()+}++fn commit_name(version: i64) -> String {+ format!("_delta_log/{version:020}.json")+}++async fn create_table_with_retention(uri: &str, retention: &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::LogRetentionDuration,+ Some(retention.to_string()),+ )+ .await+ .expect("create table");+ let s = schema(true);+ TableHandle::open(uri.to_string(), HashMap::new())+ .await+ .expect("open for seeding")+ .upsert(+ vec![batch(&s, &["a"], vec![Some(1)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("seed upsert");+ s+}++#[derive(Debug, Clone, Copy)]+enum Shape {+ /// The load reads commits after no checkpoint.+ Plain,+ /// The loaded version is a checkpoint version, so the load reads no commit file.+ EndsOnCheckpoint,+ /// Log cleanup may remove a commit as soon as it is written.+ NoRetention,+}++/// A refresh with nothing to apply costs one GET and one HEAD while the probe is proof,+/// and lists the log in every case where it is not.+#[tokio::test]+async fn a_refresh_lists_the_log_only_when_the_probe_is_not_proof() {+ register_counting_scheme();+ for (shape, probe, lists) in [+ (Shape::Plain, true, false),+ (Shape::Plain, false, true),+ (Shape::EndsOnCheckpoint, true, true),+ (Shape::NoRetention, true, true),+ ] {+ let dir = tempfile::tempdir().expect("tempdir");+ let path = dir.path().join("t");+ let uri = format!("dltest://{}", path.to_string_lossy());+ match shape {+ Shape::Plain => drop(create_seeded_table(&uri, true).await),+ Shape::EndsOnCheckpoint => drop(create_seeded_table_with(&uri, true, Some(2), 3).await),+ Shape::NoRetention => {+ drop(create_table_with_retention(&uri, "interval 0 seconds").await)+ }+ }+ let mut handle = TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open");+ handle.set_probe_refresh(probe);+ let version = handle.version();++ let start = ops_len();+ handle.refresh().await.expect("refresh");+ let ops = ops_since(start, &table_root(&path));++ let case = format!("{shape:?} probe={probe}: {ops:?}");+ assert_eq!(handle.version(), version, "{case}");+ assert_eq!(count(&ops, Op::List, "_delta_log") > 0, lists, "{case}");+ if !lists {+ assert_eq!(ops.len(), 2, "{case}");+ assert_eq!(count(&ops, Op::Get, &commit_name(version + 1)), 1, "{case}");+ assert_eq!(count(&ops, Op::Head, ".json"), 1, "{case}");+ }+ }+}++/// Commits by another writer, with or without a checkpoint among them, are all applied+/// by one refresh, and the probe is proof again afterwards.+#[tokio::test]+async fn a_refresh_applies_every_commit_made_elsewhere() {+ register_counting_scheme();+ for (interval, external) in [(None, 1), (None, 3), (Some(2), 3), (Some(2), 4)] {+ let dir = tempfile::tempdir().expect("tempdir");+ let path = dir.path().join("t");+ let uri = format!("dltest://{}", path.to_string_lossy());+ let s = create_seeded_table_with(&uri, true, interval, 2).await;+ let mut handle = TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open");+ let version = handle.version();++ for i in 0..external {+ TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open external handle")+ .upsert(+ vec![batch(&s, &[format!("k{i}").as_str()], vec![Some(i)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("external upsert");+ }++ let case = format!("interval={interval:?} external={external}");+ handle.refresh().await.expect("refresh");+ assert_eq!(handle.version(), version + external, "{case}");+ assert_eq!(+ sorted_paths(&handle),+ live_paths_from_the_log(&uri).await,+ "{case}"+ );++ let stats = handle+ .upsert(+ vec![batch(&s, &["z"], vec![Some(9)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("upsert after the refresh");+ assert_eq!(stats.version, version + external + 1, "{case}");+ assert_eq!(+ sorted_paths(&handle),+ live_paths_from_the_log(&uri).await,+ "{case}"+ );+ }+}++/// A table that was deleted and created again at the same path answers 404 for the next+/// commit of the old table. The handle must load the new table, whatever its version.+#[tokio::test]+async fn a_replaced_table_is_loaded_again() {+ register_counting_scheme();+ for new_commits in [1, 4, 6] {+ let dir = tempfile::tempdir().expect("tempdir");+ let path = dir.path().join("t");+ let uri = format!("dltest://{}", path.to_string_lossy());+ create_seeded_table_with(&uri, true, None, 4).await;+ let mut handle = TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open");+ let old_id = handle.table_id().expect("table id");+ assert_eq!(handle.version(), 4);++ std::fs::remove_dir_all(&path).expect("delete the table");+ let s = create_seeded_table_with(&uri, true, None, new_commits).await;++ let case = format!("new table at version {new_commits}");+ handle.refresh().await.expect("refresh");+ assert_ne!(handle.table_id().expect("table id"), old_id, "{case}");+ assert_eq!(handle.version(), new_commits, "{case}");+ assert_eq!(+ sorted_paths(&handle),+ live_paths_from_the_log(&uri).await,+ "{case}"+ );++ let stats = handle+ .upsert(+ vec![batch(&s, &["z"], vec![Some(9)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("upsert into the new table");+ assert_eq!(stats.version, new_commits + 1, "{case}");+ assert_eq!(+ sorted_paths(&handle),+ live_paths_from_the_log(&uri).await,+ "{case}"+ );+ }+}++/// When the table is replaced by one with fewer versions after the upsert read its+/// snapshot, the commit file after the old version does not exist, so a create-only put+/// of it would succeed and leave a gap in the new table's log. The commit must write+/// nothing, and the upsert must run again on the new table.+#[tokio::test]+async fn a_table_replaced_during_an_upsert_gets_no_commit_of_the_old_version() {+ register_counting_scheme();+ let dir = tempfile::tempdir().expect("tempdir");+ let path = dir.path().join("t");+ let uri = format!("dltest://{}", path.to_string_lossy());+ let s = create_seeded_table_with(&uri, true, None, 4).await;+ let mut handle = TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open");++ let (new_uri, old_path) = (uri.clone(), path.clone());+ before_first_put(+ &table_root(&path),+ PutKind::DataFile,+ Box::new(move || {+ Box::pin(async move {+ std::fs::remove_dir_all(&old_path).expect("delete the table");+ create_seeded_table_with(&new_uri, true, None, 1).await;+ })+ }),+ );++ let stats = handle+ .upsert(+ vec![batch(&s, &["z"], vec![Some(9)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("upsert");++ assert!(!path.join(commit_name(5)).exists());+ assert_eq!(stats.version, 2);+ assert_eq!(handle.version(), 2);+ assert_eq!(sorted_paths(&handle), live_paths_from_the_log(&uri).await);+}++#[derive(Debug, Clone, Copy)]+struct Race {+ /// Where in the first writer's upsert the second writer commits.+ at: PutKind,+ /// Whether the second writer rewrites the file that the first one read.+ overlap: bool,+}++/// A second writer that commits during an upsert is never overwritten: before the+/// commit put the probe finds its commit, and after the probe the create-only put is+/// rejected. In the two cases the upsert lands on top of the other commit.+#[tokio::test]+async fn a_writer_that_lands_during_an_upsert_is_not_overwritten() {+ register_counting_scheme();+ for race in [+ Race {+ at: PutKind::DataFile,+ overlap: false,+ },+ Race {+ at: PutKind::DataFile,+ overlap: true,+ },+ Race {+ at: PutKind::Commit,+ overlap: false,+ },+ Race {+ at: PutKind::Commit,+ overlap: true,+ },+ ] {+ let dir = tempfile::tempdir().expect("tempdir");+ let path = dir.path().join("t");+ let uri = format!("dltest://{}", path.to_string_lossy());+ let root = table_root(&path);+ let s = create_disjoint_files_table(&uri, &[&["a0", "a1"]]).await;+ let mut handle = TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open");+ let base = handle.version();++ let (other_uri, other_schema) = (uri.clone(), s.clone());+ let other_key = if race.overlap { "a0" } else { "m0" };+ before_first_put(+ &root,+ race.at,+ Box::new(move || {+ Box::pin(async move {+ TableHandle::open(other_uri, HashMap::new())+ .await+ .expect("open second writer")+ .upsert(+ vec![batch(&other_schema, &[other_key], vec![Some(7)])],+ other_schema.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("second writer");+ })+ }),+ );++ let key = if race.overlap { "a1" } else { "x0" };+ let start = ops_len();+ let stats = handle+ .upsert(+ vec![batch(&s, &[key], vec![Some(8)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .unwrap_or_else(|e| panic!("{race:?}: {e}"));+ let ops = ops_since(start, &root);++ assert_eq!(stats.version, base + 2, "{race:?}");+ assert_eq!(handle.version(), base + 2, "{race:?}");+ assert_eq!(+ sorted_paths(&handle),+ live_paths_from_the_log(&uri).await,+ "{race:?}"+ );+ assert_eq!(+ handle.num_files().expect("num_files"),+ if race.overlap { 1 } else { 3 },+ "{race:?}"+ );+ assert_eq!(+ count(&ops, Op::Put, &commit_name(base + 1)),+ if race.at == PutKind::Commit { 2 } else { 1 },+ "{race:?}: a put of the taken version happens only after a probe that saw it free"+ );+ }+}++/// A small file is read with one request when it is opened, and that request serves the+/// probe. With the switch off the open and the probe are two requests.+#[tokio::test]+async fn a_probed_small_file_costs_one_request() {+ register_counting_scheme();+ let dir = tempfile::tempdir().expect("tempdir");+ let path = dir.path().join("t");+ let uri = format!("dltest://{}", path.to_string_lossy());+ let s = create_disjoint_files_table(&uri, &[&["a0", "a9"], &["m0", "m9"]]).await;+ let mut handle = TableHandle::open(uri.clone(), HashMap::new())+ .await+ .expect("open");++ // Inside the key range of the first file but not in it: the stats keep the file,+ // the probe reads it and finds no match.+ let start = ops_len();+ let stats = handle+ .upsert(+ vec![batch(&s, &["a5"], vec![Some(1)])],+ s.clone(),+ opts(),+ MultipartConfig::default(),+ )+ .await+ .expect("upsert");+ let ops = ops_since(start, &table_root(&path));++ assert_eq!(stats.files_probed, 1);+ assert_eq!(stats.files_removed, 0);+ let data_reads: Vec<_> = ops+ .iter()+ .filter(|(op, p)| op.is_read() && p.ends_with(".parquet") && !p.contains("_delta_log"))+ .collect();+ assert_eq!(data_reads.len(), 1, "{data_reads:?}");+ assert_eq!(data_reads[0].0, Op::Get);+}diff --git a/rust/deltalite/python/Cargo.toml b/rust/deltalite/python/Cargo.tomlindex a53863282d35..66d9501e45c0 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.10"+version = "0.1.11"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 1dc03436910d..f5d17f167110 100644--- a/rust/deltalite/python/README.md+++ b/rust/deltalite/python/README.md@@ -234,14 +234,47 @@ hint, so a footer that fits arrives in one GET instead of two, and a file theprobe found a match in hands its parsed footer to the rewrite, so the file isnot opened a second time.+**Log requests.** Four changes remove LIST requests of `_delta_log/` and repeated+reads. Each one has a kill switch that restores the earlier requests: set the+variable to `0` (`false`, `off` and `no` also work).++| Switch | What it controls |+| --- | --- |+| `DELTALITE_PROBE_REFRESH` | A refresh asks if the snapshot is current with one GET and one HEAD, sent together, before it lists the log. The GET is for the commit file after the loaded version: a 404 proves that no newer version exists, because versions have no gaps and a commit file is written one time. The HEAD compares the ETag and the modification time of a commit file that the last load read, so a table that was deleted and created again is loaded again. When a newer commit exists, the refresh lists the log as before. |+| `DELTALITE_OPTIMISTIC_COMMIT_VERSION` | Before the commit put, delta-rs lists the log to find the latest version. The same GET and HEAD replace that LIST. The create-only put (`If-None-Match: *` on S3) stays the conflict check. If the put loses a race, delta-rs lists the log and checks for conflicts as before. If the table was replaced, the commit fails as a conflict, writes nothing, and the upsert runs again on the table that it loads again. |+| `DELTALITE_COMMIT_JSON_CACHE` | During one load each commit file is read one time (the kernel reads it two times), and the commit that an upsert wrote is not read back. The memory is at most 256 files and 8 MiB (1 MiB for one file), counts against `DELTALITE_CHECKPOINT_PREFETCH_MAX_BYTES` and `DELTALITE_PROCESS_MAX_BUFFERED_BYTES`, and is released when the operation ends. A commit that does not fit is read as before. |+| `DELTALITE_SMALL_FILE_SINGLE_GET` | A data file of 64 KiB or less is read with one GET when it is opened without a footer from the probe. The size comes from the Delta log. The reader takes its permit from the fetch budget (`max_fetch_bytes`, `DELTALITE_PROCESS_MAX_FETCH_BYTES`) for the whole file before the request, and the bytes are released with the reader. |++The probe is used only while a 404 is proof:++- The handle lists the log when the last LIST is older than 10 minutes, or older+ than half of `delta.logRetentionDuration` if that is shorter. Log cleanup+ removes only commit files older than the retention, so inside this time a+ missing commit file was never written.+- The handle lists the log when the last load read no commit file (the loaded+ version is a checkpoint version), when the store gives no ETag, and after its+ own commit on a checkpoint boundary.+- A log store that does not commit with a create-only put (for example the+ DynamoDB lock store) keeps the LIST before the commit put.++The probe needs a store that answers a GET or a HEAD with the current state of+the object. S3 does this (reads are strongly consistent after a write or a+delete), and so do SeaweedFS, the local file system and the in-memory store. Set+`DELTALITE_PROBE_REFRESH=0` and `DELTALITE_OPTIMISTIC_COMMIT_VERSION=0` for a+store, or a cache in front of a store, that can answer 404 for an object that+exists.+## Metricsdeltalite emits via the Rust [`metrics`](https://docs.rs/metrics) facade (staticlabels only): `deltalite_upserts_total` (`outcome`, `prune_strategy`,`error_kind`), `deltalite_upsert_duration_seconds`,`deltalite_files_{added,removed,carried_over,probed}_total`,-`deltalite_rows_{updated,inserted,copied}_total`, and-`deltalite_checkpoint_prefetch_total` (`outcome`).+`deltalite_rows_{updated,inserted,copied}_total`,+`deltalite_checkpoint_prefetch_total` (`outcome`),+`deltalite_refresh_probe_total` (`outcome`: `current`, `new_commits`,+`replaced`, `unknown`, `listed`, `no_anchor`), and+`deltalite_commit_probe_total` (`outcome`).## Compatibility & statusdiff --git a/rust/deltalite/python/pyproject.toml b/rust/deltalite/python/pyproject.tomlindex 6417b66f0c7e..56e53f0efa90 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.10"+version = "0.1.11"description = "Streaming partition upsert for Delta tables, replacing delta-rs SQL MERGE"readme = "README.md"requires-python = ">=3.12"