Skip to main content

stuffr_cli/bench/
memory.rs

1//! Peak memory for `stuffr bench`, measured in untimed child processes.
2//!
3//! After a row's timed runs, the parent runs the row once more, once for
4//! compression and once for decompression, each in a child: bench's own
5//! executable re-run as `stuffr __bench-memory-child <job>` (see
6//! [`ChildJob::to_args`]). `getrusage`'s `ru_maxrss` is a per-process
7//! high-water mark, which is why each measurement needs a fresh process,
8//! and why one per file in `--per-file` mode (the row reports the largest).
9//!
10//! **What a child measures.** Its 64 KiB read buffer, its 64 KiB output
11//! buffer and its open files (the compress child's output file included)
12//! are made first; then it samples its peak resident set as the baseline (the
13//! high-water so far, which is its current size, since nothing has run
14//! yet), runs the codec to the end, and reports the peak minus that
15//! baseline, saturating at 0. So the number is the codec's resident working
16//! memory plus a few small fixed buffers; memory reserved but never touched
17//! does not count. The compress child streams the input from the files
18//! (each read stops at the length snapshotted at load, as in the timed
19//! runs), so an encoder that buffers its whole input (the pure-tier zstd
20//! encoder) shows memory growing with the input: that is what using it
21//! costs. The compress child writes its compressed output to a guarded
22//! temp file the parent created and armed, `stuffr-bench-<pid>-<n>`; the
23//! decompress child then reads that file through the same 64 KiB buffered
24//! source the timed runs use. So the row is compressed once more, not
25//! twice (ruling F8), and a compress child that fails leaves nothing for
26//! the decompress side, which then shows `-` too.
27//!
28//! **Same conditions as the timed runs**: level, `--threads` (through
29//! [`governor_for`]) and `--memory-limit`. The backend is not sent: the
30//! child is the same executable, so it has the same one.
31//!
32//! **The wire.** The child prints one line on stdout, `ok <bytes>` or
33//! `err <text>`, and exits 0 or 1 to match. Anything else (a crash, a
34//! signal, no line) is a failed measurement. A failure never fails the row:
35//! its cell is `-` and the text goes to [`Memory::error`]. A refusal by
36//! `--memory-limit` (an `Error::ResourceLimit`) reads `refused by
37//! --memory-limit: …`, so it is told apart from a crash.
38//!
39//! A debug build's child refuses, as `bench` does, so this path is not
40//! reachable from the CLI tests; [`Runner`] lets the parent's logic be
41//! tested with a fake, and [`child_main`] is tested in-process.
42
43use std::ffi::{OsStr, OsString};
44use std::fs::File;
45use std::io::{self, BufWriter, Write};
46use std::path::{Path, PathBuf};
47use std::process::{Command, ExitCode, Stdio};
48use std::sync::atomic::{AtomicI32, Ordering};
49
50use stuffr::source::{GuardedSeek, Source};
51use stuffr::{Codec, DecodeOpts, EncodeOpts, Error, FormatKind};
52
53use super::measure::{
54    CHUNK, Mode, Plan, Snapshot, TempOut, fill, governor_for, read_some, shrank, temp_source,
55};
56use super::score::Memory;
57
58/// The hidden first argument that makes the binary a memory child. Not a
59/// clap subcommand: `main` checks for it before clap parses, so it is in no
60/// help text and the examples page's guard (which walks clap) never sees it.
61pub const CHILD_ARG: &str = "__bench-memory-child";
62
63/// What a debug build's child answers: its numbers would be meaningless.
64const DEBUG_CHILD_REFUSAL: &str = "memory runs from a debug build are meaningless";
65
66/// The pid of the memory child the parent is waiting for, 0 when none. Set
67/// once the child is spawned, cleared once it has been waited for; the
68/// signal cleanup reads it to kill the child before bench dies.
69pub static RUNNING_CHILD: AtomicI32 = AtomicI32::new(0);
70
71/// Which half of the round trip a child measures.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub enum Side {
74    Compress,
75    Decompress,
76}
77
78impl Side {
79    fn word(self) -> &'static str {
80        match self {
81            Side::Compress => "compress",
82            Side::Decompress => "decompress",
83        }
84    }
85}
86
87/// What one child runs. Compress: `files` concatenated as one stream,
88/// written to `out` (discarded when `None`). Decompress: exactly one file,
89/// the compressed copy; `out` is `None`.
90#[derive(Clone, Debug, PartialEq, Eq)]
91pub struct ChildJob {
92    pub side: Side,
93    pub codec: &'static str,
94    pub level: Option<i32>,
95    pub threads: Option<usize>,
96    pub memory_limit: u64,
97    pub out: Option<PathBuf>,
98    pub files: Vec<Snapshot>,
99}
100
101/// `-` for an absent level or thread count on the wire.
102const NONE: &str = "-";
103
104impl ChildJob {
105    /// The arguments after [`CHILD_ARG`]:
106    /// `<side> <codec> <level|-> <threads|-> <memory-limit> <out|-> [<len> <path>]…`,
107    /// `side` being `compress` or `decompress`, every number in decimal.
108    /// The decompress side ignores the level (the parent sends `-`). `out`
109    /// is `-` for none; the parent's is always an absolute temp path.
110    /// Paths go as they are (not through UTF-8), each its own argument.
111    pub fn to_args(&self) -> Vec<OsString> {
112        let opt = |v: Option<String>| OsString::from(v.unwrap_or_else(|| NONE.to_string()));
113        let mut args = vec![
114            OsString::from(self.side.word()),
115            OsString::from(self.codec),
116            opt(self.level.map(|l| l.to_string())),
117            opt(self.threads.map(|t| t.to_string())),
118            OsString::from(self.memory_limit.to_string()),
119            self.out
120                .clone()
121                .map_or_else(|| OsString::from(NONE), PathBuf::into_os_string),
122        ];
123        for s in &self.files {
124            args.push(OsString::from(s.len.to_string()));
125            args.push(s.path.clone().into_os_string());
126        }
127        args
128    }
129
130    /// Parses [`ChildJob::to_args`]'s form back. The codec must be one of
131    /// this build's.
132    pub fn from_args(args: &[OsString]) -> Result<Self, String> {
133        fn text<'a>(a: Option<&'a OsString>, what: &str) -> Result<&'a str, String> {
134            a.ok_or_else(|| format!("missing {what}"))?
135                .to_str()
136                .ok_or_else(|| format!("{what} is not UTF-8"))
137        }
138        fn num<T: std::str::FromStr>(s: &str, what: &str) -> Result<T, String> {
139            s.parse().map_err(|_| format!("bad {what} `{s}`"))
140        }
141        fn opt<T: std::str::FromStr>(s: &str, what: &str) -> Result<Option<T>, String> {
142            if s == NONE {
143                Ok(None)
144            } else {
145                num(s, what).map(Some)
146            }
147        }
148        let mut it = args.iter();
149        let side = match text(it.next(), "side")? {
150            "compress" => Side::Compress,
151            "decompress" => Side::Decompress,
152            other => return Err(format!("bad side `{other}`")),
153        };
154        let codec = codec_id(text(it.next(), "codec")?)?.as_str();
155        let level = opt(text(it.next(), "level")?, "level")?;
156        let threads = opt(text(it.next(), "threads")?, "threads")?;
157        let memory_limit = num(text(it.next(), "memory limit")?, "memory limit")?;
158        let out = it.next().ok_or("missing output")?;
159        let out = (out != NONE).then(|| PathBuf::from(out));
160        let mut files = Vec::new();
161        while let Some(len) = it.next() {
162            let len = num(text(Some(len), "length")?, "length")?;
163            let path = it.next().ok_or("a length without its path")?;
164            files.push(Snapshot {
165                path: path.into(),
166                len,
167            });
168        }
169        Ok(Self {
170            side,
171            codec,
172            level,
173            threads,
174            memory_limit,
175            out,
176            files,
177        })
178    }
179
180    /// The plan the timed runs used, as far as a child needs it.
181    fn plan(&self) -> Plan {
182        Plan {
183            mode: Mode::OneStream,
184            repeat: 1,
185            threads: self.threads,
186            memory_limit: self.memory_limit,
187        }
188    }
189}
190
191/// `name` as this build's codec id.
192fn codec_id(name: &str) -> Result<stuffr::FormatId, String> {
193    stuffr::registry()
194        .matrix()
195        .into_iter()
196        .find(|r| r.kind == FormatKind::Codec && r.id.as_str() == name)
197        .map(|r| r.id)
198        .ok_or_else(|| format!("`{name}` is not a codec in this build"))
199}
200
201/// A child's stdout line: `Some(Ok(n))` for `ok <n>`, `Some(Err(text))` for
202/// `err <text>` (text not empty), `None` for anything else.
203pub fn parse_reply(stdout: &[u8]) -> Option<Result<u64, String>> {
204    let line = std::str::from_utf8(stdout).ok()?.lines().next()?;
205    if let Some(n) = line.strip_prefix("ok ") {
206        if !n.bytes().all(|b| b.is_ascii_digit()) {
207            return None;
208        }
209        return n.parse().ok().map(Ok);
210    }
211    let text = line.strip_prefix("err ")?.trim();
212    (!text.is_empty()).then(|| Err(text.to_string()))
213}
214
215/// A child's result as its one stdout line (no newline inside).
216fn reply_line(r: &Result<u64, String>) -> String {
217    match r {
218        Ok(n) => format!("ok {n}"),
219        Err(e) => format!("err {}", e.replace(['\n', '\r'], " ")),
220    }
221}
222
223/// How a measurement failure reads in `mem_error`: a refusal by
224/// `--memory-limit` (`ResourceLimit`, which is also what an allocation
225/// failure becomes) says so; everything else is its own message.
226pub fn describe(e: &Error) -> String {
227    match e {
228        Error::ResourceLimit(s) => format!("refused by --memory-limit: {s}"),
229        other => other.to_string(),
230    }
231}
232
233/// A finished child: its reply when it gave a well-formed one and its exit
234/// status agrees (0 for `ok`, failure for `err`); otherwise a failure
235/// naming `status` and the first line of its stderr, if any.
236pub fn interpret(success: bool, status: &str, stdout: &[u8], stderr: &[u8]) -> Result<u64, String> {
237    match (parse_reply(stdout), success) {
238        (Some(Ok(n)), true) => Ok(n),
239        (Some(Err(e)), false) => Err(e),
240        _ => {
241            let why = String::from_utf8_lossy(stderr);
242            match why.lines().map(str::trim).find(|l| !l.is_empty()) {
243                Some(line) => Err(format!("the memory run failed ({status}): {line}")),
244                None => Err(format!("the memory run failed ({status})")),
245            }
246        }
247    }
248}
249
250/// The hidden entry `main` calls first: `None` unless `args[1]` is
251/// [`CHILD_ARG`]; otherwise runs the child, prints its reply line and
252/// returns its exit code. A debug build refuses.
253pub fn child_entry(args: &[OsString]) -> Option<ExitCode> {
254    if args.get(1).map(OsString::as_os_str) != Some(OsStr::new(CHILD_ARG)) {
255        return None;
256    }
257    // A malformed job is a usage error (exit 2): exit 1 is reserved for
258    // stuffr itself failing. The parent takes any non-zero exit with `err`.
259    let (result, usage) = if cfg!(debug_assertions) {
260        (Err(DEBUG_CHILD_REFUSAL.to_string()), None)
261    } else {
262        match ChildJob::from_args(&args[2..]) {
263            Ok(job) => (child_main(job), None),
264            Err(e) => (Err(e), Some(ExitCode::from(2))),
265        }
266    };
267    let mut out = io::stdout().lock();
268    let printed = writeln!(out, "{}", reply_line(&result)).and_then(|()| out.flush());
269    Some(match usage {
270        Some(code) => code,
271        None if result.is_ok() && printed.is_ok() => ExitCode::SUCCESS,
272        None => ExitCode::FAILURE,
273    })
274}
275
276/// The child: runs `job` and returns its peak resident memory above the
277/// baseline (see the module doc), in bytes.
278pub fn child_main(job: ChildJob) -> Result<u64, String> {
279    let reg = stuffr::registry();
280    let id = codec_id(job.codec)?;
281    match job.side {
282        Side::Compress => {
283            let codec = reg.require_encoder(id).map_err(|e| describe(&e))?;
284            let encode = EncodeOpts {
285                level: job.level,
286                governor: governor_for(&job.plan()),
287                ..Default::default()
288            };
289            codec.check_encode_opts(&encode).map_err(|e| describe(&e))?;
290            compress_child(codec.as_ref(), &encode, &job.files, job.out.as_deref())
291                .map_err(|e| describe(&e))
292        }
293        Side::Decompress => {
294            let codec = reg.require_decoder(id).map_err(|e| describe(&e))?;
295            let decode = DecodeOpts {
296                memory_limit: Some(job.memory_limit),
297                ..Default::default()
298            };
299            let [copy] = &job.files[..] else {
300                return Err(format!(
301                    "a decompress run takes one file, not {}",
302                    job.files.len()
303                ));
304            };
305            decompress_child(codec.as_ref(), &decode, copy).map_err(|e| describe(&e))
306        }
307    }
308}
309
310/// Streams `files` through the encoder into `out` (the parent's temp file,
311/// which it already created: opened here, truncated), or into a discarding
312/// sink when there is none.
313fn compress_child(
314    codec: &dyn Codec,
315    encode: &EncodeOpts,
316    files: &[Snapshot],
317    out: Option<&Path>,
318) -> stuffr::Result<u64> {
319    let mut feeds = files
320        .iter()
321        .map(|s| s.open().map(|f| (s, f)))
322        .collect::<io::Result<Vec<_>>>()?;
323    let mut buf = vec![0u8; CHUNK];
324    let dst: Box<dyn Write + Send> = match out {
325        Some(path) => Box::new(File::options().write(true).truncate(true).open(path)?),
326        None => Box::new(io::sink()),
327    };
328    let dst = BufWriter::with_capacity(CHUNK, dst);
329    let baseline = baseline_rss()?;
330    let mut sink = codec.encoder(Box::new(dst), encode)?;
331    for (snap, f) in &mut feeds {
332        feed(snap, f, &mut buf, &mut *sink)?;
333    }
334    sink.finish()?;
335    Ok(peak_rss()?.saturating_sub(baseline))
336}
337
338/// Reads `copy` through the decoder to its end, discarding the output.
339fn decompress_child(
340    codec: &dyn Codec,
341    decode: &DecodeOpts,
342    copy: &Snapshot,
343) -> stuffr::Result<u64> {
344    let src: Box<dyn Source> = Box::new(temp_source(
345        GuardedSeek::new(File::open(&copy.path)?),
346        copy.len,
347    ));
348    let mut buf = vec![0u8; CHUNK];
349    let baseline = baseline_rss()?;
350    let mut decoder = codec.decoder(src, decode)?;
351    while fill(&mut decoder, &mut buf).map_err(Error::from_decode_io)? == buf.len() {}
352    drop(decoder);
353    Ok(peak_rss()?.saturating_sub(baseline))
354}
355
356/// Writes all of `f` (`snap` opened) to `sink` through `buf`; a file that
357/// ends short of its loaded length is an error, as in the timed runs.
358fn feed(
359    snap: &Snapshot,
360    f: &mut io::Take<File>,
361    buf: &mut [u8],
362    sink: &mut dyn Write,
363) -> stuffr::Result<()> {
364    let mut read = 0u64;
365    loop {
366        let n = read_some(f, buf)?;
367        if n == 0 {
368            break;
369        }
370        read += n as u64;
371        sink.write_all(&buf[..n])?;
372    }
373    if read < snap.len {
374        return Err(shrank(snap, read));
375    }
376    Ok(())
377}
378
379/// Whether this platform's memory figures have been verified: macOS
380/// (`ru_maxrss`) and Linux (`/proc/self/status`). Elsewhere (the BSDs, and
381/// off unix) bench reports memory as not measured (ruling F9).
382pub const MEASURES: bool = cfg!(any(target_vendor = "apple", target_os = "linux"));
383
384/// The resident size just before the codec starts, in bytes.
385///
386/// macOS: `ru_maxrss`, the high-water so far, which is the current size
387/// since nothing has run yet. Linux: `VmRSS` from `/proc/self/status`, not
388/// `ru_maxrss`: exec copies the spawning process's high-water mark into the
389/// new image's `ru_maxrss` (fs/exec.c, `setmax_mm_hiwater_rss`), so there it
390/// starts at bench's own lifetime peak and would swallow the codec's.
391fn baseline_rss() -> io::Result<u64> {
392    #[cfg(target_os = "linux")]
393    {
394        proc_status_bytes(b"VmRSS:")
395    }
396    #[cfg(not(target_os = "linux"))]
397    {
398        peak_rss()
399    }
400}
401
402/// The address space's peak resident size so far, in bytes. macOS:
403/// `ru_maxrss` (bytes there). Linux: `VmHWM` from `/proc/self/status`, the
404/// high-water of this address space only, fresh at exec.
405#[cfg(target_vendor = "apple")]
406fn peak_rss() -> io::Result<u64> {
407    // SAFETY: `getrusage` only writes the `rusage` it is given, which is
408    // plain data and valid zeroed.
409    let mut usage: libc::rusage = unsafe { std::mem::zeroed() };
410    // SAFETY: as above; `usage` is a valid, writable `rusage`.
411    if unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut usage) } != 0 {
412        return Err(io::Error::last_os_error());
413    }
414    Ok(u64::try_from(usage.ru_maxrss).unwrap_or(0))
415}
416
417#[cfg(target_os = "linux")]
418fn peak_rss() -> io::Result<u64> {
419    proc_status_bytes(b"VmHWM:")
420}
421
422/// Elsewhere memory is not measured; bench never starts a child there.
423#[cfg(not(any(target_vendor = "apple", target_os = "linux")))]
424fn peak_rss() -> io::Result<u64> {
425    Err(io::Error::new(
426        io::ErrorKind::Unsupported,
427        "memory is not measured on this platform",
428    ))
429}
430
431/// `field` (with its colon, e.g. `VmHWM:`) of `/proc/self/status`, given
432/// there in kB, as bytes. Read into a buffer on the stack, so sampling
433/// allocates nothing on the heap that the codec's figure could include.
434#[cfg(target_os = "linux")]
435fn proc_status_bytes(field: &[u8]) -> io::Result<u64> {
436    use std::io::Read;
437    let mut buf = [0u8; 8192];
438    let mut f = File::open("/proc/self/status")?;
439    let mut len = 0;
440    while len < buf.len() {
441        match f.read(&mut buf[len..]) {
442            Ok(0) => break,
443            Ok(n) => len += n,
444            Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
445            Err(e) => return Err(e),
446        }
447    }
448    status_field_kib(&buf[..len], field)
449        .map(|kib| kib.saturating_mul(1024))
450        .ok_or_else(|| io::Error::other("no memory figure in /proc/self/status"))
451}
452
453/// The number on the line starting with `field` in a `/proc/<pid>/status`
454/// text (`VmHWM:\t   1234 kB`), in kB.
455#[cfg(any(target_os = "linux", test))]
456fn status_field_kib(text: &[u8], field: &[u8]) -> Option<u64> {
457    let line = text.split(|&b| b == b'\n').find(|l| l.starts_with(field))?;
458    let rest = line[field.len()..].trim_ascii_start();
459    let digits = rest.iter().take_while(|b| b.is_ascii_digit()).count();
460    if digits == 0 {
461        return None;
462    }
463    rest[..digits].iter().try_fold(0u64, |n, &b| {
464        n.checked_mul(10)?.checked_add(u64::from(b - b'0'))
465    })
466}
467
468/// Runs one child job and returns its reply. The real one spawns a
469/// process ([`ProcessRunner`]); tests inject a fake.
470pub trait Runner {
471    fn run(&mut self, job: &ChildJob) -> Result<u64, String>;
472}
473
474/// Runs each job as `<this executable> __bench-memory-child …`, with stdin
475/// closed and stdout and stderr captured, keeping its pid in
476/// [`RUNNING_CHILD`] while it runs. The executable is resolved once, when
477/// the runner is made at the start of the run, and reused for every child.
478pub struct ProcessRunner {
479    exe: Result<PathBuf, String>,
480}
481
482impl Default for ProcessRunner {
483    fn default() -> Self {
484        Self::new()
485    }
486}
487
488impl ProcessRunner {
489    pub fn new() -> Self {
490        Self {
491            exe: std::env::current_exe()
492                .map_err(|e| format!("cannot find bench's own executable: {e}")),
493        }
494    }
495}
496
497impl Runner for ProcessRunner {
498    fn run(&mut self, job: &ChildJob) -> Result<u64, String> {
499        let exe = self.exe.clone()?;
500        // Bench's signals are held back from the spawn until the pid is
501        // stored, so a signal sent to bench alone in between is delivered
502        // with the pid known, and the cleanup kills the child (no orphan).
503        // The child does not inherit the mask: std resets it before exec.
504        let child = crate::compat::with_run_signals_held(|| {
505            let child = Command::new(exe)
506                .arg(CHILD_ARG)
507                .args(job.to_args())
508                .stdin(Stdio::null())
509                .stdout(Stdio::piped())
510                .stderr(Stdio::piped())
511                .spawn()?;
512            RUNNING_CHILD.store(i32::try_from(child.id()).unwrap_or(0), Ordering::SeqCst);
513            Ok::<_, io::Error>(child)
514        })
515        .map_err(|e| format!("cannot start the memory run: {e}"))?;
516        // Known window, accepted (ruling F7): `wait_with_output` reaps the
517        // child before the clear below, so a signal arriving in between
518        // makes the cleanup `kill()` a pid that is no longer ours. It lasts
519        // microseconds and pids are handed out sequentially, so reuse
520        // inside it is theoretical. Clearing before the wait instead would
521        // leave the child running (orphaned) on a bare SIGTERM to bench.
522        let out = child.wait_with_output();
523        RUNNING_CHILD.store(0, Ordering::SeqCst);
524        let out = out.map_err(|e| format!("the memory run failed: {e}"))?;
525        interpret(
526            out.status.success(),
527            &out.status.to_string(),
528            &out.stdout,
529            &out.stderr,
530        )
531    }
532}
533
534/// [`measure_memory_with`] with real child processes (`runner`). Only
535/// where [`MEASURES`]: elsewhere the caller reports memory as not measured.
536pub fn measure_memory(
537    runner: &mut ProcessRunner,
538    codec: &'static str,
539    level: Option<i32>,
540    plan: &Plan,
541    input_files: &[Snapshot],
542) -> Memory {
543    measure_memory_with(runner, codec, level, plan, input_files)
544}
545
546/// One row's memory under `plan`: a compress child and a decompress child
547/// per stream (`plan.mode`: one stream over every file, or one per file),
548/// reporting each side's largest peak. Per stream the parent creates an
549/// armed temp file, the compress child writes the compressed stream into
550/// it, and the decompress child reads it back; it is removed before the
551/// next stream begins. Strictly after the row's timed runs.
552///
553/// A side whose child fails for any stream is `None`, and the first
554/// failure's text, prefixed by its side, is `error`. A failed decompress
555/// child leaves the compress side standing; a failed compress child (or a
556/// temp file that cannot be made) leaves no copy, so both sides are `None`.
557/// Never an error of its own.
558pub fn measure_memory_with(
559    runner: &mut dyn Runner,
560    codec: &'static str,
561    level: Option<i32>,
562    plan: &Plan,
563    input_files: &[Snapshot],
564) -> Memory {
565    // bench always has at least one input; with none there is nothing to
566    // measure, and a zero would wrongly win "least memory".
567    if input_files.is_empty() {
568        return Memory {
569            error: Some("no input to measure".into()),
570            ..Memory::default()
571        };
572    }
573    let streams: Vec<&[Snapshot]> = match plan.mode {
574        Mode::OneStream => vec![input_files],
575        Mode::PerFile => input_files.chunks(1).collect(),
576    };
577    // The decompress side has no level: it is sent as `-`.
578    let job = |side, out, files| ChildJob {
579        side,
580        codec,
581        level: if side == Side::Compress { level } else { None },
582        threads: plan.threads,
583        memory_limit: plan.memory_limit,
584        out,
585        files,
586    };
587    let mut compress = Some(0u64);
588    let mut decompress = Some(0u64);
589    let mut error = None;
590    let mut fail = |side: Side, e: String, cell: &mut Option<u64>| {
591        *cell = None;
592        error.get_or_insert_with(|| format!("{}: {e}", side.word()));
593    };
594    for files in streams {
595        let Some(peak) = compress else { break };
596        // The copy lives until this stream's decompress child is done; the
597        // compress child opens it by name, so the parent's handle closes.
598        let copy = match TempOut::create() {
599            Ok((copy, _file)) => copy,
600            Err(e) => {
601                fail(
602                    Side::Compress,
603                    format!("cannot make the temp file: {e}"),
604                    &mut compress,
605                );
606                decompress = None;
607                break;
608            }
609        };
610        let out = Some(copy.path().to_path_buf());
611        match runner.run(&job(Side::Compress, out, files.to_vec())) {
612            Ok(n) => compress = Some(peak.max(n)),
613            Err(e) => {
614                fail(
615                    Side::Compress,
616                    format!("{e} (so no decompress run)"),
617                    &mut compress,
618                );
619                decompress = None;
620                break;
621            }
622        }
623        if let Some(peak) = decompress {
624            let r = std::fs::metadata(copy.path())
625                .map_err(|e| format!("cannot read the compressed copy: {e}"))
626                .and_then(|m| {
627                    let snap = Snapshot {
628                        path: copy.path().to_path_buf(),
629                        len: m.len(),
630                    };
631                    runner.run(&job(Side::Decompress, None, vec![snap]))
632                });
633            match r {
634                Ok(n) => decompress = Some(peak.max(n)),
635                Err(e) => fail(Side::Decompress, e, &mut decompress),
636            }
637        }
638    }
639    Memory {
640        compress,
641        decompress,
642        error,
643    }
644}
645
646#[cfg(test)]
647mod tests {
648    use super::*;
649    use std::fs;
650    use std::path::PathBuf;
651    use std::sync::atomic::{AtomicU32, Ordering};
652
653    /// A scratch directory `stuffr-benchmem-<pid>-<n>`, removed on drop.
654    struct Scratch(PathBuf);
655
656    impl Scratch {
657        fn new() -> Self {
658            static N: AtomicU32 = AtomicU32::new(0);
659            let n = N.fetch_add(1, Ordering::Relaxed);
660            let dir =
661                std::env::temp_dir().join(format!("stuffr-benchmem-{}-{n}", std::process::id()));
662            fs::create_dir_all(&dir).unwrap();
663            Scratch(dir)
664        }
665
666        fn file(&self, name: &str, bytes: &[u8]) -> Snapshot {
667            let path = self.0.join(name);
668            fs::write(&path, bytes).unwrap();
669            Snapshot {
670                path,
671                len: bytes.len() as u64,
672            }
673        }
674    }
675
676    impl Drop for Scratch {
677        fn drop(&mut self) {
678            let _ = fs::remove_dir_all(&self.0);
679        }
680    }
681
682    /// Serialises the tests that arm the process-wide signal cleanup (the
683    /// parent's temp copies are armed).
684    fn armed_lock() -> std::sync::MutexGuard<'static, ()> {
685        crate::compat::ARM_TEST_LOCK
686            .lock()
687            .unwrap_or_else(|e| e.into_inner())
688    }
689
690    fn text(len: usize, seed: u8) -> Vec<u8> {
691        b"the quick brown fox jumps over the lazy dog, "
692            .iter()
693            .cycle()
694            .enumerate()
695            .map(|(i, &b)| b.wrapping_add(seed).wrapping_add((i / 997) as u8))
696            .take(len)
697            .collect()
698    }
699
700    fn plan(mode: Mode) -> Plan {
701        Plan {
702            mode,
703            repeat: 1,
704            threads: None,
705            memory_limit: 1 << 30,
706        }
707    }
708
709    #[test]
710    fn measure_memory_with_no_input_files_measures_nothing() {
711        struct Counting(u32);
712        impl Runner for Counting {
713            fn run(&mut self, _job: &ChildJob) -> Result<u64, String> {
714                self.0 += 1;
715                Ok(1)
716            }
717        }
718        let mut stub = Counting(0);
719        let got = measure_memory_with(&mut stub, "lz4", None, &plan(Mode::OneStream), &[]);
720        assert_eq!(
721            got,
722            Memory {
723                compress: None,
724                decompress: None,
725                error: Some("no input to measure".to_string()),
726            }
727        );
728        assert_eq!(stub.0, 0);
729    }
730
731    fn bench_temps() -> Vec<String> {
732        let prefix = format!("stuffr-bench-{}-", std::process::id());
733        fs::read_dir(std::env::temp_dir())
734            .unwrap()
735            .filter_map(|e| e.ok()?.file_name().into_string().ok())
736            .filter(|n| n.starts_with(&prefix))
737            .collect()
738    }
739
740    /// A runner that answers from `answer` and records every job it saw,
741    /// with whether each job's files (and output) existed while it ran. A
742    /// compress job that succeeds writes a stand-in copy to its output, as
743    /// the real child writes the compressed stream there.
744    struct Fake<F: FnMut(&ChildJob) -> Result<u64, String>> {
745        answer: F,
746        seen: Vec<(ChildJob, bool)>,
747    }
748
749    impl<F: FnMut(&ChildJob) -> Result<u64, String>> Runner for Fake<F> {
750        fn run(&mut self, job: &ChildJob) -> Result<u64, String> {
751            let present = job.files.iter().all(|s| s.path.exists())
752                && job.out.as_ref().is_none_or(|o| o.exists());
753            self.seen.push((job.clone(), present));
754            let r = (self.answer)(job);
755            if let (Ok(_), Some(out)) = (&r, &job.out) {
756                fs::write(out, b"copy").unwrap();
757            }
758            r
759        }
760    }
761
762    fn fake<F: FnMut(&ChildJob) -> Result<u64, String>>(answer: F) -> Fake<F> {
763        Fake {
764            answer,
765            seen: Vec::new(),
766        }
767    }
768
769    #[test]
770    fn child_args_round_trip() {
771        #[cfg(unix)]
772        let odd: PathBuf = {
773            use std::os::unix::ffi::OsStringExt;
774            OsString::from_vec(b"/tmp/a b\xff/-c".to_vec()).into()
775        };
776        #[cfg(not(unix))]
777        let odd = PathBuf::from("C:\\a b\\-c");
778        let jobs = [
779            ChildJob {
780                side: Side::Compress,
781                codec: "xz",
782                level: Some(9),
783                threads: Some(4),
784                memory_limit: 123_456_789,
785                out: Some(odd.join("out")),
786                files: vec![
787                    Snapshot {
788                        path: odd.clone(),
789                        len: 7,
790                    },
791                    Snapshot {
792                        path: PathBuf::from("-"),
793                        len: 0,
794                    },
795                ],
796            },
797            ChildJob {
798                side: Side::Decompress,
799                codec: "zstd",
800                level: Some(-5),
801                threads: None,
802                memory_limit: u64::MAX,
803                out: None,
804                files: vec![Snapshot {
805                    path: odd,
806                    len: u64::MAX,
807                }],
808            },
809            ChildJob {
810                side: Side::Compress,
811                codec: "lz4",
812                level: None,
813                threads: None,
814                memory_limit: 0,
815                out: None,
816                files: Vec::new(),
817            },
818        ];
819        for job in jobs {
820            let args = job.to_args();
821            assert_eq!(ChildJob::from_args(&args), Ok(job.clone()), "{args:?}");
822        }
823        // Not a codec of this build, a bad side, a missing output, a
824        // missing length, a bad level.
825        for bad in [
826            &["compress", "nope", "-", "-", "1", "-"][..],
827            &["sideways", "lz4", "-", "-", "1", "-"],
828            &["compress", "lz4", "-", "-", "1"],
829            &["compress", "lz4", "-", "-", "1", "/out", "/x"],
830            &["compress", "lz4", "x", "-", "1", "-"],
831        ] {
832            let args: Vec<OsString> = bad.iter().map(OsString::from).collect();
833            assert!(ChildJob::from_args(&args).is_err(), "{bad:?}");
834        }
835    }
836
837    #[test]
838    fn proc_status_fields_parse_in_kib() {
839        // The kernel pads the numbers with spaces; built, not spelled, so
840        // no literal carries a run of them.
841        let pad = " ".repeat(4);
842        let status = format!(
843            "Name:\tstuffr\nVmPeak:\t{pad}123456 kB\nVmHWM:\t{pad}6372 kB\nVmRSS:\t{pad}6100 kB\n"
844        );
845        let status = status.as_bytes();
846        assert_eq!(status_field_kib(status, b"VmHWM:"), Some(6372));
847        assert_eq!(status_field_kib(status, b"VmRSS:"), Some(6100));
848        assert_eq!(status_field_kib(status, b"VmSwap:"), None);
849        assert_eq!(status_field_kib(b"VmHWM:\t kB\n", b"VmHWM:"), None);
850    }
851
852    #[test]
853    fn child_reply_parses_ok_and_err() {
854        assert_eq!(parse_reply(b"ok 12345\n"), Some(Ok(12345)));
855        assert_eq!(parse_reply(b"ok 0\n"), Some(Ok(0)));
856        assert_eq!(
857            parse_reply(b"err refused by --memory-limit: too big\n"),
858            Some(Err("refused by --memory-limit: too big".into()))
859        );
860        for junk in [
861            &b""[..],
862            b"ok\n",
863            b"ok -3\n",
864            b"ok 12x\n",
865            b"hello\n",
866            b"err \n",
867        ] {
868            assert_eq!(
869                parse_reply(junk),
870                None,
871                "{:?}",
872                String::from_utf8_lossy(junk)
873            );
874        }
875    }
876
877    /// The env vars that make [`memory_probe`] run, and the prefix its
878    /// reply line carries in libtest's captured output.
879    #[cfg(any(target_vendor = "apple", target_os = "linux"))]
880    const PROBE_CODEC: &str = "STUFFR_BENCH_MEMORY_PROBE_CODEC";
881    #[cfg(any(target_vendor = "apple", target_os = "linux"))]
882    const PROBE_LEVEL: &str = "STUFFR_BENCH_MEMORY_PROBE_LEVEL";
883    #[cfg(any(target_vendor = "apple", target_os = "linux"))]
884    const PROBE_FILE: &str = "STUFFR_BENCH_MEMORY_PROBE_FILE";
885    #[cfg(any(target_vendor = "apple", target_os = "linux"))]
886    const PROBE_MARK: &str = "memory-probe-reply: ";
887
888    /// Not a test of its own: [`fresh_processes_measure_xz_9_above_lz4`]
889    /// re-runs this test binary with only this test, so the compress child
890    /// it runs has a process (and an `ru_maxrss` high-water mark) to
891    /// itself. Prints the child's reply line after [`PROBE_MARK`]. Does
892    /// nothing without the env vars.
893    #[cfg(any(target_vendor = "apple", target_os = "linux"))]
894    #[test]
895    #[ignore = "a probe that fresh_processes_measure_xz_9_above_lz4 runs in its own process"]
896    fn memory_probe() {
897        let (Ok(codec), Ok(level), Some(file)) = (
898            std::env::var(PROBE_CODEC),
899            std::env::var(PROBE_LEVEL),
900            std::env::var_os(PROBE_FILE),
901        ) else {
902            return;
903        };
904        let path = PathBuf::from(file);
905        let len = fs::metadata(&path).unwrap().len();
906        let args: Vec<OsString> = ["compress", &codec, &level, "-", "1073741824", "-"]
907            .iter()
908            .map(OsString::from)
909            .chain([OsString::from(len.to_string()), path.into_os_string()])
910            .collect();
911        let job = ChildJob::from_args(&args).unwrap();
912        println!("{PROBE_MARK}{}", reply_line(&child_main(job)));
913    }
914
915    /// The compress child's figures for xz -9 and lz4 over 1 MiB, each
916    /// from a fresh process running [`memory_probe`]: xz -9's encoder (a
917    /// 64 MiB dictionary's hash table) touches more than lz4's. Each figure
918    /// is that process's own peak above its own baseline, so no other test
919    /// can move it.
920    #[cfg(any(target_vendor = "apple", target_os = "linux"))]
921    #[test]
922    fn fresh_processes_measure_xz_9_above_lz4() {
923        let dir = Scratch::new();
924        let input = dir.file("in", &text(1 << 20, 3));
925        let probe = |codec: &str, level: &str| -> u64 {
926            let out = std::process::Command::new(std::env::current_exe().unwrap())
927                .args([
928                    "--exact",
929                    "bench::memory::tests::memory_probe",
930                    "--ignored",
931                    "--nocapture",
932                    "--test-threads=1",
933                ])
934                .env(PROBE_CODEC, codec)
935                .env(PROBE_LEVEL, level)
936                .env(PROBE_FILE, &input.path)
937                .stdin(std::process::Stdio::null())
938                .output()
939                .unwrap();
940            let stdout = String::from_utf8_lossy(&out.stdout);
941            let reply = stdout
942                .lines()
943                .find_map(|l| l.split_once(PROBE_MARK).map(|(_, r)| r));
944            match reply.and_then(|r| parse_reply(r.as_bytes())) {
945                Some(Ok(n)) if out.status.success() => n,
946                _ => panic!(
947                    "{codec} probe gave no `ok` reply ({}):\n--- stdout\n{stdout}\n--- stderr\n{}",
948                    out.status,
949                    String::from_utf8_lossy(&out.stderr)
950                ),
951            }
952        };
953        let lz4 = probe("lz4", "-");
954        let xz = probe("xz", "9");
955        assert!(xz > lz4, "xz -9 {xz} vs lz4 {lz4}");
956    }
957
958    /// `input` compressed by the compress child (in-process) into the
959    /// existing file `name` in `dir`, as the parent's temp file is filled.
960    #[cfg(any(target_vendor = "apple", target_os = "linux"))]
961    fn compressed_by_the_child(
962        dir: &Scratch,
963        name: &str,
964        codec: &'static str,
965        level: Option<i32>,
966        input: &Snapshot,
967    ) -> Snapshot {
968        let out = dir.file(name, b"stale bytes the child must truncate");
969        let c = child_main(ChildJob {
970            side: Side::Compress,
971            codec,
972            level,
973            threads: None,
974            memory_limit: 1 << 30,
975            out: Some(out.path.clone()),
976            files: vec![input.clone()],
977        });
978        assert!(c.is_ok(), "{codec}: {c:?}");
979        let len = fs::metadata(&out.path).unwrap().len();
980        Snapshot {
981            path: out.path,
982            len,
983        }
984    }
985
986    /// The compress child writes the compressed stream to its output file
987    /// (truncating what was there), and the decompress child runs to the
988    /// end over it and gets the input back. Only that each succeeds is
989    /// checked of the figures: in-process, they are this whole test
990    /// binary's high-water mark, shared with every test beside it.
991    #[cfg(any(target_vendor = "apple", target_os = "linux"))]
992    #[test]
993    fn the_compress_child_writes_the_copy_the_decompress_child_reads() {
994        let dir = Scratch::new();
995        let original = text(1 << 20, 3);
996        let input = dir.file("in", &original);
997        for (codec, level) in [("lz4", None), ("xz", Some(9))] {
998            let copy = compressed_by_the_child(&dir, codec, codec, level, &input);
999            let id = codec_id(codec).unwrap();
1000            let decoder = stuffr::registry().require_decoder(id).unwrap();
1001            let mut back = Vec::new();
1002            let src: Box<dyn Source> = Box::new(temp_source(
1003                GuardedSeek::new(File::open(&copy.path).unwrap()),
1004                copy.len,
1005            ));
1006            io::Read::read_to_end(
1007                &mut decoder.decoder(src, &DecodeOpts::default()).unwrap(),
1008                &mut back,
1009            )
1010            .unwrap();
1011            assert!(
1012                back == original,
1013                "{codec}: the copy does not decode to the input"
1014            );
1015            let d = child_main(ChildJob {
1016                side: Side::Decompress,
1017                codec,
1018                level: None,
1019                threads: None,
1020                memory_limit: 1 << 30,
1021                out: None,
1022                files: vec![copy],
1023            });
1024            assert!(d.is_ok(), "{codec}: {d:?}");
1025        }
1026    }
1027
1028    #[test]
1029    fn per_file_reports_the_maximum() {
1030        let _g = armed_lock();
1031        let dir = Scratch::new();
1032        let files = vec![
1033            dir.file("a", &text(10_000, 0)),
1034            dir.file("b", &text(30_000, 1)),
1035            dir.file("c", &text(20_000, 2)),
1036        ];
1037        // Compress answers 100 x the file's length; decompress answers by
1038        // order: 5, 9, 2.
1039        let mut d = [5u64, 9, 2].into_iter();
1040        let mut r = fake(|job: &ChildJob| match job.side {
1041            Side::Compress => Ok(job.files[0].len * 100),
1042            Side::Decompress => Ok(d.next().unwrap()),
1043        });
1044        let m = measure_memory_with(&mut r, "gzip", Some(6), &plan(Mode::PerFile), &files);
1045        assert_eq!(
1046            m,
1047            Memory {
1048                compress: Some(3_000_000),
1049                decompress: Some(9),
1050                error: None
1051            }
1052        );
1053        // One child pair per file, each child given exactly its one file
1054        // (compress: the input, writing to the temp copy; decompress: that
1055        // copy, present, at the length the compress child left it).
1056        let sides: Vec<Side> = r.seen.iter().map(|(j, _)| j.side).collect();
1057        use Side::{Compress as C, Decompress as D};
1058        assert_eq!(sides, [C, D, C, D, C, D]);
1059        for (i, (job, present)) in r.seen.iter().enumerate() {
1060            assert_eq!(job.files.len(), 1);
1061            assert!(present, "job {i}'s file and output should exist");
1062            let level = (job.side == Side::Compress).then_some(6);
1063            assert_eq!((job.codec, job.level), ("gzip", level));
1064            if job.side == Side::Compress {
1065                assert_eq!(job.files[0], files[i / 2]);
1066                assert!(job.out.is_some(), "a compress child writes the copy");
1067            } else {
1068                assert_eq!(job.out, None);
1069                assert_eq!(job.files[0].len, 4, "the length the compress child wrote");
1070                assert_eq!(Some(&job.files[0].path), r.seen[i - 1].0.out.as_ref());
1071            }
1072        }
1073
1074        // One stream: one pair, the compress child given every file.
1075        let mut r = fake(|job: &ChildJob| Ok(job.files.iter().map(|s| s.len).sum()));
1076        let m = measure_memory_with(&mut r, "gzip", None, &plan(Mode::OneStream), &files);
1077        assert_eq!(m.compress, Some(60_000));
1078        assert!(m.decompress.is_some_and(|n| n > 0));
1079        assert_eq!(r.seen.len(), 2);
1080        assert_eq!(r.seen[0].0.files, files);
1081        assert_eq!(r.seen[1].0.files.len(), 1);
1082    }
1083
1084    #[test]
1085    fn a_failed_child_gives_dashes_and_an_error() {
1086        let _g = armed_lock();
1087        let dir = Scratch::new();
1088        let files = vec![
1089            dir.file("a", &text(10_000, 0)),
1090            dir.file("b", &text(10_000, 1)),
1091        ];
1092        // The second file's compress child fails: it left no copy, so
1093        // there is no decompress run for that file and both cells are
1094        // dashes (ruling F8); the error says why.
1095        let mut n = 0;
1096        let mut r = fake(|job: &ChildJob| match job.side {
1097            Side::Compress => {
1098                n += 1;
1099                if n == 2 {
1100                    Err("the memory run failed (signal: 9 (SIGKILL))".into())
1101                } else {
1102                    Ok(10)
1103                }
1104            }
1105            Side::Decompress => Ok(20),
1106        });
1107        let m = measure_memory_with(&mut r, "gzip", None, &plan(Mode::PerFile), &files);
1108        assert_eq!(m.compress, None);
1109        assert_eq!(m.decompress, None);
1110        let e = m.error.unwrap();
1111        assert!(e.starts_with("compress: ") && e.contains("SIGKILL"), "{e}");
1112        assert!(e.contains("no decompress run"), "{e}");
1113        // No child ran after the failure: two compress, one decompress.
1114        assert_eq!(r.seen.len(), 3);
1115
1116        // A failed decompress child leaves the compress side standing
1117        // (spec call 16).
1118        let mut r = fake(|job: &ChildJob| match job.side {
1119            Side::Compress => Ok(10),
1120            Side::Decompress => Err("the memory run failed (exit status: 1)".into()),
1121        });
1122        let m = measure_memory_with(&mut r, "gzip", None, &plan(Mode::PerFile), &files);
1123        assert_eq!((m.compress, m.decompress), (Some(10), None));
1124        assert!(m.error.unwrap().starts_with("decompress: "));
1125
1126        // Both sides failing: two dashes.
1127        let mut r = fake(|_: &ChildJob| Err("boom".to_string()));
1128        let m = measure_memory_with(&mut r, "gzip", None, &plan(Mode::OneStream), &files);
1129        assert_eq!((m.compress, m.decompress), (None, None));
1130        assert!(m.error.unwrap().contains("boom"));
1131
1132        // A child that printed no reply, or exited badly, is a failure.
1133        assert!(interpret(false, "exit status: 101", b"", b"thread 'main' panicked\n").is_err());
1134        assert!(interpret(true, "exit status: 0", b"garbage\n", b"").is_err());
1135        assert!(interpret(false, "signal: 9 (SIGKILL)", b"ok 5\n", b"").is_err());
1136        assert_eq!(interpret(true, "exit status: 0", b"ok 5\n", b""), Ok(5));
1137        assert_eq!(
1138            interpret(false, "exit status: 1", b"err nope\n", b""),
1139            Err("nope".into())
1140        );
1141    }
1142
1143    #[test]
1144    fn a_refusal_names_the_memory_limit() {
1145        let refusal = describe(&stuffr::Error::ResourceLimit(
1146            "xz: header declares a dictionary needing 64 MiB".into(),
1147        ));
1148        assert!(
1149            refusal.starts_with("refused by --memory-limit"),
1150            "{refusal}"
1151        );
1152        assert!(refusal.contains("64 MiB"), "{refusal}");
1153        // Anything else keeps its own text.
1154        let corrupt = describe(&stuffr::Error::Corrupt("bad".into()));
1155        assert!(!corrupt.contains("--memory-limit"), "{corrupt}");
1156
1157        // The parent carries the child's refusal into the row's error.
1158        let _g = armed_lock();
1159        let dir = Scratch::new();
1160        let files = vec![dir.file("a", &text(10_000, 0))];
1161        let mut r = fake(|job: &ChildJob| match job.side {
1162            Side::Compress => Err(refusal.clone()),
1163            Side::Decompress => Ok(1),
1164        });
1165        let m = measure_memory_with(&mut r, "gzip", None, &plan(Mode::OneStream), &files);
1166        assert_eq!(m.compress, None);
1167        assert!(
1168            m.error.unwrap().contains("refused by --memory-limit"),
1169            "the refusal is distinguishable from a crash"
1170        );
1171    }
1172
1173    /// The pure xz decoder refuses a header whose dictionary exceeds the
1174    /// limit; the child reports that as a refusal. (The C tier's decoder
1175    /// takes no limit, so this is pure-tier only.)
1176    #[cfg(all(
1177        any(target_vendor = "apple", target_os = "linux"),
1178        not(feature = "xz-c")
1179    ))]
1180    #[test]
1181    fn a_child_refusal_names_the_memory_limit() {
1182        let dir = Scratch::new();
1183        let input = dir.file("in", &text(100_000, 0));
1184        let copy = compressed_by_the_child(&dir, "in.xz", "xz", Some(9), &input);
1185        let r = child_main(ChildJob {
1186            side: Side::Decompress,
1187            codec: "xz",
1188            level: None,
1189            threads: None,
1190            memory_limit: 1 << 20,
1191            out: None,
1192            files: vec![copy],
1193        });
1194        let e = r.unwrap_err();
1195        assert!(e.starts_with("refused by --memory-limit"), "{e}");
1196    }
1197
1198    #[test]
1199    fn temp_copies_are_removed() {
1200        let _g = armed_lock();
1201        let dir = Scratch::new();
1202        let files = vec![
1203            dir.file("a", &text(10_000, 0)),
1204            dir.file("b", &text(10_000, 1)),
1205        ];
1206        assert_eq!(bench_temps(), Vec::<String>::new());
1207        for mode in [Mode::OneStream, Mode::PerFile] {
1208            // While a decompress child runs, its copy exists and is the
1209            // only bench temp file: per-file copies do not pile up.
1210            let mut r = fake(|job: &ChildJob| {
1211                if job.side == Side::Decompress {
1212                    assert_eq!(bench_temps().len(), 1);
1213                }
1214                Ok(1)
1215            });
1216            let m = measure_memory_with(&mut r, "gzip", None, &plan(mode), &files);
1217            assert_eq!(m.error, None);
1218            assert!(r.seen.iter().all(|(_, present)| *present));
1219            assert_eq!(bench_temps(), Vec::<String>::new(), "{mode:?}");
1220        }
1221        // A failed child removes its copy too.
1222        let mut r = fake(|_: &ChildJob| Err("boom".to_string()));
1223        let _ = measure_memory_with(&mut r, "gzip", None, &plan(Mode::PerFile), &files);
1224        assert_eq!(bench_temps(), Vec::<String>::new());
1225    }
1226}