1use 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
58pub const CHILD_ARG: &str = "__bench-memory-child";
62
63const DEBUG_CHILD_REFUSAL: &str = "memory runs from a debug build are meaningless";
65
66pub static RUNNING_CHILD: AtomicI32 = AtomicI32::new(0);
70
71#[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#[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
101const NONE: &str = "-";
103
104impl ChildJob {
105 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 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 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
191fn 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
201pub 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
215fn 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
223pub 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
233pub 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
250pub 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 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
276pub 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
310fn 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
338fn 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(©.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
356fn 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
379pub const MEASURES: bool = cfg!(any(target_vendor = "apple", target_os = "linux"));
383
384fn 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#[cfg(target_vendor = "apple")]
406fn peak_rss() -> io::Result<u64> {
407 let mut usage: libc::rusage = unsafe { std::mem::zeroed() };
410 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#[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#[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#[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
468pub trait Runner {
471 fn run(&mut self, job: &ChildJob) -> Result<u64, String>;
472}
473
474pub 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 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 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
534pub 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
546pub 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 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 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 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 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 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 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 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 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 #[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 #[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 #[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 #[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 #[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(©.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 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 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 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 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 assert_eq!(r.seen.len(), 3);
1115
1116 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 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 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 let corrupt = describe(&stuffr::Error::Corrupt("bad".into()));
1155 assert!(!corrupt.contains("--memory-limit"), "{corrupt}");
1156
1157 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 #[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 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 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}