Skip to content

: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.

perf(deltalite): budget row-group fetches and stream parquet writes (#111440)

Tom Owerscfe7c9e07573
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index a96bbc916774..c7e6a24019e3 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -3947,17 +3947,22 @@ dependencies = [
"arrow-buffer",
"arrow-cast",
"arrow-data",
+ "arrow-ord",
"arrow-row",
"arrow-schema",
"arrow-select",
"async-trait",
+ "buoyant_kernel",
"bytes",
+ "chrono",
"deltalake",
"futures",
+ "indexmap 2.13.0",
"metrics",
"object_store",
"parquet",
"serde_json",
+ "sqlparser",
"tempfile",
"thiserror 2.0.18",
"tokio",
@@ -3968,7 +3973,7 @@ dependencies = [
[[package]]
name = "deltalite-python"
-version = "0.1.9"
+version = "0.1.10"
dependencies = [
"arrow",
"arrow-array",
diff --git a/rust/deltalite/README.md b/rust/deltalite/README.md
index 049a7bd9a71b..5b1982aa7085 100644
--- a/rust/deltalite/README.md
+++ b/rust/deltalite/README.md
@@ -2,9 +2,12 @@
Streaming partition-level upsert for Delta tables, replacing delta-rs's SQL
`MERGE` for the warehouse-sync incremental path. delta-rs stays the storage and
-protocol layer (log, checkpoints, Parquet writing, Add-action statistics, S3
-conditional-put commits, conflict resolution); only the *merge execution* is
-replaced.
+protocol layer (log, checkpoints, Parquet encoding, S3 conditional-put commits,
+conflict resolution); only the *merge execution* is replaced. Output files go
+through deltalite's own streaming writer (`core/src/writer.rs`), which encodes
+exactly what delta-rs's `RecordBatchWriter` encodes and builds the same Add-action
+statistics (code vendored from delta-rs in `core/src/stats.rs`), without holding a
+second copy of each file.
Why: MERGE executes a DataFusion hash join whose memory scales with the scanned
target and which deadlocks under a bounded memory pool
@@ -106,7 +109,8 @@ flag-gated change).
## Operational knobs
Per-call (arguments to `DeltaLiteTable.upsert`): `max_parallel_partitions` (2),
-`max_parallel_files` (4), `max_buffered_bytes` (64 MiB), `prune_strategy`
+`max_parallel_files` (4), `max_buffered_bytes` (64 MiB), `max_fetch_bytes`
+(128 MiB: compressed row-group bytes readers hold before decoding), `prune_strategy`
(`probe`), `probe_concurrency` (8), `read_batch_size` (8192),
`target_file_size` (table's `delta.targetFileSize`, else delta-rs's 100 MiB),
`max_source_bytes` (2 GiB guard), `multipart_threshold` (64 MiB) /
@@ -116,7 +120,8 @@ Process-global (environment, enforced on top of the per-call knobs so that
~15 concurrent upsert threads in one Temporal worker cannot multiply the
budgets): `DELTALITE_PROCESS_MAX_PARALLEL_PARTITIONS` (8),
`DELTALITE_PROCESS_MAX_PARALLEL_FILES` (16),
-`DELTALITE_PROCESS_MAX_BUFFERED_BYTES` (256 MiB), `DELTALITE_MAX_SOURCE_BYTES`,
+`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`.
For a rough starting point on a given pod, `python/deltalite_planner.py`
diff --git a/rust/deltalite/core/Cargo.toml b/rust/deltalite/core/Cargo.toml
index d7302d980bc9..eb61951a67fe 100644
--- a/rust/deltalite/core/Cargo.toml
+++ b/rust/deltalite/core/Cargo.toml
@@ -43,6 +43,17 @@ arrow-schema = { version = "58" }
arrow-select = { version = "58" }
parquet = { version = "58", features = ["async", "object_store"] }
object_store = { version = "0.13.2" }
+arrow-ord = { version = "58" }
+
+# Named only by the streaming writer and the stats code vendored from delta-rs
+# (src/stats.rs), which must build the exact `Add` actions `RecordBatchWriter` built.
+# All four are the crates `deltalake` already links -- delta_kernel is published as
+# `buoyant_kernel` and pinned to the version `deltalake` resolves -- so they add no
+# new code to the build.
+delta_kernel = { package = "buoyant_kernel", version = "=0.22.2", default-features = false }
+chrono = { workspace = true }
+indexmap = "2"
+sqlparser = "0.61"
async-trait = { workspace = true }
bytes = { workspace = true }
diff --git a/rust/deltalite/core/src/lib.rs b/rust/deltalite/core/src/lib.rs
index 1cb61965d9c9..cbaddd15de40 100644
--- a/rust/deltalite/core/src/lib.rs
+++ b/rust/deltalite/core/src/lib.rs
@@ -1,9 +1,10 @@
//! deltalite -- a purpose-built streaming partition upsert on top of the `deltalake`
//! crate, replacing delta-rs's SQL MERGE for PostHog's warehouse-sync incremental path.
//!
-//! Storage and protocol (log, checkpoints, Parquet writing, Add-action statistics,
-//! S3 conditional-put commits, conflict resolution) all come from `deltalake`. Only the
-//! *merge execution* is replaced: MERGE runs a DataFusion hash join whose memory scales
+//! Storage and protocol (log, checkpoints, Parquet encoding, S3 conditional-put
+//! commits, conflict resolution) all come from `deltalake`; output files go through
+//! the `writer` module's streaming writer, which matches delta-rs's `RecordBatchWriter` file for
+//! file. Only the *merge execution* is replaced: MERGE runs a DataFusion hash join whose memory scales
//! with the scanned target and which deadlocks under a bounded memory pool
//! (delta-io/delta-rs#4614); deltalite builds a PK hash set over the (small) source,
//! streams the (large) target a row group at a time, drops replaced rows, writes
@@ -34,9 +35,11 @@ pub mod limits;
pub mod pkset;
pub mod prefetch;
pub mod schema;
+mod stats;
pub mod store;
pub mod table;
pub mod upsert;
+mod writer;
pub use errors::{Error, Result};
pub use handle::{LiveFile, TableHandle};
diff --git a/rust/deltalite/core/src/limits.rs b/rust/deltalite/core/src/limits.rs
index 71c543347eb5..de2db10cf123 100644
--- a/rust/deltalite/core/src/limits.rs
+++ b/rust/deltalite/core/src/limits.rs
@@ -10,8 +10,17 @@
//! Every acquisition therefore goes through BOTH a per-call semaphore (preserving the
//! per-call knobs) and a process-global one from this module, so the process-level bound
//! means what it says regardless of how many upserts run concurrently. Acquisition order
-//! is fixed everywhere -- partition -> file -> bytes, local before global at each level
-//! -- so the two layers cannot deadlock against each other.
+//! is fixed everywhere -- partition -> file -> fetch -> bytes, local before global at
+//! each level -- so the two layers cannot deadlock against each other.
+//!
+//! The fetch budget covers the *compressed* row-group bytes a Parquet reader pulls from
+//! storage before it can decode anything: the async reader fetches every projected
+//! column chunk of a row group in one go and holds them until that row group is decoded,
+//! so a reader of a single-row-group file holds the whole file. The decode budget
+//! (`bytes`) never saw those bytes. A reader takes its fetch permit once per file, before
+//! the first byte of data is fetched, and keeps it until the stream is dropped; it may
+//! take decode permits while holding it, but nothing ever waits on a fetch permit while
+//! holding decode budget, so the two budgets cannot form a cycle.
//!
//! Limits are injected as an [`Arc<ProcessLimits>`] rather than read from a hidden
//! static, so tests can build isolated instances; the binding crate passes
@@ -30,6 +39,8 @@ pub const DEFAULT_PROCESS_MAX_PARALLEL_PARTITIONS: usize = 8;
pub const DEFAULT_PROCESS_MAX_PARALLEL_FILES: usize = 16;
/// Default process-wide cap on decompressed survivor bytes in flight.
pub const DEFAULT_PROCESS_MAX_BUFFERED_BYTES: usize = 256 * 1024 * 1024;
+/// Default process-wide cap on compressed row-group bytes held by readers.
+pub const DEFAULT_PROCESS_MAX_FETCH_BYTES: usize = 256 * 1024 * 1024;
/// Default ceiling for the source-size guard (resident source + estimated PK set).
pub const DEFAULT_MAX_SOURCE_BYTES: usize = 2 * 1024 * 1024 * 1024;
@@ -41,6 +52,13 @@ pub struct ProcessLimits {
buffer: Arc<Semaphore>,
/// Capacity of `buffer` in KiB (tokio permits are u32-denominated).
buffer_cap_kb: u32,
+ fetch: Arc<Semaphore>,
+ /// Capacity of `fetch` in KiB.
+ fetch_cap_kb: u32,
+}
+
+fn cap_kb(bytes: usize) -> u32 {
+ (bytes / 1024).clamp(1, u32::MAX as usize) as u32
}
pub(crate) fn env_usize(name: &str, default: usize) -> usize {
@@ -57,23 +75,42 @@ pub(crate) fn env_usize(name: &str, default: usize) -> usize {
}
impl ProcessLimits {
- /// Build limits with explicit capacities. Zero capacities are clamped to 1 (a
- /// zero-permit semaphore would deadlock every upsert forever).
+ /// Build limits with explicit capacities and the default fetch budget. Zero
+ /// capacities are clamped to 1 (a zero-permit semaphore would deadlock every upsert
+ /// forever).
pub fn new(max_partitions: usize, max_files: usize, max_buffered_bytes: usize) -> Self {
- let cap_kb = (max_buffered_bytes / 1024).clamp(1, u32::MAX as usize) as u32;
+ Self::with_fetch(
+ max_partitions,
+ max_files,
+ max_buffered_bytes,
+ DEFAULT_PROCESS_MAX_FETCH_BYTES,
+ )
+ }
+
+ /// [`ProcessLimits::new`] with an explicit fetch budget.
+ pub fn with_fetch(
+ max_partitions: usize,
+ max_files: usize,
+ max_buffered_bytes: usize,
+ max_fetch_bytes: usize,
+ ) -> Self {
+ let buffer_cap_kb = cap_kb(max_buffered_bytes);
+ let fetch_cap_kb = cap_kb(max_fetch_bytes);
Self {
partitions: Arc::new(Semaphore::new(max_partitions.max(1))),
files: Arc::new(Semaphore::new(max_files.max(1))),
- buffer: Arc::new(Semaphore::new(cap_kb as usize)),
- buffer_cap_kb: cap_kb,
+ buffer: Arc::new(Semaphore::new(buffer_cap_kb as usize)),
+ buffer_cap_kb,
+ fetch: Arc::new(Semaphore::new(fetch_cap_kb as usize)),
+ fetch_cap_kb,
}
}
/// Capacities from `DELTALITE_PROCESS_MAX_PARALLEL_PARTITIONS`,
- /// `DELTALITE_PROCESS_MAX_PARALLEL_FILES` and
- /// `DELTALITE_PROCESS_MAX_BUFFERED_BYTES`, with the module defaults as fallback.
+ /// `DELTALITE_PROCESS_MAX_PARALLEL_FILES`, `DELTALITE_PROCESS_MAX_BUFFERED_BYTES` and
+ /// `DELTALITE_PROCESS_MAX_FETCH_BYTES`, with the module defaults as fallback.
pub fn from_env() -> Self {
- Self::new(
+ Self::with_fetch(
env_usize(
"DELTALITE_PROCESS_MAX_PARALLEL_PARTITIONS",
DEFAULT_PROCESS_MAX_PARALLEL_PARTITIONS,
@@ -86,6 +123,10 @@ impl ProcessLimits {
"DELTALITE_PROCESS_MAX_BUFFERED_BYTES",
DEFAULT_PROCESS_MAX_BUFFERED_BYTES,
),
+ env_usize(
+ "DELTALITE_PROCESS_MAX_FETCH_BYTES",
+ DEFAULT_PROCESS_MAX_FETCH_BYTES,
+ ),
)
}
@@ -137,6 +178,21 @@ impl ProcessLimits {
pub fn buffer_cap_kb(&self) -> u32 {
self.buffer_cap_kb
}
+
+ /// Acquire `kb` KiB of the process-global fetch budget, capped at its capacity so a
+ /// row group larger than the whole budget still proceeds (alone).
+ pub async fn acquire_fetch_kb(&self, kb: u32) -> Result<OwnedSemaphorePermit> {
+ self.fetch
+ .clone()
+ .acquire_many_owned(kb.min(self.fetch_cap_kb).max(1))
+ .await
+ .map_err(|_| Error::Generic("process fetch-budget semaphore closed".into()))
+ }
+
+ /// Capacity of the fetch budget in KiB.
+ pub fn fetch_cap_kb(&self) -> u32 {
+ self.fetch_cap_kb
+ }
}
/// Estimate of what an upsert will keep resident for the whole rewrite: the cast source
@@ -271,9 +327,26 @@ mod tests {
#[tokio::test]
async fn zero_capacities_are_clamped_to_one() {
- let limits = ProcessLimits::new(0, 0, 0);
+ let limits = ProcessLimits::with_fetch(0, 0, 0, 0);
let _p = limits.acquire_partition().await.unwrap();
let _f = limits.acquire_file().await.unwrap();
let _b = limits.acquire_buffer_kb(1).await.unwrap();
+ let _x = limits.acquire_fetch_kb(1).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn fetch_requests_are_capped_and_exclusive_when_oversized() {
+ let limits = ProcessLimits::with_fetch(1, 1, 1024 * 1024, 64 * 1024);
+ assert_eq!(limits.fetch_cap_kb(), 64);
+ // Larger than the whole budget: proceeds, holding all of it.
+ let whole = limits.acquire_fetch_kb(10_000).await.unwrap();
+ let pending = tokio::time::timeout(
+ std::time::Duration::from_millis(50),
+ limits.acquire_fetch_kb(1),
+ )
+ .await;
+ assert!(pending.is_err(), "an oversized holder must run alone");
+ drop(whole);
+ let _p = limits.acquire_fetch_kb(1).await.unwrap();
}
}
diff --git a/rust/deltalite/core/src/stats.rs b/rust/deltalite/core/src/stats.rs
new file mode 100644
index 000000000000..0e54ac027662
--- /dev/null
+++ b/rust/deltalite/core/src/stats.rs
@@ -0,0 +1,655 @@
+//! Add-action statistics for files written by [`crate::writer`].
+//!
+//! Vendored from delta-rs `crates/core/src/writer/stats.rs` at deltalake 0.32.4
+//! (Apache-2.0, Copyright (2020) QP Hou and a number of other contributors), because the
+//! function that turns a written file's Parquet footer into an `Add` action
+//! (`create_add`) is `pub(crate)` there. The logic is unchanged apart from error plumbing
+//! and dropping the `itertools` dependency. The `Add` stats it produces must stay
+//! byte-for-byte what delta-rs's `RecordBatchWriter` produces: deltalite's pruning and
+//! every Delta reader trust them. `crate::writer`'s tests compare the two directly, so
+//! a deltalake bump that changes delta-rs's stats fails there instead of drifting.
+
+use std::collections::HashMap;
+use std::collections::HashSet;
+use std::ops::{AddAssign, Not};
+use std::sync::Arc;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use delta_kernel::expressions::Scalar;
+use delta_kernel::table_properties::DataSkippingNumIndexedCols;
+use deltalake::kernel::scalars::ScalarExt;
+use deltalake::kernel::Add;
+use deltalake::protocol::{ColumnCountStat, ColumnValueStat, Stats};
+use indexmap::IndexMap;
+use parquet::basic::{LogicalType, TimeUnit, Type};
+use parquet::file::metadata::{ParquetMetaData, RowGroupMetaData};
+use parquet::file::statistics::Statistics;
+use parquet::schema::types::{ColumnDescriptor, SchemaDescriptor};
+use tracing::warn;
+
+/// The subset of delta-rs's `DeltaWriterError` the stats code raises.
+#[derive(Debug)]
+enum DeltaWriterError {
+ StatsParsingFailed {
+ debug_value: String,
+ logical_type: Option<LogicalType>,
+ },
+ Generic(String),
+}
+
+impl From<DeltaWriterError> for crate::errors::Error {
+ fn from(e: DeltaWriterError) -> Self {
+ match e {
+ DeltaWriterError::StatsParsingFailed {
+ debug_value,
+ logical_type,
+ } => crate::errors::Error::Generic(format!(
+ "failed to parse file stats value {debug_value} as {logical_type:?}"
+ )),
+ DeltaWriterError::Generic(msg) => crate::errors::Error::Generic(msg),
+ }
+ }
+}
+
+pub(crate) fn create_add(
+ partition_values: &IndexMap<String, Scalar>,
+ path: String,
+ size: i64,
+ file_metadata: &ParquetMetaData,
+ num_indexed_cols: DataSkippingNumIndexedCols,
+ stats_columns: &Option<Vec<impl AsRef<str>>>,
+) -> crate::errors::Result<Add> {
+ let stats = stats_from_file_metadata(
+ partition_values,
+ file_metadata,
+ num_indexed_cols,
+ stats_columns,
+ )?;
+ let stats_string = serde_json::to_string(&stats)
+ .map_err(|e| crate::errors::Error::Generic(format!("serializing file stats: {e}")))?;
+
+ // Determine the modification timestamp to include in the add action - milliseconds since epoch
+ // Err should be impossible in this case since `SystemTime::now()` is always greater than `UNIX_EPOCH`
+ let modification_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
+ let modification_time = modification_time.as_millis() as i64;
+
+ Ok(Add {
+ path,
+ size,
+ partition_values: partition_values
+ .iter()
+ .map(|(k, v)| {
+ (
+ k.clone(),
+ if v.is_null() {
+ None
+ } else {
+ Some(v.serialize())
+ },
+ )
+ })
+ .collect(),
+ modification_time,
+ data_change: true,
+ stats: Some(stats_string),
+ tags: None,
+ deletion_vector: None,
+ base_row_id: None,
+ default_row_commit_version: None,
+ clustering_provider: None,
+ })
+}
+
+fn stats_from_file_metadata(
+ partition_values: &IndexMap<String, Scalar>,
+ file_metadata: &ParquetMetaData,
+ num_indexed_cols: DataSkippingNumIndexedCols,
+ stats_columns: &Option<Vec<impl AsRef<str>>>,
+) -> Result<Stats, DeltaWriterError> {
+ let schema_descriptor = file_metadata.file_metadata().schema_descr();
+
+ let row_group_metadata: Vec<RowGroupMetaData> = file_metadata.row_groups().to_vec();
+
+ stats_from_metadata(
+ partition_values,
+ Arc::new(schema_descriptor.clone()),
+ row_group_metadata,
+ file_metadata.file_metadata().num_rows(),
+ num_indexed_cols,
+ stats_columns,
+ )
+}
+
+fn stats_from_metadata(
+ partition_values: &IndexMap<String, Scalar>,
+ schema_descriptor: Arc<SchemaDescriptor>,
+ row_group_metadata: Vec<RowGroupMetaData>,
+ num_rows: i64,
+ num_indexed_cols: DataSkippingNumIndexedCols,
+ stats_columns: &Option<Vec<impl AsRef<str>>>,
+) -> Result<Stats, DeltaWriterError> {
+ let mut min_values: HashMap<String, ColumnValueStat> = HashMap::new();
+ let mut max_values: HashMap<String, ColumnValueStat> = HashMap::new();
+ let mut null_count: HashMap<String, ColumnCountStat> = HashMap::new();
+ let dialect = sqlparser::dialect::GenericDialect {};
+
+ let idx_to_iterate = if let Some(stats_cols) = stats_columns {
+ let stats_cols = stats_cols
+ .iter()
+ .map(|v| {
+ match sqlparser::parser::Parser::new(&dialect)
+ .try_with_sql(v.as_ref())
+ .map_err(|e| DeltaWriterError::Generic(e.to_string()))?
+ .parse_multipart_identifier()
+ {
+ Ok(parts) => Ok(parts
+ .into_iter()
+ .map(|v| v.value)
+ .collect::<Vec<_>>()
+ .join(".")),
+ Err(e) => Err(DeltaWriterError::Generic(e.to_string())),
+ }
+ })
+ .collect::<Result<Vec<String>, DeltaWriterError>>()?;
+
+ schema_descriptor
+ .columns()
+ .iter()
+ .enumerate()
+ .filter_map(|(index, col)| {
+ if stats_cols.contains(&col.name().to_string()) {
+ Some(index)
+ } else {
+ None
+ }
+ })
+ .collect()
+ } else if num_indexed_cols == DataSkippingNumIndexedCols::AllColumns {
+ (0..schema_descriptor.num_columns()).collect::<Vec<_>>()
+ } else if let DataSkippingNumIndexedCols::NumColumns(n_cols) = num_indexed_cols {
+ // The `delta.dataSkippingNumIndexedCols` budget is consumed by distinct
+ // top-level fields, not by parquet leaf columns. A single top-level
+ // column with many nested fields therefore takes one slot, not N.
+ // Partition columns do not consume a slot.
+ let limit = n_cols as usize;
+ let mut admitted: HashSet<String> = HashSet::new();
+ let mut admitted_count: usize = 0;
+ let mut idxs: Vec<usize> = Vec::new();
+ for (idx, col) in schema_descriptor.columns().iter().enumerate() {
+ let top = match col.path().parts().first() {
+ Some(t) => t.clone(),
+ None => continue,
+ };
+ if partition_values.contains_key(&top) {
+ continue;
+ }
+ if !admitted.contains(&top) {
+ if admitted_count >= limit {
+ break;
+ }
+ admitted.insert(top);
+ admitted_count += 1;
+ }
+ idxs.push(idx);
+ }
+ idxs
+ } else {
+ return Err(DeltaWriterError::Generic(
+ "delta.dataSkippingNumIndexedCols valid values are >=-1".to_string(),
+ ));
+ };
+
+ for idx in idx_to_iterate {
+ let column_descr = schema_descriptor.column(idx);
+
+ let column_path = column_descr.path();
+ let column_path_parts = column_path.parts();
+
+ // Do not include partition columns in statistics (still relevant for
+ // the `AllColumns` and explicit `stats_columns` branches).
+ if partition_values.contains_key(&column_path_parts[0]) {
+ continue;
+ }
+
+ let maybe_stats: Option<AggregatedStats> = row_group_metadata
+ .iter()
+ .flat_map(|g| {
+ g.column(idx).statistics().into_iter().filter_map(|s| {
+ let is_binary = matches!(&column_descr.physical_type(), Type::BYTE_ARRAY)
+ && matches!(column_descr.logical_type_ref(), Some(LogicalType::String))
+ .not();
+ if is_binary {
+ warn!(
+ "Skipping column {} because it's a binary field.",
+ &column_descr.name().to_string()
+ );
+ None
+ } else {
+ Some(AggregatedStats::from((s, column_descr.logical_type_ref())))
+ }
+ })
+ })
+ .reduce(|mut left, right| {
+ left += right;
+ left
+ });
+
+ if let Some(stats) = maybe_stats {
+ apply_min_max_for_column(
+ stats,
+ column_descr.clone(),
+ column_descr.path().parts(),
+ &mut min_values,
+ &mut max_values,
+ &mut null_count,
+ )?;
+ }
+ }
+
+ Ok(Stats {
+ min_values,
+ max_values,
+ num_records: num_rows,
+ null_count,
+ })
+}
+
+/// Logical scalars extracted from statistics. These are used to aggregate
+/// minimums and maximums. We can't use the physical scalars because they
+/// are not ordered correctly for some types. For example, decimals are stored
+/// as fixed length binary, and can't be sorted leixcographically.
+#[derive(Debug, Clone, PartialEq, PartialOrd)]
+enum StatsScalar {
+ Boolean(bool),
+ Int32(i32),
+ Int64(i64),
+ Float32(f32),
+ Float64(f64),
+ Date(chrono::NaiveDate),
+ Timestamp(chrono::NaiveDateTime),
+ // We are serializing to f64 later and the ordering should be the same
+ // Scale is stored to handle scale=0 serialization correctly
+ Decimal { value: f64, scale: i32 },
+ String(String),
+ Bytes(Vec<u8>),
+ Uuid(uuid::Uuid),
+}
+
+impl StatsScalar {
+ fn try_from_stats(
+ stats: &Statistics,
+ logical_type: Option<&LogicalType>,
+ use_min: bool,
+ ) -> Result<Self, DeltaWriterError> {
+ macro_rules! get_stat {
+ ($val: expr) => {
+ if use_min {
+ *$val.min_opt().unwrap()
+ } else {
+ *$val.max_opt().unwrap()
+ }
+ };
+ }
+
+ match (stats, logical_type) {
+ (Statistics::Boolean(v), _) => Ok(Self::Boolean(get_stat!(v))),
+ // Int32 can be date, decimal, or just int32
+ (Statistics::Int32(v), Some(LogicalType::Date)) => {
+ let epoch_start = chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap(); // creating from epoch should be infallible
+ let date = epoch_start + chrono::Duration::days(get_stat!(v) as i64);
+ Ok(Self::Date(date))
+ }
+ (Statistics::Int32(v), Some(LogicalType::Decimal { scale, .. })) => {
+ let val = get_stat!(v) as f64 / 10.0_f64.powi(*scale);
+ // Spark serializes these as numbers
+ Ok(Self::Decimal {
+ value: val,
+ scale: *scale,
+ })
+ }
+ (Statistics::Int32(v), _) => Ok(Self::Int32(get_stat!(v))),
+ // Int64 can be timestamp, decimal, or integer
+ (Statistics::Int64(v), Some(LogicalType::Timestamp { unit, .. })) => {
+ // For now, we assume timestamps are adjusted to UTC. Non-UTC timestamps
+ // are behind a feature gate in Delta:
+ // https://github.com/delta-io/delta/blob/master/PROTOCOL.md#timestamp-without-timezone-timestampntz
+ let v = get_stat!(v);
+ let timestamp = match unit {
+ TimeUnit::MILLIS => chrono::DateTime::from_timestamp_millis(v),
+ TimeUnit::MICROS => chrono::DateTime::from_timestamp_micros(v),
+ TimeUnit::NANOS => {
+ let secs = v / 1_000_000_000;
+ let nanosecs = (v % 1_000_000_000) as u32;
+ chrono::DateTime::from_timestamp(secs, nanosecs)
+ }
+ };
+ let timestamp = timestamp.ok_or(DeltaWriterError::StatsParsingFailed {
+ debug_value: v.to_string(),
+ logical_type: logical_type.cloned(),
+ })?;
+ Ok(Self::Timestamp(timestamp.naive_utc()))
+ }
+ (Statistics::Int64(v), Some(LogicalType::Decimal { scale, .. })) => {
+ let val = get_stat!(v) as f64 / 10.0_f64.powi(*scale);
+ // Spark serializes these as numbers
+ Ok(Self::Decimal {
+ value: val,
+ scale: *scale,
+ })
+ }
+ (Statistics::Int64(v), _) => Ok(Self::Int64(get_stat!(v))),
+ (Statistics::Float(v), _) => Ok(Self::Float32(get_stat!(v))),
+ (Statistics::Double(v), _) => Ok(Self::Float64(get_stat!(v))),
+ (Statistics::ByteArray(v), logical_type) => {
+ let bytes = if use_min {
+ v.min_bytes_opt()
+ } else {
+ v.max_bytes_opt()
+ }
+ .unwrap_or_default();
+ match logical_type {
+ None => Ok(Self::Bytes(bytes.to_vec())),
+ Some(LogicalType::String) => {
+ Ok(Self::String(String::from_utf8(bytes.to_vec()).map_err(
+ |_| DeltaWriterError::StatsParsingFailed {
+ debug_value: format!("{bytes:?}"),
+ logical_type: Some(LogicalType::String),
+ },
+ )?))
+ }
+ _ => Err(DeltaWriterError::StatsParsingFailed {
+ debug_value: format!("{bytes:?}"),
+ logical_type: logical_type.cloned(),
+ }),
+ }
+ }
+ (Statistics::FixedLenByteArray(v), Some(LogicalType::Decimal { scale, precision })) => {
+ let val = if use_min {
+ v.min_bytes_opt()
+ } else {
+ v.max_bytes_opt()
+ }
+ .unwrap_or_default();
+
+ let val = if val.len() <= 16 {
+ i128::from_be_bytes(sign_extend_be(val)) as f64
+ } else {
+ return Err(DeltaWriterError::StatsParsingFailed {
+ debug_value: format!("{val:?}"),
+ logical_type: Some(LogicalType::Decimal {
+ scale: *scale,
+ precision: *precision,
+ }),
+ });
+ };
+
+ let mut val = val / 10.0_f64.powi(*scale);
+
+ if val.is_normal()
+ && (val.trunc() as i128).to_string().len() > (precision - scale) as usize
+ {
+ // For normal values with integer parts that get rounded to a number beyond
+ // the precision - scale range take the next smaller (by magnitude) value
+ val = f64::from_bits(val.to_bits() - 1);
+ }
+
+ Ok(Self::Decimal {
+ value: val,
+ scale: *scale,
+ })
+ }
+ (Statistics::FixedLenByteArray(v), Some(LogicalType::Uuid)) => {
+ let val = if use_min {
+ v.min_bytes_opt()
+ } else {
+ v.max_bytes_opt()
+ }
+ .unwrap_or_default();
+
+ if val.len() != 16 {
+ return Err(DeltaWriterError::StatsParsingFailed {
+ debug_value: format!("{val:?}"),
+ logical_type: Some(LogicalType::Uuid),
+ });
+ }
+
+ let mut bytes = [0; 16];
+ bytes.copy_from_slice(val);
+
+ let val = uuid::Uuid::from_bytes(bytes);
+ Ok(Self::Uuid(val))
+ }
+ (stats, _) => Err(DeltaWriterError::StatsParsingFailed {
+ debug_value: format!("{stats:?}"),
+ logical_type: logical_type.cloned(),
+ }),
+ }
+ }
+}
+
+/// Performs big endian sign extension
+/// Copied from arrow-rs repo/parquet crate:
+/// https://github.com/apache/arrow-rs/blob/b25c441745602c9967b1e3cc4a28bc469cfb1311/parquet/src/arrow/buffer/bit_util.rs#L54
+pub fn sign_extend_be<const N: usize>(b: &[u8]) -> [u8; N] {
+ assert!(b.len() <= N, "Array too large, expected less than {N}");
+ let is_negative = (b[0] & 128u8) == 128u8;
+ let mut result = if is_negative { [255u8; N] } else { [0u8; N] };
+ for (d, s) in result.iter_mut().skip(N - b.len()).zip(b) {
+ *d = *s;
+ }
+ result
+}
+
+impl From<StatsScalar> for serde_json::Value {
+ fn from(scalar: StatsScalar) -> Self {
+ match scalar {
+ StatsScalar::Boolean(v) => serde_json::Value::Bool(v),
+ StatsScalar::Int32(v) => serde_json::Value::from(v),
+ StatsScalar::Int64(v) => serde_json::Value::from(v),
+ StatsScalar::Float32(v) => serde_json::Value::from(v),
+ StatsScalar::Float64(v) => serde_json::Value::from(v),
+ StatsScalar::Date(v) => serde_json::Value::from(v.format("%Y-%m-%d").to_string()),
+ StatsScalar::Timestamp(v) => {
+ serde_json::Value::from(v.format("%Y-%m-%dT%H:%M:%S%.fZ").to_string())
+ }
+ StatsScalar::Decimal { value, scale } => {
+ // For scale=0, serialize as integer since serde_json would otherwise
+ // serialize f64 as "1234.0" instead of "1234"
+ if scale == 0 {
+ serde_json::Value::from(value.round() as i64)
+ } else {
+ serde_json::Value::from(value)
+ }
+ }
+ StatsScalar::String(v) => serde_json::Value::from(v),
+ StatsScalar::Bytes(v) => {
+ let escaped_bytes = v
+ .into_iter()
+ .flat_map(std::ascii::escape_default)
+ .collect::<Vec<u8>>();
+ let escaped_string = String::from_utf8(escaped_bytes).unwrap();
+ serde_json::Value::from(escaped_string)
+ }
+ StatsScalar::Uuid(v) => serde_json::Value::from(v.hyphenated().to_string()),
+ }
+ }
+}
+
+/// Aggregated stats
+struct AggregatedStats {
+ pub min: Option<StatsScalar>,
+ pub max: Option<StatsScalar>,
+ pub null_count: u64,
+}
+
+impl From<(&Statistics, Option<&LogicalType>)> for AggregatedStats {
+ fn from(value: (&Statistics, Option<&LogicalType>)) -> Self {
+ let (stats, logical_type) = value;
+ let null_count = stats.null_count_opt().unwrap_or_default();
+ if stats.min_bytes_opt().is_some() && stats.max_bytes_opt().is_some() {
+ let min = StatsScalar::try_from_stats(stats, logical_type, true).ok();
+ let max = StatsScalar::try_from_stats(stats, logical_type, false).ok();
+ Self {
+ min,
+ max,
+ null_count,
+ }
+ } else {
+ Self {
+ min: None,
+ max: None,
+ null_count,
+ }
+ }
+ }
+}
+
+impl AddAssign for AggregatedStats {
+ fn add_assign(&mut self, rhs: Self) {
+ self.min = match (self.min.take(), rhs.min) {
+ (Some(lhs), Some(rhs)) => {
+ if lhs < rhs {
+ Some(lhs)
+ } else {
+ Some(rhs)
+ }
+ }
+ (lhs, rhs) => lhs.or(rhs),
+ };
+ self.max = match (self.max.take(), rhs.max) {
+ (Some(lhs), Some(rhs)) => {
+ if lhs > rhs {
+ Some(lhs)
+ } else {
+ Some(rhs)
+ }
+ }
+ (lhs, rhs) => lhs.or(rhs),
+ };
+
+ self.null_count += rhs.null_count;
+ }
+}
+
+/// For a list field, we don't want the inner field names. We need to chuck out
+/// the list and items fields from the path, but also need to handle the
+/// peculiar case where the user named the list field "list" or "item".
+///
+/// NOTE: As of delta_kernel 0.3.1 the name switched from `item` to `element` to line up with the
+/// parquet spec, see
+/// [here](https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#lists)
+///
+/// For example:
+///
+/// * ["some_nested_list", "list", "item", "list", "item"] -> "some_nested_list"
+/// * ["some_list", "list", "item"] -> "some_list"
+/// * ["list", "list", "item"] -> "list"
+/// * ["item", "list", "item"] -> "item"
+fn get_list_field_name(column_descr: &Arc<ColumnDescriptor>) -> Option<String> {
+ let max_rep_levels = column_descr.max_rep_level();
+ let column_path_parts = column_descr.path().parts();
+
+ // If there are more nested names, we can't handle them yet.
+ if column_path_parts.len() > (2 * max_rep_levels + 1) as usize {
+ return None;
+ }
+
+ let mut column_path_parts = column_path_parts.to_vec();
+ let mut items_seen = 0;
+ let mut lists_seen = 0;
+ while let Some(part) = column_path_parts.pop() {
+ match (part.as_str(), lists_seen, items_seen) {
+ ("list", seen, _) if seen == max_rep_levels => return Some("list".to_string()),
+ ("element", _, seen) if seen == max_rep_levels => return Some("element".to_string()),
+ ("list", _, _) => lists_seen += 1,
+ ("element", _, _) => items_seen += 1,
+ (other, _, _) => return Some(other.to_string()),
+ }
+ }
+ None
+}
+
+fn apply_min_max_for_column(
+ statistics: AggregatedStats,
+ column_descr: Arc<ColumnDescriptor>,
+ column_path_parts: &[String],
+ min_values: &mut HashMap<String, ColumnValueStat>,
+ max_values: &mut HashMap<String, ColumnValueStat>,
+ null_counts: &mut HashMap<String, ColumnCountStat>,
+) -> Result<(), DeltaWriterError> {
+ // Special handling for list column
+ if column_descr.max_rep_level() > 0 {
+ let key = get_list_field_name(&column_descr);
+
+ if let Some(key) = key {
+ null_counts.insert(key, ColumnCountStat::Value(statistics.null_count as i64));
+ }
+
+ return Ok(());
+ }
+
+ match (column_path_parts.len(), column_path_parts.first()) {
+ // Base case - we are at the leaf struct level in the path
+ (1, _) => {
+ let key = column_descr.name().to_string();
+
+ if let Some(min) = statistics.min {
+ let min = ColumnValueStat::Value(min.into());
+ min_values.insert(key.clone(), min);
+ }
+
+ if let Some(max) = statistics.max {
+ let max = ColumnValueStat::Value(max.into());
+ max_values.insert(key.clone(), max);
+ }
+
+ null_counts.insert(key, ColumnCountStat::Value(statistics.null_count as i64));
+
+ Ok(())
+ }
+ // Recurse to load value at the appropriate level of HashMap
+ (_, Some(key)) => {
+ let child_min_values = min_values
+ .entry(key.to_owned())
+ .or_insert_with(|| ColumnValueStat::Column(HashMap::new()));
+ let child_max_values = max_values
+ .entry(key.to_owned())
+ .or_insert_with(|| ColumnValueStat::Column(HashMap::new()));
+ let child_null_counts = null_counts
+ .entry(key.to_owned())
+ .or_insert_with(|| ColumnCountStat::Column(HashMap::new()));
+
+ match (child_min_values, child_max_values, child_null_counts) {
+ (
+ ColumnValueStat::Column(mins),
+ ColumnValueStat::Column(maxes),
+ ColumnCountStat::Column(null_counts),
+ ) => {
+ let remaining_parts: Vec<String> = column_path_parts
+ .iter()
+ .skip(1)
+ .map(|s| s.to_string())
+ .collect();
+
+ apply_min_max_for_column(
+ statistics,
+ column_descr,
+ remaining_parts.as_slice(),
+ mins,
+ maxes,
+ null_counts,
+ )?;
+
+ Ok(())
+ }
+ _ => {
+ unreachable!();
+ }
+ }
+ }
+ // column path parts will always have at least one element.
+ (_, None) => {
+ unreachable!();
+ }
+ }
+}
diff --git a/rust/deltalite/core/src/store.rs b/rust/deltalite/core/src/store.rs
index 080d58bbde69..dc0070554932 100644
--- a/rust/deltalite/core/src/store.rs
+++ b/rust/deltalite/core/src/store.rs
@@ -1,15 +1,14 @@
//! Multipart upload for large data files.
//!
-//! `RecordBatchWriter::flush()` uploads each finished Parquet file through
-//! `ObjectStore::put` -- a single PUT (~`target_file_size` bytes, 100 MB by default).
+//! 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).
//! On real S3 that serialises the whole file on one connection and re-uploads
//! everything on a connection reset; measured under injected per-request latency it
//! cost deltalite ~4x more wall-clock than MERGE. delta-rs's own DataFusion writer
//! uses ~5 MB multipart parts for the same reason.
//!
-//! The writer offers no hook to change this, but the store it writes through does:
-//! `RecordBatchWriter::for_table` takes `table.object_store()`, which comes from the
-//! table's `LogStore`. [`MultipartPutStore`] wraps an object store so that plain
+//! The writer uploads through `table.object_store()`, which comes from the table's
+//! `LogStore`. [`MultipartPutStore`] wraps an object store so that plain
//! overwrite `put`s above a size threshold become multipart uploads, and
//! [`MultipartLogStore`] wraps a log store to hand that store to the writer.
//!
@@ -221,7 +220,7 @@ impl ObjectStore for MultipartPutStore {
}
/// A [`LogStore`] wrapper whose `object_store()` returns a [`MultipartPutStore`] over
-/// the inner store, so data files written by `RecordBatchWriter` (and read by the
+/// the inner store, so data files written by the partition writer (and read by the
/// probe/rewrite) go through the multipart-aware store while commit-entry writes stay
/// on the inner log store's own path.
pub struct MultipartLogStore {
diff --git a/rust/deltalite/core/src/upsert.rs b/rust/deltalite/core/src/upsert.rs
index 57cadea482d5..c26981f912c4 100644
--- a/rust/deltalite/core/src/upsert.rs
+++ b/rust/deltalite/core/src/upsert.rs
@@ -9,8 +9,10 @@
//! up to `max_parallel_files` concurrent readers feeding one writer task through a
//! channel; every surviving batch holds byte-budget permits from decode until it has
//! been handed to the write buffer, so decompressed survivor data in flight never
-//! exceeds the budget no matter what the product of the parallelism knobs is. All three
-//! budgets are enforced twice: per call (the `UpsertOptions` knobs) and per process
+//! exceeds the budget no matter what the product of the parallelism knobs is. Before a
+//! reader fetches anything it also takes a fetch-budget permit for the largest
+//! compressed row group it will pull from storage, which the decode budget cannot see.
+//! All budgets are enforced twice: per call (the `UpsertOptions` knobs) and per process
//! ([`ProcessLimits`]), because production runs many upserts concurrently as threads in
//! one worker process.
//!
@@ -19,8 +21,9 @@
//! only inside its worker -- transiently for the PK set (narrow columns) and the final
//! write. Peak memory is bounded by `source (1x, shared with the caller)
//! + max_parallel_partitions * (one partition's slice + PK set + write buffer)
-//! + max_buffered_bytes + in-flight read batches`, and the source term is guarded by
-//! [`crate::limits::check_source_size`].
+//! + max_buffered_bytes + max_fetch_bytes`, and the source term is guarded by
+//! [`crate::limits::check_source_size`]. The write buffer is about one
+//! `target_file_size` per partition worker (see `crate::writer`).
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
@@ -37,7 +40,7 @@ use deltalake::protocol::checkpoints::{cleanup_metadata, create_checkpoint};
use deltalake::protocol::{DeltaOperation, SaveMode};
use deltalake::table::config::TablePropertiesExt;
use deltalake::table::state::DeltaTableState;
-use deltalake::writer::{DeltaWriter, RecordBatchWriter};
+use deltalake::writer::RecordBatchWriter;
use deltalake::{DeltaTable, ObjectStore, PartitionFilter, PartitionValue, Path};
use futures::{StreamExt, TryStreamExt};
use metrics::{counter, histogram};
@@ -57,6 +60,7 @@ use crate::limits::{
};
use crate::pkset::PkSet;
use crate::schema::{cast_to_schema, unknown_columns};
+use crate::writer::StreamingWriter;
/// One logical group of work: a partition value (or the whole table when unpartitioned).
const WHOLE_TABLE: &str = "__deltalite_whole_table__";
@@ -67,6 +71,11 @@ const INITIAL_DECODE_ESTIMATE_BYTES: usize = 4 * 1024 * 1024;
/// First-iteration pre-decode reservation for narrow PK-column probe batches.
const INITIAL_PROBE_ESTIMATE_BYTES: usize = 256 * 1024;
+/// Default per-call fetch budget. Readers of ordinary files (a few MB per row group)
+/// never wait on it at the default `max_parallel_files`; readers of files whose single
+/// row group is tens of MB do.
+pub const DEFAULT_MAX_FETCH_BYTES: usize = 128 * 1024 * 1024;
+
/// Tail bytes fetched when a data file is opened. Without a hint parquet reads the
/// 8-byte trailer first and the metadata second: two round trips per open. 64 KiB covers
/// the footer of a file with on the order of a hundred columns, and over-fetching on a
@@ -108,6 +117,28 @@ fn batch_rows_for_bytes_per_row(
(target_bytes / max_bytes_per_row).clamp(1, cap)
}
+/// Compressed bytes the async reader fetches for the largest row group of a file,
+/// counting only the leaf columns under the projected root columns (`None` = all). The
+/// reader requests every projected column chunk of a row group at once and keeps them
+/// until the row group is decoded, so this is what one reader holds.
+fn max_row_group_fetch_bytes(meta: &ParquetMetaData, roots: Option<&[usize]>) -> usize {
+ let schema = meta.file_metadata().schema_descr();
+ meta.row_groups()
+ .iter()
+ .map(|rg| {
+ rg.columns()
+ .iter()
+ .enumerate()
+ .filter(|(leaf, _)| {
+ roots.is_none_or(|r| r.contains(&schema.get_column_root_idx(*leaf)))
+ })
+ .map(|(_, c)| c.byte_range().1 as usize)
+ .sum::<usize>()
+ })
+ .max()
+ .unwrap_or(0)
+}
+
/// How the set of existing files to rewrite is chosen within each affected partition.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum PruneStrategy {
@@ -181,6 +212,13 @@ pub struct UpsertOptions {
/// call's partition workers and file readers. The process-wide cap in
/// [`ProcessLimits`] applies on top.
pub max_buffered_bytes: usize,
+ /// Per-call cap (bytes) on compressed row-group data that this call's readers hold
+ /// after fetching it from storage and before it is decoded. A reader reserves its
+ /// file's largest projected row group before fetching, so a table of large
+ /// single-row-group files runs fewer readers at once instead of holding
+ /// `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,
/// Commit retry budget handed to `CommitBuilder`.
pub commit_max_retries: usize,
/// Row-count granularity for Parquet reads and source-slice writes.
@@ -216,6 +254,7 @@ impl Default for UpsertOptions {
probe_concurrency: 8,
max_parallel_files: 4,
max_buffered_bytes: 64 * 1024 * 1024,
+ max_fetch_bytes: DEFAULT_MAX_FETCH_BYTES,
commit_max_retries: 15,
read_batch_size: 8192,
target_file_size: None,
@@ -468,19 +507,66 @@ struct BudgetPermit {
held_global_kb: u32,
}
+/// Fetch-budget permits held by one reader from before its first data fetch until its
+/// stream is dropped.
+struct FetchPermit {
+ _local: OwnedSemaphorePermit,
+ _global: OwnedSemaphorePermit,
+}
+
/// Per-call view of the budget semaphores plus their process-global counterparts.
#[derive(Clone)]
struct Budgets {
local: Arc<Semaphore>,
local_cap_kb: u32,
+ fetch_local: Arc<Semaphore>,
+ fetch_local_cap_kb: u32,
limits: Arc<ProcessLimits>,
}
impl Budgets {
+ fn new(max_buffered_bytes: usize, max_fetch_bytes: usize, limits: Arc<ProcessLimits>) -> Self {
+ // KiB units: tokio's acquire_many takes u32.
+ let local_cap_kb = (max_buffered_bytes / 1024).clamp(1, u32::MAX as usize) as u32;
+ let fetch_local_cap_kb = (max_fetch_bytes / 1024).clamp(1, u32::MAX as usize) as u32;
+ Self {
+ local: Arc::new(Semaphore::new(local_cap_kb as usize)),
+ local_cap_kb,
+ fetch_local: Arc::new(Semaphore::new(fetch_local_cap_kb as usize)),
+ fetch_local_cap_kb,
+ limits,
+ }
+ }
+
fn kb(bytes: usize) -> u64 {
(bytes / 1024).max(1) as u64
}
+ /// Reserve fetch budget for `bytes` of compressed row-group data, capped at each
+ /// budget's capacity so a row group larger than the whole budget still runs: it
+ /// takes all of it and runs alone. Local before global, as everywhere.
+ ///
+ /// Deadlock freedom: a reader takes this once per file, before it holds any decode
+ /// budget, and keeps it while it takes decode permits. Decode permits are released
+ /// by the writer task, which never waits on the fetch budget, so every fetch holder
+ /// can always finish and release.
+ async fn acquire_fetch(&self, bytes: usize) -> Result<FetchPermit> {
+ let want = Self::kb(bytes);
+ let local_kb = want.min(self.fetch_local_cap_kb as u64) as u32;
+ let global_kb = want.min(self.limits.fetch_cap_kb() as u64) as u32;
+ let local = self
+ .fetch_local
+ .clone()
+ .acquire_many_owned(local_kb)
+ .await
+ .map_err(|_| Error::Generic("fetch-budget semaphore closed".into()))?;
+ let global = self.limits.acquire_fetch_kb(global_kb).await?;
+ Ok(FetchPermit {
+ _local: local,
+ _global: global,
+ })
+ }
+
/// 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).
@@ -930,14 +1016,12 @@ async fn upsert_inner(
let rewrite_started = Instant::now();
let partitions_touched = work.len();
let semaphore = Arc::new(Semaphore::new(opts.max_parallel_partitions.max(1)));
- // Per-call byte budget in KiB units (tokio's acquire_many takes u32); the
- // process-global budget in `opts.limits` applies on top of it.
- let local_cap_kb: u32 = (opts.max_buffered_bytes / 1024).clamp(1, u32::MAX as usize) as u32;
- let budgets = Budgets {
- local: Arc::new(Semaphore::new(local_cap_kb as usize)),
- local_cap_kb,
- limits: opts.limits.clone(),
- };
+ // Per-call budgets; the process-global ones in `opts.limits` apply on top.
+ let budgets = Budgets::new(
+ opts.max_buffered_bytes,
+ opts.max_fetch_bytes,
+ opts.limits.clone(),
+ );
let opts = Arc::new(opts);
let mut handles = Vec::new();
@@ -1701,6 +1785,13 @@ async fn probe_file(
return Ok((pkset.contains_any_columns(&cols, 1)?, metadata));
}
+ // 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 mask = ProjectionMask::roots(builder.parquet_schema(), projection);
let batch_rows = byte_bounded_batch_rows(
builder.metadata(),
@@ -1735,9 +1826,13 @@ async fn probe_file(
let hit = pkset.contains_any_columns(&cols, batch.num_rows())?;
drop(permit);
if hit {
+ drop(stream);
+ drop(fetch);
return Ok((true, metadata));
}
}
+ drop(stream);
+ drop(fetch);
Ok((false, metadata))
}
@@ -1817,6 +1912,11 @@ async fn filter_file(
tx: mpsc::UnboundedSender<(RecordBatch, BudgetPermit)>,
) -> Result<FileOutcome> {
let builder = open_builder(&store, &f).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 batch_rows = byte_bounded_batch_rows(
builder.metadata(),
INITIAL_DECODE_ESTIMATE_BYTES,
@@ -1868,6 +1968,9 @@ async fn filter_file(
tx.send((survivors, permit))
.map_err(|_| Error::Generic("writer task ended before its readers".into()))?;
}
+ // The fetched row-group bytes live in the stream; release the budget only after it.
+ drop(stream);
+ drop(fetch);
Ok(FileOutcome {
rows_updated,
@@ -1933,7 +2036,7 @@ async fn rewrite_partition(
// Insert phase done; from here the set is read-only and shared by every reader.
let pkset = Arc::new(pkset);
- let writer = RecordBatchWriter::for_table(table)?;
+ let writer = StreamingWriter::for_table(table)?;
let store: Arc<dyn ObjectStore> = table.object_store();
// Content-based file selection: keep only files that actually contain a matched
@@ -1972,13 +2075,13 @@ async fn rewrite_partition(
let mut writer = writer;
let mut adds = Vec::new();
while let Some((batch, permit)) = rx.recv().await {
- writer.write(batch).await?;
- // The batch now lives (compressed) in the write buffer; release its budget.
+ writer.write(batch)?;
+ // The batch now lives (encoded) in the writer; release its budget.
drop(permit);
- // Bound resident memory: RecordBatchWriter buffers the whole partition as
- // compressed Parquet until flushed, so flush on a size threshold instead of
- // once at the end. Each flush yields Add actions and resets the buffer.
+ // Bound resident memory: the writer holds the open file until flushed, so
+ // flush on a size threshold instead of once at the end. Each flush yields
+ // Add actions and starts a new file.
if writer.buffer_len() >= target_file_size {
adds.extend(writer.flush().await?);
}
@@ -2063,7 +2166,7 @@ async fn rewrite_partition(
let mut offset = 0usize;
while offset < selected.num_rows() {
let n = (selected.num_rows() - offset).min(opts.read_batch_size.max(1));
- writer.write(selected.slice(offset, n)).await?;
+ writer.write(selected.slice(offset, n))?;
offset += n;
if writer.buffer_len() >= target_file_size {
adds.extend(writer.flush().await?);
@@ -2308,11 +2411,8 @@ mod tests {
#[tokio::test]
async fn budget_permit_tops_up_and_caps_at_capacity() {
let limits = Arc::new(crate::limits::ProcessLimits::new(1, 1, 1024 * 1024));
- let budgets = Budgets {
- local: Arc::new(Semaphore::new(512)), // 512 KiB per-call budget
- local_cap_kb: 512,
- limits: limits.clone(),
- };
+ // 512 KiB per-call budget.
+ let budgets = Budgets::new(512 * 1024, DEFAULT_MAX_FETCH_BYTES, limits.clone());
// Pre-acquire a small estimate, then top up to something bigger.
let mut p = budgets.acquire_bytes(64 * 1024).await.unwrap();
assert_eq!(p.held_local_kb, 64);
@@ -2360,11 +2460,8 @@ mod tests {
// estimate and none could grow -- a permanent wedge. Release-and-reacquire makes
// them serialize instead, so every reader completes.
let limits = Arc::new(crate::limits::ProcessLimits::new(1, 1, 100 * 1024));
- let budgets = Budgets {
- local: Arc::new(Semaphore::new(100)), // 100 KiB per-call budget
- local_cap_kb: 100,
- limits,
- };
+ // 100 KiB per-call budget.
+ let budgets = Budgets::new(100 * 1024, DEFAULT_MAX_FETCH_BYTES, limits);
let tasks: Vec<_> = (0..8)
.map(|_| {
let budgets = budgets.clone();
diff --git a/rust/deltalite/core/src/writer.rs b/rust/deltalite/core/src/writer.rs
new file mode 100644
index 000000000000..4590f061c0f5
--- /dev/null
+++ b/rust/deltalite/core/src/writer.rs
@@ -0,0 +1,989 @@
+//! Parquet writer for rewritten partitions that never copies a finished file.
+//!
+//! delta-rs's `RecordBatchWriter` encodes into one growing `Vec<u8>` per output file,
+//! copies that buffer before every `write()` (to roll back a failed write), and
+//! `flush()` copies the whole buffer again (`buffer.to_vec()`) before uploading it.
+//! A `target_file_size` file therefore costs the encoder's in-progress row group, a
+//! `Vec` that over-allocates by up to 2x as it doubles, and a full second copy at
+//! upload time: two to three times the file size.
+//!
+//! [`StreamingWriter`] is the same writer with a different sink. It drives the same
+//! parquet `ArrowWriter` with the same `WriterProperties` over the same batches, so the
+//! file bytes are identical, but the sink stores the output as fixed-size chunks and the
+//! upload sends those chunks as they are (`PutPayload` over `Bytes`, no copy). The
+//! encoder releases each column chunk as it serialises it, so the output never exists
+//! twice. File naming, partition values, `Add` statistics (see [`crate::stats`]), the
+//! size measure that drives rollover, and the upload call (`put_with_retries`, 15
+//! attempts, through the multipart-aware store) all match `RecordBatchWriter`; the
+//! tests below compare the two writers directly.
+
+use std::collections::HashMap;
+use std::io::Write;
+use std::sync::Arc;
+
+use arrow_array::{Array, ArrayRef, RecordBatch, UInt32Array};
+use arrow_row::{RowConverter, SortField};
+use arrow_schema::{Schema, SchemaRef};
+use arrow_select::take::take;
+use bytes::Bytes;
+use delta_kernel::expressions::Scalar;
+use delta_kernel::table_properties::DataSkippingNumIndexedCols;
+use deltalake::kernel::scalars::ScalarExt;
+use deltalake::kernel::schema::cast::{cast_record_batch, normalize_for_delta};
+use deltalake::kernel::Add;
+use deltalake::logstore::ObjectStoreRetryExt;
+use deltalake::writer::RecordBatchWriter;
+use deltalake::{DeltaTable, ObjectStore, Path};
+use indexmap::IndexMap;
+use object_store::PutPayload;
+use parquet::arrow::ArrowWriter;
+use parquet::basic::Compression;
+use parquet::file::properties::WriterProperties;
+use parquet::schema::types::ColumnPath;
+use uuid::Uuid;
+
+use crate::errors::{Error, Result};
+use crate::stats::create_add;
+
+/// Size of one output chunk. Small enough that the last, partly filled chunk wastes
+/// little; large enough that a 100 MiB file is ~100 `Bytes`, not thousands.
+const CHUNK_BYTES: usize = 1024 * 1024;
+
+/// Upload attempts per file, as `RecordBatchWriter::flush` uses.
+const PUT_RETRIES: usize = 15;
+
+/// `delta.dataSkippingNumIndexedCols` default (delta-rs `DEFAULT_NUM_INDEX_COLS`).
+const DEFAULT_NUM_INDEX_COLS: u64 = 32;
+
+/// `std::io::Write` sink that keeps what it receives as a list of `CHUNK_BYTES` buffers,
+/// each allocated at its final size, instead of one buffer that doubles as it grows.
+#[derive(Default)]
+struct ChunkSink {
+ full: Vec<Bytes>,
+ current: Vec<u8>,
+ len: usize,
+}
+
+impl ChunkSink {
+ fn into_payload(mut self) -> (PutPayload, usize) {
+ if !self.current.is_empty() {
+ self.full
+ .push(Bytes::from(std::mem::take(&mut self.current)));
+ }
+ (PutPayload::from_iter(self.full), self.len)
+ }
+}
+
+impl Write for ChunkSink {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ let mut rest = buf;
+ while !rest.is_empty() {
+ if self.current.capacity() == 0 {
+ self.current = Vec::with_capacity(CHUNK_BYTES);
+ }
+ let take = (CHUNK_BYTES - self.current.len()).min(rest.len());
+ self.current.extend_from_slice(&rest[..take]);
+ rest = &rest[take..];
+ if self.current.len() == CHUNK_BYTES {
+ self.full
+ .push(Bytes::from(std::mem::take(&mut self.current)));
+ }
+ }
+ self.len += buf.len();
+ Ok(buf.len())
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+}
+
+/// One output file being written for one partition value.
+struct OpenFile {
+ writer: ArrowWriter<ChunkSink>,
+ partition_values: IndexMap<String, Scalar>,
+}
+
+impl OpenFile {
+ /// Bytes the file holds so far, measured as `RecordBatchWriter::buffer_len` measures
+ /// it: bytes the sink has received plus the encoder's in-progress row group.
+ fn buffer_len(&self) -> usize {
+ self.writer.inner().len + self.writer.in_progress_size()
+ }
+}
+
+/// A partition's rows split off one batch, with the partition column removed.
+struct PartitionSlice {
+ partition_values: IndexMap<String, Scalar>,
+ batch: RecordBatch,
+}
+
+/// Drop-in replacement for the parts of `RecordBatchWriter` deltalite uses: `write`,
+/// `buffer_len` and `flush`. See the module docs.
+pub(crate) struct StreamingWriter {
+ store: Arc<dyn ObjectStore>,
+ arrow_schema: SchemaRef,
+ file_schema: SchemaRef,
+ partition_columns: Vec<String>,
+ writer_properties: WriterProperties,
+ num_indexed_cols: DataSkippingNumIndexedCols,
+ stats_columns: Option<Vec<String>>,
+ open: HashMap<String, OpenFile>,
+}
+
+impl StreamingWriter {
+ /// Build a writer for `table`, resolving schema, partitioning, writer properties and
+ /// stats configuration exactly as `RecordBatchWriter::for_table` does.
+ pub(crate) fn for_table(table: &DeltaTable) -> Result<Self> {
+ // Runs delta-rs's own table checks (it refuses column-mapping tables) and gives
+ // the arrow schema delta-rs would write with.
+ let arrow_schema = RecordBatchWriter::for_table(table)?.arrow_schema();
+ let snapshot = table.snapshot()?;
+ let metadata = snapshot.metadata();
+ let partition_columns: Vec<String> = metadata.partition_columns().to_vec();
+ let configuration = metadata.configuration();
+ let num_indexed_cols = configuration
+ .get("delta.dataSkippingNumIndexedCols")
+ .and_then(|v| {
+ v.parse::<u64>()
+ .ok()
+ .map(DataSkippingNumIndexedCols::NumColumns)
+ })
+ .unwrap_or(DataSkippingNumIndexedCols::NumColumns(
+ DEFAULT_NUM_INDEX_COLS,
+ ));
+ let stats_columns = configuration
+ .get("delta.dataSkippingStatsColumns")
+ .map(|v| v.split(',').map(|s| s.to_string()).collect());
+ Ok(Self {
+ store: table.object_store(),
+ file_schema: schema_without_partitions(&arrow_schema, &partition_columns),
+ arrow_schema,
+ partition_columns,
+ writer_properties: delta_rs_writer_properties(),
+ num_indexed_cols,
+ stats_columns,
+ open: HashMap::new(),
+ })
+ }
+
+ /// Bytes held across all open files; the rollover measure.
+ pub(crate) fn buffer_len(&self) -> usize {
+ self.open.values().map(OpenFile::buffer_len).sum()
+ }
+
+ /// Encode `values` into the open file of each partition it holds.
+ pub(crate) fn write(&mut self, values: RecordBatch) -> Result<()> {
+ let values = if values.schema() != self.arrow_schema {
+ let normalized = normalize_for_delta(&values.schema());
+ if normalized != values.schema() {
+ cast_record_batch(&values, normalized, true, false)?
+ } else {
+ values
+ }
+ } else {
+ values
+ };
+
+ for slice in self.split_by_partition(&values)? {
+ let key = hive_partition_path(&slice.partition_values);
+ let file = match self.open.entry(key) {
+ std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
+ std::collections::hash_map::Entry::Vacant(e) => e.insert(OpenFile {
+ writer: ArrowWriter::try_new(
+ ChunkSink::default(),
+ self.file_schema.clone(),
+ Some(self.writer_properties.clone()),
+ )?,
+ partition_values: slice.partition_values,
+ }),
+ };
+ if slice.batch.schema() != self.file_schema {
+ return Err(Error::SchemaMismatch(format!(
+ "Arrow RecordBatch schema does not match: RecordBatch schema: {}, {}",
+ slice.batch.schema(),
+ self.file_schema
+ )));
+ }
+ file.writer.write(&slice.batch)?;
+ }
+ Ok(())
+ }
+
+ /// Finish every open file, upload it, and return one `Add` action per file.
+ pub(crate) async fn flush(&mut self) -> Result<Vec<Add>> {
+ let files = std::mem::take(&mut self.open);
+ let mut actions = Vec::with_capacity(files.len());
+ for (_, mut file) in files {
+ let metadata = file.writer.finish()?;
+ let sink = std::mem::take(file.writer.inner_mut());
+ drop(file.writer);
+ let prefix = Path::parse(hive_partition_path(&file.partition_values))
+ .map_err(|e| Error::Generic(format!("bad partition path: {e}")))?;
+ let path = next_data_path(&prefix, &Uuid::new_v4(), &self.writer_properties);
+ let (payload, size) = sink.into_payload();
+ self.store
+ .put_with_retries(&path, payload, PUT_RETRIES)
+ .await?;
+ actions.push(create_add(
+ &file.partition_values,
+ path.to_string(),
+ size as i64,
+ &metadata,
+ self.num_indexed_cols,
+ &self.stats_columns,
+ )?);
+ }
+ Ok(actions)
+ }
+
+ /// Split `values` by partition value, as delta-rs's `divide_by_partition_values`
+ /// does. deltalite writes one partition per batch, so the common case is detected
+ /// first and keeps the columns as they are; only a batch that really spans several
+ /// partitions pays for delta-rs's sort-and-take.
+ fn split_by_partition(&self, values: &RecordBatch) -> Result<Vec<PartitionSlice>> {
+ if self.partition_columns.is_empty() {
+ return Ok(vec![PartitionSlice {
+ partition_values: IndexMap::new(),
+ batch: values.clone(),
+ }]);
+ }
+ let schema = values.schema();
+ let mut partition_arrays: Vec<ArrayRef> = Vec::with_capacity(self.partition_columns.len());
+ for c in &self.partition_columns {
+ partition_arrays.push(values.column(schema.index_of(c)?).clone());
+ }
+
+ if values.num_rows() > 0 && arrow_ord::partition::partition(&partition_arrays)?.len() == 1 {
+ let partition_values = self.partition_values_at(&partition_arrays, 0)?;
+ let batch = self.project_file_columns(values, None)?;
+ return Ok(vec![PartitionSlice {
+ partition_values,
+ batch,
+ }]);
+ }
+
+ let indices = lexsort_to_indices(&partition_arrays)?;
+ let sorted: Vec<ArrayRef> = partition_arrays
+ .iter()
+ .map(|a| take(a.as_ref(), &indices, None))
+ .collect::<std::result::Result<_, _>>()?;
+ let ranges = arrow_ord::partition::partition(&sorted)?;
+ let mut out = Vec::new();
+ for range in ranges.ranges() {
+ let idx: UInt32Array = (range.start..range.end)
+ .map(|i| Some(indices.value(i)))
+ .collect();
+ let partition_values = self.partition_values_at(&sorted, range.start)?;
+ let batch = self.project_file_columns(values, Some(&idx))?;
+ out.push(PartitionSlice {
+ partition_values,
+ batch,
+ });
+ }
+ Ok(out)
+ }
+
+ fn partition_values_at(
+ &self,
+ arrays: &[ArrayRef],
+ row: usize,
+ ) -> Result<IndexMap<String, Scalar>> {
+ let mut out = IndexMap::new();
+ for (name, arr) in self.partition_columns.iter().zip(arrays) {
+ let value = Scalar::from_array(arr.as_ref(), row).ok_or_else(|| {
+ Error::Generic("Missing partition column: failed to parse".into())
+ })?;
+ out.insert(name.clone(), value);
+ }
+ Ok(out)
+ }
+
+ /// The non-partition columns of `values` (optionally only rows `idx`), rebuilt under
+ /// the file schema the way delta-rs rebuilds them, so the result is validated
+ /// against the table's nullability exactly as delta-rs validates it.
+ fn project_file_columns(
+ &self,
+ values: &RecordBatch,
+ idx: Option<&UInt32Array>,
+ ) -> Result<RecordBatch> {
+ let schema = values.schema();
+ let mut cols: Vec<ArrayRef> = Vec::with_capacity(self.file_schema.fields().len());
+ for f in self.file_schema.fields() {
+ let col = values.column(schema.index_of(f.name())?);
+ cols.push(match idx {
+ Some(idx) => take(col.as_ref(), idx, None)?,
+ None => col.clone(),
+ });
+ }
+ Ok(RecordBatch::try_new(self.file_schema.clone(), cols)?)
+ }
+}
+
+/// `default_writer_properties(Compression::SNAPPY)` from delta-rs, which every
+/// `RecordBatchWriter` constructor uses.
+fn delta_rs_writer_properties() -> WriterProperties {
+ WriterProperties::builder()
+ .set_created_by(format!("delta-rs version {}", deltalake::crate_version()))
+ .set_compression(Compression::SNAPPY)
+ .build()
+}
+
+fn schema_without_partitions(schema: &SchemaRef, partition_columns: &[String]) -> SchemaRef {
+ Arc::new(Schema::new(
+ schema
+ .fields()
+ .iter()
+ .filter(|f| !partition_columns.contains(f.name()))
+ .map(|f| f.to_owned())
+ .collect::<Vec<_>>(),
+ ))
+}
+
+/// delta-rs's `PartitionsExt::hive_partition_path` for `IndexMap<String, Scalar>`.
+fn hive_partition_path(values: &IndexMap<String, Scalar>) -> String {
+ values
+ .iter()
+ .map(|(k, v)| format!("{k}={}", v.serialize_encoded()))
+ .collect::<Vec<_>>()
+ .join("/")
+}
+
+/// delta-rs's `next_data_path` with `part_count = 0`, which is what
+/// `RecordBatchWriter::flush` passes.
+fn next_data_path(prefix: &Path, writer_id: &Uuid, props: &WriterProperties) -> Path {
+ let ext = match props.compression(&ColumnPath::new(Vec::new())) {
+ Compression::UNCOMPRESSED => "",
+ Compression::SNAPPY => ".snappy",
+ Compression::GZIP(_) => ".gz",
+ Compression::LZO => ".lzo",
+ Compression::BROTLI(_) => ".br",
+ Compression::LZ4 => ".lz4",
+ Compression::ZSTD(_) => ".zstd",
+ Compression::LZ4_RAW => ".lz4raw",
+ };
+ prefix
+ .clone()
+ .join(format!("part-00000-{writer_id}-c000{ext}.parquet"))
+}
+
+/// delta-rs's `lexsort_to_indices` (record_batch.rs), returning errors instead of
+/// unwrapping.
+fn lexsort_to_indices(arrays: &[ArrayRef]) -> Result<UInt32Array> {
+ let fields = arrays
+ .iter()
+ .map(|a| SortField::new(a.data_type().clone()))
+ .collect();
+ let converter = RowConverter::new(fields)?;
+ let rows = converter.convert_columns(arrays)?;
+ let mut sort: Vec<_> = rows.iter().enumerate().collect();
+ sort.sort_unstable_by(|(_, a), (_, b)| a.cmp(b));
+ Ok(UInt32Array::from_iter_values(
+ sort.iter().map(|(i, _)| *i as u32),
+ ))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn chunk_sink_preserves_bytes_and_counts_them() {
+ let mut sink = ChunkSink::default();
+ let data: Vec<u8> = (0..(CHUNK_BYTES * 2 + 123))
+ .map(|i| (i % 251) as u8)
+ .collect();
+ // Uneven writes that straddle chunk boundaries.
+ for piece in data.chunks(CHUNK_BYTES / 3 + 7) {
+ sink.write_all(piece).unwrap();
+ }
+ assert_eq!(sink.len, data.len());
+ let (payload, size) = sink.into_payload();
+ assert_eq!(size, data.len());
+ let chunks: Vec<&Bytes> = payload.iter().collect();
+ assert_eq!(chunks.len(), 3);
+ assert!(chunks[..2].iter().all(|c| c.len() == CHUNK_BYTES));
+ let joined: Vec<u8> = chunks.iter().flat_map(|c| c.iter().copied()).collect();
+ assert_eq!(joined, data);
+ }
+
+ #[test]
+ fn empty_sink_is_an_empty_payload() {
+ let (payload, size) = ChunkSink::default().into_payload();
+ assert_eq!(size, 0);
+ assert_eq!(payload.content_length(), 0);
+ }
+
+ // ---- equivalence with delta-rs's RecordBatchWriter ----------------------------
+
+ use arrow_array::builder::{Int64Builder, ListBuilder};
+ use arrow_array::{Int64Array, StringArray, StructArray};
+ use arrow_schema::DataType as ArrowType;
+ use delta_kernel::schema::{ArrayType, DataType, StructField};
+ use deltalake::operations::create::CreateBuilder;
+ use deltalake::writer::DeltaWriter;
+ use object_store::ObjectStoreExt;
+ use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
+ use serde_json::Value;
+
+ /// Deterministic pseudo-random sequence (no `rand` dependency).
+ struct Lcg(u64);
+
+ impl Lcg {
+ fn next(&mut self) -> u64 {
+ self.0 = self
+ .0
+ .wrapping_mul(6364136223846793005)
+ .wrapping_add(1442695040888963407);
+ self.0 >> 11
+ }
+ }
+
+ fn wide_columns() -> Vec<StructField> {
+ vec![
+ StructField::new("id", DataType::STRING, false),
+ StructField::new("p", DataType::STRING, false),
+ StructField::new("lng", DataType::LONG, true),
+ StructField::new("int", DataType::INTEGER, true),
+ StructField::new("sht", DataType::SHORT, true),
+ StructField::new("byt", DataType::BYTE, true),
+ StructField::new("dbl", DataType::DOUBLE, true),
+ StructField::new("flt", DataType::FLOAT, true),
+ StructField::new("bln", DataType::BOOLEAN, true),
+ StructField::new("dt", DataType::DATE, true),
+ StructField::new("ts", DataType::TIMESTAMP, true),
+ StructField::new("bin", DataType::BINARY, true),
+ StructField::new("str", DataType::STRING, true),
+ StructField::new("dec_small", DataType::decimal(10, 2).unwrap(), true),
+ StructField::new("dec_wide", DataType::decimal(38, 6).unwrap(), true),
+ StructField::new("all_null", DataType::LONG, true),
+ StructField::new(
+ "arr",
+ DataType::from(ArrayType::new(DataType::LONG, true)),
+ true,
+ ),
+ StructField::new(
+ "st",
+ DataType::try_struct_type(vec![
+ StructField::new("a", DataType::LONG, true),
+ StructField::new("b", DataType::STRING, true),
+ ])
+ .unwrap(),
+ true,
+ ),
+ ]
+ }
+
+ fn narrow_columns() -> Vec<StructField> {
+ vec![
+ StructField::new("id", DataType::STRING, false),
+ StructField::new("p", DataType::STRING, false),
+ StructField::new("lng", DataType::LONG, true),
+ ]
+ }
+
+ async fn create_table(
+ dir: &std::path::Path,
+ columns: Vec<StructField>,
+ partition_by: &[&str],
+ config: &[(&str, &str)],
+ ) -> DeltaTable {
+ let mut b = CreateBuilder::new()
+ .with_location(dir.to_str().unwrap())
+ .with_columns(columns);
+ if !partition_by.is_empty() {
+ b = b.with_partition_columns(partition_by.iter().map(|s| s.to_string()));
+ }
+ if !config.is_empty() {
+ b = b.with_configuration(
+ config
+ .iter()
+ .map(|(k, v)| (k.to_string(), Some(v.to_string()))),
+ );
+ }
+ b.await.expect("create table")
+ }
+
+ /// A batch for `schema` whose every row has partition value `p_of(row)`. Nullable
+ /// columns carry nulls on a column-specific stride so null counts differ per column.
+ fn gen_batch(
+ schema: &SchemaRef,
+ rows: usize,
+ seed: u64,
+ p_of: &dyn Fn(usize) -> String,
+ ) -> RecordBatch {
+ let mut rng = Lcg(seed);
+ let base: Vec<i64> = (0..rows)
+ .map(|_| (rng.next() % 2_000_000) as i64 - 1_000_000)
+ .collect();
+ let cols: Vec<ArrayRef> = schema
+ .fields()
+ .iter()
+ .enumerate()
+ .map(|(ci, f)| {
+ let stride = 3 + ci;
+ let null_at = |i: usize| f.is_nullable() && i.is_multiple_of(stride);
+ let ints: ArrayRef = Arc::new(Int64Array::from(
+ (0..rows)
+ .map(|i| (!null_at(i)).then_some(base[i] / (ci as i64 + 1)))
+ .collect::<Vec<_>>(),
+ ));
+ let col: ArrayRef = match (f.name().as_str(), f.data_type()) {
+ ("id", _) => Arc::new(StringArray::from(
+ (0..rows)
+ .map(|i| format!("id-{seed}-{i}"))
+ .collect::<Vec<_>>(),
+ )),
+ ("p", _) => {
+ Arc::new(StringArray::from((0..rows).map(p_of).collect::<Vec<_>>()))
+ }
+ ("all_null", t) => arrow_array::new_null_array(t, rows),
+ (_, ArrowType::Utf8) => Arc::new(StringArray::from(
+ (0..rows)
+ .map(|i| (!null_at(i)).then(|| format!("s{}", base[i] % 977)))
+ .collect::<Vec<_>>(),
+ )),
+ (_, ArrowType::Binary) => {
+ let s = arrow_cast::cast(&ints, &ArrowType::Utf8).unwrap();
+ arrow_cast::cast(&s, &ArrowType::Binary).unwrap()
+ }
+ (_, ArrowType::Boolean) => {
+ let odd: ArrayRef = Arc::new(arrow_array::Int64Array::from(
+ (0..rows)
+ .map(|i| (!null_at(i)).then_some(base[i] & 1))
+ .collect::<Vec<_>>(),
+ ));
+ arrow_cast::cast(&odd, &ArrowType::Boolean).unwrap()
+ }
+ (_, ArrowType::Timestamp(_, _)) => {
+ let us: ArrayRef = Arc::new(Int64Array::from(
+ (0..rows)
+ .map(|i| {
+ (!null_at(i))
+ .then_some(1_700_000_000_000_000 + base[i] * 1_000_003)
+ })
+ .collect::<Vec<_>>(),
+ ));
+ arrow_cast::cast(&us, f.data_type()).unwrap()
+ }
+ (_, ArrowType::Date32) => {
+ let days: ArrayRef = Arc::new(arrow_array::Int32Array::from(
+ (0..rows)
+ .map(|i| (!null_at(i)).then_some((base[i] % 20_000) as i32))
+ .collect::<Vec<_>>(),
+ ));
+ arrow_cast::cast(&days, &ArrowType::Date32).unwrap()
+ }
+ (_, ArrowType::List(_)) => {
+ let mut b =
+ ListBuilder::new(Int64Builder::new()).with_field(match f.data_type() {
+ ArrowType::List(inner) => inner.clone(),
+ _ => unreachable!(),
+ });
+ for (i, v) in base.iter().enumerate() {
+ if null_at(i) {
+ b.append_null();
+ } else {
+ for k in 0..(i % 4) {
+ b.values().append_value(v + k as i64);
+ }
+ b.append(true);
+ }
+ }
+ Arc::new(b.finish())
+ }
+ (_, ArrowType::Struct(fields)) => {
+ let a: ArrayRef = Arc::new(Int64Array::from(
+ (0..rows)
+ .map(|i| (i % 5 != 0).then_some(base[i]))
+ .collect::<Vec<_>>(),
+ ));
+ let b: ArrayRef = Arc::new(StringArray::from(
+ (0..rows)
+ .map(|i| (i % 7 != 0).then(|| format!("b{}", base[i] % 31)))
+ .collect::<Vec<_>>(),
+ ));
+ let nulls = arrow_buffer::NullBuffer::from(
+ (0..rows).map(|i| !null_at(i)).collect::<Vec<_>>(),
+ );
+ Arc::new(StructArray::new(fields.clone(), vec![a, b], Some(nulls)))
+ }
+ (_, t @ (ArrowType::Int8 | ArrowType::Int16)) => {
+ let small: ArrayRef = Arc::new(Int64Array::from(
+ (0..rows)
+ .map(|i| (!null_at(i)).then_some(base[i] % 120))
+ .collect::<Vec<_>>(),
+ ));
+ arrow_cast::cast(&small, t).unwrap()
+ }
+ (_, t) => arrow_cast::cast(&ints, t).unwrap(),
+ };
+ col
+ })
+ .collect();
+ RecordBatch::try_new(schema.clone(), cols).unwrap()
+ }
+
+ /// One written file: its Add action and its bytes.
+ struct Written {
+ add: Add,
+ bytes: Bytes,
+ }
+
+ /// Drive a writer exactly as `rewrite_partition` drives it: write, then flush
+ /// whenever the buffer reaches `target`, then a final flush.
+ async fn drive<W, F, B>(
+ writer: &mut W,
+ batches: &[RecordBatch],
+ target: usize,
+ mut write: F,
+ buffer_len: B,
+ ) -> Vec<Add>
+ where
+ F: AsyncFnMut(&mut W, RecordBatch),
+ B: Fn(&W) -> usize,
+ W: FlushAdds,
+ {
+ let mut adds = Vec::new();
+ for b in batches {
+ write(writer, b.clone()).await;
+ if buffer_len(writer) >= target {
+ adds.extend(writer.flush_adds().await);
+ }
+ }
+ adds.extend(writer.flush_adds().await);
+ adds
+ }
+
+ trait FlushAdds {
+ async fn flush_adds(&mut self) -> Vec<Add>;
+ }
+
+ impl FlushAdds for RecordBatchWriter {
+ async fn flush_adds(&mut self) -> Vec<Add> {
+ self.flush().await.unwrap()
+ }
+ }
+
+ impl FlushAdds for StreamingWriter {
+ async fn flush_adds(&mut self) -> Vec<Add> {
+ self.flush().await.unwrap()
+ }
+ }
+
+ async fn read_back(table: &DeltaTable, adds: Vec<Add>) -> Vec<Written> {
+ let store = table.object_store();
+ let mut out = Vec::new();
+ for add in adds {
+ let bytes = store
+ .get(&Path::parse(&add.path).unwrap())
+ .await
+ .unwrap()
+ .bytes()
+ .await
+ .unwrap();
+ out.push(Written { add, bytes });
+ }
+ // Flush order across partitions follows a HashMap; compare in a stable order.
+ out.sort_by(|a, b| {
+ let key = |w: &Written| {
+ let mut pv: Vec<_> = w.add.partition_values.iter().collect();
+ pv.sort();
+ (format!("{pv:?}"), w.add.size, w.bytes.clone())
+ };
+ key(a).cmp(&key(b))
+ });
+ out
+ }
+
+ fn stats_json(add: &Add) -> Value {
+ serde_json::from_str(add.stats.as_deref().expect("stats present")).unwrap()
+ }
+
+ /// Writes `batches` through both writers and asserts the outputs are the same files:
+ /// byte-identical Parquet, identical sizes, partition values, stats and data
+ /// layout (directory), differing only in the random file name.
+ async fn assert_equivalent(
+ case: &str,
+ columns: Vec<StructField>,
+ partition_by: &[&str],
+ config: &[(&str, &str)],
+ batches_of: &dyn Fn(&SchemaRef) -> Vec<RecordBatch>,
+ target: usize,
+ ) -> Vec<Written> {
+ let dir = tempfile::tempdir().unwrap();
+ let table = create_table(dir.path(), columns, partition_by, config).await;
+
+ let mut old = RecordBatchWriter::for_table(&table).unwrap();
+ let schema = old.arrow_schema();
+ let batches = batches_of(&schema);
+ let old_adds = drive(
+ &mut old,
+ &batches,
+ target,
+ async |w: &mut RecordBatchWriter, b| w.write(b).await.unwrap(),
+ |w: &RecordBatchWriter| w.buffer_len(),
+ )
+ .await;
+
+ let mut new = StreamingWriter::for_table(&table).unwrap();
+ assert_eq!(new.arrow_schema, schema, "{case}: arrow schema");
+ let new_adds = drive(
+ &mut new,
+ &batches,
+ target,
+ async |w: &mut StreamingWriter, b| w.write(b).unwrap(),
+ |w: &StreamingWriter| w.buffer_len(),
+ )
+ .await;
+
+ let old_files = read_back(&table, old_adds).await;
+ let new_files = read_back(&table, new_adds).await;
+ assert_eq!(
+ old_files.len(),
+ new_files.len(),
+ "{case}: file count (rollover)"
+ );
+ assert!(!new_files.is_empty(), "{case}: wrote nothing");
+ for (o, n) in old_files.iter().zip(&new_files) {
+ assert_eq!(o.bytes, n.bytes, "{case}: parquet bytes differ");
+ assert_eq!(o.add.size, n.add.size, "{case}: size");
+ assert_eq!(
+ n.add.size as usize,
+ n.bytes.len(),
+ "{case}: size is the object size"
+ );
+ assert_eq!(
+ o.add.partition_values, n.add.partition_values,
+ "{case}: partition values"
+ );
+ assert_eq!(stats_json(&o.add), stats_json(&n.add), "{case}: stats");
+ assert_eq!(o.add.data_change, n.add.data_change, "{case}: dataChange");
+ assert_eq!(o.add.tags, n.add.tags, "{case}: tags");
+ assert!(n.add.deletion_vector.is_none());
+ let (o_dir, o_name) = o.add.path.rsplit_once('/').unwrap_or(("", &o.add.path));
+ let (n_dir, n_name) = n.add.path.rsplit_once('/').unwrap_or(("", &n.add.path));
+ assert_eq!(o_dir, n_dir, "{case}: partition directory");
+ let shape = |name: &str| {
+ name.starts_with("part-00000-")
+ && name.ends_with("-c000.snappy.parquet")
+ && Uuid::parse_str(&name[11..47]).is_ok()
+ };
+ assert!(shape(o_name) && shape(n_name), "{case}: file name {n_name}");
+ }
+ new_files
+ }
+
+ fn single_partition_batches(n: usize, rows: usize) -> impl Fn(&SchemaRef) -> Vec<RecordBatch> {
+ move |schema| {
+ (0..n)
+ .map(|i| gen_batch(schema, rows, 7 + i as u64, &|_| "2024-01-01T00".to_string()))
+ .collect()
+ }
+ }
+
+ #[tokio::test]
+ async fn streaming_writer_output_matches_record_batch_writer() {
+ let mixed = |schema: &SchemaRef| -> Vec<RecordBatch> {
+ (0..4)
+ .map(|i| {
+ gen_batch(schema, 3000, 100 + i, &|r| {
+ ["a b/c:d", "2024-01-01T01", "x%y", "ünï"][r % 4].to_string()
+ })
+ })
+ .collect()
+ };
+ type Case<'a> = (
+ &'a str,
+ fn() -> Vec<StructField>,
+ &'a [&'a str],
+ &'a [(&'a str, &'a str)],
+ Box<dyn Fn(&SchemaRef) -> Vec<RecordBatch>>,
+ usize,
+ usize,
+ );
+ let cases: Vec<Case> = vec![
+ (
+ "unpartitioned, no rollover",
+ wide_columns,
+ &[],
+ &[],
+ Box::new(single_partition_batches(3, 2500)),
+ usize::MAX,
+ 1,
+ ),
+ (
+ "one partition per batch, rollover at 64 KiB",
+ wide_columns,
+ &["p"],
+ &[],
+ Box::new(single_partition_batches(12, 2000)),
+ 64 * 1024,
+ 3,
+ ),
+ (
+ "batches spanning partitions that need percent-encoding",
+ wide_columns,
+ &["p"],
+ &[],
+ Box::new(mixed),
+ usize::MAX,
+ 4,
+ ),
+ (
+ "multi-partition batches with rollover",
+ wide_columns,
+ &["p"],
+ &[],
+ Box::new(mixed),
+ 96 * 1024,
+ 8,
+ ),
+ (
+ "dataSkippingNumIndexedCols=3",
+ wide_columns,
+ &["p"],
+ &[("delta.dataSkippingNumIndexedCols", "3")],
+ Box::new(single_partition_batches(3, 1000)),
+ usize::MAX,
+ 1,
+ ),
+ (
+ "dataSkippingNumIndexedCols=-1 (falls back to 32, as delta-rs does)",
+ wide_columns,
+ &[],
+ &[("delta.dataSkippingNumIndexedCols", "-1")],
+ Box::new(single_partition_batches(2, 1000)),
+ usize::MAX,
+ 1,
+ ),
+ (
+ "dataSkippingStatsColumns",
+ wide_columns,
+ &["p"],
+ &[("delta.dataSkippingStatsColumns", "lng,str,`ts`")],
+ Box::new(single_partition_batches(3, 1000)),
+ usize::MAX,
+ 1,
+ ),
+ ];
+ for (case, columns, partition_by, config, batches_of, target, min_files) in cases {
+ let files =
+ assert_equivalent(case, columns(), partition_by, config, &*batches_of, target)
+ .await;
+ assert!(
+ files.len() >= min_files,
+ "{case}: only {} files",
+ files.len()
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn equivalence_fixture_exercises_every_stats_type() {
+ // Guards the comparison above against vacuous passes: the default-config stats
+ // must actually carry min/max for each logical type the vendored code converts.
+ let files = assert_equivalent(
+ "stats coverage",
+ wide_columns(),
+ &["p"],
+ &[],
+ &single_partition_batches(1, 500),
+ usize::MAX,
+ )
+ .await;
+ let stats = stats_json(&files[0].add);
+ for col in [
+ "id",
+ "lng",
+ "int",
+ "sht",
+ "byt",
+ "dbl",
+ "flt",
+ "bln",
+ "dt",
+ "ts",
+ "str",
+ "dec_small",
+ "dec_wide",
+ ] {
+ assert!(
+ stats["minValues"].get(col).is_some(),
+ "no min for {col}: {stats}"
+ );
+ assert!(
+ stats["maxValues"].get(col).is_some(),
+ "no max for {col}: {stats}"
+ );
+ }
+ assert!(stats["minValues"]["st"]["a"].is_number(), "{stats}");
+ assert_eq!(stats["nullCount"]["all_null"], 500);
+ assert!(stats["nullCount"].get("arr").is_some(), "{stats}");
+ assert!(
+ stats["minValues"].get("p").is_none(),
+ "partition column has no stats"
+ );
+ }
+
+ #[tokio::test]
+ async fn streaming_writer_matches_on_multi_row_group_files() {
+ // Over the 1Mi-row row-group limit, so stats aggregate across row groups.
+ let files = assert_equivalent(
+ "multi row group",
+ narrow_columns(),
+ &["p"],
+ &[],
+ &single_partition_batches(9, 130_000),
+ usize::MAX,
+ )
+ .await;
+ let meta = ParquetRecordBatchReaderBuilder::try_new(files[0].bytes.clone())
+ .unwrap()
+ .metadata()
+ .clone();
+ assert!(meta.num_row_groups() > 1, "fixture must span row groups");
+ }
+
+ #[tokio::test]
+ async fn streaming_writer_files_read_back_as_written() {
+ let dir = tempfile::tempdir().unwrap();
+ let table = create_table(dir.path(), wide_columns(), &["p"], &[]).await;
+ let mut w = StreamingWriter::for_table(&table).unwrap();
+ let input = single_partition_batches(3, 1500)(&w.arrow_schema);
+ for b in &input {
+ w.write(b.clone()).unwrap();
+ }
+ let adds = w.flush().await.unwrap();
+ assert_eq!(adds.len(), 1);
+ let files = read_back(&table, adds).await;
+ let read: Vec<RecordBatch> =
+ ParquetRecordBatchReaderBuilder::try_new(files[0].bytes.clone())
+ .unwrap()
+ .build()
+ .unwrap()
+ .collect::<std::result::Result<_, _>>()
+ .unwrap();
+ let read = arrow_select::concat::concat_batches(&w.file_schema, &read).unwrap();
+ let expected: Vec<RecordBatch> = input
+ .iter()
+ .map(|b| w.project_file_columns(b, None).unwrap())
+ .collect();
+ let expected = arrow_select::concat::concat_batches(&w.file_schema, &expected).unwrap();
+ assert_eq!(read, expected);
+ assert_eq!(stats_json(&files[0].add)["numRecords"], 4500);
+ assert_eq!(
+ files[0].add.partition_values.get("p"),
+ Some(&Some("2024-01-01T00".to_string()))
+ );
+ }
+
+ #[tokio::test]
+ async fn flush_without_writes_adds_nothing() {
+ let dir = tempfile::tempdir().unwrap();
+ let table = create_table(dir.path(), narrow_columns(), &["p"], &[]).await;
+ let mut w = StreamingWriter::for_table(&table).unwrap();
+ assert_eq!(w.buffer_len(), 0);
+ assert!(w.flush().await.unwrap().is_empty());
+ }
+}
diff --git a/rust/deltalite/core/tests/fetch_budget.rs b/rust/deltalite/core/tests/fetch_budget.rs
new file mode 100644
index 000000000000..5e00461327c1
--- /dev/null
+++ b/rust/deltalite/core/tests/fetch_budget.rs
@@ -0,0 +1,525 @@
+//! The reader fetch budget (`UpsertOptions::max_fetch_bytes` and the process-wide
+//! `DELTALITE_PROCESS_MAX_FETCH_BYTES`): it bounds the compressed row-group bytes that
+//! readers hold at once, a row group larger than the budget still runs (alone), and
+//! nothing deadlocks when every budget is tiny and many upserts share them.
+//!
+//! The bytes are measured, not inferred from the semaphore: the test store hands out
+//! every `get_ranges` result as a `Bytes` whose owner decrements a live counter when the
+//! parquet reader drops the last slice of it.
+
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, LazyLock, Mutex};
+use std::time::Duration;
+
+use arrow_array::{Int64Array, RecordBatch, StringArray};
+use arrow_schema::{DataType, Field, Schema, SchemaRef};
+use bytes::Bytes;
+use deltalake::kernel::{DataType as KernelType, StructField};
+use deltalake::logstore::{
+ default_logstore, logstore_factories, object_store_factories, LogStore, LogStoreFactory,
+ ObjectStoreFactory, StorageConfig,
+};
+use deltalake::operations::create::CreateBuilder;
+use deltalake::writer::{DeltaWriter, RecordBatchWriter};
+use deltalake::{DeltaResult, DeltaTable, Path};
+use deltalite_core::limits::ProcessLimits;
+use deltalite_core::table::open_table;
+use deltalite_core::upsert::{upsert, PruneStrategy, UpsertOptions, UpsertStats};
+use futures::stream::BoxStream;
+use object_store::local::LocalFileSystem;
+use object_store::{
+ CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore,
+ PutMultipartOptions, PutOptions, PutPayload, PutResult, RenameOptions,
+};
+use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
+
+// ---- live-fetched-bytes accounting ----------------------------------------------
+
+#[derive(Default)]
+struct Gauge {
+ live: AtomicUsize,
+ peak: AtomicUsize,
+ fetched: AtomicUsize,
+}
+
+impl Gauge {
+ fn add(&self, n: usize) {
+ let now = self.live.fetch_add(n, Ordering::SeqCst) + n;
+ self.peak.fetch_max(now, Ordering::SeqCst);
+ self.fetched.fetch_add(n, Ordering::SeqCst);
+ }
+}
+
+/// Gauges by object-store path prefix; a test registers the directory its tables live
+/// under, so tests running concurrently in this process measure only their own reads.
+type Gauges = Vec<(String, Arc<Gauge>)>;
+static GAUGES: LazyLock<Mutex<Gauges>> = LazyLock::new(Default::default);
+
+fn gauge_for(dir: &std::path::Path) -> Arc<Gauge> {
+ let g = Arc::new(Gauge::default());
+ GAUGES.lock().unwrap().push((
+ Path::from(dir.to_string_lossy().as_ref()).to_string(),
+ g.clone(),
+ ));
+ g
+}
+
+fn find_gauge(location: &Path) -> Option<Arc<Gauge>> {
+ GAUGES
+ .lock()
+ .unwrap()
+ .iter()
+ .find(|(prefix, _)| location.as_ref().starts_with(prefix.as_str()))
+ .map(|(_, g)| g.clone())
+}
+
+/// Owner of fetched bytes that keeps the gauge honest for as long as any slice lives.
+struct Tracked {
+ bytes: Bytes,
+ gauge: Arc<Gauge>,
+}
+
+impl AsRef<[u8]> for Tracked {
+ fn as_ref(&self) -> &[u8] {
+ &self.bytes
+ }
+}
+
+impl Drop for Tracked {
+ fn drop(&mut self) {
+ self.gauge
+ .live
+ .fetch_sub(self.bytes.len(), Ordering::SeqCst);
+ }
+}
+
+#[derive(Debug)]
+struct GaugedStore {
+ inner: Arc<dyn ObjectStore>,
+}
+
+impl std::fmt::Display for GaugedStore {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "GaugedStore({})", self.inner)
+ }
+}
+
+#[async_trait::async_trait]
+impl ObjectStore for GaugedStore {
+ 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: &[std::ops::Range<u64>],
+ ) -> object_store::Result<Vec<Bytes>> {
+ let got = self.inner.get_ranges(location, ranges).await?;
+ let Some(gauge) = find_gauge(location).filter(|_| location.as_ref().ends_with(".parquet"))
+ else {
+ return Ok(got);
+ };
+ Ok(got
+ .into_iter()
+ .map(|bytes| {
+ gauge.add(bytes.len());
+ Bytes::from_owner(Tracked {
+ bytes,
+ gauge: gauge.clone(),
+ })
+ })
+ .collect())
+ }
+
+ fn delete_stream(
+ &self,
+ locations: BoxStream<'static, object_store::Result<Path>>,
+ ) -> BoxStream<'static, object_store::Result<Path>> {
+ self.inner.delete_stream(locations)
+ }
+
+ // Sorted: cloud stores list lexicographically and delta-kernel relies on it.
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, object_store::Result<ObjectMeta>> {
+ sorted(self.inner.list(prefix))
+ }
+
+ fn list_with_offset(
+ &self,
+ prefix: Option<&Path>,
+ offset: &Path,
+ ) -> BoxStream<'static, object_store::Result<ObjectMeta>> {
+ sorted(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: CopyOptions,
+ ) -> object_store::Result<()> {
+ self.inner.copy_opts(from, to, options).await
+ }
+
+ async fn rename_opts(
+ &self,
+ from: &Path,
+ to: &Path,
+ options: RenameOptions,
+ ) -> object_store::Result<()> {
+ self.inner.rename_opts(from, to, options).await
+ }
+}
+
+fn sorted(
+ stream: BoxStream<'static, object_store::Result<ObjectMeta>>,
+) -> BoxStream<'static, object_store::Result<ObjectMeta>> {
+ use futures::{StreamExt, TryStreamExt};
+ futures::stream::once(async move {
+ let mut items: Vec<ObjectMeta> = stream.try_collect().await?;
+ items.sort_by(|a, b| a.location.cmp(&b.location));
+ Ok::<_, object_store::Error>(futures::stream::iter(items.into_iter().map(Ok)))
+ })
+ .try_flatten()
+ .boxed()
+}
+
+#[derive(Debug, Default)]
+struct Factory;
+
+impl ObjectStoreFactory for Factory {
+ fn parse_url_opts(
+ &self,
+ url: &url::Url,
+ _config: &StorageConfig,
+ ) -> DeltaResult<(Arc<dyn ObjectStore>, Path)> {
+ let store = GaugedStore {
+ inner: Arc::new(LocalFileSystem::new()),
+ };
+ Ok((Arc::new(store), Path::from_url_path(url.path())?))
+ }
+}
+
+impl LogStoreFactory for Factory {
+ fn with_options(
+ &self,
+ prefixed_store: Arc<dyn ObjectStore>,
+ root_store: Arc<dyn ObjectStore>,
+ location: &url::Url,
+ options: &StorageConfig,
+ ) -> DeltaResult<Arc<dyn LogStore>> {
+ Ok(default_logstore(
+ prefixed_store,
+ root_store,
+ location,
+ options,
+ ))
+ }
+}
+
+fn register_scheme() {
+ let scheme = url::Url::parse("dlfetch://").expect("static url");
+ object_store_factories().insert(scheme.clone(), Arc::new(Factory));
+ logstore_factories().insert(scheme, Arc::new(Factory));
+}
+
+// ---- fixtures ----------------------------------------------------------------------
+
+const FILES: usize = 8;
+/// Rows per seeded file: one row group, and several read batches per row group, so a
+/// reader keeps its fetched row group while it waits for decode budget between batches.
+const ROWS: usize = 20_000;
+
+fn schema(partitioned: bool) -> SchemaRef {
+ let mut fields = vec![
+ Field::new("pk", DataType::Utf8, false),
+ Field::new("v", DataType::Int64, true),
+ Field::new("payload", DataType::Utf8, true),
+ ];
+ if partitioned {
+ fields.push(Field::new("p", DataType::Utf8, false));
+ }
+ Arc::new(Schema::new(fields))
+}
+
+/// Incompressible payload so the compressed row group is a meaningful size.
+fn payload(seed: u64, i: usize) -> String {
+ let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (i as u64);
+ (0..4)
+ .map(|_| {
+ x = x
+ .wrapping_mul(6364136223846793005)
+ .wrapping_add(1442695040888963407);
+ format!("{x:016x}")
+ })
+ .collect()
+}
+
+fn rows(
+ schema: &SchemaRef,
+ file: usize,
+ ids: &[usize],
+ v: i64,
+ partition: Option<&str>,
+) -> RecordBatch {
+ let mut cols: Vec<Arc<dyn arrow_array::Array>> = vec![
+ Arc::new(StringArray::from(
+ ids.iter()
+ .map(|i| format!("f{file}-{i}"))
+ .collect::<Vec<_>>(),
+ )),
+ Arc::new(Int64Array::from(vec![v; ids.len()])),
+ Arc::new(StringArray::from(
+ ids.iter()
+ .map(|i| payload(file as u64, *i))
+ .collect::<Vec<_>>(),
+ )),
+ ];
+ if let Some(p) = partition {
+ cols.push(Arc::new(StringArray::from(vec![p; ids.len()])));
+ }
+ RecordBatch::try_new(schema.clone(), cols).unwrap()
+}
+
+/// 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) {
+ let partitioned = !partitions.is_empty();
+ let mut create = CreateBuilder::new()
+ .with_location(dir.to_str().unwrap())
+ .with_columns(vec![
+ StructField::new("pk", KernelType::STRING, false),
+ StructField::new("v", KernelType::LONG, true),
+ StructField::new("payload", KernelType::STRING, true),
+ ]);
+ if partitioned {
+ create = create
+ .with_columns(vec![StructField::new("p", KernelType::STRING, false)])
+ .with_partition_columns(vec!["p".to_string()]);
+ }
+ let mut table = create.await.unwrap();
+ let s = schema(partitioned);
+ let ids: Vec<usize> = (0..ROWS).collect();
+ let parts: Vec<Option<&str>> = if partitioned {
+ partitions.iter().map(|p| Some(*p)).collect()
+ } else {
+ vec![None]
+ };
+ for p in parts {
+ for f in 0..FILES {
+ let mut w = RecordBatchWriter::for_table(&table).unwrap();
+ w.write(rows(&s, f, &ids, 0, p)).await.unwrap();
+ w.flush_and_commit(&mut table).await.unwrap();
+ }
+ }
+
+ let mut max_rg = 0usize;
+ for uri in table.get_file_uris().unwrap() {
+ let path = uri.strip_prefix("file://").unwrap_or(&uri);
+ let bytes = Bytes::from(std::fs::read(path).unwrap());
+ let meta = ParquetRecordBatchReaderBuilder::try_new(bytes)
+ .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);
+ }
+ (format!("dlfetch://{}", dir.to_string_lossy()), max_rg)
+}
+
+/// One update per seeded file (so every file is rewritten) and one insert per partition.
+fn source(partitions: &[&str]) -> (SchemaRef, Vec<RecordBatch>) {
+ let partitioned = !partitions.is_empty();
+ let s = schema(partitioned);
+ let parts: Vec<Option<&str>> = if partitioned {
+ partitions.iter().map(|p| Some(*p)).collect()
+ } else {
+ vec![None]
+ };
+ let mut batches = Vec::new();
+ for p in parts {
+ for f in 0..FILES {
+ batches.push(rows(&s, f, &[7], 1, p));
+ }
+ batches.push(rows(&s, 999, &[0], 1, p));
+ }
+ (s, batches)
+}
+
+fn opts(max_fetch_bytes: usize, limits: Arc<ProcessLimits>) -> UpsertOptions {
+ UpsertOptions {
+ primary_keys: vec!["pk".to_string()],
+ // Read every file without probing, so readers are the only fetchers.
+ prune_strategy: PruneStrategy::None,
+ max_parallel_partitions: 4,
+ max_parallel_files: FILES,
+ // Small decode budget: a reader waits for budget between batches while it keeps
+ // its fetched row group, so unbounded fetches overlap across all readers.
+ max_buffered_bytes: 256 * 1024,
+ max_fetch_bytes,
+ limits,
+ ..Default::default()
+ }
+}
+
+fn roomy_limits() -> Arc<ProcessLimits> {
+ Arc::new(ProcessLimits::with_fetch(64, 64, 1 << 30, 1 << 30))
+}
+
+async fn run(
+ uri: &str,
+ schema: SchemaRef,
+ batches: Vec<RecordBatch>,
+ o: UpsertOptions,
+) -> UpsertStats {
+ let table: DeltaTable = open_table(uri, HashMap::new()).await.unwrap();
+ tokio::time::timeout(Duration::from_secs(300), upsert(&table, batches, schema, o))
+ .await
+ .expect("upsert deadlocked")
+ .expect("upsert failed")
+}
+
+fn assert_rewrote_everything(stats: &UpsertStats, partitions: usize) {
+ assert_eq!(stats.files_removed, FILES * partitions);
+ assert_eq!(stats.rows_updated, FILES * partitions);
+ assert_eq!(stats.rows_inserted, partitions);
+ assert_eq!(stats.rows_copied, (ROWS - 1) * FILES * partitions);
+}
+
+// ---- tests -------------------------------------------------------------------------
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn fetch_budget_bounds_live_fetched_bytes() {
+ register_scheme();
+ // (case, budget in row groups, expected peak range in row groups)
+ let cases: [(&str, f64, f64, f64); 3] = [
+ // Without a binding budget every reader holds its row group at once.
+ ("unbounded", 1e9, 3.0, FILES as f64 + 0.5),
+ // A budget of 1.5 row groups admits exactly one reader at a time.
+ ("one-and-a-half row groups", 1.5, 0.9, 1.5),
+ // Smaller than one row group: the reader still runs, alone.
+ ("smaller than one row group", 0.25, 0.9, 1.01),
+ ];
+ for (case, budget_rgs, min_peak, max_peak) in cases {
+ let dir = tempfile::tempdir().unwrap();
+ let (uri, rg) = seed(dir.path(), &[]).await;
+ let gauge = gauge_for(dir.path());
+ let (s, batches) = source(&[]);
+ let budget = ((rg as f64) * budget_rgs).min((1u64 << 40) as f64) as usize;
+ let stats = run(&uri, s, batches, opts(budget, roomy_limits())).await;
+ assert_rewrote_everything(&stats, 1);
+
+ let peak = gauge.peak.load(Ordering::SeqCst) as f64 / rg as f64;
+ eprintln!(
+ "{case}: row group {rg} B, budget {budget} B, peak live fetched {peak:.2} row groups"
+ );
+ assert!(
+ gauge.fetched.load(Ordering::SeqCst) >= FILES * rg * 9 / 10,
+ "{case}: every file's row group must be fetched through get_ranges"
+ );
+ assert!(
+ (min_peak..=max_peak).contains(&peak),
+ "{case}: peak live fetched bytes = {peak:.2} row groups, expected {min_peak}..={max_peak}"
+ );
+ assert_eq!(
+ gauge.live.load(Ordering::SeqCst),
+ 0,
+ "{case}: fetched bytes leaked"
+ );
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn process_fetch_budget_bounds_concurrent_upserts() {
+ register_scheme();
+ let root = tempfile::tempdir().unwrap();
+ let gauge = gauge_for(root.path());
+ let mut uris = Vec::new();
+ let mut rg = 0;
+ for i in 0..4 {
+ let (uri, r) = seed(&root.path().join(format!("t{i}")), &[]).await;
+ uris.push(uri);
+ rg = r;
+ }
+ // Per-call budgets are roomy; only the shared process-wide fetch budget binds.
+ let shared = Arc::new(ProcessLimits::with_fetch(64, 64, 1 << 30, rg * 3 / 2));
+ let runs = uris.iter().map(|uri| {
+ let (s, batches) = source(&[]);
+ run(uri, s, batches, opts(1 << 40, shared.clone()))
+ });
+ for stats in futures::future::join_all(runs).await {
+ assert_rewrote_everything(&stats, 1);
+ }
+ let peak = gauge.peak.load(Ordering::SeqCst);
+ eprintln!(
+ "4 concurrent upserts: row group {rg} B, process budget {} B, peak {peak} B",
+ rg * 3 / 2
+ );
+ assert!(
+ peak <= rg * 3 / 2,
+ "process-wide peak {peak} B exceeds the {} B budget",
+ rg * 3 / 2
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn tiny_budgets_shared_by_many_upserts_never_deadlock() {
+ register_scheme();
+ let root = tempfile::tempdir().unwrap();
+ let partitions = ["a", "b", "c"];
+ let mut uris = Vec::new();
+ for i in 0..3 {
+ let (uri, _) = seed(&root.path().join(format!("t{i}")), &partitions).await;
+ uris.push(uri);
+ }
+ // Every budget is smaller than any single row group or decoded batch, and the
+ // process-wide ones are shared by all three upserts, with the probe on.
+ let shared = Arc::new(ProcessLimits::with_fetch(2, 3, 32 * 1024, 16 * 1024));
+ let runs = uris.iter().map(|uri| {
+ let (s, batches) = source(&partitions);
+ let mut o = opts(8 * 1024, shared.clone());
+ o.prune_strategy = PruneStrategy::Probe;
+ o.max_buffered_bytes = 16 * 1024;
+ run(uri, s, batches, o)
+ });
+ for stats in futures::future::join_all(runs).await {
+ assert_rewrote_everything(&stats, partitions.len());
+ assert_eq!(stats.files_probed, FILES * partitions.len());
+ }
+}
diff --git a/rust/deltalite/python/Cargo.toml b/rust/deltalite/python/Cargo.toml
index 0879c0573210..a53863282d35 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.9"
+version = "0.1.10"
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.md
index a0c83c1f7064..22cc5e1b6aa8 100644
--- a/rust/deltalite/python/README.md
+++ b/rust/deltalite/python/README.md
@@ -6,8 +6,10 @@ is bounded by the size of the incoming batch and a few concurrency knobs —
**never by the size of the target table**.
delta-rs stays the storage and protocol layer (transaction log, checkpoints,
-Parquet writing, Add-action statistics, S3 conditional-put commits, conflict
-resolution). deltalite replaces only the *merge execution*.
+Parquet encoding, S3 conditional-put commits, conflict resolution). deltalite
+replaces only the *merge execution*, and writes output files through a streaming
+writer that produces the same files and Add-action statistics as delta-rs's
+`RecordBatchWriter` without holding a second copy of each file.
```python
import deltalite
@@ -152,7 +154,8 @@ All inherit from `DeltaLiteError`, so you can catch the base or branch on kind:
|---|---|---|
| `max_parallel_partitions` | `2` | Partitions merged concurrently. |
| `max_parallel_files` | `4` | Files read concurrently within a partition. |
-| `max_buffered_bytes` | `64 MiB` | Output buffered in memory before flushing. |
+| `max_buffered_bytes` | `64 MiB` | Decoded rows in flight between the file readers and the writer. |
+| `max_fetch_bytes` | `128 MiB` | Compressed row-group bytes the file readers hold before decoding. A reader reserves its file's largest row group before fetching; a row group larger than the cap still runs, alone. |
| `prune_strategy` | `"probe"` | `"probe"` skips files that can't contain a source key; `"none"` scans all. |
| `skip_unmatched_files` | `True` | Convenience toggle: `False` ≡ `prune_strategy="none"`. |
| `probe_concurrency` | `8` | Concurrent statistics/probe reads. |
@@ -170,6 +173,7 @@ budgets:
`DELTALITE_PROCESS_MAX_PARALLEL_PARTITIONS` (8),
`DELTALITE_PROCESS_MAX_PARALLEL_FILES` (16),
`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`.
diff --git a/rust/deltalite/python/deltalite_planner.py b/rust/deltalite/python/deltalite_planner.py
index c27cbeadab10..3f1696a2144f 100644
--- a/rust/deltalite/python/deltalite_planner.py
+++ b/rust/deltalite/python/deltalite_planner.py
@@ -12,7 +12,8 @@ module relies on:
costs roughly its write buffer (`target_file_size`, 100 MB by default) plus
in-flight row groups.
* `max_parallel_files` ("mpf") is a wall-clock dial with little memory effect of its
- own -- decoded data in flight is capped by the byte budget, not by mpf.
+ own -- decoded data in flight is capped by the byte budget, and fetched (still
+ compressed) row groups by the fetch budget (`max_fetch_bytes`), not by mpf.
* Upserts running as threads in one process share the interpreter/runtime overhead
and do not peak simultaneously, so a process fits noticeably more than
N x (single-upsert peak).
diff --git a/rust/deltalite/python/pyproject.toml b/rust/deltalite/python/pyproject.toml
index 0233b80aba87..6417b66f0c7e 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.9"
+version = "0.1.10"
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.rs
index b1039cc1b15d..fb5ae725accb 100644
--- a/rust/deltalite/python/src/lib.rs
+++ b/rust/deltalite/python/src/lib.rs
@@ -365,6 +365,10 @@ impl DeltaLiteTable {
/// 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).
+ ///
+ /// `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
+ /// per process). A row group larger than the cap still runs, alone.
#[pyo3(signature = (
data,
primary_keys,
@@ -374,6 +378,7 @@ impl DeltaLiteTable {
max_parallel_partitions = 2,
max_parallel_files = 4,
max_buffered_bytes = 67108864,
+ max_fetch_bytes = 134217728,
skip_unmatched_files = true,
prune_strategy = None,
probe_concurrency = 8,
@@ -395,6 +400,7 @@ impl DeltaLiteTable {
max_parallel_partitions: usize,
max_parallel_files: usize,
max_buffered_bytes: usize,
+ max_fetch_bytes: usize,
skip_unmatched_files: bool,
prune_strategy: Option<String>,
probe_concurrency: usize,
@@ -430,6 +436,7 @@ impl DeltaLiteTable {
probe_concurrency,
max_parallel_files,
max_buffered_bytes,
+ max_fetch_bytes,
commit_max_retries,
read_batch_size,
target_file_size,