Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 19 additions & 9 deletions docs/7z-extract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
39 changes: 31 additions & 8 deletions src/sevenzip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::path::PathBuf>,
/// 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
Expand All @@ -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<u64> {
// 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)
Comment on lines +132 to +135

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Account for the container memory limit when sizing the budget

On Linux containers with a memory limit below the host's RAM, _SC_PHYS_PAGES reports host memory rather than the cgroup allowance. For example, a 512 MiB container on a host with at least 16 GiB now gets a 2 GiB parallel budget instead of the previous 256 MiB. This can cause an OOM kill during multi-block extraction: lzma2_par::plan permits additional workers and decoded blocks accumulate behind the head up to this budget. The normal extraction paths in src/extract.rs construct SevenZipLimits::default() directly, so they inherit this regression. Bound the detected memory by the effective cgroup memory limit before calculating the default.

Useful? React with 👍 / 👎.

}

#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd")))]
fn physical_memory() -> Option<u64> {
None
}

/// Which of [`SevenZipLimits`] an archive went past.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
Expand Down
67 changes: 64 additions & 3 deletions src/sevenzip/lzma2_par.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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<u64>,
/// 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<Vec<u8>>,
stop: bool,
Expand Down Expand Up @@ -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<Piece> {
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)
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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,
}),
Expand Down Expand Up @@ -1660,6 +1696,14 @@ mod tests {
}
}

/// The pieces started when the first was handed out in full.
fn opened_at_first_pop(&self) -> Option<u64> {
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<u64> {
match &self.mode {
Expand Down Expand Up @@ -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]
Expand Down
Loading
Loading