From c8359577ca4e32ab252abf7564bbd8a4cb0bbb54 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:11:11 -0800 Subject: [PATCH] 7z LZMA2 threads: blocks reach idle workers early, and the parallel budget scales with memory The 7z extractor already decoded LZMA2 dictionary-reset blocks on several threads (#235), but on 7-Zip -mmt archives with 64-128 MiB blocks it ran at about 1.8 cores whatever the thread count: - The 256 MiB budget held about one and a half 64 MiB blocks in flight. The default is now an eighth of physical memory, 256 MiB to 2 GiB (1 GiB where memory can't be read). - Reading ahead to find the next block was bounded by the output so far, so the second block was found half way through the first, and stored (random-data) blocks were read 256 KiB at a time, so LZMA blocks after them reached the workers late. Now, while a worker waits with no piece, only the budget bounds reading ahead; before the workers start the lookahead may reach four dictionary windows (one 7-Zip block). Output order, CRC checks and error placement are unchanged. Tests: BCJ and Delta after a multi-block LZMA2 coder, damage in the middle, shuffled block layouts, idle-worker read-ahead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gZ63jJDJGeNcamsGrj --- docs/7z-extract.md | 28 +++-- src/sevenzip.rs | 39 +++++-- src/sevenzip/lzma2_par.rs | 67 +++++++++++- tests/sevenzip_lzma2_threads.rs | 185 +++++++++++++++++++++++++++++++- 4 files changed, 294 insertions(+), 25 deletions(-) diff --git a/docs/7z-extract.md b/docs/7z-extract.md index 75e78abe..603ef238 100644 --- a/docs/7z-extract.md +++ b/docs/7z-extract.md @@ -145,8 +145,9 @@ core), an LZMA2 coder whose output is at least 2 MiB decodes such blocks side by - Worker threads start only with a second piece: an LZMA-coded stream of one block (one-thread 7-Zip, `-mmt1`, liblzma) is decoded on the run's thread alone, with a short lookahead. -Memory is bounded by `SevenZipLimits::lzma2_parallel_bytes` (256 MiB, at least 4 MiB), so several extractions at -once stay modest. Each worker costs its dictionary (the coder's, shrunk to the folder's output) and its one 1 MiB +Memory is bounded by `SevenZipLimits::lzma2_parallel_bytes`: by default an eighth of the machine's memory, at least +256 MiB and at most 2 GiB (1 GiB where the memory can't be read; at least 4 MiB is used). It is a cap, not an +allocation: memory is taken only as blocks are decoded ahead of the one being written. Each worker costs its dictionary (the coder's, shrunk to the folder's output) and its one 1 MiB output buffer, which it makes only when it has output to make (a short last segment goes out in a buffer of its own size, and every queued buffer counts by what it allocates); the workers take at most a third of the budget, and fewer start when they would take more (none: one thread). Their dictionaries also come out of what @@ -160,7 +161,13 @@ run is waiting for those: the run always moves, and a run that stops reading (wr consumer) stops the head too, so a block of zeros cannot pile up decoded output. Reading ahead also stops once the packed bytes waiting in the piece being read pass the larger of 8 MiB and the output handed out so far, capped by the budget (256 KiB in a piece that is nine tenths stored chunks, which cost only a copy to decode), so a one-block stream holds little more -than the one-thread decoder does. All told, the threads hold at most the budget and two segments at any moment. +than the one-thread decoder does. Two exceptions, so that the blocks reach the threads early: before the workers +start (the first piece, which may be the only one) that lookahead may reach four dictionary windows, one 7-Zip +block's packed bytes, so the second piece is found while the first is still decoding; and while a worker waits with +no piece to decode, only the budget bounds reading ahead, since every piece found then puts a thread to work. (On +the 1.28 GB archive below, the second piece used to be found only half way through the first, and the stored +pieces of its random files were read 256 KiB at a time, so the text blocks after them reached the workers a second +late.) All told, the threads hold at most the budget and two segments at any moment. Peak resident memory can read higher: each piece's decoder allocates its dictionary afresh (liblzma offers no way to reuse one), and on Linux glibc keeps freed blocks of that size in its per-thread arenas instead of returning them. So on glibc a worker asks it to trim its arenas (`malloc_trim`) after finishing pieces, at most once per 4 MiB of @@ -169,12 +176,15 @@ dictionaries freed. With 12 threads on the 16 MiB-block archive below that broug back by itself) gave 287 MiB, and 8 threads 296 MiB without either. 7-Zip's blocks are four times its dictionary: 4 MiB at `-md=1m`, 64 MiB at `-mx5`'s 16 MiB, 256 MiB at `-mx9`'s -64 MiB (7-Zip 26 at `-mx5 -mmt8` wrote 134 MiB blocks with a 32 MiB dictionary for the measured archive). With the -256 MiB default such a stream gets two workers (a 32 MiB dictionary and a 1 MiB buffer each) and 190 MiB for bytes -in flight, about one and a half blocks, so it decodes only partly side by side: about 1.6 times one thread on that -archive, whatever the thread count. Streams of smaller blocks (16 MiB at `-md=4m`) get every thread. A caller that -wants the most speed on large blocks and has the memory raises `lzma2_parallel_bytes` (1 GiB lets the six 134 MiB -blocks overlap: about 3.4 times one thread at 8 threads, with peak memory near 1 GiB). +64 MiB (7-Zip 26 at `-mx5 -mmt8` wrote 134 MiB blocks with a 32 MiB dictionary for one archive). Blocks decoded +ahead of the one being written are held whole, so how many decode side by side is about the bytes in flight over +the block size. With the old 256 MiB default a stream of 64 MiB blocks got about one and a half blocks in flight and +decoded only partly side by side, whatever the thread count; the memory-scaled default lets a dozen or more 64 MiB +blocks overlap. A caller running several extractions at once may lower it. + +Measured on 1.28 GB of mixed data (600 MB of text, 600 MB of random bytes, 80 MB of short runs; `7z a -m0=lzma2 +-mx5 -mmt`), median of 3 runs, extracting to local disk: see the pull request that made the default scale with +memory for the table against `7zz`. Failures keep their place. A piece that does not decode, ends early, or whose packed bytes cannot be read gives the output it decoded before the failure and then the failure, in stream order, so the failure lands on the member it diff --git a/src/sevenzip.rs b/src/sevenzip.rs index cd3df55e..fa8f0c23 100644 --- a/src/sevenzip.rs +++ b/src/sevenzip.rs @@ -84,13 +84,16 @@ pub struct SevenZipLimits { /// nothing is left behind however the process ends, and the run uses one descriptor however many members it /// holds back. pub spool_dir: Option, - /// Memory an LZMA2 coder decoding its blocks on several threads may add: 256 MiB (at least 4 MiB is used). A - /// stream 7-Zip wrote with `-mmt` is a run of independent blocks; with more than one thread they are decoded - /// side by side. Each worker thread costs its dictionary and a 1 MiB output buffer; the workers take at most a - /// third of this (fewer start when they would take more; their dictionaries count against `dictionary_bytes` - /// too), and the packed and decoded bytes in flight the rest: a worker waits while that is spent. Large blocks - /// (7-Zip's are four times the dictionary: 64 MiB to 256 MiB at `-mx5` to `-mx9`) then decode only partly side - /// by side; a caller that wants the most speed and has the memory raises it. See `docs/7z-extract.md`. + /// Memory an LZMA2 coder decoding its blocks on several threads may add: by default an eighth of the machine's + /// memory, at least 256 MiB and at most 2 GiB (1 GiB where the machine's memory can't be read); at least 4 MiB + /// is used. A stream 7-Zip wrote with `-mmt` is a run of independent blocks; with more than one thread they are + /// decoded side by side. Each worker thread costs its dictionary and a 1 MiB output buffer; the workers take at + /// most a third of this (fewer start when they would take more; their dictionaries count against + /// `dictionary_bytes` too), and the packed and decoded bytes in flight the rest: a worker waits while that is + /// spent. Blocks decoded ahead of the one being written are held whole, so how many decode side by side is about + /// this budget over the block size (7-Zip's blocks are four times the dictionary: 64 MiB to 256 MiB at `-mx5` to + /// `-mx9`). The memory is taken only as blocks need it; a caller running several extractions at once may lower + /// it. See `docs/7z-extract.md`. pub lzma2_parallel_bytes: u64, /// Threads [`print_selected`] (and reading one member through `extract::SelectedEntry`) decode a folder's /// LZMA2 blocks on: None for one per core, `Some(1)` for the calling thread alone. [`run`] takes @@ -111,12 +114,32 @@ impl Default for SevenZipLimits { spool_member_bytes: 8 << 30, spool_memory_bytes: 1 << 20, spool_dir: None, - lzma2_parallel_bytes: 256 << 20, + lzma2_parallel_bytes: default_lzma2_parallel_bytes(), decode_threads: None, } } } +/// [`SevenZipLimits::lzma2_parallel_bytes`] by default: an eighth of the machine's memory, from 256 MiB to 2 GiB. +fn default_lzma2_parallel_bytes() -> u64 { + physical_memory().map_or(1 << 30, |bytes| (bytes / 8).clamp(256 << 20, 2 << 30)) +} + +/// The machine's physical memory, where it can be read. +#[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))] +fn physical_memory() -> Option { + // SAFETY: sysconf only reads a system setting; it has no preconditions and touches no memory of ours. + let (pages, page) = unsafe { (libc::sysconf(libc::_SC_PHYS_PAGES), libc::sysconf(libc::_SC_PAGESIZE)) }; + let pages = u64::try_from(pages).ok().filter(|&n| n > 0)?; + let page = u64::try_from(page).ok().filter(|&n| n > 0)?; + pages.checked_mul(page) +} + +#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd")))] +fn physical_memory() -> Option { + None +} + /// Which of [`SevenZipLimits`] an archive went past. #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[non_exhaustive] diff --git a/src/sevenzip/lzma2_par.rs b/src/sevenzip/lzma2_par.rs index 2754ff64..5fe2d2ed 100644 --- a/src/sevenzip/lzma2_par.rs +++ b/src/sevenzip/lzma2_par.rs @@ -45,7 +45,9 @@ //! Reading ahead also stops once the packed bytes waiting in the piece being read pass the larger of [`LOOKAHEAD`] //! and the output handed out so far (at most the budget), or [`STORED_LOOKAHEAD`] in a piece of stored //! chunks (which cost a copy to decode, so finding the next piece early gains little), so a one-block stream holds -//! little more than the one-thread reader does. +//! little more than the one-thread reader does. Two exceptions put blocks on threads early: before the workers start, +//! the lookahead may reach [`FIND_BLOCKS`] dictionary windows (one 7-Zip block), so the second piece is found while +//! the first decodes; and while a worker waits with no piece to decode, the budget alone bounds reading ahead. //! //! A piece that fails gives the output it decoded before the failure and then the failure, in order, so the failure //! lands on the member it lands on in one-thread decoding. Workers check the [`Cancellation`] every [`SEGMENT`] bytes @@ -82,6 +84,8 @@ const SPARE: usize = 64; const READ: usize = 64 << 10; /// Packed bytes that may wait for decoders before any output is handed out (see the module documentation). const LOOKAHEAD: u64 = 8 << 20; +/// Before the workers start, the lookahead may reach this many dictionary windows: 7-Zip's blocks are four windows. +const FIND_BLOCKS: u64 = 4; /// The lookahead in a piece of stored chunks (nine tenths or more of its output so far). const STORED_LOOKAHEAD: u64 = 256 << 10; /// Packed bytes read ahead at most before the caller's thread looks at its own work again. @@ -325,10 +329,18 @@ struct State { buffers: u64, /// the most `held` and `buffers` have been together, for the tests peak_total: u64, + /// pieces started, and how many had been when the first was handed out in full, for the tests + #[cfg(test)] + opened: u64, + #[cfg(test)] + opened_at_first_pop: Option, /// dictionary bytes freed since the arenas were last trimmed freed: u64, /// workers waiting for room in the budget budget_waiters: usize, + /// workers waiting for a piece: while there are more of them than pieces waiting for a thread, reading ahead to + /// the next piece pays, so it is bounded by the budget alone ([`Parallel::room`]) + idle: usize, /// packed blocks the decoders are done with, for the reader to read into again spare: Vec>, stop: bool, @@ -358,6 +370,10 @@ impl State { /// Drops the head piece, once it is handed out; the bytes it never read leave the budget. fn pop(&mut self) -> Option { let piece = self.pieces.pop_front()?; + #[cfg(test)] + if self.head == 0 { + self.opened_at_first_pop = Some(self.opened); + } self.head += 1; self.held -= piece.queued; Some(piece) @@ -549,7 +565,9 @@ fn work(shared: &Shared) { guard.number = Some(number); break number; } + state.idle += 1; state = shared.wait(&shared.jobs, state); + state.idle -= 1; } }; let fault = match Decoder::new(number, shared.dict) { @@ -811,6 +829,10 @@ impl Parallel { } } let mut state = self.shared.lock(); + #[cfg(test)] + { + state.opened = state.opened.max(number + 1); + } state.pieces.push_back(Piece::default()); if number > 0 { state.jobs.push_back(number); @@ -879,11 +901,20 @@ impl Parallel { Some(Feeding { number, decoded, stored }) => { // Stored chunks cost a copy to decode: finding the next piece early gains little, and a long // lookahead would leave the cache. Otherwise the lookahead grows with the output, up to the budget. - let limit = if stored * 10 >= decoded * 9 { + // But a worker with nothing to do gains from every piece found: while one waits, the budget alone + // bounds reading ahead. Before the workers start (the first piece, which may be the only one) the + // lookahead may reach one 7-Zip block's packed bytes (four windows), so that a second piece is found + // while the first is still decoding, without reading a one-block stream far ahead. + let mut limit = if stored * 10 >= decoded * 9 { STORED_LOOKAHEAD } else { - LOOKAHEAD.max(self.produced).min(self.shared.memory.max(HEAD_INPUT)) + let first = if self.threads.is_empty() { FIND_BLOCKS * dict_size(self.shared.dict) } else { 0 }; + LOOKAHEAD.max(self.produced).max(first) }; + if !self.threads.is_empty() && state.idle > state.jobs.len() { + limit = limit.max(self.shared.memory); + } + let limit = limit.min(self.shared.memory.max(HEAD_INPUT)); (state.piece(number).map_or(0, |p| p.queued), limit, number == state.head) } None => (0, LOOKAHEAD, true), @@ -1104,8 +1135,13 @@ impl Lzma2Blocks { peak: 0, buffers: 0, peak_total: 0, + #[cfg(test)] + opened: 1, + #[cfg(test)] + opened_at_first_pop: None, freed: 0, budget_waiters: 0, + idle: 0, spare: Vec::new(), stop: false, }), @@ -1660,6 +1696,14 @@ mod tests { } } + /// The pieces started when the first was handed out in full. + fn opened_at_first_pop(&self) -> Option { + match &self.mode { + Mode::Parallel(parallel) => parallel.shared.lock().opened_at_first_pop, + _ => None, + } + } + /// The most bytes the pipeline has held, once it runs. fn peak(&self) -> Option { match &self.mode { @@ -1822,6 +1866,23 @@ mod tests { } } + /// A slow first piece, then stored ones (which decode at once and leave their workers idle), then LZMA ones: + /// with workers idle the reader reads on past the stored pieces within the budget, so every piece has reached + /// a thread before the first is handed out, instead of the stored pieces being read a little at a time as the + /// first one decodes. + #[test] + fn idle_workers_get_the_pieces_after_stored_ones_early() { + let mut blocks = vec![(6 << 20, 40, true)]; + blocks.extend((0..4).map(|i| (4 << 20, 41 + i, false))); + blocks.extend([(2 << 20, 50, true), (2 << 20, 51, true)]); + let (packed, plain) = stream(&blocks); + let mut reader = + Lzma2Blocks::new(cursor(&packed), plain.len() as u64, DICT, 4, 1 << 30, &Cancellation::default()).unwrap(); + let got = drain(&mut reader, plain.len() as u64); + assert!(got.1.is_none() && got.0 == plain, "{:?}", got.1); + assert_eq!(reader.opened_at_first_pop(), Some(blocks.len() as u64)); + } + /// Blocks of zeros 1 MiB and one byte long: each ends in a one-byte segment. With the reader paused the queued /// buffers, counted by what they allocate, stay within the budget and the head's segments. #[test] diff --git a/tests/sevenzip_lzma2_threads.rs b/tests/sevenzip_lzma2_threads.rs index 0b70ba80..85a9c814 100644 --- a/tests/sevenzip_lzma2_threads.rs +++ b/tests/sevenzip_lzma2_threads.rs @@ -197,11 +197,39 @@ fn num(out: &mut Vec, value: u64) { /// A 7z archive of one solid LZMA2 folder (dictionary property 16, 1 MiB) holding `files`, each with its CRC, whose /// packed stream is `packed`. fn solid_lzma2(files: &[(String, Vec)], packed: &[u8]) -> Vec { + solid(files, packed, None, true) +} + +/// A filter coder after the LZMA2 coder: its method id and properties. +type Filter<'a> = (&'a [u8], &'a [u8]); + +/// x86 BCJ, after LZMA2. +const BCJ: Filter = (&[0x03, 0x03, 0x01, 0x03], &[]); + +/// A 7z archive of one solid folder holding `files` whose packed stream is `packed`: LZMA2 (dictionary property 16), +/// then `filter` on its output if given. Each file carries its CRC when `crcs` is set. +fn solid(files: &[(String, Vec)], packed: &[u8], filter: Option, crcs: bool) -> Vec { let total: u64 = files.iter().map(|(_, d)| d.len() as u64).sum(); let mut h = vec![0x01, 0x04, 0x06, 0x00, 0x01, 0x09]; num(&mut h, packed.len() as u64); - // one folder: one LZMA2 coder, property byte 16 - h.extend([0x00, 0x07, 0x0B, 0x01, 0x00, 0x01, 0x21, 0x21, 0x01, 16, 0x0C]); + h.extend([0x00, 0x07, 0x0B, 0x01, 0x00]); + match filter { + // one folder: one LZMA2 coder, property byte 16 + None => h.extend([0x01, 0x21, 0x21, 0x01, 16, 0x0C]), + // the filter (coder 0) reads the LZMA2 coder's output (coder 1), which reads the packed stream + Some((id, props)) => { + h.push(0x02); + h.push(id.len() as u8 | if props.is_empty() { 0 } else { 0x20 }); + h.extend_from_slice(id); + if !props.is_empty() { + num(&mut h, props.len() as u64); + h.extend_from_slice(props); + } + h.extend([0x21, 0x21, 0x01, 16]); + h.extend([0x00, 0x01, 0x0C]); + num(&mut h, total); + } + } num(&mut h, total); h.push(0x00); // substreams: the files' sizes (all but the last) and all their CRCs @@ -211,9 +239,11 @@ fn solid_lzma2(files: &[(String, Vec)], packed: &[u8]) -> Vec { for (_, data) in &files[..files.len() - 1] { num(&mut h, data.len() as u64); } - h.extend([0x0A, 0x01]); - for (_, data) in files { - h.extend(crc32fast::hash(data).to_le_bytes()); + if crcs { + h.extend([0x0A, 0x01]); + for (_, data) in files { + h.extend(crc32fast::hash(data).to_le_bytes()); + } } h.extend([0x00, 0x00]); h.push(0x05); @@ -387,3 +417,148 @@ fn a_canceled_multi_block_folder_stops_promptly() { assert!(seen < plain.len(), "{threads} threads printed everything"); } } + +/// Each extracted member's bytes, in archive order, for `threads`; or the run's error. +fn extracted(archive: &Path, files: &[(String, Vec)], threads: usize) -> Result>, String> { + let dir = tempfile::tempdir().unwrap(); + let summary = + extract::run(archive, &opts(Mode::Extract, dir.path(), threads), |_| {}).map_err(|e| e.to_string())?; + if !summary.errors.is_empty() { + return Err(format!("{:?}", summary.errors)); + } + Ok(files.iter().map(|(name, _)| fs::read(dir.path().join(name)).unwrap()).collect()) +} + +/// Delta (which the test can encode, so the members' CRCs check) and x86 BCJ (whose output the test compares with +/// one thread's) after a multi-block LZMA2 coder: the filter runs over the reassembled stream, in order, so the +/// output is one thread's at every thread count, and damage fails alike. +#[test] +fn a_filter_after_a_multi_block_lzma2_coder_decodes_alike() { + let dir = tempfile::tempdir().unwrap(); + let mut files = members(); + // x86 call and jump opcodes all through the text, so BCJ has addresses to convert + for (i, (_, data)) in files.iter_mut().enumerate() { + for at in (i * 7..data.len()).step_by(997) { + data[at] = if at % 2 == 0 { 0xE8 } else { 0xE9 }; + } + } + let plain: Vec = files.iter().flat_map(|(_, d)| d.iter().copied()).collect(); + + // Delta, distance 4: each byte is stored less the byte four before it + let encoded: Vec = + (0..plain.len()).map(|i| plain[i].wrapping_sub(if i >= 4 { plain[i - 4] } else { 0 })).collect(); + let delta = + write(dir.path(), "delta.7z", &solid(&files, &blocks(&encoded, 1_000_000), Some((&[0x03], &[3])), true)); + let want: Vec<(u64, Vec)> = files.iter().enumerate().map(|(i, (_, d))| (i as u64, d.clone())).collect(); + for threads in [1, 2, 4, 8] { + let printed = print(&delta, None, &limits(threads, None)).unwrap(); + assert!(printed.1.errors.is_empty(), "delta, {threads} threads: {:?}", printed.1.errors); + assert!(printed.0 == want, "delta, {threads} threads: printed members"); + let out = extracted(&delta, &files, threads).unwrap(); + assert!(out.iter().zip(&files).all(|(a, (_, b))| a == b), "delta, {threads} threads: extracted members"); + } + + // BCJ over the same blocks, without CRCs: every thread count gives one thread's bytes + let packed = blocks(&plain, 1_000_000); + let bcj = write(dir.path(), "bcj.7z", &solid(&files, &packed, Some(BCJ), false)); + let one = print(&bcj, None, &limits(1, None)).unwrap(); + assert!(one.1.errors.is_empty(), "{:?}", one.1.errors); + assert!(one.0 != want, "BCJ converted no address"); + let one_extracted = extracted(&bcj, &files, 1).unwrap(); + for threads in [2, 4, 8] { + for memory in [None, Some(0), Some(8 << 20)] { + same_print(&bcj, None, threads, memory); + } + assert!(extracted(&bcj, &files, threads).unwrap() == one_extracted, "BCJ, {threads} threads"); + assert_eq!(tested(&bcj, None, threads), tested(&bcj, None, 1), "BCJ, {threads} threads"); + } + + // a damaged block in the middle fails as on one thread + let mut damaged = packed.clone(); + let starts: Vec = plain + .chunks(1_000_000) + .scan(0, |at, piece| { + let start = *at; + *at += lzma2_block(piece).len(); + Some(start) + }) + .collect(); + // a control byte LZMA2 has no meaning for, at the start of a block in the middle + damaged[starts[starts.len() / 2]] = 0x05; + let bcj = write(dir.path(), "bcj-damaged.7z", &solid(&files, &damaged, Some(BCJ), false)); + let one = tested(&bcj, None, 1); + assert!(!matches!(&one, Ok(t) if t.0.is_empty()), "the damage went unnoticed"); + for threads in [2, 4, 8] { + assert_eq!(tested(&bcj, None, threads), one, "damaged BCJ, {threads} threads"); + same_print(&bcj, None, threads, None); + assert_eq!(extracted(&bcj, &files, threads).err(), extracted(&bcj, &files, 1).err(), "{threads} threads"); + } +} + +/// A tiny deterministic generator for the stress test. +struct Rng(u64); + +impl Rng { + fn below(&mut self, n: u64) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 % n + } +} + +/// Folders of shuffled blocks (stored noise and LZMA text of many sizes, as `7z -mmt` writes for mixed data), +/// members cut at random places, whole and with one damaged block: every thread count and budget decodes what one +/// thread does. +#[test] +fn shuffled_block_layouts_decode_alike() { + let dir = tempfile::tempdir().unwrap(); + for seed in 1..=4u64 { + let mut rng = Rng(seed.wrapping_mul(0x2545_F491_4F6C_DD1D) | 1); + let (mut plain, mut packed, mut starts) = (Vec::new(), Vec::new(), Vec::new()); + for piece in 0..(4 + rng.below(6)) { + let len = 64 << 10 | rng.below(5 << 19) as usize; + let data = bytes(len, seed * 100 + piece, rng.below(3) != 0); + starts.push(packed.len()); + packed.extend(lzma2_block(&data)); + plain.extend(data); + } + packed.push(0); + let mut cuts: Vec = (0..rng.below(6)).map(|_| rng.below(plain.len() as u64) as usize).collect(); + cuts.extend([0, plain.len()]); + cuts.sort_unstable(); + cuts.dedup(); + let files: Vec<(String, Vec)> = + cuts.windows(2).enumerate().map(|(i, w)| (format!("s{i}.bin"), plain[w[0]..w[1]].to_vec())).collect(); + let archive = write(dir.path(), &format!("shuffled{seed}.7z"), &solid_lzma2(&files, &packed)); + let want: Vec<(u64, Vec)> = files.iter().enumerate().map(|(i, (_, d))| (i as u64, d.clone())).collect(); + for threads in [2, 3, 4, 8] { + let printed = print(&archive, None, &limits(threads, None)).unwrap(); + assert!(printed.1.errors.is_empty(), "seed {seed}, {threads} threads: {:?}", printed.1.errors); + assert!(printed.0 == want, "seed {seed}, {threads} threads: printed members"); + same_print(&archive, None, threads, Some(0)); + same_print(&archive, None, threads, Some(8 << 20)); + } + assert_eq!(tested(&archive, None, 4), tested(&archive, None, 1), "seed {seed}"); + + // one block damaged somewhere past the first + let block = 1 + rng.below(starts.len() as u64 - 1) as usize; + let end = starts.get(block + 1).copied().unwrap_or(packed.len() - 1); + let mut damaged = packed.clone(); + damaged[starts[block] + (end - starts[block]) / 2] ^= 0xA5; + let archive = write(dir.path(), &format!("shuffled{seed}-damaged.7z"), &solid_lzma2(&files, &damaged)); + let one = tested(&archive, None, 1); + for threads in [2, 4, 8] { + assert_eq!(tested(&archive, None, threads), one, "seed {seed}, damaged block {block}, {threads} threads"); + same_print(&archive, None, threads, None); + same_print(&archive, None, threads, Some(0)); + } + } +} + +/// The default parallel budget scales with the machine's memory, within 256 MiB and 2 GiB. +#[test] +fn the_default_parallel_budget_is_bounded() { + let budget = SevenZipLimits::default().lzma2_parallel_bytes; + assert!((256 << 20..=2 << 30).contains(&budget), "{budget}"); +}