diff --git a/crates/ec-av1/src/dumpio.rs b/crates/ec-av1/src/dumpio.rs index 924a6c28..dd3afd6f 100644 --- a/crates/ec-av1/src/dumpio.rs +++ b/crates/ec-av1/src/dumpio.rs @@ -155,7 +155,9 @@ impl LoudDump { /// filesystem-level reservation failure all land here rather than in /// `write`. pub fn finish(mut self) { - let Some(mut file) = self.file.take() else { return }; + let Some(mut file) = self.file.take() else { + return; + }; if let Err(e) = file.flush() { abort( &self.site, @@ -193,18 +195,93 @@ impl LoudDump { /// The single failure line every short dump now ends on. `site`, the path, the /// bytes on disk vs the bytes owed, and the reason. fn abort(site: &str, path: &Path, got: usize, expected: Option, why: &str) -> ! { + panic!("{}", failure_line(site, path, got, expected, why)); +} + +/// The failure line itself, so the fatal and the reporting shapes cannot +/// drift apart. +fn failure_line(site: &str, path: &Path, got: usize, expected: Option, why: &str) -> String { let owed = match expected { Some(e) => format!("{e}"), None => "an unknown number of".to_string(), }; - panic!( + format!( "ec-av1 dump FAILED [{}] {}: wrote {} of {} bytes: {}", site, path.display(), got, owed, why - ); + ) +} + +/// Write `bytes` to `path` as a FATAL pin: [`pin`] IS a wrapper -- three +/// [`LoudDump`] calls (`create`/`write`/`finish`), so it inherits the flush and +/// the flush-then-stat ordering for free. +/// +/// lane-av1pinloud: the test-pin sites in `stream.rs` wrote with +/// `let _ = std::fs::write(..)` and then named the path in the panic that +/// followed ("stream pinned at {}"), so an `ENOSPC`/`EFBIG` left a TRUNCATED +/// stream at exactly the path the reader was told to replay -- the same +/// silent-truncation class as the dump path, one hop later. Success path is +/// byte-identical: same bytes, same path, truncate-then-write. +pub fn pin(site: &str, path: impl AsRef, bytes: &[u8]) { + let mut d = LoudDump::create(site, path, bytes.len()); + d.write(bytes); + d.finish(); +} + +/// [`pin`]'s NON-FATAL twin, for a site that must not die on a failed pin -- a +/// gate whose real failure is the assert that comes after the pin attempt, and +/// whose comment says so. +/// +/// This one RE-IMPLEMENTS the check rather than wrapping [`LoudDump`], whose +/// failure channel is `panic!`: it cannot report instead of dying. So it does +/// `fs::write` + `metadata` itself. Only the failure LINE is shared, via +/// [`failure_line`] -- the ordering (flush-then-stat) and the +/// write-error-handling are not shared with [`LoudDump`], and a reader must not +/// assume they are. +/// +/// Non-fatal, but not silent: a shortfall comes back as the very same failure +/// line [`pin`] would have panicked with, expected-vs-on-disk counts included, +/// for the caller to print as a warning. +pub fn pin_reporting(site: &str, path: impl AsRef, bytes: &[u8]) -> Result<(), String> { + let path = path.as_ref(); + let expected = bytes.len(); + if let Err(e) = std::fs::write(path, bytes) { + let on_disk = std::fs::metadata(path) + .map(|m| m.len() as usize) + .unwrap_or(0); + return Err(failure_line( + site, + path, + on_disk, + Some(expected), + &format!("could not write the pin: {e}"), + )); + } + let on_disk = match std::fs::metadata(path) { + Ok(m) => m.len() as usize, + Err(e) => { + return Err(failure_line( + site, + path, + expected, + Some(expected), + &format!("could not stat the written pin: {e}"), + )); + } + }; + if on_disk != expected { + return Err(failure_line( + site, + path, + on_disk, + Some(expected), + "the pinned file on disk is not the length of the stream", + )); + } + Ok(()) } /// Write `planes` (already narrowed to their dump's sample width) as ONE dump @@ -391,9 +468,100 @@ mod tests { if std::env::var("EC_AV1_DUMPLOUD_CHILD").is_err() { return; } - let path = - std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/420_mixll_256x128_6f.obu"); + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures/420_mixll_256x128_6f.obu"); let bytes = std::fs::read(&path).expect("the pinned fixture"); let _ = crate::stream::decode_stream(&bytes); } + + #[test] + fn pin_success_path_is_byte_identical() { + let p = scratch("pin-ok"); + pin("TEST_PIN", &p, b"stream bytes"); + assert_eq!(std::fs::read(&p).unwrap(), b"stream bytes"); + let _ = std::fs::remove_file(&p); + } + + #[test] + #[cfg(unix)] + fn pin_to_a_full_device_is_loud() { + let msg = caught(|| pin("TEST_PIN", "/dev/full", b"stream bytes")); + assert!( + msg.starts_with("ec-av1 dump FAILED [TEST_PIN] /dev/full: wrote "), + "{msg}" + ); + assert!(msg.contains("No space left on device"), "{msg}"); + assert!(msg.contains(" of 12 bytes"), "{msg}"); + } + + /// The reporting shape: same failure line, returned instead of panicked, + /// so a gate whose real failure is the assert after the pin keeps that + /// assert -- but the reader still learns the pin is short. + #[test] + #[cfg(unix)] + fn pin_reporting_is_loud_but_not_fatal() { + let line = pin_reporting("TEST_PIN", "/dev/full", b"stream bytes").unwrap_err(); + assert!( + line.contains("ec-av1 dump FAILED [TEST_PIN] /dev/full"), + "{line}" + ); + assert!(line.contains(" of 12 bytes"), "{line}"); + let p = scratch("pin-reporting-ok"); + pin_reporting("TEST_PIN", &p, b"stream bytes").expect("a healthy pin reports nothing"); + assert_eq!(std::fs::read(&p).unwrap(), b"stream bytes"); + let _ = std::fs::remove_file(&p); + } + + /// The pin path's own reproduction: a real `RLIMIT_FSIZE` leaves a real + /// truncated stream at the path the panic names. Without the check the + /// reader replays the fragment and blames the decoder. + #[test] + #[cfg(unix)] + fn a_pin_under_a_file_size_cap_fails_loudly() { + let dir = std::env::temp_dir().join(format!("ec-av1-pin-cap-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let out = Command::new("bash") + .args([ + "-c", + "ulimit -f 8; trap \"\" XFSZ; exec \"$0\" \"$@\"", + std::env::current_exe().unwrap().to_str().unwrap(), + "--exact", + "dumpio::tests::pin_child_under_cap", + "--nocapture", + ]) + .env("EC_AV1_PINLOUD_CHILD", &dir) + .output() + .expect("spawning the capped child"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "a short pin must fail\n{stderr}"); + assert!(stderr.contains("ec-av1 dump FAILED [TEST_PIN]"), "{stderr}"); + assert!(stderr.contains("File too large"), "{stderr}"); + let frag = std::fs::metadata(dir.join("cap-pinned.obu")).unwrap().len(); + assert!( + frag < 32768, + "the capped child left {frag} bytes where 32768 B was owed" + ); + assert!( + stderr.contains(&format!("wrote {frag} of 32768 bytes")), + "{stderr}" + ); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Child half of [`a_pin_under_a_file_size_cap_fails_loudly`]. Not a gate: + /// with no `EC_AV1_PINLOUD_CHILD` set it writes nothing and asserts nothing. + #[test] + fn pin_child_under_cap() { + let Ok(dir) = std::env::var("EC_AV1_PINLOUD_CHILD") else { + return; + }; + // `ulimit -f 8` is 8 KiB, so 4x that is guaranteed to run PAST the cap + // (a write of exactly the cap size succeeds) and land a fragment. + pin( + "TEST_PIN", + Path::new(&dir).join("cap-pinned.obu"), + &[7u8; 32768], + ); + } } diff --git a/crates/ec-av1/src/msac.rs b/crates/ec-av1/src/msac.rs index 1b5e0c07..ed57d9a9 100644 --- a/crates/ec-av1/src/msac.rs +++ b/crates/ec-av1/src/msac.rs @@ -1133,16 +1133,16 @@ pub(crate) mod symtrace { let (buf, n) = &mut *b.borrow_mut(); if !buf.is_empty() { // lane-av1dumploud: loud on a short write. `std::fs::write` - // returns a `Result` that this used to discard; the expected - // length is exactly the buffer's own. + // returned a `Result` this used to discard, and the check was + // hand-rolled against the buffer length only; lane-av1pinloud + // folded it into the shared writer so this site also gets the + // on-disk length check the dump path already had. let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let (bytes, at) = (buf.as_bytes(), format!("{dir}/{side}-{seq:05}.txt")); - if let Err(e) = std::fs::write(&at, bytes) { - panic!( - "ec-av1 dump FAILED [EC_AV1_SYMTRACE] {at}: wrote 0 of {} bytes: {e}", - bytes.len() - ); - } + crate::dumpio::pin( + "EC_AV1_SYMTRACE", + format!("{dir}/{side}-{seq:05}.txt"), + buf.as_bytes(), + ); } buf.clear(); *n = 0; diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 08e3b13d..c1cd47be 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -2214,7 +2214,11 @@ fn decode_frame( crate::dumpio::write_planes( "EC_AV1_DECODE_ORDER_DUMP", format!("{path}.f{decode_idx}"), - &[&narrow(&picture.y), &narrow(&picture.u), &narrow(&picture.v)], + &[ + &narrow(&picture.y), + &narrow(&picture.u), + &narrow(&picture.v), + ], ); } // lane-hidden r1: the frame exactly as it is about to be stored into @@ -2257,8 +2261,11 @@ fn decode_frame( // writer that builds the wrong buffer still gets caught. let sample_width = if bit_depth == 8 { 1 } else { 2 }; let expected = (picture.y.len() + picture.u.len() + picture.v.len()) * sample_width; - let mut f = - crate::dumpio::LoudDump::create("EC_AV1_FINAL_DUMP", format!("{prefix}.f{decode_idx}"), expected); + let mut f = crate::dumpio::LoudDump::create( + "EC_AV1_FINAL_DUMP", + format!("{prefix}.f{decode_idx}"), + expected, + ); for plane in [&picture.y, &picture.u, &picture.v] { if bit_depth == 8 { f.write(&plane.iter().map(|&s| s as u8).collect::>()); @@ -14188,7 +14195,7 @@ exit 0 assert_eq!(a.len(), b.len(), "{name}: frame {i} {plane} plane length"); if a != b { let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu")); - let _ = std::fs::write(&pin, &stream); + crate::dumpio::pin("TEST_PIN", &pin, &stream); let at = a .iter() .zip(b.iter()) @@ -18198,7 +18205,7 @@ exit 0 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { if got.y != want.y || got.u != want.u || got.v != want.v { let pin = std::env::temp_dir().join("ec-av1-10bit-inter-gate-fail.obu"); - let _ = std::fs::write(&pin, &stream); + crate::dumpio::pin("TEST_PIN", &pin, &stream); let first = |a: &Vec, b: &Vec| { a.iter() .zip(b) @@ -23167,7 +23174,7 @@ exit 0 Ok(frames) => frames, Err(e) => { let pin = std::env::temp_dir().join(format!("{name}-refused.obu")); - let _ = std::fs::write(&pin, &stream); + crate::dumpio::pin("TEST_PIN", &pin, &stream); panic!( "{name}: decode_stream refused a real aomenc stream: {e} (pinned at {})", pin.display() @@ -23187,7 +23194,7 @@ exit 0 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { if got.y != want.y || got.u != want.u || got.v != want.v { let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu")); - let _ = std::fs::write(&pin, &stream); + crate::dumpio::pin("TEST_PIN", &pin, &stream); panic!( "{name}: frame {i} mismatch vs ffmpeg -- stream pinned at {}", pin.display() @@ -23586,7 +23593,7 @@ exit 0 } Err(e) => { let pin = std::env::temp_dir().join(format!("{name}-refused.obu")); - let _ = std::fs::write(&pin, &stream); + crate::dumpio::pin("TEST_PIN", &pin, &stream); panic!( "{name}: decode_stream failed on a real aomenc stream (cq={cq} period={period}): {e} (pinned at {})", pin.display() @@ -23608,7 +23615,7 @@ exit 0 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { if got.y != want.y || got.u != want.u || got.v != want.v { let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu")); - let _ = std::fs::write(&pin, &stream); + crate::dumpio::pin("TEST_PIN", &pin, &stream); panic!( "{name}: frame {i} mismatch vs ffmpeg (cq={cq} period={period}) -- stream pinned at {}", pin.display() @@ -27901,7 +27908,7 @@ exit 0 "ec-av1-deblocking-gate-fail-s{}-cq{cq}.obu", 42 + round )); - let _ = std::fs::write(&pin, &stream); + crate::dumpio::pin("TEST_PIN", &pin, &stream); panic!( "frame {i} mismatch vs ffmpeg (seed {} cq {cq}, deblock fired: \ {counted}) -- stream pinned at {}", @@ -28134,14 +28141,18 @@ exit 0 // The pin goes to `fixtures/`, which outlives the session: an // earlier version wrote to a session scratchpad, so once tmpfs // reaped it a real mismatch aborted on the write instead of - // reporting itself. A failed write must not mask the assert - // below either, so it warns rather than panicking. + // reporting itself. A failed write must not mask the asserts + // below either, so it warns rather than panicking -- lane-av1pinloud + // routed it through `pin_reporting` rather than bare `fs::write`, + // so the warning now carries on-disk-vs-owed byte counts: a + // truncated pin was as silent here as anywhere else, and this + // is the one site where dying on the write is wrong. let sp = pin_dir(); let stream_pin = sp.join(format!("cdfflake-stream-seed{seed}.bin")); let ref_pin = sp.join(format!("cdfflake-ffmpeg-raw-seed{seed}.bin")); for (path, bytes) in [(&stream_pin, &stream), (&ref_pin, &ffmpeg_raw)] { - if let Err(e) = std::fs::write(path, bytes) { - eprintln!("cdfflake: could not pin to {}: {e}", path.display()); + if let Err(line) = crate::dumpio::pin_reporting("TEST_PIN", path, bytes) { + eprintln!("cdfflake: {line}"); } } eprintln!( @@ -28893,9 +28904,9 @@ exit 0 if mismatched { let pin = std::env::temp_dir().join("ec-av1-reference-select-gate-fail.obu"); - let _ = std::fs::write(&pin, &stream); + crate::dumpio::pin("TEST_PIN", &pin, &stream); if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); + crate::dumpio::pin("EC_AV1_GATE_DUMP", &path, &stream); eprintln!( "EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}" ); @@ -29103,9 +29114,9 @@ exit 0 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); if mismatched { let pin = std::env::temp_dir().join("ec-av1-compound-refs-gate-fail.obu"); - let _ = std::fs::write(&pin, &stream); + crate::dumpio::pin("TEST_PIN", &pin, &stream); if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); + crate::dumpio::pin("EC_AV1_GATE_DUMP", &path, &stream); eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); } for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { diff --git a/lanes/av1pinloud.report.md b/lanes/av1pinloud.report.md new file mode 100644 index 00000000..b288917d --- /dev/null +++ b/lanes/av1pinloud.report.md @@ -0,0 +1,130 @@ +# lane av1pinloud — loud self-pins in `stream.rs` + +## Defect + +Every self-pin site in `crates/ec-av1/src/stream.rs` wrote with + +```rust +let _ = std::fs::write(&pin, &stream); +``` + +and then named the path in the very next statement's failure message +("stream pinned at {}"). A partial write (`ENOSPC`, `RLIMIT_FSIZE`) therefore left a +**truncated stream at exactly the path the reader was told to replay** — the same +silent-truncation class that produced two false defect rows on the dump path +(`lanes/unwritten-dep.report.md`), one hop downstream. `fs::write`'s `Result` was +discarded, so nothing said so. + +Nine sites: `stream.rs` 14191, 18201, 23170, 23190, 23589, 23611, 27904, 28896, +29106 — plus the two `EC_AV1_GATE_DUMP` writes beside 28896/29106 +(`stream.rs` 28898, 29108), which checked the write but never checked the resulting +length. + +## Change + +`crates/ec-av1/src/dumpio.rs` gains two pin helpers plus a `failure_line` helper so the +fatal and reporting message shapes cannot drift: + +- `pin(site, path, bytes)` — fatal. Same shape as `write_planes` for a single blob: + create, `write_all`, then stat the file and compare against `bytes.len()`. + Success path is byte-identical to the old `fs::write`: same bytes, same path, + truncate-then-write. +- `pin_reporting(site, path, bytes) -> Result<(), String>` — non-fatal, not silent. + Returns the **same** failure line `pin` would have panicked with + (`ec-av1 dump FAILED [TEST_PIN] : wrote N of M bytes: `). + +These are NOT both wrappers over `LoudDump`, and the difference is load-bearing: + +- `pin` **is** a wrapper — three `LoudDump` calls (`create`/`write`/`finish`), so it + inherits the flush and the flush-then-stat ordering for free. +- `pin_reporting` **re-implements** the check with `fs::write` + `metadata`, because + `LoudDump`'s failure channel is `panic!` and this site must not die. Only the failure + *line* is shared (via `failure_line`); the ordering is not. + +All nine pin sites now call `pin("TEST_PIN", ...)`; both `EC_AV1_GATE_DUMP` writes call +`pin("EC_AV1_GATE_DUMP", ...)` (previously `fs::write(...).expect(...)`, loud on a write +error but blind to a short file on disk). + +One more in-crate site of the same shape: `msac.rs:1140` (`EC_AV1_SYMTRACE` flush) had a +hand-rolled panic that compared the buffer length but never stat'ed the file. Folded +into `pin` so it gets the on-disk check. + +### Site label + +The label is **`TEST_PIN`**, deliberately outside the `EC_AV1_*` env-var namespace: no +env var of that name exists (a real `EC_AV1_PIN` env var does — the scratch replay +helper's — and reusing that name would have pointed a triager at the wrong thing), and +every other failure-line label in this module names the env var that triggers the write. +`EC_AV1_GATE_DUMP` and `EC_AV1_SYMTRACE` keep their real env-var names because they *are* +real env vars. + +### `stream.rs:28143` — the warns-by-design site: decision + +Routed through `pin_reporting`, keeping it non-fatal. The two shapes differ for a +stated reason, not by accident: + +- the nine sites run **inside the arm that is already panicking** — the pin exists to + feed that panic, so dying on a short pin replaces a message with a strictly better one + (same panic, plus the byte counts). +- 28143's real failure is the `assert_eq!` three lines below (luma/U/V vs ffmpeg). + Panicking on the write would **mask that assert** with an unrelated filesystem + error — the exact failure its comment refuses. So it must not be fatal. + +What changed is what it *prints*: the old `could not pin to {path}: {e}` warning became +`cdfflake: ec-av1 dump FAILED [TEST_PIN] {path}: wrote N of M bytes: {why}` — same +severity (a warning, then the asserts run), now carrying expected-vs-on-disk counts. A +truncated pin there was previously indistinguishable from a good one. + +## Proof + +`dumpio::tests::a_pin_under_a_file_size_cap_fails_loudly` is the real reproduction: a +child under `ulimit -f 8` (8 KiB) pins 32 KiB, leaving a fragment and dying on the +counts, not carrying on. + +``` +$ EC_AV1_PINLOUD_CHILD=/tmp/pincap2 bash -c 'ulimit -f 8; trap "" XFSZ; exec "$0" "$@"' \ + --exact dumpio::tests::pin_child_under_cap --nocapture +ec-av1 dump FAILED [TEST_PIN] /tmp/pincap2/cap-pinned.obu: wrote 8192 of 32768 bytes: + write failed with 0 bytes confirmed in hand: File too large (os error 27) +test dumpio::tests::pin_child_under_cap ... FAILED +$ ls -l /tmp/pincap2 +-rw-r--r-- 1 tahinli tahinli 8192 cap-pinned.obu +``` + +8192 B on disk where 32768 B was owed — bytes-expected vs bytes-on-disk, and the +reported count is the file's real length, not what `write_all` acknowledged. + +Also: `pin_success_path_is_byte_identical` (bytes on disk equal the bytes handed in), +`pin_to_a_full_device_is_loud`, `pin_reporting_is_loud_but_not_fatal` (the same line, +returned rather than panicked, plus a healthy pin returning `Ok`). + +Scoped runs (`CARGO_TARGET_DIR=/home/user/.cache/tgt/av1pinloud`): + +``` +cargo test -p ec-av1 --lib dumpio:: 12 passed; 0 failed +cargo test -p ec-av1 --lib -- --exact \ + stream::tests::a_444_intra_in_inter_128root_muchroma_pinned_stream_decodes_pixel_exact + 1 passed; 0 failed +cargo check -p ec-av1 --tests clean +``` + +## Class sweep, other crates + +`grep` for `let _ = std::fs::write` / `let _ = …write_all` / discarded `fs::write` across +every `ec-*` crate: + +| Site | Shape | Disposition | +|---|---|---| +| `ec-vorbis/tests/oracle.rs:1447,1452` | `let _ = fs::write` of sweep tables into `lanes/*.txt` | **Reported, not fixed.** Not the same shape: the path is not printed in a failure message, the file is a human-read report rather than a replay artefact, and the asserts that follow (`rows > 0`, `failures.is_empty()`) do not depend on it. Sibling lane material. | +| `ec-ac3/examples/ac3dec.rs:89,96` | `let _ = out.write_all(..)` to raw stdout of an example decoder | **Reported, not fixed.** No path is named; a short write there is the encoder of a raw file a downstream `cmp` measures. Different class (unverified output, not a mis-pointed replay path). | +| `ec-h264/tests/encode.rs:475,1068`, `ec-h265/tests/encode.rs:289,341` | `std::fs::write(..).ok()?` feeding an `ffmpeg` subprocess | **Reported, NOT fixed — half-open.** The `Err` path IS closed: `.ok()?` propagates the failure as `None` and the helper bails instead of running ffmpeg on a fragment. The `Ok`-but-short path is NOT closed: `fs::write` returning `Ok` does not guarantee the on-disk length — exactly the gap `LoudDump::finish()` exists to close — and these sites have no equivalent, the file going straight to ffmpeg as decoder input. Same mis-pointed-artefact family, one hop removed. A following lane should route these four through a loud writer; those crates have no shared helper yet, so the fix is per-crate. | + +Two of the sibling shapes are open in the weaker sense above; none of the sibling sites +has the "discard the error, then hand the reader that exact path" shape. Fixed only +`ec-av1` (plus its own msac site). + +## Notes for the reviewer + +- Success path is byte-identical; the only behavioural delta is that a short pin is now + fatal (9 sites + 2 gate dumps + the symtrace flush) or loud-with-counts (28143). +- Grep `TEST_PIN` (not `EC_AV1_PIN`) when triaging a short-pin failure line. \ No newline at end of file