: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): parallel multipart uploads and ranged reads (#121932)
Tom Owers2093d252780c
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex ca095f155a7f..16c68553f8b5 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -3986,7 +3986,7 @@ dependencies = [[[package]]name = "deltalite-python"-version = "0.1.14"+version = "0.1.15"dependencies = ["arrow","arrow-array",diff --git a/rust/deltalite/README.md b/rust/deltalite/README.mdindex 56d46eadc35a..bc56808e6117 100644--- a/rust/deltalite/README.md+++ b/rust/deltalite/README.md@@ -116,8 +116,11 @@ Per-call (arguments to `DeltaLiteTable.upsert`): `max_parallel_partitions` (2),`isolate_source_rows` (off: the batch's rows share an output file with the copiedsurvivors; on: they get their own files),`max_row_group_bytes` (`None`: row groups close only at the encoder's row cap),-`max_source_bytes` (2 GiB guard), `multipart_threshold` (64 MiB) /-`multipart_part_size` (16 MiB), `commit_max_retries` (15), `use_probe_cache`+`max_source_bytes` (2 GiB guard), `multipart_threshold` (16 MiB) /+`multipart_part_size` (8 MiB) / `multipart_concurrency` (4 parts at once; `1`+uploads parts one after another, with the earlier 64 MiB / 16 MiB defaults),+`range_get_part_size` (8 MiB) / `range_get_concurrency` (4; `1` reads a row group+with one request), `read_ahead_row_groups` (off), `commit_max_retries` (15), `use_probe_cache`(on: the probe decides a file whose PK hashes the process-wide probe cache holdswithout reading it; see `python/README.md`, "Probe cache").@@ -128,6 +131,8 @@ budgets): `DELTALITE_PROCESS_MAX_PARALLEL_PARTITIONS` (8),`DELTALITE_PROCESS_MAX_BUFFERED_BYTES` (256 MiB),`DELTALITE_PROCESS_MAX_FETCH_BYTES` (256 MiB), `DELTALITE_MAX_SOURCE_BYTES`,`DELTALITE_MULTIPART_THRESHOLD_BYTES`, `DELTALITE_MULTIPART_PART_SIZE_BYTES`,+`DELTALITE_MULTIPART_CONCURRENCY`, `DELTALITE_RANGE_GET_PART_SIZE_BYTES`,+`DELTALITE_RANGE_GET_CONCURRENCY`,`DELTALITE_PROBE_CACHE_BYTES` (128 MiB, `0` off: the byte cap of the probe cache).Kill switches for the request savings on the log and on small files (set to `0`diff --git a/rust/deltalite/core/src/lib.rs b/rust/deltalite/core/src/lib.rsindex 898caba68fda..9376dac14baf 100644--- a/rust/deltalite/core/src/lib.rs+++ b/rust/deltalite/core/src/lib.rs@@ -37,6 +37,7 @@ mod logprobe;pub mod pkset;pub mod prefetch;pub mod probecache;+mod readahead;pub mod schema;mod smallfile;mod stats;diff --git a/rust/deltalite/core/src/readahead.rs b/rust/deltalite/core/src/readahead.rsnew file mode 100644index 000000000000..346874cbdd12--- /dev/null+++ b/rust/deltalite/core/src/readahead.rs@@ -0,0 +1,262 @@+//! Read-ahead of the next row group of a data file.+//!+//! The async Parquet reader fetches a row group, decodes all of it, and only then asks+//! for the next one, so a reader of a file with several row groups waits for storage+//! once per row group. [`ReadAheadStore`] serves the reader of one file: when the reader+//! asks for the column chunks of row group `i`, the store starts a background read of+//! row group `i + 1`, and serves the next request from that read.+//!+//! The store reads at most one row group ahead, so a reader holds at most two row groups:+//! the one it decodes and the one being read. The caller reserves that pair from the+//! fetch budget (see [`max_row_group_pair_fetch_bytes`]). The background read is aborted+//! when the store is dropped, which happens with the reader, before the reader returns+//! its fetch permit.++use std::ops::Range;+use std::sync::{Arc, Mutex};++use async_trait::async_trait;+use bytes::Bytes;+use futures::stream::BoxStream;+use metrics::counter;+use object_store::path::Path;+use object_store::{+ GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore,+ PutMultipartOptions, PutOptions, PutPayload, PutResult,+};+use parquet::file::metadata::ParquetMetaData;+use tokio::task::JoinHandle;++/// Byte span of each row group: from the first byte of its first column chunk to the+/// last byte of its last one.+fn row_group_spans(meta: &ParquetMetaData) -> Vec<Range<u64>> {+ meta.row_groups()+ .iter()+ .map(|rg| {+ let mut span: Option<Range<u64>> = None;+ for c in rg.columns() {+ let (start, len) = c.byte_range();+ let end = start + len;+ span = Some(match span {+ None => start..end,+ Some(s) => s.start.min(start)..s.end.max(end),+ });+ }+ span.unwrap_or(0..0)+ })+ .collect()+}++/// Compressed bytes a reader with read-ahead holds at most: the largest sum of two+/// consecutive row group spans, or the one span of a single-row-group file. Spans, not+/// column chunk lengths, because the read ahead fetches and holds the whole span.+pub(crate) fn max_row_group_pair_fetch_bytes(meta: &ParquetMetaData) -> usize {+ let sizes: Vec<usize> = row_group_spans(meta)+ .iter()+ .map(|g| (g.end - g.start) as usize)+ .collect();+ if sizes.len() < 2 {+ return sizes.first().copied().unwrap_or(0);+ }+ sizes.windows(2).map(|w| w[0] + w[1]).max().unwrap_or(0)+}++/// Aborts the task when dropped, so a read nobody waits for stops holding memory.+struct AbortOnDrop(JoinHandle<object_store::Result<Bytes>>);++impl Drop for AbortOnDrop {+ fn drop(&mut self) {+ self.0.abort();+ }+}++struct Pending {+ group: usize,+ read: AbortOnDrop,+}++/// Serves the reader of one data file and reads its next row group ahead. Every other+/// request is delegated.+pub(crate) struct ReadAheadStore {+ inner: Arc<dyn ObjectStore>,+ path: Path,+ groups: Vec<Range<u64>>,+ pending: Mutex<Option<Pending>>,+}++impl ReadAheadStore {+ pub(crate) fn new(inner: Arc<dyn ObjectStore>, path: Path, meta: &ParquetMetaData) -> Self {+ Self {+ inner,+ path,+ groups: row_group_spans(meta),+ pending: Mutex::new(None),+ }+ }++ fn take_pending(&self) -> Option<Pending> {+ self.pending+ .lock()+ .unwrap_or_else(|p| p.into_inner())+ .take()+ }++ /// The row group whose span holds every range of `ranges`.+ fn group_of(&self, ranges: &[Range<u64>]) -> Option<usize> {+ let lo = ranges.iter().map(|r| r.start).min()?;+ let hi = ranges.iter().map(|r| r.end).max()?;+ self.groups+ .iter()+ .position(|g| g.start <= lo && hi <= g.end && g.start < g.end)+ }++ fn read_ahead(&self, group: usize) {+ let Some(span) = self.groups.get(group).cloned() else {+ return;+ };+ let inner = self.inner.clone();+ let path = self.path.clone();+ let task = tokio::spawn(async move {+ let mut got = inner.get_ranges(&path, std::slice::from_ref(&span)).await?;+ got.pop().ok_or_else(|| object_store::Error::Generic {+ store: "deltalite",+ source: "ranged read returned no data".into(),+ })+ });+ *self.pending.lock().unwrap_or_else(|p| p.into_inner()) = Some(Pending {+ group,+ read: AbortOnDrop(task),+ });+ }+}++impl std::fmt::Debug for ReadAheadStore {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "ReadAheadStore({})", self.inner)+ }+}++impl std::fmt::Display for ReadAheadStore {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "ReadAheadStore({})", self.inner)+ }+}++#[async_trait]+impl ObjectStore for ReadAheadStore {+ 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> {+ self.inner.get_opts(location, options).await+ }++ async fn get_ranges(+ &self,+ location: &Path,+ ranges: &[Range<u64>],+ ) -> object_store::Result<Vec<Bytes>> {+ let valid = ranges.iter().all(|r| r.start < r.end);+ let group = match (valid && location == &self.path).then(|| self.group_of(ranges)) {+ Some(Some(group)) => group,+ _ => return self.inner.get_ranges(location, ranges).await,+ };+ let data = match self.take_pending() {+ Some(mut pending) if pending.group == group => {+ counter!("deltalite_row_group_read_ahead_total", "outcome" => "hit").increment(1);+ let span =+ (&mut pending.read.0)+ .await+ .map_err(|e| object_store::Error::Generic {+ store: "deltalite",+ source: Box::new(e),+ })??;+ let Range { start: base, end } = self.groups[group].clone();+ if span.len() as u64 != end - base {+ return Err(object_store::Error::Generic {+ store: "deltalite",+ source: format!(+ "read ahead of {} for bytes {base}..{end} returned {} bytes",+ self.path,+ span.len()+ )+ .into(),+ });+ }+ ranges+ .iter()+ .map(|r| span.slice((r.start - base) as usize..(r.end - base) as usize))+ .collect()+ }+ other => {+ if other.is_some() {+ counter!("deltalite_row_group_read_ahead_total", "outcome" => "miss")+ .increment(1);+ }+ drop(other);+ self.inner.get_ranges(location, ranges).await?+ }+ };+ self.read_ahead(group + 1);+ Ok(data)+ }++ 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+ }+}diff --git a/rust/deltalite/core/src/store.rs b/rust/deltalite/core/src/store.rsindex e3896782de04..bf0626331b00 100644--- a/rust/deltalite/core/src/store.rs+++ b/rust/deltalite/core/src/store.rs@@ -1,4 +1,4 @@-//! Multipart upload for large data files.+//! Multipart upload for large data files, and split ranged reads of them.//!//! The partition writer (`crate::writer`, like delta-rs's `RecordBatchWriter`)//! uploads each finished Parquet file through `ObjectStore::put` -- a single PUT (~`target_file_size` bytes, 100 MB by default).@@ -12,6 +12,12 @@//! overwrite `put`s above a size threshold become multipart uploads, and//! [`MultipartLogStore`] wraps a log store to hand that store to the writer.//!+//! One S3 connection moves a few tens of MB/s, so a data file that is uploaded or read+//! on one connection spends most of its time on bandwidth, not on request latency. The+//! wrapper therefore uploads several parts of a file at once, and splits a large ranged+//! read of a data file (a whole row group for a rewrite) into concurrent requests. The+//! readers of the probe and the rewrite read through the same store.+//!//! Commit safety is deliberately untouched: log-store commit writes go through//! `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@@ -21,6 +27,7 @@//! commit put ("what is the latest version?") without a LIST of the log; see//! [`CommitProbe`].+use std::ops::Range;use std::sync::{Arc, Mutex};use std::time::Instant;@@ -28,60 +35,90 @@ 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 futures::stream::{BoxStream, FuturesUnordered, StreamExt, TryStreamExt};+use futures::FutureExt;use metrics::counter;use object_store::path::Path;use object_store::{- GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, ObjectStoreExt,- PutMode, PutMultipartOptions, PutOptions, PutPayload, PutResult,+ GetOptions, GetRange, GetResult, GetResultPayload, ListResult, MultipartUpload, ObjectMeta,+ ObjectStore, ObjectStoreExt, PutMode, PutMultipartOptions, PutOptions, PutPayload, PutResult,};use uuid::Uuid;use crate::logprobe::{commit_path, probe_log, LogAnchor, LogProbe};+use crate::table::MultipartConfig;++/// Default size above which a single `put` becomes a multipart upload. One S3 stream+/// moves data much slower than a few streams in parallel, so a file of a few part sizes+/// already uploads faster as concurrent parts than as one PUT.+pub const DEFAULT_MULTIPART_THRESHOLD: usize = 16 * 1024 * 1024;+/// Default part size for multipart uploads. S3 needs at least 5 MiB per part.+pub const DEFAULT_MULTIPART_PART_SIZE: usize = 8 * 1024 * 1024;+/// Default number of parts of one upload in flight at once.+pub const DEFAULT_MULTIPART_CONCURRENCY: usize = 4;+/// Multipart threshold when parts upload one after another: a serial multipart upload+/// is slower than one PUT of the same bytes, so it is used only for large files, where a+/// connection reset must not restart the whole upload.+pub const SERIAL_MULTIPART_THRESHOLD: usize = 64 * 1024 * 1024;+/// Part size when parts upload one after another.+pub const SERIAL_MULTIPART_PART_SIZE: usize = 16 * 1024 * 1024;+/// Default request size of a split ranged read of a data file.+pub const DEFAULT_RANGE_GET_PART_SIZE: usize = 8 * 1024 * 1024;+/// Default number of requests of one split ranged read in flight at once.+pub const DEFAULT_RANGE_GET_CONCURRENCY: usize = 4;-/// 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-/// count against retry granularity.-pub const DEFAULT_MULTIPART_PART_SIZE: usize = 16 * 1024 * 1024;+/// Gap below which two requested ranges are read with one request, as `object_store`+/// coalesces them.+const RANGE_COALESCE_BYTES: u64 = object_store::OBJECT_STORE_COALESCE_DEFAULT;/// Objects deleted concurrently by the per-object `delete_stream` override.const DELETE_CONCURRENCY: usize = 16;/// An [`ObjectStore`] wrapper that turns large plain-overwrite `put`s into multipart-/// uploads and delegates everything else.+/// uploads with concurrent parts, splits large ranged reads of data files into+/// concurrent requests, and delegates everything else.+///+/// Neither rewrite adds memory: the parts of an upload are slices of the payload the+/// caller already holds, and a split read streams each request into its place in one+/// buffer of the size that a single request returns.#[derive(Debug)]pub struct MultipartPutStore {inner: Arc<dyn ObjectStore>,- threshold: usize,- part_size: usize,+ config: MultipartConfig,}impl MultipartPutStore {- /// Wrap `inner`; `threshold` of 0 disables the rewrite (pure delegation).- pub fn new(inner: Arc<dyn ObjectStore>, threshold: usize, part_size: usize) -> Self {+ /// Wrap `inner`; a `threshold` of 0 disables the upload rewrite and a+ /// `range_concurrency` of 1 disables the read split.+ pub fn new(inner: Arc<dyn ObjectStore>, config: MultipartConfig) -> Self {Self {inner,- threshold,- part_size: part_size.max(5 * 1024 * 1024),+ config: MultipartConfig {+ part_size: config.part_size.max(5 * 1024 * 1024),+ concurrency: config.concurrency.max(1),+ range_part_size: config.range_part_size.max(1),+ range_concurrency: config.range_concurrency.max(1),+ ..config+ },}}/// Split `payload` into parts of at most `part_size` bytes, zero-copy (`Bytes`/// slices share the underlying allocation).fn split_parts(&self, payload: &PutPayload) -> Vec<PutPayload> {+ let part_size = self.config.part_size;let mut parts: Vec<PutPayload> = Vec::new();let mut current: Vec<Bytes> = Vec::new();let mut current_len = 0usize;for chunk in payload.as_ref() {let mut offset = 0usize;while offset < chunk.len() {- let room = self.part_size - current_len;+ let room = part_size - current_len;let take = room.min(chunk.len() - offset);current.push(chunk.slice(offset..offset + take));current_len += take;offset += take;- if current_len == self.part_size {+ if current_len == part_size {parts.push(PutPayload::from_iter(current.drain(..)));current_len = 0;}@@ -92,6 +129,172 @@ impl MultipartPutStore {}parts}++ /// Upload every part with at most `concurrency` in flight. The part number of each+ /// part is fixed when `put_part` is called, in payload order, so the completion+ /// order does not change the assembled object.+ ///+ /// After a part fails no new part starts, and the parts already started run to the+ /// end: S3 may still store a part whose request was dropped, after the abort.+ async fn upload_parts(+ &self,+ upload: &mut Box<dyn MultipartUpload>,+ parts: Vec<PutPayload>,+ ) -> object_store::Result<()> {+ let mut parts = parts.into_iter();+ let mut in_flight = FuturesUnordered::new();+ let mut first_error = None;+ loop {+ while first_error.is_none() && in_flight.len() < self.config.concurrency {+ let Some(part) = parts.next() else { break };+ in_flight.push(upload.put_part(part));+ }+ match in_flight.next().await {+ Some(Err(e)) => {+ first_error.get_or_insert(e);+ }+ Some(Ok(())) => {}+ None => break,+ }+ }+ match first_error {+ Some(e) => Err(e),+ None => Ok(()),+ }+ }++ /// Whether ranged reads of `location` may be split: data files only. Log files keep+ /// their exact reads, which the checkpoint prefetch below this store serves.+ fn splits_reads_of(&self, location: &Path) -> bool {+ self.config.range_concurrency > 1 && !location.parts().any(|p| p.as_ref() == "_delta_log")+ }++ /// Read each range of `ranges` as requests of at most `range_part_size` bytes, each+ /// streamed into its own slice of the buffer of its range. The requests of all the+ /// ranges share one queue of `range_concurrency`.+ async fn get_split(+ &self,+ location: &Path,+ ranges: &[Range<u64>],+ ) -> object_store::Result<Vec<Bytes>> {+ let piece = self.config.range_part_size;+ let mut bufs = ranges+ .iter()+ .map(|r| {+ usize::try_from(r.end - r.start)+ .map(|len| vec![0u8; len])+ .map_err(|e| object_store::Error::Generic {+ store: "deltalite",+ source: Box::new(e),+ })+ })+ .collect::<object_store::Result<Vec<Vec<u8>>>>()?;+ let reads: Vec<_> = ranges+ .iter()+ .zip(bufs.iter_mut())+ .flat_map(move |(range, buf)| {+ buf.chunks_mut(piece).enumerate().map(move |(i, dst)| {+ let start = range.start + (i * piece) as u64;+ self.read_into(location, start..start + dst.len() as u64, dst)+ .boxed()+ })+ })+ .collect();+ futures::stream::iter(reads)+ .buffer_unordered(self.config.range_concurrency)+ .try_collect::<()>()+ .await?;+ Ok(bufs.into_iter().map(Bytes::from).collect())+ }++ async fn read_into(+ &self,+ location: &Path,+ range: Range<u64>,+ dst: &mut [u8],+ ) -> object_store::Result<()> {+ let options = GetOptions {+ range: Some(GetRange::Bounded(range.clone())),+ ..Default::default()+ };+ let mut result = self.inner.get_opts(location, options).await?;+ // A local file would stream in 8 KiB reads; read it straight into `dst` without+ // blocking a Tokio worker.+ if let GetResultPayload::File(file, _) = &mut result.payload {+ return read_file_into(file, location, &range, dst).await;+ }+ let mut stream = result.into_stream();+ let mut filled = 0usize;+ while let Some(chunk) = stream.next().await {+ let chunk = chunk?;+ let end = filled + chunk.len();+ if end > dst.len() {+ return Err(short_read(location, &range, end));+ }+ dst[filled..end].copy_from_slice(&chunk);+ filled = end;+ }+ if filled != dst.len() {+ return Err(short_read(location, &range, filled));+ }+ Ok(())+ }+}++async fn read_file_into(+ file: &std::fs::File,+ location: &Path,+ range: &Range<u64>,+ dst: &mut [u8],+) -> object_store::Result<()> {+ use tokio::io::{AsyncReadExt, AsyncSeekExt};++ let generic = |e: std::io::Error| object_store::Error::Generic {+ store: "deltalite",+ source: Box::new(e),+ };+ let mut file = tokio::fs::File::from_std(file.try_clone().map_err(generic)?);+ file.seek(std::io::SeekFrom::Start(range.start))+ .await+ .map_err(generic)?;+ let mut filled = 0usize;+ while filled < dst.len() {+ match file.read(&mut dst[filled..]).await {+ Ok(0) => return Err(short_read(location, range, filled)),+ Ok(n) => filled += n,+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}+ Err(e) => return Err(generic(e)),+ }+ }+ Ok(())+}++fn short_read(location: &Path, range: &Range<u64>, got: usize) -> object_store::Error {+ object_store::Error::Generic {+ store: "deltalite",+ source: format!(+ "ranged read of {location} for bytes {range:?} returned {got} bytes, expected {}",+ range.end - range.start+ )+ .into(),+ }+}++/// `ranges` merged where they overlap or lie within [`RANGE_COALESCE_BYTES`] of each+/// other, sorted by start.+fn merge_ranges(ranges: &[Range<u64>]) -> Vec<Range<u64>> {+ let mut sorted: Vec<Range<u64>> = ranges.to_vec();+ sorted.sort_unstable_by_key(|r| r.start);+ let mut merged: Vec<Range<u64>> = Vec::with_capacity(sorted.len());+ for r in sorted {+ match merged.last_mut() {+ Some(last) if r.start <= last.end.saturating_add(RANGE_COALESCE_BYTES) => {+ last.end = last.end.max(r.end);+ }+ _ => merged.push(r),+ }+ }+ merged}impl std::fmt::Display for MultipartPutStore {@@ -111,9 +314,9 @@ impl ObjectStore for MultipartPutStore {// Only rewrite the plain overwrite path (data-file uploads). Conditional puts// (PutMode::Create -- Delta log commits -- or Update) must keep their exact// semantics, so they are forwarded untouched.- if self.threshold == 0+ if self.config.threshold == 0|| !matches!(opts.mode, PutMode::Overwrite)- || payload.content_length() < self.threshold+ || payload.content_length() < self.config.threshold{return self.inner.put_opts(location, payload, opts).await;}@@ -127,13 +330,13 @@ impl ObjectStore for MultipartPutStore {.inner.put_multipart_opts(location, multipart_opts).await?;- for part in self.split_parts(&payload) {- if let Err(e) = upload.put_part(part).await {- // Best-effort cleanup of the incomplete upload; the original error is- // what the caller needs to see.- drop(upload.abort().await);- return Err(e);- }+ let parts = self.split_parts(&payload);+ if let Err(e) = self.upload_parts(&mut upload, parts).await {+ // Best-effort cleanup of the incomplete upload; the original error is what+ // the caller needs to see. The parts in flight finished above, and without+ // `complete` no object is created.+ drop(upload.abort().await);+ return Err(e);}match upload.complete().await {Ok(result) => Ok(result),@@ -165,7 +368,23 @@ impl ObjectStore for MultipartPutStore {location: &Path,ranges: &[std::ops::Range<u64>],) -> object_store::Result<Vec<Bytes>> {- self.inner.get_ranges(location, ranges).await+ if !self.splits_reads_of(location) || ranges.iter().any(|r| r.start >= r.end) {+ return self.inner.get_ranges(location, ranges).await;+ }+ let merged = merge_ranges(ranges);+ let split_above = self.config.range_part_size as u64;+ if merged.iter().all(|m| m.end - m.start <= split_above) {+ return self.inner.get_ranges(location, ranges).await;+ }+ let fetched = self.get_split(location, &merged).await?;+ Ok(ranges+ .iter()+ .map(|r| {+ let i = merged.partition_point(|m| m.start <= r.start) - 1;+ let base = merged[i].start;+ fetched[i].slice((r.start - base) as usize..(r.end - base) as usize)+ })+ .collect())}fn delete_stream(@@ -233,8 +452,7 @@ impl ObjectStore for MultipartPutStore {/// on the inner log store's own path.pub struct MultipartLogStore {inner: Arc<dyn LogStore>,- threshold: usize,- part_size: usize,+ config: MultipartConfig,commit_probe: Option<CommitProbe>,}@@ -317,12 +535,11 @@ fn replaced_table_error(version: u64) -> deltalake::DeltaTableError {}impl MultipartLogStore {- /// Wrap `inner` with the given multipart threshold and part size.- pub fn new(inner: Arc<dyn LogStore>, threshold: usize, part_size: usize) -> Self {+ /// Wrap `inner` with the given upload and read settings.+ pub fn new(inner: Arc<dyn LogStore>, config: MultipartConfig) -> Self {Self {inner,- threshold,- part_size,+ config,commit_probe: None,}}@@ -415,16 +632,14 @@ impl LogStore for MultipartLogStore {fn object_store(&self, operation_id: Option<Uuid>) -> Arc<dyn ObjectStore> {Arc::new(MultipartPutStore::new(self.inner.object_store(operation_id),- self.threshold,- self.part_size,+ self.config,))}fn root_object_store(&self, operation_id: Option<Uuid>) -> Arc<dyn ObjectStore> {Arc::new(MultipartPutStore::new(self.inner.root_object_store(operation_id),- self.threshold,- self.part_size,+ self.config,))}@@ -434,6 +649,8 @@ impl LogStore for MultipartLogStore {}#[cfg(test)]+// Single ranges in arrays are requests of one range here, not ranges to expand.+#[allow(clippy::single_range_in_vec_init)]mod tests {use super::*;use object_store::memory::InMemory;@@ -443,10 +660,207 @@ mod tests {PutPayload::from_bytes(Bytes::from(vec![7u8; len]))}+ const MIB: usize = 1024 * 1024;++ fn config(threshold: usize, part_size: usize, concurrency: usize) -> MultipartConfig {+ MultipartConfig {+ threshold,+ part_size,+ concurrency,+ range_part_size: DEFAULT_RANGE_GET_PART_SIZE,+ range_concurrency: 1,+ }+ }++ fn reads(range_part_size: usize, range_concurrency: usize) -> MultipartConfig {+ MultipartConfig {+ range_part_size,+ range_concurrency,+ ..config(0, 0, 1)+ }+ }++ fn pattern(len: usize) -> Vec<u8> {+ (0..len).map(|i| (i % 251) as u8).collect()+ }++ /// Counts requests and the most of them in flight at once. Each part upload and each+ /// read yields to the runtime before it runs, so the requests a caller issues+ /// together overlap; a part with a lower number yields more often, so the parts+ /// complete in reverse order.+ #[derive(Debug, Default)]+ struct Probe {+ gets: std::sync::atomic::AtomicUsize,+ in_flight: std::sync::atomic::AtomicUsize,+ max_in_flight: std::sync::atomic::AtomicUsize,+ aborted: std::sync::atomic::AtomicBool,+ }++ impl Probe {+ fn enter(&self) {+ use std::sync::atomic::Ordering::SeqCst;+ let now = self.in_flight.fetch_add(1, SeqCst) + 1;+ self.max_in_flight.fetch_max(now, SeqCst);+ }+ fn leave(&self) {+ self.in_flight+ .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);+ }+ fn max_in_flight(&self) -> usize {+ self.max_in_flight.load(std::sync::atomic::Ordering::SeqCst)+ }+ fn gets(&self) -> usize {+ self.gets.load(std::sync::atomic::Ordering::SeqCst)+ }+ fn aborted(&self) -> bool {+ self.aborted.load(std::sync::atomic::Ordering::SeqCst)+ }+ }++ async fn yield_times(n: usize) {+ for _ in 0..n {+ tokio::task::yield_now().await;+ }+ }++ #[derive(Debug)]+ struct ProbedUpload {+ inner: Box<dyn MultipartUpload>,+ probe: Arc<Probe>,+ next: usize,+ fail_part: Option<usize>,+ }++ #[async_trait]+ impl MultipartUpload for ProbedUpload {+ fn put_part(&mut self, data: PutPayload) -> object_store::UploadPart {+ let idx = self.next;+ self.next += 1;+ let fail = self.fail_part == Some(idx);+ let probe = self.probe.clone();+ let put = self.inner.put_part(data);+ Box::pin(async move {+ probe.enter();+ yield_times(16usize.saturating_sub(idx)).await;+ probe.leave();+ if fail {+ return Err(object_store::Error::Generic {+ store: "test",+ source: format!("part {idx} failed").into(),+ });+ }+ put.await+ })+ }+ async fn complete(&mut self) -> object_store::Result<PutResult> {+ self.inner.complete().await+ }+ async fn abort(&mut self) -> object_store::Result<()> {+ self.probe+ .aborted+ .store(true, std::sync::atomic::Ordering::SeqCst);+ self.inner.abort().await+ }+ }++ #[derive(Debug)]+ struct ProbedStore {+ inner: Arc<InMemory>,+ probe: Arc<Probe>,+ fail_part: Option<usize>,+ }++ impl ProbedStore {+ fn new(fail_part: Option<usize>) -> Arc<Self> {+ Arc::new(Self {+ inner: Arc::new(InMemory::new()),+ probe: Arc::default(),+ fail_part,+ })+ }+ }++ impl std::fmt::Display for ProbedStore {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "ProbedStore")+ }+ }++ #[async_trait]+ impl ObjectStore for ProbedStore {+ 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>> {+ Ok(Box::new(ProbedUpload {+ inner: self.inner.put_multipart_opts(location, opts).await?,+ probe: self.probe.clone(),+ next: 0,+ fail_part: self.fail_part,+ }))+ }+ async fn get_opts(+ &self,+ location: &Path,+ options: GetOptions,+ ) -> object_store::Result<GetResult> {+ self.probe+ .gets+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ self.probe.enter();+ yield_times(4).await;+ self.probe.leave();+ self.inner.get_opts(location, options).await+ }+ 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)+ }+ 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+ }+ }+#[tokio::test]async fn small_put_is_delegated_and_readable() {let inner = Arc::new(InMemory::new());- let store = MultipartPutStore::new(inner.clone(), 1024, 5 * 1024 * 1024);+ let store = MultipartPutStore::new(inner.clone(), config(1024, 5 * MIB, 4));let path = Path::from("small");store.put(&path, payload_of(100)).await.unwrap();let got = inner.get(&path).await.unwrap().bytes().await.unwrap();@@ -454,27 +868,69 @@ mod tests {}#[tokio::test]- async fn large_put_goes_multipart_and_content_is_identical() {- let inner = Arc::new(InMemory::new());- // Force multipart with a tiny threshold; part size is clamped to >= 5 MiB, so- // use a payload bigger than one part to exercise splitting.- let store = MultipartPutStore::new(inner.clone(), 1024, 5 * 1024 * 1024);- let path = Path::from("large");- let len = 11 * 1024 * 1024; // 3 parts at 5 MiB- let mut data = Vec::with_capacity(len);- for i in 0..len {- data.push((i % 251) as u8);- }- let payload = PutPayload::from_bytes(Bytes::from(data.clone()));- store.put(&path, payload).await.unwrap();- let got = inner.get(&path).await.unwrap().bytes().await.unwrap();- assert_eq!(got.as_ref(), data.as_slice(), "content must round-trip");+ async fn multipart_uploads_assemble_parts_in_order_at_every_boundary() {+ // (payload length, chunk length of the payload, concurrency). Part size is 5 MiB.+ let cases = [+ (10 * MIB, MIB, 1),+ (10 * MIB, MIB, 4),+ (10 * MIB + 1, 3 * MIB + 7, 4),+ (15 * MIB - 1, 5 * MIB, 4),+ (5 * MIB + 1, 5 * MIB + 1, 4),+ (31 * MIB + 123, 7 * MIB + 5, 3),+ (31 * MIB + 123, 7 * MIB + 5, 16),+ ];+ for (len, chunk, concurrency) in cases {+ let store = ProbedStore::new(None);+ let wrapped = MultipartPutStore::new(store.clone(), config(1024, 5 * MIB, concurrency));+ let data = pattern(len);+ let payload = PutPayload::from_iter(data.chunks(chunk).map(Bytes::copy_from_slice));+ let path = Path::from("large");+ wrapped.put(&path, payload).await.unwrap();++ let got = store.inner.get(&path).await.unwrap().bytes().await.unwrap();+ assert!(+ got.as_ref() == data.as_slice(),+ "content differs for {len} bytes at concurrency {concurrency}"+ );+ let parts = len.div_ceil(5 * MIB);+ assert_eq!(+ store.probe.max_in_flight(),+ concurrency.min(parts),+ "parts in flight for {len} bytes at concurrency {concurrency}"+ );+ }+ }++ #[tokio::test]+ async fn a_failed_part_aborts_the_upload_and_creates_no_object() {+ // (failing part of 4, concurrency)+ for (fail_part, concurrency) in [(0, 1), (2, 1), (0, 4), (2, 4), (3, 4)] {+ let store = ProbedStore::new(Some(fail_part));+ let wrapped = MultipartPutStore::new(store.clone(), config(1024, 5 * MIB, concurrency));+ let path = Path::from("failed");+ let err = wrapped.put(&path, payload_of(20 * MIB)).await.unwrap_err();+ assert!(+ err.to_string()+ .contains(&format!("part {fail_part} failed")),+ "{err}"+ );+ assert!(store.probe.aborted(), "the upload must be aborted");+ assert_eq!(+ store.probe.in_flight.load(std::sync::atomic::Ordering::SeqCst),+ 0,+ "parts already started must finish before the abort (part {fail_part}, concurrency {concurrency})"+ );+ assert!(+ matches!(store.inner.head(&path).await, Err(object_store::Error::NotFound { .. })),+ "no object may exist after a failed upload (part {fail_part}, concurrency {concurrency})"+ );+ }}#[tokio::test]async fn conditional_puts_are_never_rewritten() {let inner = Arc::new(InMemory::new());- let store = MultipartPutStore::new(inner.clone(), 1, 5 * 1024 * 1024);+ let store = MultipartPutStore::new(inner.clone(), config(1, 5 * MIB, 4));let path = Path::from("commit");let opts = PutOptions::from(PutMode::Create);store@@ -492,7 +948,7 @@ mod tests {#[test]fn split_parts_respects_part_size_and_preserves_bytes() {- let store = MultipartPutStore::new(Arc::new(InMemory::new()), 1, 5 * 1024 * 1024);+ let store = MultipartPutStore::new(Arc::new(InMemory::new()), config(1, 5 * MIB, 1));let a = Bytes::from(vec![1u8; 3 * 1024 * 1024]);let b = Bytes::from(vec![2u8; 9 * 1024 * 1024]);let payload = PutPayload::from_iter(vec![a, b]);@@ -503,6 +959,98 @@ mod tests {assert_eq!(total, 12 * 1024 * 1024);}+ #[tokio::test]+ async fn split_ranged_reads_return_the_requested_bytes() {+ let len = 3 * MIB;+ let data = pattern(len);+ let far = 2 * MIB as u64;+ // (requested ranges, requests expected) at 1,000-byte requests, 3 at once.+ let cases: Vec<(Vec<Range<u64>>, usize)> = vec![+ (vec![0..1_000], 1),+ (vec![0..1_001], 2),+ (vec![17..5_017], 5),+ (vec![3..2_999, 3_100..9_000, 2_500..2_600], 9),+ (vec![0..10, far..far + 2_999], 4),+ (vec![(len as u64) - 4_321..len as u64], 5),+ ];+ for (ranges, requests) in cases {+ let store = ProbedStore::new(None);+ let path = Path::from("data/part-0.parquet");+ store+ .inner+ .put(&path, PutPayload::from(data.clone()))+ .await+ .unwrap();+ let wrapped = MultipartPutStore::new(store.clone(), reads(1_000, 3));++ let got = wrapped.get_ranges(&path, &ranges).await.unwrap();+ for (r, bytes) in ranges.iter().zip(&got) {+ assert!(+ bytes.as_ref() == &data[r.start as usize..r.end as usize],+ "bytes differ for {r:?} of {ranges:?}"+ );+ }+ assert_eq!(store.probe.gets(), requests, "requests for {ranges:?}");+ assert!(store.probe.max_in_flight() <= 3, "{ranges:?}");+ }+ }++ #[tokio::test]+ async fn ranged_reads_are_not_split_for_log_files_or_at_concurrency_one() {+ for (path, concurrency) in [+ ("t/_delta_log/00000000000000000010.checkpoint.parquet", 4),+ ("t/part-0.parquet", 1),+ ] {+ let store = ProbedStore::new(None);+ let path = Path::from(path);+ store+ .inner+ .put(&path, PutPayload::from(pattern(10_000)))+ .await+ .unwrap();+ let wrapped = MultipartPutStore::new(store.clone(), reads(1_000, concurrency));+ let got = wrapped.get_ranges(&path, &[0..9_000]).await.unwrap();+ assert_eq!(got[0].len(), 9_000);+ assert_eq!(store.probe.gets(), 1, "{path}");+ }+ }++ #[tokio::test]+ async fn a_short_object_fails_a_split_read() {+ let store = ProbedStore::new(None);+ let path = Path::from("data/part-0.parquet");+ store+ .inner+ .put(&path, PutPayload::from(pattern(2_500)))+ .await+ .unwrap();+ let wrapped = MultipartPutStore::new(store.clone(), reads(1_000, 4));+ assert!(wrapped.get_ranges(&path, &[0..3_000]).await.is_err());+ }++ #[tokio::test]+ async fn split_ranged_reads_of_local_files_return_the_requested_bytes() {+ let dir = tempfile::tempdir().unwrap();+ let local =+ Arc::new(object_store::local::LocalFileSystem::new_with_prefix(dir.path()).unwrap());+ let path = Path::from("data/part-0.parquet");+ let data = pattern(5_000);+ local+ .put(&path, PutPayload::from(data.clone()))+ .await+ .unwrap();+ let wrapped = MultipartPutStore::new(local, reads(1_000, 3));+ let ranges = [17..2_517, 4_000..5_000];+ let got = wrapped.get_ranges(&path, &ranges).await.unwrap();+ for (r, bytes) in ranges.iter().zip(&got) {+ assert!(+ bytes.as_ref() == &data[r.start as usize..r.end as usize],+ "{r:?}"+ );+ }+ assert!(wrapped.get_ranges(&path, &[3_000..6_000]).await.is_err());+ }+/// A log store over an in-memory object store that counts the LIST-based version/// questions it answers.struct FakeLogStore {@@ -578,7 +1126,7 @@ mod tests {latest: 9,listings: Default::default(),});- let wrapped = MultipartLogStore::new(fake.clone(), 0, 0)+ let wrapped = MultipartLogStore::new(fake.clone(), MultipartConfig::default()).with_commit_probe(CommitProbe::new(anchor, deadline));(fake, wrapped)}diff --git a/rust/deltalite/core/src/table.rs b/rust/deltalite/core/src/table.rsindex 1cc4258f79e5..f6371e58c094 100644--- a/rust/deltalite/core/src/table.rs+++ b/rust/deltalite/core/src/table.rs@@ -9,37 +9,101 @@ use crate::errors::{Error, Result};use crate::prefetch::{CheckpointCache, CheckpointPrefetchLogStore};use crate::store::{CommitProbe, MultipartLogStore};-/// How data-file uploads are performed.+/// How data files are uploaded and read.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct MultipartConfig {/// Files at or above this size upload as multipart; 0 disables the rewrite.pub threshold: usize,/// Part size for multipart uploads (clamped to >= 5 MiB by the store wrapper).pub part_size: usize,+ /// Parts of one multipart upload in flight at once; 1 uploads them one after another.+ pub concurrency: usize,+ /// A ranged read of a data file larger than this is split into concurrent requests of+ /// this size.+ pub range_part_size: usize,+ /// Requests of one split ranged read in flight at once; 1 disables the split.+ pub range_concurrency: usize,}impl Default for MultipartConfig {fn default() -> Self {- Self {- threshold: crate::store::DEFAULT_MULTIPART_THRESHOLD,- part_size: crate::store::DEFAULT_MULTIPART_PART_SIZE,- }+ Self::resolve_with(None, None, None, None, None, |_, default| default)}}impl MultipartConfig {- /// Resolve from explicit arguments, then `DELTALITE_MULTIPART_THRESHOLD_BYTES` /- /// `DELTALITE_MULTIPART_PART_SIZE_BYTES`, then the defaults. An explicit- /// `Some(0)` threshold disables multipart entirely.- pub fn resolve(threshold: Option<usize>, part_size: Option<usize>) -> Self {- let d = Self::default();+ /// Resolve from explicit arguments, then `DELTALITE_MULTIPART_THRESHOLD_BYTES`,+ /// `DELTALITE_MULTIPART_PART_SIZE_BYTES`, `DELTALITE_MULTIPART_CONCURRENCY`,+ /// `DELTALITE_RANGE_GET_PART_SIZE_BYTES` and `DELTALITE_RANGE_GET_CONCURRENCY`, then the+ /// defaults. An explicit `Some(0)` threshold disables multipart entirely.+ ///+ /// The threshold and part size default to the serial values when the concurrency is 1,+ /// so a concurrency of 1 restores the upload behavior from before concurrent parts.+ pub fn resolve(+ threshold: Option<usize>,+ part_size: Option<usize>,+ concurrency: Option<usize>,+ range_part_size: Option<usize>,+ range_concurrency: Option<usize>,+ ) -> Self {+ Self::resolve_with(+ threshold,+ part_size,+ concurrency,+ range_part_size,+ range_concurrency,+ crate::limits::env_usize,+ )+ }++ fn resolve_with(+ threshold: Option<usize>,+ part_size: Option<usize>,+ concurrency: Option<usize>,+ range_part_size: Option<usize>,+ range_concurrency: Option<usize>,+ env: impl Fn(&str, usize) -> usize,+ ) -> Self {+ use crate::store::{+ DEFAULT_MULTIPART_CONCURRENCY, DEFAULT_MULTIPART_PART_SIZE,+ DEFAULT_MULTIPART_THRESHOLD, DEFAULT_RANGE_GET_CONCURRENCY,+ DEFAULT_RANGE_GET_PART_SIZE, SERIAL_MULTIPART_PART_SIZE, SERIAL_MULTIPART_THRESHOLD,+ };+ let concurrency = concurrency+ .unwrap_or_else(|| {+ env(+ "DELTALITE_MULTIPART_CONCURRENCY",+ DEFAULT_MULTIPART_CONCURRENCY,+ )+ })+ .max(1);+ let (default_threshold, default_part_size) = if concurrency > 1 {+ (DEFAULT_MULTIPART_THRESHOLD, DEFAULT_MULTIPART_PART_SIZE)+ } else {+ (SERIAL_MULTIPART_THRESHOLD, SERIAL_MULTIPART_PART_SIZE)+ };Self {- threshold: threshold.unwrap_or_else(|| {- crate::limits::env_usize("DELTALITE_MULTIPART_THRESHOLD_BYTES", d.threshold)- }),- part_size: part_size.unwrap_or_else(|| {- crate::limits::env_usize("DELTALITE_MULTIPART_PART_SIZE_BYTES", d.part_size)- }),+ threshold: threshold+ .unwrap_or_else(|| env("DELTALITE_MULTIPART_THRESHOLD_BYTES", default_threshold)),+ part_size: part_size+ .unwrap_or_else(|| env("DELTALITE_MULTIPART_PART_SIZE_BYTES", default_part_size)),+ concurrency,+ range_part_size: range_part_size+ .unwrap_or_else(|| {+ env(+ "DELTALITE_RANGE_GET_PART_SIZE_BYTES",+ DEFAULT_RANGE_GET_PART_SIZE,+ )+ })+ .max(1),+ range_concurrency: range_concurrency+ .unwrap_or_else(|| {+ env(+ "DELTALITE_RANGE_GET_CONCURRENCY",+ DEFAULT_RANGE_GET_CONCURRENCY,+ )+ })+ .max(1),}}}@@ -114,11 +178,7 @@ pub fn wrap_multipart(table: DeltaTable, multipart: MultipartConfig) -> DeltaTabif multipart.threshold == 0 {return table;}- let wrapped = Arc::new(MultipartLogStore::new(- table.log_store(),- multipart.threshold,- multipart.part_size,- ));+ let wrapped = Arc::new(MultipartLogStore::new(table.log_store(), multipart));let mut wrapped_table = DeltaTable::new(wrapped, Default::default());wrapped_table.state = table.state;wrapped_table@@ -132,12 +192,15 @@ pub(crate) fn wrap_multipart_view(multipart: MultipartConfig,commit_probe: Option<CommitProbe>,) -> DeltaTable {- let threshold = if multipart.threshold == 0 {- usize::MAX- } else {- multipart.threshold+ let multipart = MultipartConfig {+ threshold: if multipart.threshold == 0 {+ usize::MAX+ } else {+ multipart.threshold+ },+ ..multipart};- let mut wrapped = MultipartLogStore::new(table.log_store(), threshold, multipart.part_size);+ let mut wrapped = MultipartLogStore::new(table.log_store(), multipart);if let Some(probe) = commit_probe {wrapped = wrapped.with_commit_probe(probe);}@@ -145,3 +208,45 @@ pub(crate) fn wrap_multipart_view(wrapped_table.state = table.state;wrapped_table}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::store::{+ DEFAULT_MULTIPART_PART_SIZE, DEFAULT_MULTIPART_THRESHOLD, SERIAL_MULTIPART_PART_SIZE,+ SERIAL_MULTIPART_THRESHOLD,+ };++ #[test]+ fn concurrency_one_restores_the_serial_upload_defaults() {+ let no_env = |_: &str, default: usize| default;+ let parallel = MultipartConfig::resolve_with(None, None, None, None, None, no_env);+ assert_eq!(parallel.threshold, DEFAULT_MULTIPART_THRESHOLD);+ assert_eq!(parallel.part_size, DEFAULT_MULTIPART_PART_SIZE);+ assert!(parallel.concurrency > 1 && parallel.range_concurrency > 1);++ let serial = MultipartConfig::resolve_with(None, None, Some(1), None, Some(1), no_env);+ assert_eq!(serial.threshold, SERIAL_MULTIPART_THRESHOLD);+ assert_eq!(serial.part_size, SERIAL_MULTIPART_PART_SIZE);++ let env_serial = MultipartConfig::resolve_with(None, None, None, None, None, |name, d| {+ if name == "DELTALITE_MULTIPART_CONCURRENCY" {+ 1+ } else {+ d+ }+ });+ assert_eq!(env_serial.threshold, SERIAL_MULTIPART_THRESHOLD);++ let explicit =+ MultipartConfig::resolve_with(Some(0), Some(6), Some(0), Some(0), Some(0), no_env);+ assert_eq!(+ (explicit.threshold, explicit.part_size, explicit.concurrency),+ (0, 6, 1)+ );+ assert_eq!(+ (explicit.range_part_size, explicit.range_concurrency),+ (1, 1)+ );+ }+}diff --git a/rust/deltalite/core/src/upsert.rs b/rust/deltalite/core/src/upsert.rsindex 226b7c7159bc..1c3b5d163296 100644--- a/rust/deltalite/core/src/upsert.rs+++ b/rust/deltalite/core/src/upsert.rs@@ -63,6 +63,7 @@ use crate::pkset::PkSet;use crate::probecache::{file_key, key_signature, sorted_intersect, CollectedKeys, KeyCollector, ProbeCache,};+use crate::readahead::{max_row_group_pair_fetch_bytes, ReadAheadStore};use crate::schema::{cast_to_schema, unknown_columns};use crate::smallfile::{fetch_small_file, reads_whole, SmallFileStore};use crate::writer::StreamingWriter;@@ -228,6 +229,11 @@ pub struct UpsertOptions {/// `max_parallel_files` whole files. A row group larger than the cap still runs, alone./// The process-wide cap in [`ProcessLimits`] applies on top.pub max_fetch_bytes: usize,+ /// Read the next row group of a file while the reader decodes the current one (see+ /// `crate::readahead`). A reader then holds up to two row groups, and reserves both+ /// from the fetch budget. A file whose two largest neighbouring row groups do not fit+ /// the fetch budget is read without read-ahead. Off by default.+ pub read_ahead_row_groups: bool,/// Commit retry budget handed to `CommitBuilder`.pub commit_max_retries: usize,/// Row-count granularity for Parquet reads and source-slice writes.@@ -286,6 +292,7 @@ impl Default for UpsertOptions {max_parallel_files: 4,max_buffered_bytes: 64 * 1024 * 1024,max_fetch_bytes: DEFAULT_MAX_FETCH_BYTES,+ read_ahead_row_groups: false,commit_max_retries: 15,read_batch_size: 8192,target_file_size: None,@@ -616,6 +623,12 @@ impl Budgets {})}+ /// Bytes of compressed row-group data one reader can hold without passing either+ /// fetch budget.+ pub(crate) fn fetch_cap_bytes(&self) -> usize {+ self.fetch_local_cap_kb.min(self.limits.fetch_cap_kb()) as usize * 1024+ }+/// Acquire byte budget for `bytes`, capped at both budgets' capacities so a batch/// larger than either budget still makes progress. Local before global, the fixed/// order used everywhere (see `crate::limits` module docs).@@ -2290,15 +2303,31 @@ async fn filter_file(budgets: Budgets,tx: mpsc::UnboundedSender<(RecordBatch, BudgetPermit)>,) -> Result<FileOutcome> {- let (builder, held_fetch) = open_builder(&store, &f, &budgets).await?;+ let (mut 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 = match held_fetch {Some(fetch) => fetch,None => {- budgets- .acquire_fetch(max_row_group_fetch_bytes(builder.metadata(), None))- .await?+ let meta = builder.metadata().clone();+ let pair = max_row_group_pair_fetch_bytes(&meta);+ if opts.read_ahead_row_groups+ && meta.num_row_groups() > 1+ && pair <= budgets.fetch_cap_bytes()+ {+ let path = Path::parse(&f.path)+ .map_err(|e| Error::Generic(format!("bad data file path {:?}: {e}", f.path)))?;+ let read_ahead: Arc<dyn ObjectStore> =+ Arc::new(ReadAheadStore::new(store.clone(), path.clone(), &meta));+ let reader = ParquetObjectReader::new(read_ahead, path).with_file_size(f.size);+ let arrow_meta = ArrowReaderMetadata::try_new(meta, Default::default())?;+ builder = ParquetRecordBatchStreamBuilder::new_with_metadata(reader, arrow_meta);+ budgets.acquire_fetch(pair).await?+ } else {+ budgets+ .acquire_fetch(max_row_group_fetch_bytes(&meta, None))+ .await?+ }}};let batch_rows = byte_bounded_batch_rows(diff --git a/rust/deltalite/core/tests/fetch_budget.rs b/rust/deltalite/core/tests/fetch_budget.rsindex 5e00461327c1..1848fc3026de 100644--- a/rust/deltalite/core/tests/fetch_budget.rs+++ b/rust/deltalite/core/tests/fetch_budget.rs@@ -33,6 +33,7 @@ use object_store::{PutMultipartOptions, PutOptions, PutPayload, PutResult, RenameOptions,};use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;+use parquet::file::properties::WriterProperties;// ---- live-fetched-bytes accounting ----------------------------------------------@@ -310,6 +311,15 @@ fn rows(/// A table of `FILES` single-row-group files per partition, written straight through/// delta-rs. Returns the table's URI and the largest compressed row group in bytes.async fn seed(dir: &std::path::Path, partitions: &[&str]) -> (String, usize) {+ seed_row_groups(dir, partitions, 1).await+}++/// [`seed`] with `row_groups` equal row groups per file.+async fn seed_row_groups(+ dir: &std::path::Path,+ partitions: &[&str],+ row_groups: usize,+) -> (String, usize) {let partitioned = !partitions.is_empty();let mut create = CreateBuilder::new().with_location(dir.to_str().unwrap())@@ -333,7 +343,12 @@ async fn seed(dir: &std::path::Path, partitions: &[&str]) -> (String, usize) {};for p in parts {for f in 0..FILES {- let mut w = RecordBatchWriter::for_table(&table).unwrap();+ let props = WriterProperties::builder()+ .set_max_row_group_row_count(Some(ROWS.div_ceil(row_groups)))+ .build();+ let mut w = RecordBatchWriter::for_table(&table)+ .unwrap()+ .with_writer_properties(props);w.write(rows(&s, f, &ids, 0, p)).await.unwrap();w.flush_and_commit(&mut table).await.unwrap();}@@ -347,18 +362,11 @@ async fn seed(dir: &std::path::Path, partitions: &[&str]) -> (String, usize) {.unwrap().metadata().clone();- assert_eq!(- meta.num_row_groups(),- 1,- "fixture files are single-row-group"- );- let rg: usize = meta- .row_group(0)- .columns()- .iter()- .map(|c| c.byte_range().1 as usize)- .sum();- max_rg = max_rg.max(rg);+ assert_eq!(meta.num_row_groups(), row_groups);+ for g in meta.row_groups() {+ let rg: usize = g.columns().iter().map(|c| c.byte_range().1 as usize).sum();+ max_rg = max_rg.max(rg);+ }}(format!("dlfetch://{}", dir.to_string_lossy()), max_rg)}@@ -465,6 +473,39 @@ async fn fetch_budget_bounds_live_fetched_bytes() {}}+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn read_ahead_holds_two_row_groups_only_when_the_budget_has_room() {+ register_scheme();+ // (budget in row groups, expected peak range in row groups)+ let cases: [(f64, f64, f64); 2] = [+ // Room for the pair: the reader holds its row group and the next.+ (2.5, 1.5, 2.5),+ // No room for the pair: the reader runs without read-ahead.+ (1.5, 0.9, 1.5),+ ];+ for (budget_rgs, min_peak, max_peak) in cases {+ let dir = tempfile::tempdir().unwrap();+ let (uri, rg) = seed_row_groups(dir.path(), &[], 4).await;+ let gauge = gauge_for(dir.path());+ let (s, batches) = source(&[]);+ let budget = (rg as f64 * budget_rgs) as usize;+ let mut o = opts(budget, roomy_limits());+ // One reader, so the peak measures what a single reader holds.+ o.max_parallel_files = 1;+ o.read_ahead_row_groups = true;+ let stats = run(&uri, s, batches, o).await;+ assert_rewrote_everything(&stats, 1);++ let peak = gauge.peak.load(Ordering::SeqCst) as f64 / rg as f64;+ assert!(+ (min_peak..=max_peak).contains(&peak),+ "budget {budget_rgs} row groups: peak live fetched bytes = {peak:.2} row groups, \+ expected {min_peak}..={max_peak}"+ );+ assert_eq!(gauge.live.load(Ordering::SeqCst), 0, "fetched bytes leaked");+ }+}+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]async fn process_fetch_budget_bounds_concurrent_upserts() {register_scheme();diff --git a/rust/deltalite/python/Cargo.toml b/rust/deltalite/python/Cargo.tomlindex 06636d3b831d..afc175eba7d2 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.14"+version = "0.1.15"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 13d9c14c8dbb..bfa1a7da51c5 100644--- a/rust/deltalite/python/README.md+++ b/rust/deltalite/python/README.md@@ -203,7 +203,10 @@ All inherit from `DeltaLiteError`, so you can catch the base or branch on kind:| `isolate_source_rows` | `False` | Write the batch's rows to their own files, apart from the unchanged rows copied out of the rewritten files. A later batch that touches the same rows then rewrites only those files. Costs up to one more file per touched partition. || `max_row_group_bytes` | `None` | Close an output row group at this many encoded bytes. A later upsert's reader fetches one whole row group at a time, so smaller row groups lower its memory. `None` closes row groups only at the encoder's row cap. || `max_source_bytes` | `2 GiB` | Oversized-batch guard (`0` disables). |-| `multipart_threshold` / `multipart_part_size` | `64 MiB` / `16 MiB` | Multipart upload thresholds (`0` threshold disables). |+| `multipart_threshold` / `multipart_part_size` | `16 MiB` / `8 MiB` | Multipart upload thresholds (`0` threshold disables). With `multipart_concurrency=1` the defaults are `64 MiB` / `16 MiB`. |+| `multipart_concurrency` | `4` | Parts of one upload sent at once. The parts are slices of the finished file, so more parts in flight add no memory. `1` sends them one after another. |+| `range_get_part_size` / `range_get_concurrency` | `8 MiB` / `4` | A ranged read of a data file (a row group) larger than the part size is split into requests of that size, this many at once. Each request writes into its place in one buffer, so the split adds no memory. `1` turns the split off. |+| `read_ahead_row_groups` | `False` | Read the next row group of a file while the current one decodes. A reader then holds up to two row groups, and reserves both from `max_fetch_bytes`; a file whose two largest neighbouring row groups do not fit is read without it. || `commit_max_retries` | `15` | Conditional-put commit retry budget. || `commit_metadata` | `None` | Extra key/values recorded in the Delta commit. || `use_probe_cache` | `True` | Use the process-wide probe cache (see below). `False` reads every candidate file from storage. |@@ -217,7 +220,9 @@ budgets:`DELTALITE_PROCESS_MAX_BUFFERED_BYTES` (256 MiB),`DELTALITE_PROCESS_MAX_FETCH_BYTES` (256 MiB),`DELTALITE_MAX_SOURCE_BYTES`, `DELTALITE_MULTIPART_THRESHOLD_BYTES`,-`DELTALITE_MULTIPART_PART_SIZE_BYTES`.+`DELTALITE_MULTIPART_PART_SIZE_BYTES`, `DELTALITE_MULTIPART_CONCURRENCY`,+`DELTALITE_RANGE_GET_PART_SIZE_BYTES`, `DELTALITE_RANGE_GET_CONCURRENCY`.+The last five are the defaults of the per-call arguments of the same names.**Probe cache.** The probe reads a footer and the PK column of every candidatefile, so on object storage its cost grows with the number of files in thediff --git a/rust/deltalite/python/pyproject.toml b/rust/deltalite/python/pyproject.tomlindex b7fcc623a468..80ade625212c 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.14"+version = "0.1.15"description = "Streaming partition upsert for Delta tables, replacing delta-rs SQL MERGE"readme = "README.md"requires-python = ">=3.12"diff --git a/rust/deltalite/python/src/lib.rs b/rust/deltalite/python/src/lib.rsindex 07ac05aca06f..8d5199be87f3 100644--- a/rust/deltalite/python/src/lib.rs+++ b/rust/deltalite/python/src/lib.rs@@ -386,7 +386,15 @@ impl DeltaLiteTable {/// `max_source_bytes` guards against oversized batches (resident source + estimated/// PK set); `0` disables the guard, `None` uses `DELTALITE_MAX_SOURCE_BYTES` or the/// built-in 2 GiB default. `multipart_threshold` / `multipart_part_size` control- /// multipart upload of output files (`0` threshold disables).+ /// multipart upload of output files (`0` threshold disables), and+ /// `multipart_concurrency` sets how many parts upload at once. A ranged read of a+ /// data file larger than `range_get_part_size` is split into requests of that size,+ /// `range_get_concurrency` at once. A concurrency of `1` turns either off; see the+ /// README for the defaults and environment variables.+ ///+ /// `read_ahead_row_groups=True` reads the next row group of a file while the+ /// current one decodes. A reader then holds up to two row groups from the fetch+ /// budget. Off by default.////// `max_fetch_bytes` caps the compressed row-group bytes this call's file readers/// hold between fetching and decoding (`DELTALITE_PROCESS_MAX_FETCH_BYTES` caps it@@ -423,6 +431,10 @@ impl DeltaLiteTable {max_source_bytes = None,multipart_threshold = None,multipart_part_size = None,+ multipart_concurrency = None,+ range_get_part_size = None,+ range_get_concurrency = None,+ read_ahead_row_groups = false,use_probe_cache = true,))]#[allow(clippy::too_many_arguments)]@@ -448,6 +460,10 @@ impl DeltaLiteTable {max_source_bytes: Option<usize>,multipart_threshold: Option<usize>,multipart_part_size: Option<usize>,+ multipart_concurrency: Option<usize>,+ range_get_part_size: Option<usize>,+ range_get_concurrency: Option<usize>,+ read_ahead_row_groups: bool,use_probe_cache: bool,) -> PyResult<UpsertStats> {// Import while holding the GIL (it reads a Python object), then release it for@@ -476,6 +492,7 @@ impl DeltaLiteTable {max_parallel_files,max_buffered_bytes,max_fetch_bytes,+ read_ahead_row_groups,commit_max_retries,read_batch_size,target_file_size,@@ -487,7 +504,13 @@ impl DeltaLiteTable {limits: ProcessLimits::global().clone(),probe_cache: use_probe_cache.then(|| ProbeCache::global().clone()),};- let multipart = MultipartConfig::resolve(multipart_threshold, multipart_part_size);+ let multipart = MultipartConfig::resolve(+ multipart_threshold,+ multipart_part_size,+ multipart_concurrency,+ range_get_part_size,+ range_get_concurrency,+ );// Conflict retries, snapshot refreshes and the post-commit reload all live in// `TableHandle::upsert` (shared with the Rust benchmarks); the handle refreshes@@ -538,6 +561,9 @@ impl DeltaLiteTable {dry_run = false,multipart_threshold = None,multipart_part_size = None,+ multipart_concurrency = None,+ range_get_part_size = None,+ range_get_concurrency = None,))]#[allow(clippy::too_many_arguments)]fn compact(@@ -561,6 +587,9 @@ impl DeltaLiteTable {dry_run: bool,multipart_threshold: Option<usize>,multipart_part_size: Option<usize>,+ multipart_concurrency: Option<usize>,+ range_get_part_size: Option<usize>,+ range_get_concurrency: Option<usize>,) -> PyResult<Py<PyAny>> {let opts = deltalite_core::CompactOptions {target_file_size,@@ -585,7 +614,13 @@ impl DeltaLiteTable {dry_run,limits: ProcessLimits::global().clone(),};- let multipart = MultipartConfig::resolve(multipart_threshold, multipart_part_size);+ let multipart = MultipartConfig::resolve(+ multipart_threshold,+ multipart_part_size,+ multipart_concurrency,+ range_get_part_size,+ range_get_concurrency,+ );let handle = &mut self.handle;let s = py.detach(|| runtime().block_on(handle.compact(opts, multipart)))