forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

dumpio.rs568 lines, 22.4 KiBHistoryRawDownload
1//! Loud dump writing: a dump that cannot hold every byte it claims to hold is
2//! a failure, not a diagnostic artefact.
3//!
4//! lane-av1dumploud: every dump site in this crate wrote through
5//! `let _ = f.write_all(..)`. A full filesystem, an `RLIMIT_FSIZE`, or any other
6//! `ENOSPC`/`EFBIG` therefore left a SHORT file on disk and nothing said so.
7//! Measured consequence, twice in one day: a sentinel-vs-plain hash difference
8//! that read as decoder nondeterminism reproduced bit-for-bit as a truncated
9//! dump (`lanes/unwritten-dep.report.md`: frames 0..4 complete plus 13 320 192
10//! bytes of frame 5, with `EC_AV1_FINAL_DUMP`'s discarded write error), and an
11//! empty dump read as instability. That artefact started a whole defect class,
12//! and a silently wrong diagnostic is worse than a loud one, so every dump site
13//! goes through [`LoudDump`]: the caller states the expected byte count from the
14//! geometry it already has, the writer checks that count twice -- once against
15//! the bytes it was handed, once against the file's own length on disk -- and
16//! any shortfall aborts the decode with the file, the counts, and the OS error.
17//!
18//! The success path is byte-identical to the old `write_all` loop: same bytes,
19//! same order, same file names.
20//!
21//! The failure path is a panic, not a returned `Result`: the dump sites sit in
22//! the middle of `fn decode_*` functions with no error channel for them, and a
23//! dump that failed IS a decode failure (the run's measurement is void). This
24//! is a debug instrument -- it only runs when its env var is set -- so the
25//! panic cannot affect a normal decode.
26
27use std::fs::{File, OpenOptions};
28use std::io::Write;
29use std::path::{Path, PathBuf};
30
31/// One dump file, with the byte count it owes accounted for as it goes.
32pub struct LoudDump {
33 /// Human-readable label for the failure line: the env var, or
34 /// `VAR.suffix` when the file names something the var alone does not.
35 site: String,
36 path: PathBuf,
37 file: Option<File>,
38 written: usize,
39 /// `None` only for a stream whose total length is genuinely unknowable at
40 /// open time (an append-mode text table). Short-write detection still
41 /// applies -- `write_all` reports a short write as `Err` -- but the failure
42 /// line then carries no expected count, because inventing one would be a
43 /// guess.
44 expected: Option<usize>,
45}
46
47impl LoudDump {
48 /// Open `path` for `site`, expecting exactly `expected` bytes in total.
49 ///
50 /// Failing to CREATE is loud too: a requested dump that does not exist is
51 /// the same silent hole as one that is short (the reader sees no file, or
52 /// an empty one), and it is the more common of the two (a missing parent
53 /// directory, a path a sweep reused as a directory).
54 pub fn create(site: &str, path: impl AsRef<Path>, expected: usize) -> Self {
55 let path = path.as_ref().to_path_buf();
56 let file = File::create(&path).unwrap_or_else(|e| {
57 abort(
58 site,
59 &path,
60 0,
61 Some(expected),
62 &format!("could not create the dump file: {e}"),
63 )
64 });
65 Self {
66 site: site.to_string(),
67 path,
68 file: Some(file),
69 written: 0,
70 expected: Some(expected),
71 }
72 }
73
74 /// Open `path` for `site` in APPEND mode with no knowable total length --
75 /// the CDF-table text dump, whose file spans every frame of a run. Write
76 /// errors are still fatal; the length check is simply absent (see
77 /// [`LoudDump::expected`]).
78 pub fn append_unknown(site: &str, path: impl AsRef<Path>) -> Self {
79 let path = path.as_ref().to_path_buf();
80 let file = OpenOptions::new()
81 .create(true)
82 .append(true)
83 .open(&path)
84 .unwrap_or_else(|e| {
85 abort(
86 site,
87 &path,
88 0,
89 None,
90 &format!("could not open the dump file: {e}"),
91 )
92 });
93 Self {
94 site: site.to_string(),
95 path,
96 file: Some(file),
97 written: 0,
98 expected: None,
99 }
100 }
101
102 /// Hand `chunk` to the file. Overrunning `expected` is a caller bug (the
103 /// count and the writer disagree) and aborts just as loudly as a short
104 /// write, because one of the two is certainly lying.
105 pub fn write(&mut self, chunk: &[u8]) {
106 if let Some(exp) = self.expected
107 && self.written + chunk.len() > exp
108 {
109 abort(
110 &self.site,
111 &self.path,
112 self.written,
113 Some(exp),
114 &format!(
115 "the writer was handed {} bytes but only {} remained of the {} it declared",
116 chunk.len(),
117 exp - self.written,
118 exp
119 ),
120 );
121 }
122 let r = self.file.as_mut().expect("live dump").write_all(chunk);
123 if let Err(e) = r {
124 // MEASURED, do not assume: under `RLIMIT_FSIZE` the kernel stores
125 // everything up to the cap and THEN returns `EFBIG` (measured:
126 // a 49 152 B frame under caps of 4 KiB / 10 KiB / 30 KiB left
127 // 4 096 / 10 240 / 30 720 B on disk, with `write_all` confirming
128 // none of it). So "bytes written" on this line is the file's real
129 // length, not the count `write_all` got to acknowledge -- the
130 // acknowledged count rides along in the reason.
131 let f = self.file.as_ref().expect("live dump");
132 let on_disk = f
133 .metadata()
134 .map(|m| m.len() as usize)
135 .unwrap_or(self.written);
136 abort(
137 &self.site,
138 &self.path,
139 on_disk,
140 self.expected,
141 &format!(
142 "write failed with {} bytes confirmed in hand: {e}",
143 self.written
144 ),
145 );
146 }
147 self.written += chunk.len();
148 }
149
150 /// Close the dump: flush, then check the file's own length on disk.
151 ///
152 /// The on-disk check is not redundant with the write loop. `write_all`
153 /// reports what the FILE ACCEPTED, and the reader's question is what the
154 /// filesystem ended up holding -- a sparse/short final flush, a quota, or a
155 /// filesystem-level reservation failure all land here rather than in
156 /// `write`.
157 pub fn finish(mut self) {
158 let Some(mut file) = self.file.take() else {
159 return;
160 };
161 if let Err(e) = file.flush() {
162 abort(
163 &self.site,
164 &self.path,
165 self.written,
166 self.expected,
167 &format!("flush failed after {} bytes: {e}", self.written),
168 );
169 }
170 let Some(exp) = self.expected else {
171 return;
172 };
173 let on_disk = match file.metadata() {
174 Ok(m) => m.len() as usize,
175 Err(e) => abort(
176 &self.site,
177 &self.path,
178 self.written,
179 Some(exp),
180 &format!("could not stat the finished dump: {e}"),
181 ),
182 };
183 if on_disk != exp {
184 abort(
185 &self.site,
186 &self.path,
187 on_disk,
188 Some(exp),
189 "the file on disk is not the length the writer declared",
190 );
191 }
192 }
193}
194
195/// The single failure line every short dump now ends on. `site`, the path, the
196/// bytes on disk vs the bytes owed, and the reason.
197fn abort(site: &str, path: &Path, got: usize, expected: Option<usize>, why: &str) -> ! {
198 panic!("{}", failure_line(site, path, got, expected, why));
199}
200
201/// The failure line itself, so the fatal and the reporting shapes cannot
202/// drift apart.
203fn failure_line(site: &str, path: &Path, got: usize, expected: Option<usize>, why: &str) -> String {
204 let owed = match expected {
205 Some(e) => format!("{e}"),
206 None => "an unknown number of".to_string(),
207 };
208 format!(
209 "ec-av1 dump FAILED [{}] {}: wrote {} of {} bytes: {}",
210 site,
211 path.display(),
212 got,
213 owed,
214 why
215 )
216}
217
218/// Write `bytes` to `path` as a FATAL pin: [`pin`] IS a wrapper -- three
219/// [`LoudDump`] calls (`create`/`write`/`finish`), so it inherits the flush and
220/// the flush-then-stat ordering for free.
221///
222/// lane-av1pinloud: the test-pin sites in `stream.rs` wrote with
223/// `let _ = std::fs::write(..)` and then named the path in the panic that
224/// followed ("stream pinned at {}"), so an `ENOSPC`/`EFBIG` left a TRUNCATED
225/// stream at exactly the path the reader was told to replay -- the same
226/// silent-truncation class as the dump path, one hop later. Success path is
227/// byte-identical: same bytes, same path, truncate-then-write.
228pub fn pin(site: &str, path: impl AsRef<Path>, bytes: &[u8]) {
229 let mut d = LoudDump::create(site, path, bytes.len());
230 d.write(bytes);
231 d.finish();
232}
233
234/// [`pin`]'s NON-FATAL twin, for a site that must not die on a failed pin -- a
235/// gate whose real failure is the assert that comes after the pin attempt, and
236/// whose comment says so.
237///
238/// This one RE-IMPLEMENTS the check rather than wrapping [`LoudDump`], whose
239/// failure channel is `panic!`: it cannot report instead of dying. So it does
240/// `fs::write` + `metadata` itself. Only the failure LINE is shared, via
241/// [`failure_line`] -- the ordering (flush-then-stat) and the
242/// write-error-handling are not shared with [`LoudDump`], and a reader must not
243/// assume they are.
244///
245/// Non-fatal, but not silent: a shortfall comes back as the very same failure
246/// line [`pin`] would have panicked with, expected-vs-on-disk counts included,
247/// for the caller to print as a warning.
248#[cfg(test)] // only the self-test below calls it; keeps the non-test build free of dead code
249pub fn pin_reporting(site: &str, path: impl AsRef<Path>, bytes: &[u8]) -> Result<(), String> {
250 let path = path.as_ref();
251 let expected = bytes.len();
252 if let Err(e) = std::fs::write(path, bytes) {
253 let on_disk = std::fs::metadata(path)
254 .map(|m| m.len() as usize)
255 .unwrap_or(0);
256 return Err(failure_line(
257 site,
258 path,
259 on_disk,
260 Some(expected),
261 &format!("could not write the pin: {e}"),
262 ));
263 }
264 let on_disk = match std::fs::metadata(path) {
265 Ok(m) => m.len() as usize,
266 Err(e) => {
267 return Err(failure_line(
268 site,
269 path,
270 expected,
271 Some(expected),
272 &format!("could not stat the written pin: {e}"),
273 ));
274 }
275 };
276 if on_disk != expected {
277 return Err(failure_line(
278 site,
279 path,
280 on_disk,
281 Some(expected),
282 "the pinned file on disk is not the length of the stream",
283 ));
284 }
285 Ok(())
286}
287
288/// Write `planes` (already narrowed to their dump's sample width) as ONE dump
289/// file, failing loudly on any shortfall. `expected` is the sum of the plane
290/// lengths -- the same extents the writer iterates, so a plane that is shorter
291/// than its geometry claims cannot hide here.
292pub fn write_planes(site: &str, path: impl AsRef<Path>, planes: &[&[u8]]) {
293 let expected: usize = planes.iter().map(|p| p.len()).sum();
294 let mut d = LoudDump::create(site, path, expected);
295 for p in planes {
296 d.write(p);
297 }
298 d.finish();
299}
300
301#[cfg(test)]
302mod tests {
303 use super::*;
304 use std::process::Command;
305
306 fn scratch(tag: &str) -> PathBuf {
307 let p = std::env::temp_dir().join(format!("ec-av1-dumpio-{tag}-{}", std::process::id()));
308 let _ = std::fs::remove_file(&p);
309 p
310 }
311
312 fn caught(f: impl FnOnce() + std::panic::UnwindSafe) -> String {
313 let prev = std::panic::take_hook();
314 std::panic::set_hook(Box::new(|_| {}));
315 let r = std::panic::catch_unwind(f);
316 std::panic::set_hook(prev);
317 let e = r.expect_err("the short dump must abort");
318 e.downcast_ref::<String>()
319 .cloned()
320 .or_else(|| e.downcast_ref::<&str>().map(|s| (*s).to_string()))
321 .expect("panic payload is a string")
322 }
323
324 #[test]
325 fn success_path_is_byte_identical_to_the_old_write_all_loop() {
326 let p = scratch("ok");
327 let planes: [&[u8]; 3] = [b"abc", b"", b"de"];
328 write_planes("T", &p, &planes);
329 assert_eq!(std::fs::read(&p).unwrap(), b"abcde");
330 let _ = std::fs::remove_file(&p);
331 }
332
333 /// `/dev/full` accepts an `open` for write and returns `ENOSPC` from every
334 /// write -- the hermetic stand-in for the full filesystem that produced the
335 /// 13 320 192-byte truncated frame in `lanes/unwritten-dep.report.md`.
336 #[test]
337 #[cfg(unix)]
338 fn full_device_short_write_is_loud() {
339 let msg = caught(|| write_planes("EC_AV1_FINAL_DUMP", "/dev/full", &[b"abc", b"de"]));
340 assert!(
341 msg.starts_with("ec-av1 dump FAILED [EC_AV1_FINAL_DUMP] /dev/full: wrote "),
342 "{msg}"
343 );
344 assert!(msg.contains("No space left on device"), "{msg}");
345 // The counts must be there, or the line does not say what was lost.
346 assert!(msg.contains(" of 5 bytes"), "{msg}");
347 }
348
349 #[test]
350 fn uncreatable_dump_is_loud() {
351 let p = std::env::temp_dir().join(format!("ec-av1-nodir-{}/x", std::process::id()));
352 let msg = caught(|| write_planes("T", &p, &[b"abc"]));
353 assert!(msg.contains("could not create the dump file"), "{msg}");
354 }
355
356 /// A writer that under-declares its own expected length is the same silent
357 /// hole: the reader gets a file the site believes is complete.
358 #[test]
359 fn under_declared_expected_length_is_loud() {
360 let p = scratch("under");
361 let msg = caught(|| {
362 let mut d = LoudDump::create("T", &p, 2);
363 d.write(b"abcdef");
364 d.finish();
365 });
366 assert!(
367 msg.contains("was handed 6 bytes but only 2 remained of the 2 it declared"),
368 "{msg}"
369 );
370 let _ = std::fs::remove_file(&p);
371 }
372
373 #[test]
374 fn append_unknown_takes_no_length_claim() {
375 let p = scratch("append");
376 {
377 let mut a = LoudDump::append_unknown("T", &p);
378 a.write(b"x");
379 a.finish();
380 let mut b = LoudDump::append_unknown("T", &p);
381 b.write(b"y");
382 b.finish();
383 }
384 assert_eq!(std::fs::read(&p).unwrap(), b"xy");
385 let msg = caught(|| {
386 let mut a = LoudDump::append_unknown("T", "/dev/full");
387 a.write(b"x");
388 a.finish();
389 });
390 assert!(msg.contains("of an unknown number of bytes"), "{msg}");
391 let _ = std::fs::remove_file(&p);
392 }
393 /// THE reproduction of the incident this module exists for: a real decode,
394 /// a real `RLIMIT_FSIZE`, a real truncated `EC_AV1_FINAL_DUMP` file left
395 /// on disk -- and the run stopping with the bytes-vs-bytes line instead of
396 /// carrying on to a measurement built on the fragment.
397 ///
398 /// `/dev/full` (the unit test above) proves the writer's check works but
399 /// never leaves a partial file behind, because `create` on it succeeds and
400 /// nothing is ever stored. `RLIMIT_FSIZE` is the shape
401 /// `lanes/unwritten-dep.report.md` actually measured: frames 0..4 complete
402 /// plus 13 320 192 bytes of frame 5. `SIGXFSZ` is IGNORED (`trap "" XFSZ`)
403 /// so the limit surfaces as `write`'s `EFBIG` -- exactly what a full
404 /// filesystem's `ENOSPC` does -- instead of killing the child outright.
405 #[test]
406 #[cfg(unix)]
407 fn a_real_decode_under_a_file_size_cap_fails_loudly() {
408 let dir = std::env::temp_dir().join(format!("ec-av1-dumpio-cap-{}", std::process::id()));
409 let _ = std::fs::remove_dir_all(&dir);
410 std::fs::create_dir_all(&dir).unwrap();
411 let prefix = dir.join("ours");
412 // 8 blocks of 512 B = 4096 B: far below one 256x128 4:2:0 8-bit frame
413 // (49 152 B), far above the file header, so the write lands and fails
414 // PART way rather than at create.
415 let out = Command::new("bash")
416 .args([
417 "-c",
418 "ulimit -f 8; trap \"\" XFSZ; exec \"$0\" \"$@\"",
419 // $0 for `bash -c` is the test binary itself.
420 std::env::current_exe().unwrap().to_str().unwrap(),
421 "--exact",
422 "dumpio::tests::dumpio_child_decode",
423 "--nocapture",
424 ])
425 .env("EC_AV1_DUMPLOUD_CHILD", "1")
426 .env("EC_AV1_FINAL_DUMP", &prefix)
427 // One thread, so the dump panic lands on the main thread and the
428 // child's exit status is the decode's own.
429 .env("EC_AV1_THREADS", "1")
430 .output()
431 .expect("spawning the capped child");
432 let stderr = String::from_utf8_lossy(&out.stderr);
433 assert!(
434 !out.status.success(),
435 "the decode must FAIL under a file-size cap, not finish with a truncated dump\n{stderr}"
436 );
437 assert!(
438 stderr.contains("ec-av1 dump FAILED [EC_AV1_FINAL_DUMP]"),
439 "the failure line must name the dump site\n{stderr}"
440 );
441 assert!(
442 stderr.contains("File too large"),
443 "the failure line must carry the OS error\n{stderr}"
444 );
445 // One 256x128 4:2:0 8-bit frame is 256*128*3/2 = 49 152 B, and the
446 // failure line's "wrote N of 49152" must name the file's REAL length,
447 // not the count `write_all` managed to acknowledge: a line that
448 // under-reports is a line that sends the reader back to the dump to
449 // measure it themselves.
450 let frag = std::fs::metadata(format!("{}.f0", prefix.display()))
451 .unwrap()
452 .len();
453 assert!(
454 frag < 49152,
455 "the capped child left a {frag}-byte frame where 49152 B was owed"
456 );
457 assert!(
458 stderr.contains(&format!("wrote {frag} of 49152 bytes")),
459 "the failure line's written count must be the file's actual length ({frag})\n{stderr}"
460 );
461 let _ = std::fs::remove_dir_all(&dir);
462 }
463
464 /// Child half of [`a_real_decode_under_a_file_size_cap_fails_loudly`]. It is
465 /// not a gate: with no `EC_AV1_DUMPLOUD_CHILD` guard it decodes nothing and
466 /// asserts nothing, so a plain `cargo test` run is unaffected.
467 #[test]
468 fn dumpio_child_decode() {
469 if std::env::var("EC_AV1_DUMPLOUD_CHILD").is_err() {
470 return;
471 }
472 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
473 .join("fixtures/420_mixll_256x128_6f.obu");
474 let bytes = std::fs::read(&path).expect("the pinned fixture");
475 let _ = crate::stream::decode_stream(&bytes);
476 }
477
478 #[test]
479 fn pin_success_path_is_byte_identical() {
480 let p = scratch("pin-ok");
481 pin("TEST_PIN", &p, b"stream bytes");
482 assert_eq!(std::fs::read(&p).unwrap(), b"stream bytes");
483 let _ = std::fs::remove_file(&p);
484 }
485
486 #[test]
487 #[cfg(unix)]
488 fn pin_to_a_full_device_is_loud() {
489 let msg = caught(|| pin("TEST_PIN", "/dev/full", b"stream bytes"));
490 assert!(
491 msg.starts_with("ec-av1 dump FAILED [TEST_PIN] /dev/full: wrote "),
492 "{msg}"
493 );
494 assert!(msg.contains("No space left on device"), "{msg}");
495 assert!(msg.contains(" of 12 bytes"), "{msg}");
496 }
497
498 /// The reporting shape: same failure line, returned instead of panicked,
499 /// so a gate whose real failure is the assert after the pin keeps that
500 /// assert -- but the reader still learns the pin is short.
501 #[test]
502 #[cfg(unix)]
503 fn pin_reporting_is_loud_but_not_fatal() {
504 let line = pin_reporting("TEST_PIN", "/dev/full", b"stream bytes").unwrap_err();
505 assert!(
506 line.contains("ec-av1 dump FAILED [TEST_PIN] /dev/full"),
507 "{line}"
508 );
509 assert!(line.contains(" of 12 bytes"), "{line}");
510 let p = scratch("pin-reporting-ok");
511 pin_reporting("TEST_PIN", &p, b"stream bytes").expect("a healthy pin reports nothing");
512 assert_eq!(std::fs::read(&p).unwrap(), b"stream bytes");
513 let _ = std::fs::remove_file(&p);
514 }
515
516 /// The pin path's own reproduction: a real `RLIMIT_FSIZE` leaves a real
517 /// truncated stream at the path the panic names. Without the check the
518 /// reader replays the fragment and blames the decoder.
519 #[test]
520 #[cfg(unix)]
521 fn a_pin_under_a_file_size_cap_fails_loudly() {
522 let dir = std::env::temp_dir().join(format!("ec-av1-pin-cap-{}", std::process::id()));
523 let _ = std::fs::remove_dir_all(&dir);
524 std::fs::create_dir_all(&dir).unwrap();
525 let out = Command::new("bash")
526 .args([
527 "-c",
528 "ulimit -f 8; trap \"\" XFSZ; exec \"$0\" \"$@\"",
529 std::env::current_exe().unwrap().to_str().unwrap(),
530 "--exact",
531 "dumpio::tests::pin_child_under_cap",
532 "--nocapture",
533 ])
534 .env("EC_AV1_PINLOUD_CHILD", &dir)
535 .output()
536 .expect("spawning the capped child");
537 let stderr = String::from_utf8_lossy(&out.stderr);
538 assert!(!out.status.success(), "a short pin must fail\n{stderr}");
539 assert!(stderr.contains("ec-av1 dump FAILED [TEST_PIN]"), "{stderr}");
540 assert!(stderr.contains("File too large"), "{stderr}");
541 let frag = std::fs::metadata(dir.join("cap-pinned.obu")).unwrap().len();
542 assert!(
543 frag < 32768,
544 "the capped child left {frag} bytes where 32768 B was owed"
545 );
546 assert!(
547 stderr.contains(&format!("wrote {frag} of 32768 bytes")),
548 "{stderr}"
549 );
550 let _ = std::fs::remove_dir_all(&dir);
551 }
552
553 /// Child half of [`a_pin_under_a_file_size_cap_fails_loudly`]. Not a gate:
554 /// with no `EC_AV1_PINLOUD_CHILD` set it writes nothing and asserts nothing.
555 #[test]
556 fn pin_child_under_cap() {
557 let Ok(dir) = std::env::var("EC_AV1_PINLOUD_CHILD") else {
558 return;
559 };
560 // `ulimit -f 8` is 8 KiB, so 4x that is guaranteed to run PAST the cap
561 // (a write of exactly the cap size succeeds) and land a fragment.
562 pin(
563 "TEST_PIN",
564 Path::new(&dir).join("cap-pinned.obu"),
565 &[7u8; 32768],
566 );
567 }
568}