Repository navigation
feat(write): add parallel compression and batch appending for ZipWriter with Rayon - #1225
Conversation
…er with Rayon - Expose `PreparedZipFile::from_data` and `PreparedZipFile::from_path` for single-shot file compression into prepared entries. - Add `PreparedZipFile` accessor methods (`file_name_raw`, `crc32`, `uncompressed_size`, `compressed_size`). - Re-export `PreparedZipFile` at the root crate level. - Add `ZipWriter::add_prepared_files` for sequentially appending multiple pre-compressed files. - Under the `rayon` feature, add high-throughput parallel writing APIs on `ZipWriter`: - `par_append_data`: compresses in-memory entries concurrently across Rayon threads. - `par_append_data_batches`: bounds peak memory while compressing in parallel chunks. - `par_append_from_paths`: reads and compresses disk files concurrently. - `par_append_from_paths_batches`: chunked disk file parallel compression. - Add comprehensive integration test suite in `tests/write_parallel.rs`.
|
|
||
| /// Compresses and appends in-memory data entries in parallel batches of `batch_size`. | ||
| /// | ||
| /// This bounds peak memory consumption by processing at most `batch_size` files |
There was a problem hiding this comment.
Do these batched methods actually serve a purpose that can't be served better by wrapping the main ones in rayon::ThreadPoolBuilder::new().num_threads(num_threads).build()?.install(|| /*...*/)? That has the advantage that one new file can start when one previous file finishes, rather than having to wait for the whole previous batch to finish.
There was a problem hiding this comment.
It’s not ready yet; I’m going to add a few more things, and then you can take a comprehensive look at it later.
There was a problem hiding this comment.
A scoped thread pool bounds active compute worker threads, but if callers pass a large collection of entries to par_append_data, into_par_iter().map(...).collect() buffers all compressed payloads simultaneously in RAM before sequential write. For large multi-gigabyte archival runs with many files, par_append_*_batches bounds peak working-set heap memory by processing and committing files in bounded chunks. Empirical benchmarks with Criterion have also been added in benches/deflate_alloc.rs showing 2.8x speedup and >3 GiB/s throughput.
There was a problem hiding this comment.
I still think this is unnecessary now that we have the one-loop rewrite.
There was a problem hiding this comment.
Under the two-phase atomic approach (par_append_data_atomic), batching was necessary because collect() buffers all compressed payloads in memory before writing.
However, if we transition to a Bounded MPSC Channel (sync_channel) pipeline, the channel's bounded capacity (2 * num_threads) provides automatic hardware backpressure. Workers block when the channel buffer is full, which natively bounds peak working-set memory to O(num_threads * file_size) without callers ever having to manually slice their data into batches.
Under that bounded streaming model, we can safely deprecate the manual par_append_*_batches methods in favor of a single, self-throttling par_append_data pipeline.
There was a problem hiding this comment.
I think rayon::iter::ParallelBridge will do that for us in the case of std::sync::mpsc::Channel.
There was a problem hiding this comment.
Here is the architectural distinction we have in mind:
rayon::iter::ParallelBridge bridges a sequential input iterator into Rayon (rx.into_iter().par_bridge()) by distributing items to worker threads via an internal mutex.
However, in par_append_data, the bottleneck we want to eliminate is on the output / writing side:
If Rayon workers finish compression and try to write directly to ZipWriter, they must contend for a shared Mutex<&mut ZipWriter<W>>. When a worker acquires the mutex and writes a multi-megabyte compressed payload to disk/SSD, all other workers that finish compression stall waiting on the lock (kernel futex descheduling).
What We Have in Mind (Zero-Mutex Bounded Pipeline)
Instead of putting a Mutex around ZipWriter, we invert the data flow using a bounded channel with Rayon scope:
let (tx, rx) = std::sync::mpsc::sync_channel(rayon::current_num_threads() * 2);
rayon::scope(|s| {
// 1. Rayon workers compress concurrently and send finished files to the channel
s.spawn(move |_| {
let _ = entries.into_par_iter().try_for_each(|(name, options, data)| {
// ... fast collision check ...
let prepared = PreparedZipFile::from_data(name, options, data.as_ref())?;
tx.send(Ok(prepared)).map_err(|_| invalid!("channel disconnected"))?;
Ok(())
});
});
// 2. Caller thread exclusively owns ZipWriter (ZERO MUTEX, ZERO CONTENTION)
// Dedicated sequential I/O at raw storage speed
for item in rx {
let prepared = item?;
self.add_prepared_file(prepared)?;
}
Ok(())
})Why this solves all the open questions cleanly:
- Zero Locks on
ZipWriter: The caller thread maintains unshared, exclusive&mut self. Zero mutex overhead, zero lock poisoning, andWdoesn't even need to beSync. - Automatic Hardware Backpressure: Because
sync_channelhas a fixed capacity (2 * num_threads), if disk I/O is slower than compression, Rayon workers naturally block ontx.send(). Peak memory is strictly capped atO(num_threads * file_size)without callers ever needing to specify a manualbatch_size. - Optimal Sequential I/O: Storage controllers receive continuous, uninterrupted sequential writes from a single dedicated thread.
This completely eliminates the need for both the Mutex on ZipWriter and the manual par_append_*_batches APIs.
Here is what we have in mind for this pipeline architecture — what do you think?
There was a problem hiding this comment.
Looks good, but I think (at least in the from_paths case) callers should be able to specify the channel capacity, because lots of different variables (I/O speed, compression ratios, available memory) will affect what capacity is optimal.
There was a problem hiding this comment.
Implemented in 9661444.
Summary of Changes:
- Zero-Lock Bounded Channel Pipeline: Replaced the shared
Mutex<&mut ZipWriter>with a producer-consumer pipeline usingstd::thread::scope. Rayon worker threads compress concurrently in the background and stream finished files through a boundedsync_channel. A dedicated consumer thread maintains exclusive, lock-free ownership ofZipWriter, writing sequentially at raw disk speed with zero lock contention and zero lock poisoning. - Channel Capacity Control: Added
par_append_data_with_capacityandpar_append_from_paths_with_capacityacceptingchannel_capacity: NonZeroUsize, allowing callers to fine-tune memory bounds and backpressure according to disk I/O characteristics and system RAM. The defaultpar_append_data/par_append_from_pathsmethods automatically default to2 * rayon::current_num_threads(). - CP437 Raw Byte Override Support: Duplicate filename pre-checks now strictly honor
options.name.unwrap_or(name_str.as_bytes())to ensure pre-validation matches the central directory byte stream. - Overflow-Safe Pre-allocation: Uses
self.files.len().saturating_add(par_iter.opt_len().unwrap_or(0))to pre-size the collision tracking set in a single allocation with zero integer overflow risk. - Batching Deprecation: The slice-based batch APIs have been marked deprecated in favor of the capacity-bounded streaming pipeline.
All 15 integration and stress tests passing cleanly.
…for total transactional atomicity
…detection and atomic fallback
| .collect(); | ||
| .try_for_each(|(name, options, data)| -> ZipResult<()> { | ||
| let name_str = name.as_ref(); | ||
| let name_bytes: Box<[u8]> = name_str.as_bytes().into(); |
There was a problem hiding this comment.
Use options.name instead if it's Some, because that's how BCP437 names are specified.
There was a problem hiding this comment.
Good catch on CP437 raw byte overrides. When options.name is Some(custom_raw_bytes), that takes precedence over the UTF-8 name.as_ref() for local and central directory headers and collision tracking.
We can resolve the canonical filename bytes as:
let name_bytes: Box<[u8]> = options.name.as_deref().unwrap_or_else(|| name.as_ref().as_bytes()).into();This ensures duplicate detection strictly matches the exact bytes written to the central directory.
|
|
||
| /// Compresses and appends in-memory data entries in parallel batches of `batch_size`. | ||
| /// | ||
| /// This bounds peak memory consumption by processing at most `batch_size` files |
There was a problem hiding this comment.
I still think this is unnecessary now that we have the one-loop rewrite.
|
@ByGh00st How much longer do you expect this PR to take? If it will be more than two or three hours, I'll probably release 9.2.0 without it and target it for a 9.3.0 instead, since we have a security fix ready to release. |
|
It will be over soon; there’s very little left. @Pr0methean |
…ty control - Replace Mutex-guarded writer with a zero-mutex bounded MPSC channel pipeline using std::thread::scope. - Dedicated consumer thread performs continuous sequential I/O to ZipWriter while Rayon workers compress concurrently with hardware backpressure. - Add par_append_data_with_capacity and par_append_from_paths_with_capacity APIs allowing custom channel depth tuning. - Support CP437 raw byte filename overrides via options.name in duplicate collision pre-checks. - Use saturating_add and par_iter.opt_len() for pre-allocating collision set with zero integer overflow risk. - Deprecate slice-based batch APIs in favor of self-throttling capacity-bounded streaming.
- Remove unreleased deprecated batch methods in favor of capacity streaming.
- Simplify consumer loop using \or item in rx { self.add_prepared_file(item?)?; }\.
- Remove redundant explicit drop(rx) relying on RAII drop semantics.
- Specialize default channel capacity: 1x num_threads for in-memory data and 2x num_threads for disk path streaming.
|
Hey @Pr0methean , I really appreciate the thoughtful review, sharp feedback, and great discussion on this PR. Digging deep into the microarchitectural trade-offs with you — from zero-lock streaming and hardware backpressure to CP437 raw byte precedence and capacity tuning — was honestly a fantastic learning experience for me. It really pushed me to level up my own thinking, and the result is a significantly more robust, defensive, and high-performance pipeline than a typical implementation. Kudos to you for keeping such high engineering standards for zip2. I hope you enjoy the latest commits and architecture — looking forward to your final thoughts and to seeing this land! Best regards, |
Head branch was pushed to by a user without write access
|
This PR exceeds the recommended size of 1000 lines. Please make sure you are NOT addressing multiple issues with one PR. Note this PR might be rejected due to its size. |
Summary of Changes
While
zip2supports parallel archive extraction viaZipArchive::par_extract*,ZipWriterpreviously had no parallel compression driver. Users creating archives with hundreds or thousands of files were limited to single-threaded sequential compression, leaving multi-core systems largely idle.This PR introduces high-throughput, hardware-adaptive parallel writing APIs on
ZipWriterbacked by Rayon, leveraging the existingZipFileBuilderandPreparedZipFilearchitecture.1. First-Class Parallel Compression on
ZipWriter(feature = "rayon")ZipWriter::par_append_data: Compresses an arbitrary collection of in-memory entries in parallel across Rayon worker threads and streams them sequentially to the archive with default hardware backpressure (capacity = num_threads).ZipWriter::par_append_from_paths: Opens, reads, and compresses files from disk paths concurrently on Rayon worker threads and streams them to the archive with double-buffered disk read-ahead backpressure (capacity = 2 * num_threads).ZipWriter::par_append_data_with_capacity&ZipWriter::par_append_from_paths_with_capacity: Zero-lock bounded streaming pipeline powered bystd::thread::scopeandsync_channel. Enforces hardware backpressure and caps in-flight memory footprint without mutex contention.2. Enhanced
PreparedZipFileErgonomics & Zero-Allocation PrecisionPreparedZipFile::from_data(name, options, data)for single-shot in-memory compression.PreparedZipFile::from_path(name, path, options)for single-shot disk file compression.file_name_raw(),crc32(),uncompressed_size(),compressed_size().ZipWriter::add_prepared_files(files)for sequentially appending multiple pre-compressed files.PreparedZipFileat the root crate level (zip::PreparedZipFile).opt_len()andsaturating_addto prevent heap reallocation and arithmetic overflow.3. Total Transactional Atomicity & Pre-Validation
self.filesin the archive.Empirical Benchmark Measurements
Benchmarks conducted using Criterion (
benches/deflate_alloc.rs) with release optimizations on an x86_64 host (12 logical cores, standard Criterion statistical analysis in a clean environment).1. Heavyweight Archival Workload: 240 MB Payload (24 files x 10 MB each)
ZipWriter179.13 ms1.31 GiB/s1.00x(baseline)par_append_data(Rayon default)30.77 ms7.62 GiB/spar_append_data_with_capacity(cap=24)29.21 ms8.02 GiB/s2. Realistic Document Workload: 64 KiB Structured Compressible Documents
ZipWriter1.05 ms1.16 GiB/s1.00x(baseline)par_append_data_with_capacity(cap=25)0.80 ms1.53 GiB/spar_append_data(Rayon default)0.59 ms2.07 GiB/sZipWriter5.10 ms1.20 GiB/s1.00x(baseline)par_append_data_with_capacity(cap=25)1.80 ms3.39 GiB/spar_append_data(Rayon default)1.78 ms3.42 GiB/s3. Small File Allocation Workload (1 KiB Run-Length Payload)
150.02 µs235.07 µs(thread dispatch overhead)65.10 MiB/s41.54 MiB/s1.33 ms1.47 ms73.28 MiB/s66.38 MiB/s6.50 ms6.00 ms75.17 MiB/s81.42 MiB/sVerification and Test Evidence
cargo clippy --all-targets --features rayonpasses with 0 warnings and 0 errors (-D warnings).cargo clippy --all-targets(without rayon) passes with 0 warnings and 0 errors.cargo fmt --checkpasses cleanly.cargo check --no-default-featuresandcargo check --all-featurespass cleanly.Created exhaustive integration test suite
tests/write_parallel.rscovering all extreme edge cases:test_par_append_data_in_memory(50 files concurrent compression roundtrip)test_par_append_data_with_capacity_chunks(bounded channel capacity backpressure)test_par_append_from_paths(concurrent disk file reading and compression)test_par_append_from_paths_with_capacity_chunks(chunked disk file batch processing)test_par_append_with_capacity_and_backpressure(backpressure verification under full pipeline saturation)test_prepared_zip_file_accessors(metadata getters and single-shot constructors)test_par_append_cp437_raw_name_override(verifies raw byte filename preservation)test_par_append_duplicate_name_error(error propagation on duplicate input names)test_par_append_empty_inputs(empty vectors and empty slices across all APIs)test_par_append_zero_byte_empty_file(0-byte payload roundtrip for Stored and Deflated)test_par_append_unicode_and_special_paths(Unicode, Turkish characters, emojis, subdirectories, spaces)test_par_append_channel_capacity_edge_cases(capacity=1, non-divisors, large capacities)test_par_append_duplicate_pre_existing_atomicity(verifies zero partial writes when colliding with existing archive file)test_par_append_nonexistent_disk_path_atomicity(verifies archive remains pristine when 1 path fails)test_par_append_scoped_single_thread_pool(verifies execution on 1-thread Rayon pool without deadlocks)All 15 tests passed cleanly in 0.06s.
Existing
tests/prepared_files.rs(5/5 passed) andtests/extract_parallel.rs(9/9 passed) continue to pass.