:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(deltalite): native partition-aware compaction (#111503)
Tom Owersfe9a869b2b8e
diff --git a/rust/deltalite/README.md b/rust/deltalite/README.mdindex 5b1982aa7085..d64aba2271a7 100644--- a/rust/deltalite/README.md+++ b/rust/deltalite/README.md@@ -124,6 +124,10 @@ budgets): `DELTALITE_PROCESS_MAX_PARALLEL_PARTITIONS` (8),`DELTALITE_PROCESS_MAX_FETCH_BYTES` (256 MiB), `DELTALITE_MAX_SOURCE_BYTES`,`DELTALITE_MULTIPART_THRESHOLD_BYTES`, `DELTALITE_MULTIPART_PART_SIZE_BYTES`.+`DeltaLiteTable.compact` takes the same budget knobs plus its own (see+`python/README.md`, "Compaction"); it shares the process-global limits with+every upsert in the process.+For a rough starting point on a given pod, `python/deltalite_planner.py`suggests knob values from concurrency + pod memory, e.g.`python deltalite_planner.py 15 8000 --source-mb 250`.diff --git a/rust/deltalite/core/src/compact.rs b/rust/deltalite/core/src/compact.rsnew file mode 100644index 000000000000..8b1653f34576--- /dev/null+++ b/rust/deltalite/core/src/compact.rs@@ -0,0 +1,1284 @@+//! Small-file compaction: delta-rs's `optimize.compact`, rewritten to stream row groups.+//!+//! delta-rs scans each bin through DataFusion, which decodes a whole row group (up to+//! 8192 rows) per batch and reads several files of a bin at once, so its peak memory+//! follows row width times rows per batch, not the bin's size. This module keeps+//! delta-rs's plan and commit semantics and replaces the execution.+//!+//! **Plan.** Bins come from the loaded snapshot alone, with no storage request, by+//! delta-rs's stable-order rule: a partition's files keep log order, neighbours are+//! packed while the bin's compressed size stays at or under the target, a file above+//! the target is skipped and splits the run, and a bin of one file is dropped. A+//! partition is rewritten only when its bins remove at least+//! [`CompactOptions::min_partition_removable_files`] more files than they produce.+//!+//! **Rewrite.** A bin reads one file at a time, in plan order, in batches bounded by+//! decoded bytes, through the same fetch and decode budgets and the same process-wide+//! partition and file permits the upsert uses (order partition -> file -> fetch -> bytes,+//! see `crate::limits`). A reader task decodes while the bin's writer encodes; a batch+//! keeps its decode permit until the writer has encoded it, and the writer never waits+//! on a budget, so the reader always makes progress. Output goes through+//! [`StreamingWriter`] with the writer properties `optimize` uses (ZSTD level 4), which+//! makes the output the same size as delta-rs's. A bin's output rolls to a new file at the+//! compressed target, or when the decoded bytes written to it (from the input footers)+//! reach [`CompactOptions::max_decoded_file_bytes`], so no output file decodes past the+//! 2 GiB Arrow offset limit. Row groups close at+//! [`CompactOptions::max_row_group_decoded_bytes`], which bounds what a later reader of+//! the output (an upsert, ClickHouse) fetches and decodes per row group.+//!+//! **Commit.** Removes and adds carry `dataChange=false`, and `commitInfo` is an+//! `OPTIMIZE` with `readVersion`, `isBlindAppend=false` and delta-rs's+//! `operationMetrics`. Every bin lands in one commit, or in chunks of+//! [`CompactOptions::max_bins_per_commit`] bins. Conflicts are resolved here, not by+//! delta-rs's checker, whose read set without DataFusion is the whole snapshot (a+//! concurrent merge in any partition would abort the compaction). When another writer+//! commits first, the table is refreshed and a bin is kept only if every file it removes+//! is still live at the same size. A bin that lost a file is dropped and its output+//! deleted, so a compaction never resurrects rows a merge replaced and never removes a+//! file twice. A changed schema, partitioning or protocol aborts with+//! [`Error::Conflict`]. The partitions of dropped bins are planned again from the+//! refreshed snapshot, up to [`CompactOptions::max_replan_rounds`] times.++use std::collections::{HashMap, HashSet};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;+use std::time::{Duration, Instant};++use arrow_array::{new_null_array, ArrayRef, RecordBatch, StringArray};+use arrow_schema::{DataType, Field, Schema, SchemaRef};+use deltalake::kernel::transaction::{CommitBuilder, CommitProperties, TransactionError};+use deltalake::kernel::{Action, Add, Remove};+use deltalake::protocol::DeltaOperation;+use deltalake::table::config::TablePropertiesExt;+use deltalake::table::state::DeltaTableState;+use deltalake::writer::RecordBatchWriter;+use deltalake::{DeltaTable, DeltaTableError, ObjectStore, Path};+use futures::{StreamExt, TryStreamExt};+use object_store::ObjectStoreExt;+use parquet::file::metadata::ParquetMetaData;+use serde_json::{json, Value};+use tokio::sync::mpsc;+use tracing::{info, warn};+use uuid::Uuid;++use crate::errors::{Error, Result};+use crate::limits::ProcessLimits;+use crate::schema::cast_to_schema;+use crate::upsert::{+ best_effort_log_maintenance, byte_bounded_batch_rows, ensure_supported_table,+ max_row_group_fetch_bytes, open_builder, BudgetPermit, Budgets, TargetFile,+ INITIAL_DECODE_ESTIMATE_BYTES,+};+use crate::writer::{optimize_writer_properties, StreamingWriter};++/// Half the 2 GiB Arrow offset limit, the bound maintenance.py already plans bins to.+pub const DEFAULT_MAX_DECODED_FILE_BYTES: usize = 1024 * 1024 * 1024;+/// Decoded bytes per output row group.+pub const DEFAULT_MAX_ROW_GROUP_DECODED_BYTES: usize = 128 * 1024 * 1024;++/// Decoded batches a bin's reader may hold ready for its writer.+const READ_AHEAD_BATCHES: usize = 2;++/// Encoder state on top of the buffered output (page buffers, dictionaries, footer),+/// as a fraction of the target, when sizing bins against a memory slot.+const WRITER_OVERHEAD_DIVISOR: usize = 4;++/// Knobs for one compaction.+///+/// Memory is the fetch and decode budgets plus `max_parallel_bins` output files held+/// until upload, each up to `target_file_size` compressed. `slot_budget_bytes` fits all+/// three into one memory slot.+#[derive(Debug, Clone)]+pub struct CompactOptions {+ /// Bin and output size in compressed bytes; `None` uses `delta.targetFileSize`.+ pub target_file_size: Option<usize>,+ /// Bins rewritten at the same time. Files inside one bin are read one at a time.+ pub max_parallel_bins: usize,+ /// Memory one compaction may use. When set, the decode and fetch budgets are each+ /// capped at a quarter of it, and `max_parallel_bins` is lowered so the output files+ /// fit in the rest. One bin always runs.+ pub slot_budget_bytes: Option<usize>,+ pub max_buffered_bytes: usize,+ pub max_fetch_bytes: usize,+ /// Upper bound on rows per decoded batch; the byte bound usually wins first.+ pub read_batch_size: usize,+ /// Decoded bytes one batch should hold, which sets the rows read per batch.+ pub decode_batch_bytes: usize,+ /// Decoded bytes after which an output file is closed and a new one started.+ pub max_decoded_file_bytes: usize,+ /// Decoded bytes after which an output row group is closed.+ pub max_row_group_decoded_bytes: usize,+ /// Only these partition values are planned (`None` = every partition). Refused for+ /// an unpartitioned table.+ pub partitions: Option<Vec<String>>,+ /// A partition is rewritten only when its bins remove at least this many more files+ /// than they produce (one output per bin). `1` rewrites every partition that has a+ /// mergeable bin, as delta-rs does.+ pub min_partition_removable_files: usize,+ /// Commit after this many bins instead of once at the end (`None` = one commit).+ pub max_bins_per_commit: Option<usize>,+ /// Times the partitions of bins dropped on a conflict are planned and rewritten again.+ pub max_replan_rounds: usize,+ /// Times a commit is re-validated and retried after another writer committed first.+ pub commit_max_retries: usize,+ pub commit_metadata: Option<HashMap<String, Value>>,+ /// Plan only: report what would be rewritten without reading or writing data.+ pub dry_run: bool,+ pub limits: Arc<ProcessLimits>,+}++impl Default for CompactOptions {+ fn default() -> Self {+ Self {+ target_file_size: None,+ max_parallel_bins: 2,+ slot_budget_bytes: None,+ max_buffered_bytes: 64 * 1024 * 1024,+ max_fetch_bytes: 128 * 1024 * 1024,+ read_batch_size: 8192,+ decode_batch_bytes: INITIAL_DECODE_ESTIMATE_BYTES,+ max_decoded_file_bytes: DEFAULT_MAX_DECODED_FILE_BYTES,+ max_row_group_decoded_bytes: DEFAULT_MAX_ROW_GROUP_DECODED_BYTES,+ partitions: None,+ min_partition_removable_files: 1,+ max_bins_per_commit: None,+ max_replan_rounds: 1,+ commit_max_retries: 15,+ commit_metadata: None,+ dry_run: false,+ limits: ProcessLimits::global().clone(),+ }+ }+}++/// What a compaction did. With `dry_run`, the bin, partition and removal figures are+/// what the plan would rewrite.+#[derive(Debug, Clone, Default)]+pub struct CompactStats {+ pub files_considered: usize,+ /// Files the plan left alone: above the target, alone in their bin, or in a+ /// partition under `min_partition_removable_files`.+ pub files_skipped: usize,+ pub partitions_compacted: usize,+ pub bins: usize,+ pub files_removed: usize,+ pub files_added: usize,+ pub bytes_removed: u64,+ pub bytes_added: u64,+ pub rows_rewritten: usize,+ pub batches_read: usize,+ /// Bins that ran at the same time after `slot_budget_bytes` sizing.+ pub parallel_bins: usize,+ pub commits: usize,+ /// Commit attempts repeated because another writer committed first.+ pub commit_retries: usize,+ /// Bins discarded because a concurrent writer removed one of their files.+ pub bins_dropped: usize,+ pub replan_rounds: usize,+ pub largest_bin_files: usize,+ pub plan_ms: u64,+ pub rewrite_ms: u64,+ pub commit_ms: u64,+ /// Version of the last compaction commit, or the table version when none was made.+ pub version: i64,+ pub dry_run: bool,+}++#[derive(Debug, Clone)]+struct PlannedFile {+ path: String,+ size: u64,+ num_records: Option<usize>,+ remove: Remove,+}++#[derive(Debug)]+struct Bin {+ partition: Option<String>,+ files: Vec<PlannedFile>,+}++#[derive(Debug, Default)]+struct Plan {+ considered: usize,+ skipped: usize,+ partitions: usize,+ bins: Vec<Bin>,+}++/// delta-rs's `plan_compaction_bins_in_stable_order` plus its single-file pruning.+fn plan_bins(files: Vec<PlannedFile>, target: u64) -> Vec<Vec<PlannedFile>> {+ let mut bins: Vec<Vec<PlannedFile>> = Vec::new();+ let mut current: Vec<PlannedFile> = Vec::new();+ let mut current_size = 0u64;+ for f in files {+ if f.size > target {+ bins.push(std::mem::take(&mut current));+ current_size = 0;+ continue;+ }+ if !current.is_empty() && current_size + f.size > target {+ bins.push(std::mem::take(&mut current));+ current_size = 0;+ }+ current_size += f.size;+ current.push(f);+ }+ bins.push(current);+ bins.retain(|b| b.len() >= 2);+ bins+}++/// Bins for every selected partition of `table`'s loaded snapshot, in log order.+fn plan(+ table: &DeltaTable,+ partition_col: Option<&str>,+ target: u64,+ only: Option<&HashSet<Option<String>>>,+ min_removable: usize,+) -> Result<Plan> {+ let snapshot = table.snapshot()?;+ let mut order: Vec<Option<String>> = Vec::new();+ let mut by_partition: HashMap<Option<String>, Vec<PlannedFile>> = HashMap::new();+ let mut out = Plan::default();+ for view in snapshot.log_data().iter() {+ let remove = view.remove_action(false);+ let partition = partition_col.and_then(|c| {+ remove+ .partition_values+ .as_ref()+ .and_then(|pv| pv.get(c).cloned().flatten())+ });+ if only.is_some_and(|only| !only.contains(&partition)) {+ continue;+ }+ out.considered += 1;+ let file = PlannedFile {+ path: view.path().into_owned(),+ size: view.size().max(0) as u64,+ num_records: view.num_records(),+ remove,+ };+ by_partition+ .entry(partition.clone())+ .or_insert_with(|| {+ order.push(partition);+ Vec::new()+ })+ .push(file);+ }+ for partition in order {+ let files = by_partition.remove(&partition).unwrap_or_default();+ let total = files.len();+ let bins = plan_bins(files, target);+ let binned: usize = bins.iter().map(Vec::len).sum();+ if bins.is_empty() || binned - bins.len() < min_removable.max(1) {+ out.skipped += total;+ continue;+ }+ out.skipped += total - binned;+ out.partitions += 1;+ out.bins.extend(bins.into_iter().map(|files| Bin {+ partition: partition.clone(),+ files,+ }));+ }+ Ok(out)+}++/// Parallelism and budgets after fitting them into `slot_budget_bytes`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+struct Sizing {+ parallel_bins: usize,+ max_buffered_bytes: usize,+ max_fetch_bytes: usize,+}++fn size_for_slot(opts: &CompactOptions, target: usize) -> Sizing {+ let mut s = Sizing {+ parallel_bins: opts.max_parallel_bins.max(1),+ max_buffered_bytes: opts.max_buffered_bytes,+ max_fetch_bytes: opts.max_fetch_bytes,+ };+ if let Some(slot) = opts.slot_budget_bytes.filter(|s| *s > 0) {+ s.max_buffered_bytes = s.max_buffered_bytes.min(slot / 4).max(1024);+ s.max_fetch_bytes = s.max_fetch_bytes.min(slot / 4).max(1024);+ let writers = slot.saturating_sub(s.max_buffered_bytes + s.max_fetch_bytes);+ let per_bin = target+ .saturating_add(target / WRITER_OVERHEAD_DIVISOR)+ .max(1);+ s.parallel_bins = (writers / per_bin).clamp(1, s.parallel_bins);+ }+ s+}++/// Footer-reported decoded bytes per row of one file (0 when the footer has none).+fn decoded_bytes_per_row(meta: &ParquetMetaData) -> f64 {+ let (bytes, rows) = meta.row_groups().iter().fold((0i64, 0i64), |(b, r), rg| {+ (b + rg.total_byte_size().max(0), r + rg.num_rows().max(0))+ });+ if rows == 0 {+ 0.0+ } else {+ bytes as f64 / rows as f64+ }+}++/// `batch` with the partition column set to the log's value for the file. The value is+/// authoritative even when a writer also stored the column in the file.+fn with_partition_column(+ batch: &RecordBatch,+ column: Option<&str>,+ value: Option<&str>,+) -> Result<RecordBatch> {+ let Some(column) = column else {+ return Ok(batch.clone());+ };+ let n = batch.num_rows();+ let values: ArrayRef = match value {+ Some(v) => Arc::new(StringArray::from(vec![v; n])),+ None => new_null_array(&DataType::Utf8, n),+ };+ let schema = batch.schema();+ let mut fields = Vec::with_capacity(schema.fields().len() + 1);+ let mut columns = Vec::with_capacity(schema.fields().len() + 1);+ for (field, col) in schema.fields().iter().zip(batch.columns()) {+ if field.name() != column {+ fields.push(field.clone());+ columns.push(col.clone());+ }+ }+ fields.push(Arc::new(Field::new(column, DataType::Utf8, true)));+ columns.push(values);+ Ok(RecordBatch::try_new(+ Arc::new(Schema::new(fields)),+ columns,+ )?)+}++fn add_num_records(add: &Add) -> Option<usize> {+ let stats: Value = serde_json::from_str(add.stats.as_deref()?).ok()?;+ stats.get("numRecords")?.as_u64().map(|n| n as usize)+}++/// Output file name, unique per file (the writer puts a fresh UUID in it). Compared by+/// name because the log returns paths decoded and the writer records them encoded.+fn file_name(path: &str) -> &str {+ path.rsplit('/').next().unwrap_or(path)+}++struct RewriteCtx {+ table: DeltaTable,+ store: Arc<dyn ObjectStore>,+ table_schema: SchemaRef,+ partition_col: Option<String>,+ budgets: Budgets,+ limits: Arc<ProcessLimits>,+ target_file_size: usize,+ read_batch_size: usize,+ decode_batch_bytes: usize,+ max_decoded_file_bytes: usize,+ max_row_group_decoded_bytes: usize,+ /// Set when one bin fails, so the others stop at their next batch.+ cancel: AtomicBool,+}++impl RewriteCtx {+ fn check_cancelled(&self) -> Result<()> {+ if self.cancel.load(Ordering::Relaxed) {+ return Err(Error::Generic(+ "compaction stopped because another bin failed".into(),+ ));+ }+ Ok(())+ }+}++struct BinOutput {+ partition: Option<String>,+ removes: Vec<Remove>,+ adds: Vec<Add>,+ rows: usize,+ batches: usize,+ bytes_removed: u64,+}++/// Paths of the output files `bins` uploaded.+fn output_paths<'a>(bins: impl IntoIterator<Item = &'a BinOutput>) -> Vec<String> {+ bins.into_iter()+ .flat_map(|b| b.adds.iter().map(|a| a.path.clone()))+ .collect()+}++async fn delete_outputs(store: &Arc<dyn ObjectStore>, paths: Vec<String>) {+ for path in paths {+ let result = match Path::parse(&path) {+ Ok(p) => store.delete(&p).await.map_err(|e| e.to_string()),+ Err(e) => Err(e.to_string()),+ };+ if let Err(error) = result {+ warn!(%path, %error, "could not delete an uncommitted compaction output");+ }+ }+}++/// Rewrite one bin. Output files it uploaded are deleted again when it fails.+async fn rewrite_bin(ctx: Arc<RewriteCtx>, bin: Bin) -> Result<BinOutput> {+ ctx.check_cancelled()?;+ let _partition = ctx.limits.acquire_partition().await?;+ let mut written = Vec::new();+ match rewrite_bin_inner(&ctx, bin, &mut written).await {+ Ok(out) => Ok(out),+ Err(e) => {+ delete_outputs(&ctx.store, written.iter().map(|a| a.path.clone()).collect()).await;+ Err(e)+ }+ }+}++/// A batch on its way from a bin's reader to its writer, cast to the table schema. It+/// keeps its decode budget until the writer has encoded it.+struct ReadBatch {+ batch: RecordBatch,+ /// Decoded bytes by the input footer's measure.+ decoded: f64,+ _permit: BudgetPermit,+}++/// Read `files` in order and send their batches to the bin's writer. Stops quietly when+/// the writer has gone away (it failed, and reports why).+async fn read_bin(+ ctx: Arc<RewriteCtx>,+ files: Vec<PlannedFile>,+ partition: Option<String>,+ tx: mpsc::Sender<ReadBatch>,+) -> Result<()> {+ for f in files {+ ctx.check_cancelled()?;+ let target = TargetFile {+ path: f.path.clone(),+ size: f.size,+ stats: None,+ remove: f.remove,+ metadata: None,+ };+ let _file = ctx.limits.acquire_file().await?;+ let builder = open_builder(&ctx.store, &target).await?;+ let bytes_per_row = decoded_bytes_per_row(builder.metadata());+ let _fetch = ctx+ .budgets+ .acquire_fetch(max_row_group_fetch_bytes(builder.metadata(), None))+ .await?;+ let batch_rows = byte_bounded_batch_rows(+ builder.metadata(),+ ctx.decode_batch_bytes,+ ctx.read_batch_size,+ );+ let mut stream = builder.with_batch_size(batch_rows).build()?;+ let mut estimate = ctx.decode_batch_bytes;+ let mut file_rows = 0usize;+ loop {+ ctx.check_cancelled()?;+ let mut permit = ctx.budgets.acquire_bytes(estimate).await?;+ let Some(batch) = stream.try_next().await? else {+ break;+ };+ let actual = batch.get_array_memory_size();+ ctx.budgets.top_up(&mut permit, actual).await?;+ estimate = actual.max(64 * 1024);+ if batch.num_rows() == 0 {+ continue;+ }+ file_rows += batch.num_rows();+ let decoded = batch.num_rows() as f64 * bytes_per_row;+ let batch =+ with_partition_column(&batch, ctx.partition_col.as_deref(), partition.as_deref())?;+ let item = ReadBatch {+ batch: cast_to_schema(&batch, &ctx.table_schema)?,+ decoded,+ _permit: permit,+ };+ if tx.send(item).await.is_err() {+ return Ok(());+ }+ }+ if let Some(expected) = f.num_records {+ if expected != file_rows {+ return Err(Error::Generic(format!(+ "read {file_rows} rows from {} but its Add statistics record {expected}",+ f.path+ )));+ }+ }+ }+ Ok(())+}++/// The bin's writer. A reader task decodes the next batches while this encodes, so one+/// bin keeps two cores busy; files still arrive in plan order, so the output keeps the+/// bin's row order, and the bin holds at most one reader's row group at a time.+async fn rewrite_bin_inner(+ ctx: &Arc<RewriteCtx>,+ bin: Bin,+ written: &mut Vec<Add>,+) -> Result<BinOutput> {+ let mut writer = StreamingWriter::for_table(&ctx.table)?+ .with_writer_properties(optimize_writer_properties());+ let removes: Vec<Remove> = bin.files.iter().map(|f| f.remove.clone()).collect();+ let bytes_removed: u64 = bin.files.iter().map(|f| f.size).sum();+ let (tx, mut rx) = mpsc::channel(READ_AHEAD_BATCHES);+ let reader = tokio::spawn(read_bin(ctx.clone(), bin.files, bin.partition.clone(), tx));++ let (mut rows, mut batches) = (0usize, 0usize);+ let written_ok: Result<()> = async {+ let (mut file_decoded, mut row_group_decoded) = (0f64, 0f64);+ while let Some(item) = rx.recv().await {+ rows += item.batch.num_rows();+ batches += 1;+ writer.write(item.batch)?;+ file_decoded += item.decoded;+ row_group_decoded += item.decoded;+ if writer.buffer_len() >= ctx.target_file_size+ || file_decoded >= ctx.max_decoded_file_bytes as f64+ {+ written.extend(writer.flush().await?);+ file_decoded = 0.0;+ row_group_decoded = 0.0;+ } else if writer.in_progress_rows() == 0 {+ // The encoder closed the row group itself at its row cap.+ row_group_decoded = 0.0;+ } else if row_group_decoded >= ctx.max_row_group_decoded_bytes as f64 {+ writer.flush_row_groups()?;+ row_group_decoded = 0.0;+ }+ }+ Ok(())+ }+ .await;+ // Closing the channel stops a reader the writer gave up on at its next send.+ drop(rx);+ let read_ok = reader+ .await+ .map_err(|e| Error::Generic(format!("compaction reader panicked: {e}")))?;+ written_ok?;+ read_ok?;+ written.extend(writer.flush().await?);++ let rows_written: Option<usize> = written.iter().map(add_num_records).sum();+ if let Some(rows_written) = rows_written {+ if rows_written != rows {+ return Err(Error::Generic(format!(+ "compaction read {rows} rows but wrote {rows_written}"+ )));+ }+ }+ let adds = written+ .drain(..)+ .map(|mut a| {+ a.data_change = false;+ a+ })+ .collect();+ Ok(BinOutput {+ partition: bin.partition,+ removes,+ adds,+ rows,+ batches,+ bytes_removed,+ })+}++/// The file-size summary delta-rs records for `filesAdded` / `filesRemoved`.+fn size_details(sizes: impl Iterator<Item = i64>) -> String {+ let (mut n, mut total, mut min, mut max) = (0usize, 0i64, i64::MAX, 0i64);+ for s in sizes {+ n += 1;+ total += s;+ min = min.min(s);+ max = max.max(s);+ }+ let avg = if n == 0 { 0.0 } else { total as f64 / n as f64 };+ json!({+ "avg": avg,+ "max": max,+ "min": if n == 0 { 0 } else { min },+ "totalFiles": n,+ "totalSize": total,+ })+ .to_string()+}++enum CommitFailure {+ /// The commit did not land; the bins' outputs are safe to delete.+ Unapplied(Error, Vec<BinOutput>),+ /// The outcome is unknown (the log write itself failed); outputs must stay.+ Unknown(Error),+}++/// `true` when the commit lost the race for its version to another writer. With no+/// delta-rs retries both "the log moved" and "the version exists" surface this way.+fn lost_race(e: &DeltaTableError) -> bool {+ matches!(+ e,+ DeltaTableError::Transaction {+ source: TransactionError::MaxCommitAttempts(_)+ | TransactionError::VersionAlreadyExists(_)+ }+ )+}++struct TableShape {+ schema: String,+ partition_columns: Vec<String>,+ protocol: String,+}++impl TableShape {+ fn of(table: &DeltaTable) -> Result<Self> {+ let snapshot = table.snapshot()?;+ let protocol = snapshot.protocol();+ Ok(Self {+ schema: serde_json::to_string(snapshot.schema().as_ref())+ .map_err(|e| Error::Generic(format!("serialising table schema: {e}")))?,+ partition_columns: snapshot.metadata().partition_columns().to_vec(),+ protocol: format!(+ "{}/{}/{:?}/{:?}",+ protocol.min_reader_version(),+ protocol.min_writer_version(),+ protocol.reader_features(),+ protocol.writer_features()+ ),+ })+ }+}++/// Commit state that carries over between chunks and re-plan rounds.+struct Committer {+ /// Working table; its snapshot is the base the next commit attempt validates against.+ table: DeltaTable,+ shape: TableShape,+ operation: DeltaOperation,+ operation_id: Uuid,+ read_version: u64,+ max_retries: usize,+ commit_metadata: HashMap<String, Value>,+ files_considered: usize,+ files_skipped: usize,+ commits: usize,+ retries: usize,+ last_version: Option<u64>,+}++impl Committer {+ fn app_metadata(&self, bins: &[BinOutput]) -> HashMap<String, Value> {+ let partitions: HashSet<&Option<String>> = bins.iter().map(|b| &b.partition).collect();+ let metrics = json!({+ "numFilesAdded": bins.iter().map(|b| b.adds.len()).sum::<usize>(),+ "numFilesRemoved": bins.iter().map(|b| b.removes.len()).sum::<usize>(),+ "filesAdded": size_details(bins.iter().flat_map(|b| b.adds.iter().map(|a| a.size))),+ "filesRemoved": size_details(+ bins.iter().flat_map(|b| b.removes.iter().map(|r| r.size.unwrap_or(0)))+ ),+ "partitionsOptimized": partitions.len(),+ "numBatches": bins.iter().map(|b| b.batches).sum::<usize>(),+ "totalConsideredFiles": self.files_considered,+ "totalFilesSkipped": self.files_skipped,+ "preserveInsertionOrder": true,+ });+ let mut md = self.commit_metadata.clone();+ md.insert("readVersion".into(), json!(self.read_version));+ md.insert("isBlindAppend".into(), json!(false));+ md.insert("operationMetrics".into(), metrics);+ md+ }++ /// Commit `bins`, re-validating them against each commit that beat this one. Returns+ /// the bins that landed and the bins dropped because a file they remove is gone.+ async fn commit(+ &mut self,+ bins: Vec<BinOutput>,+ ) -> std::result::Result<(Vec<BinOutput>, Vec<BinOutput>), CommitFailure> {+ let mut live = bins;+ let mut dropped: Vec<BinOutput> = Vec::new();+ let mut attempt = 0usize;+ loop {+ if live.is_empty() {+ return Ok((live, dropped));+ }+ let snapshot = match self.table.snapshot() {+ Ok(s) => s,+ Err(e) => {+ live.extend(dropped);+ return Err(CommitFailure::Unapplied(e.into(), live));+ }+ };+ let checkpoint_interval = snapshot.table_config().checkpoint_interval().get();+ let cleanup_enabled = snapshot.table_config().enable_expired_log_cleanup();+ // Vacuum retention counts from the deletion timestamp, so it is the time of+ // this attempt, not of the plan a long rewrite ago.+ let now = chrono::Utc::now().timestamp_millis();+ let mut actions: Vec<Action> = Vec::new();+ for b in &live {+ actions.extend(b.removes.iter().map(|r| {+ Action::Remove(Remove {+ deletion_timestamp: Some(now),+ ..r.clone()+ })+ }));+ actions.extend(b.adds.iter().cloned().map(Action::Add));+ }+ // Retries stay here: delta-rs would re-check against the whole snapshot (see+ // the module docs) and could not drop just the bins that lost a file.+ let props = CommitProperties::default()+ .with_max_retries(0)+ .with_create_checkpoint(false)+ .with_cleanup_expired_logs(Some(false))+ .with_metadata(self.app_metadata(&live));+ let result = CommitBuilder::from(props)+ .with_actions(actions)+ .with_operation_id(self.operation_id)+ .build(+ Some(snapshot),+ self.table.log_store(),+ self.operation.clone(),+ )+ .await;+ match result {+ Ok(finalized) => {+ let version = finalized.version();+ self.table.state = Some(finalized.snapshot);+ self.commits += 1;+ self.last_version = Some(version);+ if (version + 1) % checkpoint_interval == 0 {+ best_effort_log_maintenance(&self.table, version, cleanup_enabled).await;+ }+ return Ok((live, dropped));+ }+ Err(e) if lost_race(&e) => {+ attempt += 1;+ self.retries += 1;+ tokio::time::sleep(Duration::from_millis(50 * attempt.min(10) as u64)).await;+ if let Err(e) = self.table.update_incremental(None).await {+ return Err(CommitFailure::Unknown(e.into()));+ }+ let snapshot = match self.table.snapshot() {+ Ok(s) => s,+ Err(e) => return Err(CommitFailure::Unknown(e.into())),+ };+ let mut live_files: HashMap<String, i64> = HashMap::new();+ let mut live_names: HashSet<String> = HashSet::new();+ for view in snapshot.log_data().iter() {+ let path = view.path().into_owned();+ live_names.insert(file_name(&path).to_string());+ live_files.insert(path, view.size());+ }+ let version = snapshot.version();+ // A write whose response was lost reports "version exists" for its own+ // commit; its outputs being live is the proof.+ if live+ .iter()+ .flat_map(|b| &b.adds)+ .any(|a| live_names.contains(file_name(&a.path)))+ {+ self.commits += 1;+ self.last_version = Some(version);+ return Ok((live, dropped));+ }+ if let Err(e) = self.check_shape() {+ live.extend(dropped);+ return Err(CommitFailure::Unapplied(e, live));+ }+ if attempt > self.max_retries {+ live.extend(dropped);+ return Err(CommitFailure::Unapplied(+ Error::Conflict(format!(+ "compaction lost the commit race {attempt} times; retry later"+ )),+ live,+ ));+ }+ let (keep, lost): (Vec<_>, Vec<_>) = live.into_iter().partition(|b| {+ b.removes+ .iter()+ .all(|r| live_files.get(&r.path).copied() == r.size)+ });+ if !lost.is_empty() {+ info!(+ dropped = lost.len(),+ kept = keep.len(),+ version,+ "compaction bins lost a file to a concurrent commit"+ );+ }+ dropped.extend(lost);+ live = keep;+ }+ Err(e) => return Err(CommitFailure::Unknown(e.into())),+ }+ }+ }++ fn check_shape(&self) -> Result<()> {+ ensure_supported_table(&self.table)?;+ let now = TableShape::of(&self.table)?;+ if now.schema != self.shape.schema+ || now.partition_columns != self.shape.partition_columns+ || now.protocol != self.shape.protocol+ {+ return Err(Error::Conflict(+ "a concurrent commit changed the table's schema, partitioning or protocol; \+ compaction must be planned again"+ .into(),+ ));+ }+ Ok(())+ }+}++/// Commit `pending` and fold the result into `stats`. Bins dropped on a conflict have+/// their outputs deleted and their partitions recorded in `dropped_partitions`.+async fn commit_pending(+ committer: &mut Committer,+ store: &Arc<dyn ObjectStore>,+ pending: &mut Vec<BinOutput>,+ dropped_partitions: &mut HashSet<Option<String>>,+ committed_partitions: &mut HashSet<Option<String>>,+ stats: &mut CompactStats,+) -> Result<()> {+ if pending.is_empty() {+ return Ok(());+ }+ let started = Instant::now();+ let outcome = committer.commit(std::mem::take(pending)).await;+ stats.commit_ms += started.elapsed().as_millis() as u64;+ match outcome {+ Ok((committed, dropped)) => {+ for b in &committed {+ committed_partitions.insert(b.partition.clone());+ stats.bins += 1;+ stats.files_removed += b.removes.len();+ stats.files_added += b.adds.len();+ stats.bytes_removed += b.bytes_removed;+ stats.bytes_added += b.adds.iter().map(|a| a.size.max(0) as u64).sum::<u64>();+ stats.rows_rewritten += b.rows;+ stats.batches_read += b.batches;+ stats.largest_bin_files = stats.largest_bin_files.max(b.removes.len());+ }+ stats.bins_dropped += dropped.len();+ for b in &dropped {+ dropped_partitions.insert(b.partition.clone());+ }+ delete_outputs(store, output_paths(&dropped)).await;+ Ok(())+ }+ Err(CommitFailure::Unapplied(e, bins)) => {+ delete_outputs(store, output_paths(&bins)).await;+ Err(e)+ }+ Err(CommitFailure::Unknown(e)) => {+ warn!(error = %e, "compaction commit outcome unknown; its output files are kept");+ Err(e)+ }+ }+}++/// Rewrite `bins` with `parallel` bins in flight and commit them in chunks of `chunk`.+/// Returns the partitions of bins dropped on a conflict.+async fn run_round(+ committer: &mut Committer,+ ctx: Arc<RewriteCtx>,+ bins: Vec<Bin>,+ parallel: usize,+ chunk: usize,+ committed_partitions: &mut HashSet<Option<String>>,+ stats: &mut CompactStats,+) -> Result<HashSet<Option<String>>> {+ let store = ctx.store.clone();+ let spawn_ctx = ctx.clone();+ let mut results = futures::stream::iter(bins)+ .map(move |bin| tokio::spawn(rewrite_bin(spawn_ctx.clone(), bin)))+ .buffered(parallel.max(1));+ let mut pending: Vec<BinOutput> = Vec::new();+ let mut dropped_partitions = HashSet::new();+ let mut failure: Option<Error> = None;+ while let Some(joined) = results.next().await {+ match joined {+ Ok(Ok(out)) => pending.push(out),+ Ok(Err(e)) => {+ failure = Some(e);+ break;+ }+ Err(e) => {+ failure = Some(Error::Generic(format!("compaction worker panicked: {e}")));+ break;+ }+ }+ if pending.len() >= chunk {+ if let Err(e) = commit_pending(+ committer,+ &store,+ &mut pending,+ &mut dropped_partitions,+ committed_partitions,+ stats,+ )+ .await+ {+ failure = Some(e);+ break;+ }+ }+ }+ if let Some(e) = failure {+ // In-flight bins see the flag, delete their own outputs and stop; bins that+ // already finished were never committed, so their outputs go too.+ ctx.cancel.store(true, Ordering::Relaxed);+ while let Some(joined) = results.next().await {+ if let Ok(Ok(out)) = joined {+ pending.push(out);+ }+ }+ delete_outputs(&store, output_paths(&pending)).await;+ return Err(e);+ }+ commit_pending(+ committer,+ &store,+ &mut pending,+ &mut dropped_partitions,+ committed_partitions,+ stats,+ )+ .await?;+ Ok(dropped_partitions)+}++/// Compact the small files of `table`'s loaded snapshot. Returns the stats and, when a+/// commit was made, the table state after the last one.+pub async fn compact(+ table: &DeltaTable,+ opts: CompactOptions,+) -> Result<(CompactStats, Option<DeltaTableState>)> {+ let plan_started = Instant::now();+ ensure_supported_table(table)?;+ let snapshot = table.snapshot()?;+ let partition_columns: Vec<String> = snapshot.metadata().partition_columns().to_vec();+ if partition_columns.len() > 1 {+ return Err(Error::Unsupported(format!(+ "deltalite supports at most one partition column, table has {partition_columns:?}"+ )));+ }+ let partition_col = partition_columns.first().cloned();+ if partition_col.is_none() && opts.partitions.is_some() {+ return Err(Error::SchemaMismatch(+ "partitions were given but the table is not partitioned".into(),+ ));+ }+ let target_file_size = match opts.target_file_size {+ Some(v) if v > 0 => v,+ _ => snapshot.table_config().target_file_size().get() as usize,+ };+ let only: Option<HashSet<Option<String>>> = opts+ .partitions+ .as_ref()+ .map(|values| values.iter().cloned().map(Some).collect());+ let first = plan(+ table,+ partition_col.as_deref(),+ target_file_size as u64,+ only.as_ref(),+ opts.min_partition_removable_files,+ )?;+ let sizing = size_for_slot(&opts, target_file_size);+ let mut stats = CompactStats {+ files_considered: first.considered,+ files_skipped: first.skipped,+ parallel_bins: sizing.parallel_bins,+ dry_run: opts.dry_run,+ version: i64::try_from(snapshot.version()).unwrap_or(i64::MAX),+ plan_ms: plan_started.elapsed().as_millis() as u64,+ ..Default::default()+ };+ if opts.dry_run || first.bins.is_empty() {+ stats.partitions_compacted = first.partitions;+ stats.bins = first.bins.len();+ for b in &first.bins {+ stats.files_removed += b.files.len();+ stats.bytes_removed += b.files.iter().map(|f| f.size).sum::<u64>();+ stats.largest_bin_files = stats.largest_bin_files.max(b.files.len());+ }+ return Ok((stats, None));+ }++ let predicate = match &opts.partitions {+ Some(values) => {+ json!([[partition_col.clone().unwrap_or_default(), "in", values]]).to_string()+ }+ None => "[]".to_string(),+ };+ let mut committer = Committer {+ table: table.clone(),+ shape: TableShape::of(table)?,+ operation: DeltaOperation::Optimize {+ predicate: Some(predicate),+ target_size: target_file_size as i64,+ },+ operation_id: Uuid::new_v4(),+ read_version: snapshot.version(),+ max_retries: opts.commit_max_retries,+ commit_metadata: opts.commit_metadata.clone().unwrap_or_default(),+ files_considered: first.considered,+ files_skipped: first.skipped,+ commits: 0,+ retries: 0,+ last_version: None,+ };+ let budgets = Budgets::new(+ sizing.max_buffered_bytes,+ sizing.max_fetch_bytes,+ opts.limits.clone(),+ );+ let table_schema = RecordBatchWriter::for_table(table)?.arrow_schema();+ let chunk = opts+ .max_bins_per_commit+ .filter(|n| *n > 0)+ .unwrap_or(usize::MAX);+ let mut committed_partitions: HashSet<Option<String>> = HashSet::new();++ let rewrite_started = Instant::now();+ let mut bins = first.bins;+ let mut round = 0usize;+ loop {+ let ctx = Arc::new(RewriteCtx {+ table: committer.table.clone(),+ store: committer.table.object_store(),+ table_schema: table_schema.clone(),+ partition_col: partition_col.clone(),+ budgets: budgets.clone(),+ limits: opts.limits.clone(),+ target_file_size,+ read_batch_size: opts.read_batch_size,+ decode_batch_bytes: opts.decode_batch_bytes,+ max_decoded_file_bytes: opts.max_decoded_file_bytes.max(1),+ max_row_group_decoded_bytes: opts.max_row_group_decoded_bytes.max(1),+ cancel: AtomicBool::new(false),+ });+ let dropped = run_round(+ &mut committer,+ ctx,+ bins,+ sizing.parallel_bins,+ chunk,+ &mut committed_partitions,+ &mut stats,+ )+ .await?;+ if dropped.is_empty() || round >= opts.max_replan_rounds {+ break;+ }+ round += 1;+ stats.replan_rounds = round;+ // The committer refreshed its table while it resolved the conflict, so this plans+ // against what the concurrent writer left behind.+ let again = plan(+ &committer.table,+ partition_col.as_deref(),+ target_file_size as u64,+ Some(&dropped),+ opts.min_partition_removable_files,+ )?;+ if again.bins.is_empty() {+ break;+ }+ bins = again.bins;+ }+ stats.rewrite_ms =+ (rewrite_started.elapsed().as_millis() as u64).saturating_sub(stats.commit_ms);+ stats.partitions_compacted = committed_partitions.len();+ stats.commits = committer.commits;+ stats.commit_retries = committer.retries;+ if let Some(v) = committer.last_version {+ stats.version = i64::try_from(v)+ .map_err(|_| Error::Generic("committed version overflows i64".into()))?;+ }+ info!(+ version = stats.version,+ bins = stats.bins,+ bins_dropped = stats.bins_dropped,+ files_removed = stats.files_removed,+ files_added = stats.files_added,+ commits = stats.commits,+ commit_retries = stats.commit_retries,+ plan_ms = stats.plan_ms,+ rewrite_ms = stats.rewrite_ms,+ commit_ms = stats.commit_ms,+ "compaction finished"+ );+ let state = if committer.commits > 0 {+ committer.table.state+ } else {+ None+ };+ Ok((stats, state))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn file(size: u64) -> PlannedFile {+ PlannedFile {+ path: format!("f{size}"),+ size,+ num_records: None,+ remove: Remove {+ path: format!("f{size}"),+ data_change: false,+ deletion_timestamp: None,+ extended_file_metadata: None,+ partition_values: None,+ size: Some(size as i64),+ tags: None,+ deletion_vector: None,+ base_row_id: None,+ default_row_commit_version: None,+ },+ }+ }++ fn sizes(bins: &[Vec<PlannedFile>]) -> Vec<Vec<u64>> {+ bins.iter()+ .map(|b| b.iter().map(|f| f.size).collect())+ .collect()+ }++ #[test]+ fn bins_pack_neighbours_skip_large_files_and_drop_singletons() {+ let files = [10, 20, 80, 30, 200, 5, 6, 7, 100]+ .into_iter()+ .map(file)+ .collect();+ // 10+20 fit and 80 would overflow; [80] then meets 30 (overflow) and is dropped;+ // [30] is cut by the oversized 200; [5,6,7] packs; 100 equals the target, so it+ // is a candidate, but 5+6+7+100 overflows and [100] alone is dropped.+ assert_eq!(+ sizes(&plan_bins(files, 100)),+ vec![vec![10, 20], vec![5, 6, 7]]+ );+ }++ #[test]+ fn a_partition_of_one_file_or_only_oversized_files_plans_nothing() {+ assert!(plan_bins(vec![file(10)], 100).is_empty());+ assert!(plan_bins(vec![file(101), file(150)], 100).is_empty());+ assert!(plan_bins(Vec::new(), 100).is_empty());+ }++ #[test]+ fn a_bin_may_reach_the_target_exactly() {+ assert_eq!(+ sizes(&plan_bins(vec![file(50), file(50), file(1)], 100)),+ vec![vec![50, 50]]+ );+ }++ fn opts_with(slot: Option<usize>, bins: usize) -> CompactOptions {+ CompactOptions {+ slot_budget_bytes: slot,+ max_parallel_bins: bins,+ max_buffered_bytes: 64 << 20,+ max_fetch_bytes: 128 << 20,+ ..Default::default()+ }+ }++ #[test]+ fn slot_budget_caps_parallel_bins_and_budgets() {+ let mb = 1 << 20;+ assert_eq!(+ size_for_slot(&opts_with(None, 4), 100 * mb),+ Sizing {+ parallel_bins: 4,+ max_buffered_bytes: 64 * mb,+ max_fetch_bytes: 128 * mb+ }+ );+ // 2000 MB: both budgets sit under a quarter and 1808 MB of writers fits 14 bins+ // of 125 MB, capped at the 4 asked for.+ assert_eq!(+ size_for_slot(&opts_with(Some(2000 * mb), 4), 100 * mb).parallel_bins,+ 4+ );+ // 400 MB: the fetch budget drops to 100 MB, leaving 236 MB, one 125 MB bin.+ assert_eq!(+ size_for_slot(&opts_with(Some(400 * mb), 4), 100 * mb),+ Sizing {+ parallel_bins: 1,+ max_buffered_bytes: 64 * mb,+ max_fetch_bytes: 100 * mb+ }+ );+ // 1000 MB: 808 MB of writers fits 6 bins, capped at 4; with 8 asked, 6.+ assert_eq!(+ size_for_slot(&opts_with(Some(1000 * mb), 8), 100 * mb).parallel_bins,+ 6+ );+ assert_eq!(+ size_for_slot(&opts_with(Some(10 * mb), 4), 100 * mb).parallel_bins,+ 1+ );+ assert_eq!(+ size_for_slot(&opts_with(Some(0), 3), 100 * mb).parallel_bins,+ 3+ );+ }++ #[test]+ fn partition_column_takes_the_log_value_and_replaces_a_stored_one() {+ let id: ArrayRef = Arc::new(StringArray::from(vec!["a", "b"]));+ let stored: ArrayRef = Arc::new(StringArray::from(vec!["stale", "stale"]));+ let batch = RecordBatch::try_from_iter(vec![("id", id), ("p", stored)]).unwrap();+ let out = with_partition_column(&batch, Some("p"), Some("x y")).unwrap();+ assert_eq!(out.num_columns(), 2);+ let p = out+ .column_by_name("p")+ .unwrap()+ .as_any()+ .downcast_ref::<StringArray>()+ .unwrap();+ assert_eq!(p.iter().collect::<Vec<_>>(), vec![Some("x y"), Some("x y")]);++ let null = with_partition_column(&batch, Some("p"), None).unwrap();+ assert_eq!(null.column_by_name("p").unwrap().null_count(), 2);++ let unpartitioned = with_partition_column(&batch, None, Some("x")).unwrap();+ assert_eq!(unpartitioned.schema(), batch.schema());+ }++ #[test]+ fn size_details_match_the_delta_rs_shape() {+ let v: Value = serde_json::from_str(&size_details([10i64, 30].into_iter())).unwrap();+ assert_eq!(v["totalFiles"], 2);+ assert_eq!(v["totalSize"], 40);+ assert_eq!(v["min"], 10);+ assert_eq!(v["max"], 30);+ assert_eq!(v["avg"], 20.0);+ let empty: Value = serde_json::from_str(&size_details(std::iter::empty())).unwrap();+ assert_eq!(empty["min"], 0);+ assert_eq!(empty["totalFiles"], 0);+ }++ #[test]+ fn output_files_match_by_name_across_path_encodings() {+ assert_eq!(+ file_name("p=a%20b/part-1-abc.zstd.parquet"),+ "part-1-abc.zstd.parquet"+ );+ assert_eq!(+ file_name("p=a b/part-1-abc.zstd.parquet"),+ "part-1-abc.zstd.parquet"+ );+ assert_eq!(file_name("part-1-abc.parquet"), "part-1-abc.parquet");+ }+}diff --git a/rust/deltalite/core/src/handle.rs b/rust/deltalite/core/src/handle.rsindex 1b1c7a80fa18..335f3e3d7277 100644--- a/rust/deltalite/core/src/handle.rs+++ b/rust/deltalite/core/src/handle.rs@@ -262,6 +262,27 @@ impl TableHandle {}}+ /// Compact small files (see [`crate::compact`]) against a refreshed snapshot, then+ /// adopt the committed state so later writes through this handle see it.+ pub async fn compact(+ &mut self,+ opts: crate::compact::CompactOptions,+ multipart: MultipartConfig,+ ) -> Result<crate::compact::CompactStats> {+ self.refresh().await?;+ let view = wrap_multipart(self.table.clone(), multipart);+ let (stats, state) = crate::compact::compact(&view, opts).await?;+ if let Some(state) = state {+ if self.adopt_commit_snapshot {+ self.table.state = Some(state);+ self.prefetch.clear();+ } else {+ self.refresh().await?;+ }+ }+ Ok(stats)+ }+/// The open cost, handed out once so per-upsert stats sum to the handle's total.fn take_initial_open_ms(&mut self) -> u64 {if self.initial_open_reported {diff --git a/rust/deltalite/core/src/lib.rs b/rust/deltalite/core/src/lib.rsindex cbaddd15de40..914aa6efa04e 100644--- a/rust/deltalite/core/src/lib.rs+++ b/rust/deltalite/core/src/lib.rs@@ -29,6 +29,7 @@//! This crate is pure Rust; the Python bindings live in the sibling `deltalite-python`//! crate (built with maturin, imported as `deltalite`).+pub mod compact;pub mod errors;pub mod handle;pub mod limits;@@ -41,6 +42,7 @@ pub mod table;pub mod upsert;mod writer;+pub use compact::{compact, CompactOptions, CompactStats};pub use errors::{Error, Result};pub use handle::{LiveFile, TableHandle};pub use limits::ProcessLimits;diff --git a/rust/deltalite/core/src/upsert.rs b/rust/deltalite/core/src/upsert.rsindex 12fc23af4f15..0ac59d5a89b0 100644--- a/rust/deltalite/core/src/upsert.rs+++ b/rust/deltalite/core/src/upsert.rs@@ -68,7 +68,7 @@ const WHOLE_TABLE: &str = "__deltalite_whole_table__";/// First-iteration pre-decode budget reservation for full-width row groups; adapts to/// the observed batch size after the first decode.-const INITIAL_DECODE_ESTIMATE_BYTES: usize = 4 * 1024 * 1024;+pub(crate) 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;@@ -92,7 +92,11 @@ const FOOTER_SIZE_HINT: usize = 64 * 1024;/// compressible rows can't inflate a single decoded batch far past the pre-decode reservation/// (which would otherwise sit unaccounted while the reader tops its permit up). Clamped to/// `[1, cap]`; falls back to `cap` when metadata carries no usable sizes.-fn byte_bounded_batch_rows(meta: &ParquetMetaData, target_bytes: usize, cap: usize) -> usize {+pub(crate) fn byte_bounded_batch_rows(+ meta: &ParquetMetaData,+ target_bytes: usize,+ cap: usize,+) -> usize {let max_bytes_per_row = meta.row_groups().iter()@@ -122,7 +126,7 @@ fn batch_rows_for_bytes_per_row(/// 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 {+pub(crate) fn max_row_group_fetch_bytes(meta: &ParquetMetaData, roots: Option<&[usize]>) -> usize {let schema = meta.file_metadata().schema_descr();meta.row_groups().iter()@@ -369,14 +373,14 @@ impl RelaxCache {}/// A file selected for rewrite, with the metadata needed to tombstone it.-struct TargetFile {- path: String,- size: u64,- stats: Option<String>,- remove: Remove,+pub(crate) struct TargetFile {+ pub(crate) path: String,+ pub(crate) size: u64,+ pub(crate) stats: Option<String>,+ pub(crate) remove: Remove,/// Footer the probe parsed, handed to the rewrite so a hit file is opened once. Lives/// only as long as this partition's rewrite: the reader task consumes it.- metadata: Option<Arc<ParquetMetaData>>,+ pub(crate) metadata: Option<Arc<ParquetMetaData>>,}/// Which rows of one source batch belong to a partition. Chosen so the common shapes@@ -497,7 +501,7 @@ struct PartitionOutcome {/// A unit of byte budget: one permit from the per-call budget and one from the/// process-global budget. Both ride with a batch from decode until the writer has/// copied it into its buffer.-struct BudgetPermit {+pub(crate) struct BudgetPermit {/// `None` only transiently inside `top_up`, while the estimate's permits have been/// released and the grown permits are being re-acquired.local: Option<OwnedSemaphorePermit>,@@ -510,14 +514,14 @@ struct BudgetPermit {/// Fetch-budget permits held by one reader from before its first data fetch until its/// stream is dropped.-struct FetchPermit {+pub(crate) struct FetchPermit {_local: OwnedSemaphorePermit,_global: OwnedSemaphorePermit,}/// Per-call view of the budget semaphores plus their process-global counterparts.#[derive(Clone)]-struct Budgets {+pub(crate) struct Budgets {local: Arc<Semaphore>,local_cap_kb: u32,fetch_local: Arc<Semaphore>,@@ -526,7 +530,11 @@ struct Budgets {}impl Budgets {- fn new(max_buffered_bytes: usize, max_fetch_bytes: usize, limits: Arc<ProcessLimits>) -> Self {+ pub(crate) 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;@@ -551,7 +559,7 @@ impl Budgets {/// 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> {+ pub(crate) 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;@@ -571,7 +579,7 @@ impl Budgets {/// 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).- async fn acquire_bytes(&self, bytes: usize) -> Result<BudgetPermit> {+ pub(crate) async fn acquire_bytes(&self, bytes: usize) -> Result<BudgetPermit> {let want = Self::kb(bytes);let local_kb = want.min(self.local_cap_kb as u64) as u32;let global_kb = want.min(self.limits.buffer_cap_kb() as u64) as u32;@@ -603,7 +611,7 @@ impl Budgets {/// while holding any of it, so some waiter can always make progress. The decoded batch/// stays resident during the brief re-acquire gap, but it is already allocated and the/// wait is bounded by the budget draining as writers flush.- async fn top_up(&self, permit: &mut BudgetPermit, total_bytes: usize) -> Result<()> {+ pub(crate) async fn top_up(&self, permit: &mut BudgetPermit, total_bytes: usize) -> Result<()> {let want = Self::kb(total_bytes);let want_local = want.min(self.local_cap_kb as u64) as u32;let want_global = want.min(self.limits.buffer_cap_kb() as u64) as u32;@@ -1166,7 +1174,11 @@ async fn upsert_inner(/// `checkpoint_interval` boundary; cleanup therefore also runs per boundary rather than/// per commit (as delta-rs's hook does) -- cleanup can only delete logs behind a/// checkpoint anyway, and gating it cuts the bulk-delete traffic by the interval factor.-async fn best_effort_log_maintenance(table: &DeltaTable, version: u64, cleanup_enabled: bool) {+pub(crate) async fn best_effort_log_maintenance(+ table: &DeltaTable,+ version: u64,+ cleanup_enabled: bool,+) {let result: std::result::Result<(), (&'static str, deltalake::DeltaTableError)> = async {let mut post = table.clone();post.update_incremental(None)@@ -1233,7 +1245,7 @@ fn source_footprint(}/// Refuse tables whose features would make a blind file rewrite unsafe.-fn ensure_supported_table(table: &DeltaTable) -> Result<()> {+pub(crate) fn ensure_supported_table(table: &DeltaTable) -> Result<()> {let snapshot = table.snapshot()?;let protocol = snapshot.protocol();@@ -1626,7 +1638,7 @@ fn target_file(v: &LogicalFileView) -> TargetFile {/// Open a Parquet stream builder for `f`. A footer the probe already parsed is reused/// without I/O; otherwise the footer is read with [`FOOTER_SIZE_HINT`] so it arrives in/// one round trip.-async fn open_builder(+pub(crate) async fn open_builder(store: &Arc<dyn ObjectStore>,f: &TargetFile,) -> Result<ParquetRecordBatchStreamBuilder<ParquetObjectReader>> {diff --git a/rust/deltalite/core/src/writer.rs b/rust/deltalite/core/src/writer.rsindex 4590f061c0f5..7ff3706f990e 100644--- a/rust/deltalite/core/src/writer.rs+++ b/rust/deltalite/core/src/writer.rs@@ -37,7 +37,7 @@ use deltalake::{DeltaTable, ObjectStore, Path};use indexmap::IndexMap;use object_store::PutPayload;use parquet::arrow::ArrowWriter;-use parquet::basic::Compression;+use parquet::basic::{Compression, ZstdLevel};use parquet::file::properties::WriterProperties;use parquet::schema::types::ColumnPath;use uuid::Uuid;@@ -167,11 +167,34 @@ impl StreamingWriter {})}+ /// Encode with `props` instead of delta-rs's write defaults. Compaction passes+ /// [`optimize_writer_properties`], the properties delta-rs's `optimize` writes with.+ pub(crate) fn with_writer_properties(mut self, props: WriterProperties) -> Self {+ self.writer_properties = props;+ self+ }+/// Bytes held across all open files; the rollover measure.pub(crate) fn buffer_len(&self) -> usize {self.open.values().map(OpenFile::buffer_len).sum()}+ /// Rows in the row groups the open files have not closed yet.+ pub(crate) fn in_progress_rows(&self) -> usize {+ self.open+ .values()+ .map(|f| f.writer.in_progress_rows())+ .sum()+ }++ /// Close the in-progress row group of every open file, keeping the files open.+ pub(crate) fn flush_row_groups(&mut self) -> Result<()> {+ for file in self.open.values_mut() {+ file.writer.flush()?;+ }+ Ok(())+ }+/// 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 {@@ -329,6 +352,15 @@ fn delta_rs_writer_properties() -> WriterProperties {.build()}+/// `default_writer_properties(Compression::ZSTD(4))` from delta-rs, which `optimize`+/// uses when the caller passes no writer properties (the Python package passes none).+pub(crate) fn optimize_writer_properties() -> WriterProperties {+ WriterProperties::builder()+ .set_created_by(format!("delta-rs version {}", deltalake::crate_version()))+ .set_compression(Compression::ZSTD(ZstdLevel::try_new(4).unwrap_or_default()))+ .build()+}+fn schema_without_partitions(schema: &SchemaRef, partition_columns: &[String]) -> SchemaRef {Arc::new(Schema::new(schemadiff --git a/rust/deltalite/core/tests/compact.rs b/rust/deltalite/core/tests/compact.rsnew file mode 100644index 000000000000..061c60e8716f--- /dev/null+++ b/rust/deltalite/core/tests/compact.rs@@ -0,0 +1,860 @@+//! Integration tests for `deltalite_core::compact`: the OPTIMIZE commit it writes, the+//! no-I/O plan, the output layout knobs, and its behaviour when another writer commits+//! between its plan and its commit. Every test checks the log replays cleanly (no file+//! removed twice or removed while not live) and that no uncommitted output file is left+//! in the table directory.++use std::collections::{BTreeMap, HashMap, HashSet};+use std::sync::Arc;+use std::time::Duration;++use arrow_array::{Array, Int64Array, RecordBatch, StringArray};+use arrow_schema::{DataType, Field, Schema, SchemaRef};+use bytes::Bytes;+use deltalake::kernel::{DataType as KernelType, StructField};+use deltalake::operations::create::CreateBuilder;+use deltalake::writer::{DeltaWriter, RecordBatchWriter};+use deltalake::{DeltaTable, Path};+use deltalite_core::compact::{compact, CompactOptions, CompactStats};+use deltalite_core::handle::TableHandle;+use deltalite_core::limits::ProcessLimits;+use deltalite_core::table::{open_table, MultipartConfig};+use deltalite_core::upsert::UpsertOptions;+use deltalite_core::Error;+use object_store::ObjectStoreExt;+use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;+use parquet::file::properties::WriterProperties;+use serde_json::Value;++// ---- fixtures ----------------------------------------------------------------------++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, true));+ }+ Arc::new(Schema::new(fields))+}++/// Rows `pk = <prefix><i>` for `i` in `ids`, each with value `v` and a `payload_len`+/// payload (every third payload NULL).+fn rows(+ s: &SchemaRef,+ prefix: &str,+ ids: std::ops::Range<usize>,+ v: i64,+ payload_len: usize,+ p: Option<&str>,+) -> RecordBatch {+ let n = ids.len();+ let pks: Vec<String> = ids.clone().map(|i| format!("{prefix}{i:06}")).collect();+ let payload: Vec<Option<String>> = ids+ .map(|i| (i % 3 != 0).then(|| format!("{i}-").repeat(payload_len / 4 + 1)))+ .collect();+ let mut cols: Vec<Arc<dyn Array>> = vec![+ Arc::new(StringArray::from(pks)),+ Arc::new(Int64Array::from(vec![v; n])),+ Arc::new(StringArray::from(payload)),+ ];+ if s.fields().len() == 4 {+ cols.push(Arc::new(StringArray::from(vec![p; n])));+ }+ RecordBatch::try_new(s.clone(), cols).unwrap()+}++async fn create(dir: &std::path::Path, partitioned: bool) -> DeltaTable {+ let mut builder = 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 {+ builder = builder+ .with_columns(vec![StructField::new("p", KernelType::STRING, true)])+ .with_partition_columns(vec!["p".to_string()]);+ }+ builder.await.unwrap()+}++/// Append `batch` as one commit through delta-rs (one new file per partition).+async fn append(table: &mut DeltaTable, batch: RecordBatch, props: Option<WriterProperties>) {+ let mut w = RecordBatchWriter::for_table(table).unwrap();+ if let Some(props) = props {+ w = w.with_writer_properties(props);+ }+ w.write(batch).await.unwrap();+ w.flush_and_commit(table).await.unwrap();+}++/// `files` small appends per partition value, keys disjoint across files.+async fn fragmented(+ dir: &std::path::Path,+ partitions: &[Option<&str>],+ files: usize,+ rows_per_file: usize,+) -> DeltaTable {+ let partitioned = !partitions.is_empty();+ let mut table = create(dir, partitioned).await;+ let s = schema(partitioned);+ let parts: Vec<Option<&str>> = if partitioned {+ partitions.to_vec()+ } else {+ vec![None]+ };+ for f in 0..files {+ for (i, p) in parts.iter().enumerate() {+ let start = f * rows_per_file;+ let b = rows(+ &s,+ &format!("k{i}-"),+ start..start + rows_per_file,+ f as i64,+ 40,+ *p,+ );+ append(&mut table, b, None).await;+ }+ }+ table+}++type Row = (Option<String>, String, Option<i64>, Option<String>);++/// Every live row as (partition, pk, v, payload), sorted, read through the table's store.+async fn read_rows(table: &DeltaTable) -> Vec<Row> {+ let store = table.object_store();+ let mut out = Vec::new();+ for view in table.snapshot().unwrap().log_data().iter() {+ let remove = view.remove_action(false);+ let p = remove+ .partition_values+ .as_ref()+ .and_then(|pv| pv.get("p").cloned().flatten());+ let path = Path::parse(view.path().as_ref()).unwrap();+ let bytes: Bytes = store.get(&path).await.unwrap().bytes().await.unwrap();+ for batch in ParquetRecordBatchReaderBuilder::try_new(bytes)+ .unwrap()+ .build()+ .unwrap()+ {+ let batch = batch.unwrap();+ let col = |name: &str| batch.column(batch.schema().index_of(name).unwrap()).clone();+ let pk = col("pk");+ let pk = pk.as_any().downcast_ref::<StringArray>().unwrap();+ let v = col("v");+ let v = v.as_any().downcast_ref::<Int64Array>().unwrap();+ let payload = col("payload");+ let payload = payload.as_any().downcast_ref::<StringArray>().unwrap();+ for i in 0..batch.num_rows() {+ out.push((+ p.clone(),+ pk.value(i).to_string(),+ (!v.is_null(i)).then(|| v.value(i)),+ (!payload.is_null(i)).then(|| payload.value(i).to_string()),+ ));+ }+ }+ }+ out.sort();+ out+}++async fn reopen(dir: &std::path::Path) -> DeltaTable {+ open_table(dir.to_str().unwrap(), HashMap::new())+ .await+ .unwrap()+}++/// Actions of every commit, by version.+fn commits(dir: &std::path::Path) -> BTreeMap<u64, Vec<Value>> {+ let mut out = BTreeMap::new();+ for entry in std::fs::read_dir(dir.join("_delta_log")).unwrap() {+ let path = entry.unwrap().path();+ let name = path.file_name().unwrap().to_string_lossy().to_string();+ let Some(stem) = name.strip_suffix(".json") else {+ continue;+ };+ let Ok(version) = stem.parse::<u64>() else {+ continue;+ };+ let actions = std::fs::read_to_string(&path)+ .unwrap()+ .lines()+ .map(|l| serde_json::from_str(l).unwrap())+ .collect();+ out.insert(version, actions);+ }+ out+}++fn name(path: &str) -> String {+ path.rsplit('/').next().unwrap().to_string()+}++/// Replays the log: no remove of a file that is not live, every OPTIMIZE action has+/// `dataChange=false`. Returns the live file names and the OPTIMIZE commits.+fn assert_log_valid(dir: &std::path::Path) -> (HashSet<String>, Vec<Vec<Value>>) {+ let mut live: HashSet<String> = HashSet::new();+ let mut optimizes = Vec::new();+ let log = commits(dir);+ let versions: Vec<u64> = log.keys().copied().collect();+ assert_eq!(+ versions,+ (0..versions.len() as u64).collect::<Vec<_>>(),+ "contiguous log"+ );+ for (version, actions) in log {+ let op = actions+ .iter()+ .find_map(|a| a.get("commitInfo"))+ .and_then(|c| c.get("operation"))+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();+ for a in &actions {+ if let Some(r) = a.get("remove") {+ let n = name(r["path"].as_str().unwrap());+ assert!(+ live.remove(&n),+ "v{version} ({op}) removes {n}, which is not live"+ );+ if op == "OPTIMIZE" {+ assert_eq!(r["dataChange"], false, "v{version} remove");+ }+ }+ if let Some(add) = a.get("add") {+ let n = name(add["path"].as_str().unwrap());+ assert!(live.insert(n.clone()), "v{version} adds {n} twice");+ if op == "OPTIMIZE" {+ assert_eq!(add["dataChange"], false, "v{version} add");+ }+ }+ }+ if op == "OPTIMIZE" {+ optimizes.push(actions);+ }+ }+ (live, optimizes)+}++/// Every compaction output (ZSTD; the fixtures and upserts write SNAPPY) in the table+/// directory was added by some commit. Upserts that lose a race leave their own+/// outputs behind, which is not what these tests check.+fn assert_no_orphans(dir: &std::path::Path) {+ let mut added: HashSet<String> = HashSet::new();+ for actions in commits(dir).values() {+ for a in actions {+ if let Some(add) = a.get("add") {+ added.insert(name(add["path"].as_str().unwrap()));+ }+ }+ }+ let mut stack = vec![dir.to_path_buf()];+ while let Some(d) = stack.pop() {+ for entry in std::fs::read_dir(&d).unwrap() {+ let path = entry.unwrap().path();+ if path.is_dir() {+ if !path.ends_with("_delta_log") {+ stack.push(path);+ }+ } else if path.to_string_lossy().ends_with(".zstd.parquet") {+ let n = path.file_name().unwrap().to_string_lossy().to_string();+ assert!(added.contains(&n), "orphan output file {path:?}");+ }+ }+ }+}++fn files_per_partition(table: &DeltaTable) -> BTreeMap<Option<String>, usize> {+ let mut out = BTreeMap::new();+ for view in table.snapshot().unwrap().log_data().iter() {+ let p = view+ .remove_action(false)+ .partition_values+ .and_then(|pv| pv.get("p").cloned().flatten());+ *out.entry(p).or_default() += 1;+ }+ out+}++fn limits() -> Arc<ProcessLimits> {+ Arc::new(ProcessLimits::with_fetch(8, 16, 256 << 20, 256 << 20))+}++fn opts() -> CompactOptions {+ CompactOptions {+ target_file_size: Some(64 << 20),+ limits: limits(),+ ..Default::default()+ }+}++async fn run(table: &DeltaTable, o: CompactOptions) -> (CompactStats, DeltaTable) {+ let (stats, state) = tokio::time::timeout(Duration::from_secs(120), compact(table, o))+ .await+ .expect("compaction hung")+ .expect("compaction failed");+ let mut after = table.clone();+ if let Some(state) = state {+ after.state = Some(state);+ }+ (stats, after)+}++fn upsert_opts() -> UpsertOptions {+ UpsertOptions {+ primary_keys: vec!["pk".to_string()],+ partition_key: Some("p".to_string()),+ ..Default::default()+ }+}++// ---- tests -------------------------------------------------------------------------++/// Every partition with small files, including a NULL partition and values that need+/// path encoding, lands as one file in one OPTIMIZE commit with the same rows.+#[tokio::test]+async fn compacts_every_partition_in_one_optimize_commit() {+ let dir = tempfile::tempdir().unwrap();+ let parts = [Some("x"), Some("a b/c=d%e"), None, Some("ü")];+ let table = fragmented(dir.path(), &parts, 5, 50).await;+ let before = read_rows(&table).await;+ let version_before = table.version().unwrap();++ let (stats, after) = run(&table, opts()).await;++ assert_eq!(stats.files_considered, 20);+ assert_eq!(stats.partitions_compacted, 4);+ assert_eq!(stats.bins, 4);+ assert_eq!(stats.files_removed, 20);+ assert_eq!(stats.files_added, 4);+ assert_eq!(stats.rows_rewritten, 1000);+ assert_eq!(stats.commits, 1);+ assert_eq!(stats.version as u64, version_before + 1);+ assert_eq!(+ files_per_partition(&after)+ .values()+ .copied()+ .collect::<Vec<_>>(),+ vec![1; 4]+ );+ let fresh = reopen(dir.path()).await;+ assert_eq!(read_rows(&fresh).await, before);+ assert_eq!(files_per_partition(&fresh), files_per_partition(&after));++ let (_, optimizes) = assert_log_valid(dir.path());+ assert_eq!(optimizes.len(), 1);+ let info = optimizes[0]+ .iter()+ .find_map(|a| a.get("commitInfo"))+ .unwrap();+ assert_eq!(info["isBlindAppend"], false);+ assert_eq!(info["readVersion"], version_before);+ assert_eq!(info["operationParameters"]["targetSize"], "67108864");+ let metrics = &info["operationMetrics"];+ assert_eq!(metrics["numFilesRemoved"], 20);+ assert_eq!(metrics["numFilesAdded"], 4);+ assert_eq!(metrics["partitionsOptimized"], 4);+ let removed: Value = serde_json::from_str(metrics["filesRemoved"].as_str().unwrap()).unwrap();+ assert_eq!(removed["totalFiles"], 20);+ // ZSTD, as delta-rs's optimize writes.+ for a in &optimizes[0] {+ if let Some(add) = a.get("add") {+ assert!(add["path"].as_str().unwrap().ends_with(".zstd.parquet"));+ }+ }+ assert_no_orphans(dir.path());+}++#[tokio::test]+async fn unpartitioned_table_with_oversized_and_lone_files() {+ let dir = tempfile::tempdir().unwrap();+ let mut table = fragmented(dir.path(), &[], 4, 100).await;+ let s = schema(false);+ // One big file splits the run: the four small files before it form a bin, the two+ // after it form another.+ append(&mut table, rows(&s, "big", 0..4000, 9, 2000, None), None).await;+ for f in 0..2 {+ append(+ &mut table,+ rows(&s, &format!("t{f}-"), 0..10, 1, 40, None),+ None,+ )+ .await;+ }+ let before = read_rows(&table).await;+ let big = table+ .snapshot()+ .unwrap()+ .log_data()+ .iter()+ .map(|v| v.size() as usize)+ .max()+ .unwrap();+ let (stats, after) = run(+ &table,+ CompactOptions {+ target_file_size: Some(big - 1),+ ..opts()+ },+ )+ .await;+ assert_eq!(stats.bins, 2);+ assert_eq!(stats.files_removed, 6);+ assert_eq!(stats.files_skipped, 1);+ assert_eq!(after.snapshot().unwrap().log_data().num_files(), 3);+ assert_eq!(read_rows(&reopen(dir.path()).await).await, before);+ assert_log_valid(dir.path());+}++/// Planning reads only the log: with every data file deleted from disk, a dry run still+/// reports the full plan and commits nothing.+#[tokio::test]+async fn dry_run_plans_from_the_log_alone() {+ let dir = tempfile::tempdir().unwrap();+ let table = fragmented(dir.path(), &[Some("x"), Some("y")], 3, 20).await;+ for entry in walk(dir.path()) {+ if entry.extension().is_some_and(|e| e == "parquet") {+ std::fs::remove_file(entry).unwrap();+ }+ }+ let (stats, state) = compact(+ &table,+ CompactOptions {+ dry_run: true,+ ..opts()+ },+ )+ .await+ .unwrap();+ assert!(state.is_none());+ assert!(stats.dry_run);+ assert_eq!(stats.bins, 2);+ assert_eq!(stats.files_removed, 6);+ assert_eq!(stats.partitions_compacted, 2);+ assert_eq!(stats.files_added, 0);+ assert_eq!(reopen(dir.path()).await.version(), table.version());+}++fn walk(dir: &std::path::Path) -> Vec<std::path::PathBuf> {+ let mut out = Vec::new();+ let mut stack = vec![dir.to_path_buf()];+ while let Some(d) = stack.pop() {+ for entry in std::fs::read_dir(&d).unwrap() {+ let path = entry.unwrap().path();+ if path.is_dir() {+ stack.push(path);+ } else {+ out.push(path);+ }+ }+ }+ out+}++/// `min_partition_removable_files` leaves partitions that would gain little alone, and+/// `partitions` restricts the plan to the named values.+#[tokio::test]+async fn partition_selection() {+ let dir = tempfile::tempdir().unwrap();+ let mut table = fragmented(dir.path(), &[Some("many")], 6, 10).await;+ let s = schema(true);+ for f in 0..2 {+ append(+ &mut table,+ rows(&s, &format!("few{f}-"), 0..10, 1, 40, Some("few")),+ None,+ )+ .await;+ }+ let dry = |o: CompactOptions| {+ let table = table.clone();+ async move {+ compact(&table, CompactOptions { dry_run: true, ..o })+ .await+ .unwrap()+ .0+ }+ };+ // Every partition with a mergeable bin, as delta-rs.+ assert_eq!(dry(opts()).await.partitions_compacted, 2);+ // "few" would remove 2 files and write 1: below a threshold of 2.+ let s2 = dry(CompactOptions {+ min_partition_removable_files: 2,+ ..opts()+ })+ .await;+ assert_eq!(s2.partitions_compacted, 1);+ assert_eq!(s2.files_removed, 6);+ assert_eq!(s2.files_skipped, 2);+ let named = dry(CompactOptions {+ partitions: Some(vec!["few".into()]),+ ..opts()+ })+ .await;+ assert_eq!((named.files_considered, named.files_removed), (2, 2));+ let flat = tempfile::tempdir().unwrap();+ assert!(matches!(+ compact(+ &fragmented(flat.path(), &[], 2, 5).await,+ CompactOptions {+ partitions: Some(vec!["x".into()]),+ ..opts()+ }+ )+ .await,+ Err(Error::SchemaMismatch(_))+ ));+}++/// Multi-row-group inputs; the decoded caps split row groups and output files.+#[tokio::test]+async fn decoded_caps_split_row_groups_and_files() {+ let dir = tempfile::tempdir().unwrap();+ let mut table = create(dir.path(), true).await;+ let s = schema(true);+ let small_groups = WriterProperties::builder()+ .set_max_row_group_row_count(Some(100))+ .build();+ for f in 0..4 {+ append(+ &mut table,+ rows(&s, &format!("f{f}-"), 0..1000, f, 400, Some("x")),+ Some(small_groups.clone()),+ )+ .await;+ }+ let before = read_rows(&table).await;++ let (stats, after) = run(+ &table,+ CompactOptions {+ max_row_group_decoded_bytes: 64 * 1024,+ max_decoded_file_bytes: 1024 * 1024,+ decode_batch_bytes: 32 * 1024,+ ..opts()+ },+ )+ .await;+ assert_eq!(stats.bins, 1);+ assert!(stats.files_added >= 2, "{stats:?}");+ assert_eq!(read_rows(&reopen(dir.path()).await).await, before);+ let store = after.object_store();+ let mut row_groups = 0;+ for view in after.snapshot().unwrap().log_data().iter() {+ let path = Path::parse(view.path().as_ref()).unwrap();+ let bytes = store.get(&path).await.unwrap().bytes().await.unwrap();+ let meta = ParquetRecordBatchReaderBuilder::try_new(bytes)+ .unwrap()+ .metadata()+ .clone();+ // A row group or file closes on the batch that crosses its cap, so each may+ // overshoot by one input batch (one 100-row input row group here).+ for rg in meta.row_groups() {+ assert!(+ rg.total_byte_size() < 128 * 1024,+ "{}",+ rg.total_byte_size()+ );+ }+ row_groups += meta.num_row_groups();+ let decoded: i64 = meta.row_groups().iter().map(|r| r.total_byte_size()).sum();+ assert!(decoded < 1024 * 1024 + 64 * 1024, "{decoded}");+ }+ assert!(row_groups > stats.files_added, "{row_groups}");+ assert_log_valid(dir.path());+}++/// `max_bins_per_commit` commits as bins finish instead of once.+#[tokio::test]+async fn chunked_commits() {+ let dir = tempfile::tempdir().unwrap();+ let table = fragmented(dir.path(), &[Some("x"), Some("y"), Some("z")], 3, 10).await;+ let before = read_rows(&table).await;+ let (stats, _) = run(+ &table,+ CompactOptions {+ max_bins_per_commit: Some(1),+ max_parallel_bins: 1,+ ..opts()+ },+ )+ .await;+ assert_eq!((stats.commits, stats.bins), (3, 3));+ assert_eq!(read_rows(&reopen(dir.path()).await).await, before);+ let (_, optimizes) = assert_log_valid(dir.path());+ assert_eq!(optimizes.len(), 3);+}++/// A merge that rewrote a file of one planned bin commits between the compaction's plan+/// and its commit. That bin is dropped (its output deleted), the untouched partition+/// still lands, and the touched partition is planned again from the merge's result.+#[tokio::test]+async fn concurrent_merge_drops_only_the_touched_bin_and_replans_it() {+ for replan in [1usize, 0] {+ let dir = tempfile::tempdir().unwrap();+ let stale = fragmented(dir.path(), &[Some("x"), Some("y")], 3, 10).await;++ let mut handle = TableHandle::open(dir.path().to_str().unwrap().into(), HashMap::new())+ .await+ .unwrap();+ let s = schema(true);+ handle+ .upsert(+ vec![rows(&s, "k0-", 3..4, 777, 8, Some("x"))],+ s.clone(),+ upsert_opts(),+ MultipartConfig::default(),+ )+ .await+ .unwrap();+ let expected = read_rows(&reopen(dir.path()).await).await;+ let updated: Row = (Some("x".into()), "k0-000003".into(), Some(777), None);+ assert!(expected.contains(&updated));++ let (stats, _) = run(+ &stale,+ CompactOptions {+ max_replan_rounds: replan,+ ..opts()+ },+ )+ .await;+ assert_eq!(stats.commit_retries, 1, "{stats:?}");+ assert_eq!(stats.bins_dropped, 1, "{stats:?}");+ let fresh = reopen(dir.path()).await;+ assert_eq!(read_rows(&fresh).await, expected, "no row resurrected");+ let layout = files_per_partition(&fresh);+ assert_eq!(layout[&Some("y".to_string())], 1);+ if replan == 1 {+ assert_eq!((stats.commits, stats.replan_rounds, stats.bins), (2, 1, 2));+ assert_eq!(layout[&Some("x".to_string())], 1);+ } else {+ assert_eq!((stats.commits, stats.replan_rounds, stats.bins), (1, 0, 1));+ assert_eq!(layout[&Some("x".to_string())], 3);+ }+ assert_log_valid(dir.path());+ assert_no_orphans(dir.path());+ }+}++/// A concurrent schema change aborts the compaction as a retryable conflict and leaves+/// no output behind.+#[tokio::test]+async fn concurrent_schema_change_is_a_conflict() {+ let dir = tempfile::tempdir().unwrap();+ let stale = fragmented(dir.path(), &[Some("x")], 3, 10).await;+ let mut evolved = reopen(dir.path()).await;+ // Append once so the compaction's first attempt certainly loses the race, then add+ // a column.+ let s = schema(true);+ append(&mut evolved, rows(&s, "late", 0..5, 1, 8, Some("x")), None).await;+ reopen(dir.path())+ .await+ .add_columns()+ .with_fields(vec![StructField::new("extra", KernelType::STRING, true)])+ .await+ .unwrap();++ let err = compact(&stale, opts()).await.unwrap_err();+ assert!(matches!(err, Error::Conflict(_)), "{err:?}");+ assert_log_valid(dir.path());+ assert_no_orphans(dir.path());+}++/// Upserts running on other handles while compactions run: every upsert's rows survive,+/// nothing is removed twice, and no uncommitted output is left behind.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn compactions_racing_upserts_keep_every_row() {+ let dir = tempfile::tempdir().unwrap();+ let parts = [Some("a"), Some("b"), Some("c")];+ fragmented(dir.path(), &parts, 4, 20).await;+ let uri = dir.path().to_str().unwrap().to_string();++ let writer = {+ let uri = uri.clone();+ tokio::spawn(async move {+ let s = schema(true);+ let mut handle = TableHandle::open(uri, HashMap::new()).await.unwrap();+ for round in 0..12i64 {+ let p = ["a", "b", "c"][round as usize % 3];+ // Update a key from the first file of each partition and insert a new one.+ let mut b = vec![rows(&s, "k0-", 0..2, 1000 + round, 8, Some(p))];+ b.push(rows(&s, &format!("new{round}-"), 0..3, round, 8, Some(p)));+ handle+ .upsert(b, s.clone(), upsert_opts(), MultipartConfig::default())+ .await+ .unwrap();+ }+ })+ };+ let compactor = {+ let uri = uri.clone();+ tokio::spawn(async move {+ let mut totals = CompactStats::default();+ for _ in 0..6 {+ let table = open_table(&uri, HashMap::new()).await.unwrap();+ match compact(+ &table,+ CompactOptions {+ target_file_size: Some(64 << 20),+ commit_max_retries: 50,+ max_replan_rounds: 2,+ limits: limits(),+ ..Default::default()+ },+ )+ .await+ {+ Ok((s, _)) => {+ totals.commits += s.commits;+ totals.bins_dropped += s.bins_dropped;+ totals.commit_retries += s.commit_retries;+ }+ Err(Error::Conflict(_)) => {}+ Err(e) => panic!("compaction failed: {e:?}"),+ }+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ totals+ })+ };+ writer.await.unwrap();+ let totals = compactor.await.unwrap();+ assert!(totals.commits > 0, "{totals:?}");++ // The same upserts applied to a table nobody compacts.+ let reference = tempfile::tempdir().unwrap();+ fragmented(reference.path(), &parts, 4, 20).await;+ let s = schema(true);+ let mut handle = TableHandle::open(reference.path().to_str().unwrap().into(), HashMap::new())+ .await+ .unwrap();+ for round in 0..12i64 {+ let p = ["a", "b", "c"][round as usize % 3];+ let mut b = vec![rows(&s, "k0-", 0..2, 1000 + round, 8, Some(p))];+ b.push(rows(&s, &format!("new{round}-"), 0..3, round, 8, Some(p)));+ handle+ .upsert(b, s.clone(), upsert_opts(), MultipartConfig::default())+ .await+ .unwrap();+ }+ assert_eq!(+ read_rows(&reopen(dir.path()).await).await,+ read_rows(&reopen(reference.path()).await).await+ );+ assert_log_valid(dir.path());+ assert_no_orphans(dir.path());+}++/// A bin whose input cannot be read fails the compaction, commits nothing, and deletes+/// every output already written, including other bins'.+#[tokio::test]+async fn a_failing_bin_commits_nothing_and_leaves_no_outputs() {+ let dir = tempfile::tempdir().unwrap();+ let table = fragmented(dir.path(), &[Some("ok"), Some("broken")], 3, 10).await;+ let version = table.version();+ let victim = table+ .snapshot()+ .unwrap()+ .log_data()+ .iter()+ .find(|v| v.path().contains("broken"))+ .unwrap()+ .path()+ .into_owned();+ let victim = walk(dir.path())+ .into_iter()+ .find(|p| p.to_string_lossy().ends_with(&name(&victim)))+ .unwrap();+ std::fs::write(&victim, b"not parquet").unwrap();++ let err = compact(+ &table,+ CompactOptions {+ max_parallel_bins: 2,+ ..opts()+ },+ )+ .await+ .unwrap_err();+ assert!(matches!(err, Error::Generic(_)), "{err:?}");+ assert_eq!(reopen(dir.path()).await.version(), version);+ assert_no_orphans(dir.path());+}++/// Budgets far smaller than one batch, shared by several compactions and an upsert in+/// one process, still finish: every holder of a fetch or decode permit can complete+/// without waiting on another permit.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn tiny_shared_budgets_never_deadlock() {+ let tiny = Arc::new(ProcessLimits::with_fetch(1, 1, 16 * 1024, 16 * 1024));+ let dirs: Vec<_> = (0..3).map(|_| tempfile::tempdir().unwrap()).collect();+ for d in &dirs {+ fragmented(d.path(), &[Some("a"), Some("b"), Some("c")], 4, 200).await;+ }+ let mut tasks = Vec::new();+ for d in &dirs {+ let uri = d.path().to_str().unwrap().to_string();+ let limits = tiny.clone();+ tasks.push(tokio::spawn(async move {+ let table = open_table(&uri, HashMap::new()).await.unwrap();+ compact(+ &table,+ CompactOptions {+ target_file_size: Some(64 << 20),+ max_parallel_bins: 3,+ max_buffered_bytes: 8 * 1024,+ max_fetch_bytes: 8 * 1024,+ decode_batch_bytes: 4 * 1024,+ limits,+ ..Default::default()+ },+ )+ .await+ .unwrap()+ .0+ }));+ }+ let upsert_dir = dirs[0].path().to_str().unwrap().to_string();+ let limits = tiny.clone();+ let upsert = tokio::spawn(async move {+ let s = schema(true);+ let mut handle = TableHandle::open(upsert_dir, HashMap::new()).await.unwrap();+ handle+ .upsert(+ vec![rows(&s, "z", 0..50, 1, 8, Some("a"))],+ s.clone(),+ UpsertOptions {+ max_buffered_bytes: 8 * 1024,+ max_fetch_bytes: 8 * 1024,+ limits,+ ..upsert_opts()+ },+ MultipartConfig::default(),+ )+ .await+ .unwrap();+ });+ let all = async {+ for t in tasks {+ let stats = t.await.unwrap();+ // The upsert only inserts, so it removes nothing a compaction planned.+ assert_eq!(stats.files_removed, 12, "{stats:?}");+ }+ upsert.await.unwrap();+ };+ tokio::time::timeout(Duration::from_secs(120), all)+ .await+ .expect("budgets deadlocked");+ for d in &dirs {+ assert_log_valid(d.path());+ assert_no_orphans(d.path());+ }+}diff --git a/rust/deltalite/python/README.md b/rust/deltalite/python/README.mdindex 22cc5e1b6aa8..1dc03436910d 100644--- a/rust/deltalite/python/README.md+++ b/rust/deltalite/python/README.md@@ -101,6 +101,7 @@ rejected (raising `DeltaLiteError`) rather than silently double-inserted.| `DeltaLiteTable.open(uri, storage_options=None)` | Open an existing Delta table. `storage_options` is the usual object-store dict (S3/GCS/Azure/local). || `DeltaLiteTable.is_deltatable(uri, storage_options=None)` | `True` if a Delta table exists at `uri`. || `.upsert(data, primary_keys, partition_key=None, **opts)` | Insert-or-replace `data` by key. Returns `UpsertStats`. See knobs below. |+| `.compact(**opts)` | Small-file compaction, the replacement for `DeltaTable.optimize.compact`. Returns a stats dict. See "Compaction" below. || `.version()` | Current table version (`int`). || `.reload()` | Bring the table state up to date with the log (incremental; falls back to a full re-open). || `.table_id()` | The table id from the metadata action (`str`). |@@ -133,6 +134,39 @@ upserts counts it once), `open_ms` (snapshot refreshes around the upsert),non-zero only on checkpoint-boundary commits). `columns_relaxed` countsnon-nullable columns flipped to nullable before the write.+### Compaction++`compact` plans bins exactly as delta-rs's `optimize.compact` does, from the+loaded log with no storage reads, and commits them the same way (ZSTD level 4,+one `OPTIMIZE` commit, `dataChange=false`). Each bin is streamed one file and+one byte-bounded batch at a time through the upsert's fetch and decode budgets,+so memory follows the knobs, not the bin. Output files and row groups are also+capped by decoded size, so a bin that decodes past a cap writes more than one+file where delta-rs writes one.++| Knob | Default | Meaning |+|---|---|---|+| `target_file_size` | table's `delta.targetFileSize` | Bin size and output file size (compressed bytes). |+| `max_parallel_bins` | 2 | Bins rewritten at once. |+| `slot_budget_bytes` | none | Memory for the whole call: caps the decode and fetch budgets at a quarter each and lowers `max_parallel_bins` so the output files fit the rest. |+| `max_decoded_file_bytes` | 1 GiB | An output file closes when its decoded bytes reach this (keeps files under the 2 GiB Arrow offset limit). |+| `max_row_group_decoded_bytes` | 128 MiB | An output row group closes at this many decoded bytes. |+| `partitions` | all | Only these partition values. |+| `min_partition_removable_files` | 1 | Rewrite a partition only when its bins remove at least this many more files than they write. `1` is delta-rs's behavior. |+| `max_bins_per_commit` | one commit | Commit every N bins instead. |+| `max_replan_rounds` | 1 | Times the partitions of bins dropped on a conflict are planned and rewritten again. |+| `commit_max_retries` | 15 | Commit attempts after another writer committed first. |+| `dry_run` | `False` | Plan only; report what would be rewritten. |++Conflicts: when another writer commits first, compaction keeps each bin whose+input files are all still live and drops the others (deleting their output), so+it never resurrects rows a merge replaced. A concurrent schema, partitioning or+protocol change raises `DeltaLiteCommitConflictError`. Tables the upsert refuses+are refused here too (`DeltaLiteUnsupportedTableError`). The result dict carries+deltalite's counters plus delta-rs's `numFilesAdded`, `numFilesRemoved`,+`partitionsOptimized`, `numBatches`, `totalConsideredFiles` and+`totalFilesSkipped`.+### ExceptionsAll inherit from `DeltaLiteError`, so you can catch the base or branch on kind:diff --git a/rust/deltalite/python/src/lib.rs b/rust/deltalite/python/src/lib.rsindex fb5ae725accb..27e884b5c51c 100644--- a/rust/deltalite/python/src/lib.rs+++ b/rust/deltalite/python/src/lib.rs@@ -460,6 +460,126 @@ impl DeltaLiteTable {Ok(stats)}+ /// Compact small files the way `DeltaTable.optimize.compact` does, streaming each bin+ /// one file and one byte-bounded batch at a time (see `deltalite_core::compact`).+ ///+ /// Bins are planned from the loaded log with no storage reads. A partition is+ /// rewritten when its bins remove at least `min_partition_removable_files` more files+ /// than they write (`1` = every partition with two neighbouring small files, as+ /// delta-rs does). `partitions` limits the plan to those partition values.+ /// `dry_run=True` only plans. `slot_budget_bytes` fits the decode and fetch budgets+ /// and the in-flight output files into one memory slot by lowering+ /// `max_parallel_bins`. Every bin lands in one OPTIMIZE commit unless+ /// `max_bins_per_commit` is set. A concurrent commit that removed a file of a bin+ /// drops that bin; its partition is planned again up to `max_replan_rounds` times.+ ///+ /// Returns a dict of deltalite stats plus the count keys delta-rs's `optimize` returns+ /// (`numFilesAdded`, `numFilesRemoved`, `partitionsOptimized`, `numBatches`,+ /// `totalConsideredFiles`, `totalFilesSkipped`).+ #[pyo3(signature = (+ *,+ target_file_size = None,+ max_parallel_bins = 2,+ slot_budget_bytes = None,+ max_buffered_bytes = 67108864,+ max_fetch_bytes = 134217728,+ read_batch_size = 8192,+ decode_batch_bytes = 4194304,+ max_decoded_file_bytes = 1073741824,+ max_row_group_decoded_bytes = 134217728,+ partitions = None,+ min_partition_removable_files = 1,+ max_bins_per_commit = None,+ max_replan_rounds = 1,+ commit_max_retries = 15,+ commit_metadata = None,+ dry_run = false,+ multipart_threshold = None,+ multipart_part_size = None,+ ))]+ #[allow(clippy::too_many_arguments)]+ fn compact(+ &mut self,+ py: Python<'_>,+ target_file_size: Option<usize>,+ max_parallel_bins: usize,+ slot_budget_bytes: Option<usize>,+ max_buffered_bytes: usize,+ max_fetch_bytes: usize,+ read_batch_size: usize,+ decode_batch_bytes: usize,+ max_decoded_file_bytes: usize,+ max_row_group_decoded_bytes: usize,+ partitions: Option<Vec<String>>,+ min_partition_removable_files: usize,+ max_bins_per_commit: Option<usize>,+ max_replan_rounds: usize,+ commit_max_retries: usize,+ commit_metadata: Option<HashMap<String, String>>,+ dry_run: bool,+ multipart_threshold: Option<usize>,+ multipart_part_size: Option<usize>,+ ) -> PyResult<Py<PyAny>> {+ let opts = deltalite_core::CompactOptions {+ target_file_size,+ max_parallel_bins,+ slot_budget_bytes,+ max_buffered_bytes,+ max_fetch_bytes,+ read_batch_size,+ decode_batch_bytes,+ max_decoded_file_bytes,+ max_row_group_decoded_bytes,+ partitions,+ min_partition_removable_files,+ max_bins_per_commit,+ max_replan_rounds,+ commit_max_retries,+ commit_metadata: commit_metadata.map(|m| {+ m.into_iter()+ .map(|(k, v)| (k, Value::String(v)))+ .collect::<HashMap<String, Value>>()+ }),+ dry_run,+ limits: ProcessLimits::global().clone(),+ };+ let multipart = MultipartConfig::resolve(multipart_threshold, multipart_part_size);+ let handle = &mut self.handle;+ let s = py+ .detach(|| runtime().block_on(handle.compact(opts, multipart)))+ .map_err(to_py_err)?;+ let d = PyDict::new(py);+ d.set_item("files_considered", s.files_considered)?;+ d.set_item("files_skipped", s.files_skipped)?;+ d.set_item("partitions_compacted", s.partitions_compacted)?;+ d.set_item("bins", s.bins)?;+ d.set_item("files_removed", s.files_removed)?;+ d.set_item("files_added", s.files_added)?;+ d.set_item("bytes_removed", s.bytes_removed)?;+ d.set_item("bytes_added", s.bytes_added)?;+ d.set_item("rows_rewritten", s.rows_rewritten)?;+ d.set_item("batches_read", s.batches_read)?;+ d.set_item("parallel_bins", s.parallel_bins)?;+ d.set_item("commits", s.commits)?;+ d.set_item("commit_retries", s.commit_retries)?;+ d.set_item("bins_dropped", s.bins_dropped)?;+ d.set_item("replan_rounds", s.replan_rounds)?;+ d.set_item("largest_bin_files", s.largest_bin_files)?;+ d.set_item("plan_ms", s.plan_ms)?;+ d.set_item("rewrite_ms", s.rewrite_ms)?;+ d.set_item("commit_ms", s.commit_ms)?;+ d.set_item("version", s.version)?;+ d.set_item("dry_run", s.dry_run)?;+ // The keys delta-rs's optimize returns, so a caller can log either result alike.+ d.set_item("numFilesAdded", s.files_added)?;+ d.set_item("numFilesRemoved", s.files_removed)?;+ d.set_item("partitionsOptimized", s.partitions_compacted)?;+ d.set_item("numBatches", s.batches_read)?;+ d.set_item("totalConsideredFiles", s.files_considered)?;+ d.set_item("totalFilesSkipped", s.files_skipped)?;+ Ok(d.into_any().unbind())+ }+/// Commit metadata of the most recent `limit` commits, oldest first.fn history(&self, py: Python<'_>, limit: usize) -> PyResult<Py<PyAny>> {let table = self.handle.table().clone();diff --git a/rust/deltalite/python/tests/test_compact.py b/rust/deltalite/python/tests/test_compact.pynew file mode 100644index 000000000000..ea1fd5ef89dc--- /dev/null+++ b/rust/deltalite/python/tests/test_compact.py@@ -0,0 +1,326 @@+"""Differential parity: `DeltaLiteTable.compact` against delta-rs `optimize.compact`.++Each case builds one fragmented table, copies it, and compacts one copy with each+implementation at the same target size. The two results must hold the same rows, the+same partitions with the same file counts, and output files whose Add statistics match+the Parquet they describe and match delta-rs's own statistics. The output is read back+through delta-rs, pyarrow (file by file) and DuckDB, and its Parquet schema must equal+the one delta-rs writes, so any reader of delta-rs's output can read deltalite's.+"""++from __future__ import annotations++import sys+import json+import shutil+import decimal+import datetime as dt+from pathlib import Path++import pytest++import duckdb+import pyarrow as pa+import deltalake+import pyarrow.parquet as pq++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from harness.common import PARTITION_KEY, read_sorted, upsert_path # noqa: E402++TARGET = 64 * 1024 * 1024+++def frame(n: int, start: int, part: str | None, partitioned: bool = True, wide: bool = False) -> pa.Table:+ ids = list(range(start, start + n))+ cols: dict[str, pa.Array] = {+ "id": pa.array([f"id-{i:07d}" for i in ids], pa.string()),+ "n": pa.array([i if i % 7 else None for i in ids], pa.int64()),+ "f": pa.array([i / 3 for i in ids], pa.float64()),+ "flag": pa.array([i % 2 == 0 for i in ids], pa.bool_()),+ "ts": pa.array(+ [dt.datetime(2024, 1, 1, tzinfo=dt.UTC) + dt.timedelta(seconds=i) for i in ids],+ pa.timestamp("us", tz="UTC"),+ ),+ "day": pa.array([dt.date(2024, 1, 1) + dt.timedelta(days=i % 30) for i in ids], pa.date32()),+ "amount": pa.array([decimal.Decimal(i) / 100 for i in ids], pa.decimal128(18, 4)),+ "blob": pa.array([str(i).encode() for i in ids], pa.binary()),+ "tags": pa.array([[i, i + 1] if i % 5 else None for i in ids], pa.list_(pa.int64())),+ "obj": pa.array([{"a": i, "b": str(i)} for i in ids], pa.struct([("a", pa.int64()), ("b", pa.string())])),+ "payload": pa.array(+ [None if i % 3 == 0 else (f"{i}:" * (40_000 if wide else 24)) for i in ids],+ pa.string(),+ ),+ }+ if partitioned:+ cols[PARTITION_KEY] = pa.array([part] * n, pa.string())+ return pa.table(cols)+++def append(uri: str, data: pa.Table, partitioned: bool, row_group: int | None = None) -> None:+ kwargs = {}+ if row_group:+ kwargs["writer_properties"] = deltalake.WriterProperties(max_row_group_size=row_group)+ deltalake.write_deltalake(+ uri,+ data,+ mode="append",+ partition_by=[PARTITION_KEY] if partitioned else None,+ **kwargs,+ )+++def fragment(+ uri: str, parts: list[str] | None, files: int, rows: int, row_group: int | None = None, wide: bool = False+) -> None:+ """`files` appends of `rows` rows per partition (`parts=None`: unpartitioned)."""+ partitioned = parts is not None+ for f in range(files):+ for i, p in enumerate(parts or [None]):+ start = (i * files + f) * rows+ append(uri, frame(rows, start, p, partitioned, wide), partitioned, row_group)+++def live_stats(uri: str) -> dict[tuple, list[dict]]:+ """The live files, grouped by partition values."""+ import deltalite++ out: dict[tuple, list[dict]] = {}+ for f in deltalite.DeltaLiteTable.open(uri).files():+ key = tuple(sorted(f["partition_values"].items()))+ out.setdefault(key, []).append(f)+ return out+++def add_stats(uri: str) -> list[tuple[str, dict]]:+ """(path, parsed stats) of every live file, from the log."""+ dtab = deltalake.DeltaTable(uri)+ out = []+ for line_file in sorted((Path(uri) / "_delta_log").glob("*.json")):+ for line in line_file.read_text().splitlines():+ action = json.loads(line)+ if "add" in action:+ out.append((action["add"]["path"], json.loads(action["add"].get("stats") or "{}")))+ if "remove" in action:+ out = [(p, s) for p, s in out if p != action["remove"]["path"]]+ live = {Path(u).name for u in dtab.file_uris()}+ return [(p, s) for p, s in out if Path(p).name in live]+++def assert_stats_describe_files(uri: str) -> None:+ """numRecords and nullCount of every live file match the Parquet it points at."""+ by_name = {Path(u).name: u for u in deltalake.DeltaTable(uri).file_uris()}+ for path, stats in add_stats(uri):+ table = pq.ParquetFile(by_name[Path(path).name]).read()+ assert stats["numRecords"] == table.num_rows, path+ for col, nulls in stats.get("nullCount", {}).items():+ if isinstance(nulls, dict):+ continue+ assert table.column(col).null_count == nulls, (path, col)+ for col, lo in stats.get("minValues", {}).items():+ if isinstance(lo, dict) or col == "payload":+ continue+ values = [v for v in table.column(col).to_pylist() if v is not None]+ if values and isinstance(lo, int | float):+ assert min(values) == lo, (path, col)+++def compact_both(src: str, tmp: Path, **deltalite_kwargs) -> tuple[str, str, dict, dict]:+ import deltalite++ rs, dl = str(tmp / "delta_rs"), str(tmp / "deltalite")+ shutil.copytree(src, rs)+ shutil.copytree(src, dl)+ rs_metrics = deltalake.DeltaTable(rs).optimize.compact(target_size=TARGET)+ dl_stats = deltalite.DeltaLiteTable.open(dl).compact(target_file_size=TARGET, **deltalite_kwargs)+ return rs, dl, rs_metrics, dl_stats+++def assert_parity(src: str, rs: str, dl: str, rs_metrics: dict, dl_stats: dict) -> None:+ before, schema_before = read_sorted(src)+ rows_rs, schema_rs = read_sorted(rs)+ rows_dl, schema_dl = read_sorted(dl)+ assert schema_dl == schema_rs == schema_before+ assert rows_dl == before, "deltalite changed the rows"+ assert rows_rs == before, "delta-rs changed the rows"++ assert dl_stats["numFilesRemoved"] == rs_metrics["numFilesRemoved"]+ assert dl_stats["numFilesAdded"] == rs_metrics["numFilesAdded"]+ assert dl_stats["partitionsOptimized"] == rs_metrics["partitionsOptimized"]+ assert dl_stats["totalConsideredFiles"] == rs_metrics["totalConsideredFiles"]+ assert dl_stats["totalFilesSkipped"] == rs_metrics["totalFilesSkipped"]++ layout_rs = {k: len(v) for k, v in live_stats(rs).items()}+ layout_dl = {k: len(v) for k, v in live_stats(dl).items()}+ assert layout_dl == layout_rs++ assert_stats_describe_files(dl)+ # Where each partition ends as one file, both writers saw the same rows, so the+ # order-independent statistics must agree exactly.+ stats_rs = dict(add_stats(rs))+ stats_dl = dict(add_stats(dl))+ by_part_rs = live_stats(rs)+ by_part_dl = live_stats(dl)+ for part, files in by_part_dl.items():+ if len(files) != 1 or len(by_part_rs[part]) != 1:+ continue+ s_dl = next(s for p, s in stats_dl.items() if Path(p).name == Path(files[0]["path"]).name)+ s_rs = next(s for p, s in stats_rs.items() if Path(p).name == Path(by_part_rs[part][0]["path"]).name)+ assert s_dl == s_rs, part++ # Other readers, and the physical Parquet schema delta-rs writes.+ con = duckdb.connect()+ con.execute("INSTALL delta; LOAD delta;")+ counts = [con.execute(f"SELECT count(*), count(DISTINCT id) FROM delta_scan('{u}')").fetchone() for u in (rs, dl)]+ assert counts[0] == counts[1]+ con.close()+ rs_files = [u for u in deltalake.DeltaTable(rs).file_uris() if ".zstd." in u]+ dl_files = [u for u in deltalake.DeltaTable(dl).file_uris() if ".zstd." in u]+ assert bool(rs_files) == bool(dl_files)+ for f in dl_files:+ pf = pq.ParquetFile(f)+ assert pf.schema.equals(pq.ParquetFile(rs_files[0]).schema), f+ assert pf.metadata.row_group(0).column(0).compression == "ZSTD"+ pf.read()++ history = deltalake.DeltaTable(dl).history(1)[0]+ if dl_stats["numFilesRemoved"]:+ assert history["operation"] == "OPTIMIZE"+ assert history["isBlindAppend"] is False+ assert history["operationMetrics"]["numFilesRemoved"] == dl_stats["numFilesRemoved"]+++CASES = {+ "partitioned": {"parts": ["2024-01", "2024-02", "2024-03"], "files": 6, "rows": 200},+ "unpartitioned": {"parts": None, "files": 8, "rows": 300},+ "encoded_partition_values": {"parts": ["a b", "x/y", "50%", "ü", "k=v", "#?&"], "files": 3, "rows": 50},+ "multi_row_group_inputs": {"parts": ["p"], "files": 5, "rows": 1000, "row_group": 128},+ "wide_strings": {"parts": ["w"], "files": 4, "rows": 20, "wide": True},+}++[email protected]("case", list(CASES))+def test_parity_with_delta_rs_optimize(tmp_path, case):+ spec = CASES[case]+ src = str(tmp_path / "src")+ fragment(src, spec["parts"], spec["files"], spec["rows"], spec.get("row_group"), spec.get("wide", False))+ rs, dl, rs_metrics, dl_stats = compact_both(src, tmp_path)+ assert dl_stats["numFilesRemoved"] > 0+ assert_parity(src, rs, dl, rs_metrics, dl_stats)+++def test_parity_with_a_null_partition(tmp_path):+ src = str(tmp_path / "src")+ for f in range(4):+ data = pa.concat_tables([frame(30, f * 100, "a"), frame(30, f * 100 + 50, None)])+ append(src, data, True)+ rs, dl, rs_metrics, dl_stats = compact_both(src, tmp_path)+ assert dl_stats["partitions_compacted"] == 2+ assert_parity(src, rs, dl, rs_metrics, dl_stats)+++def test_parity_after_a_partition_lost_every_file(tmp_path):+ src = str(tmp_path / "src")+ fragment(src, ["keep", "gone"], 4, 40)+ deltalake.DeltaTable(src).delete(f"{PARTITION_KEY} = 'gone'")+ rs, dl, rs_metrics, dl_stats = compact_both(src, tmp_path)+ assert dl_stats["partitions_compacted"] == 1+ assert_parity(src, rs, dl, rs_metrics, dl_stats)+ assert all(dict(k).get(PARTITION_KEY) != "gone" for k in live_stats(dl))+++def test_parity_across_schema_evolution_and_upsert_history(tmp_path):+ """Files written before a column existed, and tombstones from deltalite upserts."""+ src = str(tmp_path / "src")+ fragment(src, ["p1", "p2"], 3, 50)+ deltalake.DeltaTable(src).alter.add_columns([deltalake.schema.Field("late", "string", nullable=True)])+ later = frame(20, 10_000, "p1").append_column("late", pa.array(["x"] * 20, pa.string()))+ append(src, later, True)+ update = frame(5, 0, "p1").append_column("late", pa.array(["u"] * 5, pa.string()))+ upsert_path(src, update, ["id"], PARTITION_KEY)+ rs, dl, rs_metrics, dl_stats = compact_both(src, tmp_path)+ assert_parity(src, rs, dl, rs_metrics, dl_stats)+++def test_nothing_to_compact_commits_nothing(tmp_path):+ import deltalite++ src = str(tmp_path / "src")+ fragment(src, ["a", "b"], 1, 10)+ version = deltalake.DeltaTable(src).version()+ stats = deltalite.DeltaLiteTable.open(src).compact(target_file_size=TARGET)+ assert stats["files_removed"] == 0+ assert stats["commits"] == 0+ assert stats["version"] == version+ assert deltalake.DeltaTable(src).version() == version+++def test_dry_run_and_partition_selection(tmp_path):+ import deltalite++ src = str(tmp_path / "src")+ fragment(src, ["big", "small"], 2, 10)+ fragment(src, ["big"], 6, 10)+ t = deltalite.DeltaLiteTable.open(src)+ version = t.version()+ plan = t.compact(target_file_size=TARGET, dry_run=True)+ assert (plan["dry_run"], plan["bins"], plan["files_removed"], plan["files_added"]) == (True, 2, 10, 0)+ # "small" would remove two files and write one: below the threshold.+ only_big = t.compact(target_file_size=TARGET, dry_run=True, min_partition_removable_files=2)+ assert (only_big["partitions_compacted"], only_big["files_removed"]) == (1, 8)+ named = t.compact(target_file_size=TARGET, dry_run=True, partitions=["small"])+ assert (named["files_considered"], named["files_removed"]) == (2, 2)+ assert deltalake.DeltaTable(src).version() == version++ stats = t.compact(target_file_size=TARGET, partitions=["small"], commit_metadata={"source": "test"})+ assert stats["files_removed"] == 2+ history = deltalake.DeltaTable(src).history(1)[0]+ assert history["source"] == "test"+ assert t.version() == version + 1+++def test_deletion_vector_table_is_refused(tmp_path):+ import deltalite++ uri = str(tmp_path / "dv")+ deltalake.DeltaTable.create(+ uri,+ deltalake.Schema.from_arrow(frame(0, 0, "p").schema),+ partition_by=[PARTITION_KEY],+ configuration={"delta.enableDeletionVectors": "true"},+ )+ with pytest.raises(deltalite.DeltaLiteUnsupportedTableError, match="deletionVectors"):+ deltalite.DeltaLiteTable.open(uri).compact()+ assert deltalake.DeltaTable(uri).version() == 0+++def test_column_mapping_table_is_refused(tmp_path):+ """A legacy-protocol column-mapping table, crafted by hand as in test_operations."""+ import deltalite++ uri = tmp_path / "cm"+ (uri / "_delta_log").mkdir(parents=True)+ field = {+ "name": "id",+ "type": "string",+ "nullable": True,+ "metadata": {"delta.columnMapping.id": 1, "delta.columnMapping.physicalName": "col-1"},+ }+ with open(uri / "_delta_log" / "00000000000000000000.json", "w") as f:+ f.write(json.dumps({"protocol": {"minReaderVersion": 2, "minWriterVersion": 5}}) + "\n")+ f.write(+ json.dumps(+ {+ "metaData": {+ "id": "11111111-1111-1111-1111-111111111111",+ "format": {"provider": "parquet", "options": {}},+ "schemaString": json.dumps({"type": "struct", "fields": [field]}),+ "partitionColumns": [],+ "configuration": {"delta.columnMapping.mode": "name", "delta.columnMapping.maxColumnId": "1"},+ "createdTime": 1700000000000,+ }+ }+ )+ + "\n"+ )+ with pytest.raises(deltalite.DeltaLiteUnsupportedTableError, match="columnMapping"):+ deltalite.DeltaLiteTable.open(str(uri)).compact()