forge
Explore
Log in

Don't you dare go Hollow

h26xpinloud: the h26x test pins fail loudly on an Ok-but-short write

Browse files at this commit

3aa53dd6af0eb8d5c53d6717e34e8fdee8ace5f9Ahmet Kaan GümüşParent: 69db758
ec-av1 already owns this class (dumpio::LoudDump: declare the expected byte
count, write, then stat the file's own length). These two crates had no
shared helper, so four sites called fs::write directly:

  ec-h264/tests/encode.rs:475  ffmpeg_decode    -> ffmpeg -i <stream>
  ec-h264/tests/encode.rs:1068 x264_encode_qp   -> ffmpeg -i <raw>
  ec-h265/tests/encode.rs:289  ffmpeg_decode    -> ffmpeg -i <stream>
  ec-h265/tests/encode.rs:341  x265_encode_qp   -> ffmpeg -i <raw>

Each was fs::write(&path, bytes).ok()?. That closes the Err path; the
Ok-but-short path stayed open, and it is the one that hands another tool a
silently truncated stream, which then reads as a wrong pixel or a shifted
PSNR number rather than a write failure. Measured: 1234 bytes written
through a path that looks like a stream file but whose filesystem accepts
every byte and stores none returns Ok, and the file on disk is 0 bytes.

Each site now goes through a per-crate pin_loud: write, then check the
on-disk length against the same bytes.len() the writer used, and fail with
the path, both counts, and the OS error. The helper returns the failure
LINE, not a panic, because these callers bail (or, at one h264 site, turn
None into a SKIP) today and that semantics is kept -- the shortfall is
printed in full and the existing bail stands. Only write_au panicked
before, so only it gets the panicking twin.

The helper is local per crate (no cross-crate dep, no new support crate):
ec-h265 keeps it in tests/common/mod.rs because its fifth site lives in a
different test binary, ec-h264 keeps it in tests/encode.rs where both of
its sites are.

Two non-vacuity tests per crate: a /dev/null symlink reproduces a genuine
Ok-but-short (0 of 1234), with a whole-file control read back byte for
byte; and a child under `ulimit -f 1` with SIGXFSZ ignored proves the Err
arm reports what actually LANDED (512 of 4096, EFBIG) rather than the
count the writer confirmed. Deleting the check turns the first RED.

Sweep of both crates: five sites fixed (the four named plus ec-h265's
write_au, File::create + write_all, whose path goes to ffmpeg the same
way), and one more -- ec-h264's append-mode $EC_H264_RD_TRACE writer,
which discarded its write result -- made fatal instead, because append
mode has no knowable total and so admits no length check. Everything else
in the two crates is ffmpeg's own output, a read-only path, a directory,
or an in-memory BitWriter.

Success path byte-identical: same bytes, same path, truncate-then-write.
crates/ec-h264/src/enc/mod.rsmodified+8 -2
@@ -744,14 +744,20 @@ fn rd_trace_write(pic: &Picture, src: &Source, frame: u64, pre: Option<Vec<(i64,
744744 for (addr, &(pre_luma, pre_chroma)) in pre.iter().enumerate() {
745745 let (post_luma, post_chroma) = rd_trace_ssd(pic, src, addr % pic.mb_w, addr / pic.mb_w);
746746 let f = pic.mb_flags[addr];
747- let _ = writeln!(
747+ // A discarded write result here is a SILENTLY SHORT trace: the reader
748+ // of `$EC_H264_RD_TRACE` attributes decisions from it and cannot tell a
749+ // short line count from a real one. No length check is possible (append
750+ // mode has no knowable total), so this is the ec-av1 `append_unknown`
751+ // shape: the write error is fatal instead.
752+ writeln!(
748753 out,
749754 "{frame} {addr} {} {} {} {} {pre_luma} {pre_chroma} {post_luma} {post_chroma}",
750755 u8::from(f & FLAG_INTER == 0),
751756 u8::from(f & FLAG_TRANS8X8 != 0),
752757 u8::from(f & FLAG_SKIP != 0),
753758 pic.mb_qp[addr]
754- );
759+ )
760+ .expect("write EC_H264_RD_TRACE");
755761 }
756762 }
757763
crates/ec-h264/tests/encode.rsmodified+161 -2
@@ -459,6 +459,165 @@ fn require_fixture(path: &std::path::Path, generator: &str) -> bool {
459459 present
460460 }
461461
462+/// Write `bytes` to `path` and PROVE the file on disk is exactly that long.
463+///
464+/// lane-h26xpinloud: every write below used `std::fs::write(..).ok()?` and then
465+/// handed `path` to ffmpeg, which closes only the ERROR path. An Ok-but-short
466+/// write -- a filesystem that reports success and stores fewer bytes (ENOSPC on
467+/// a full mount, EFBIG under a size cap, a quota, a failed final flush) -- left
468+/// ffmpeg decoding a truncated stream, and the failure surfaced as a
469+/// plausible-looking wrong pixel or a shifted PSNR number, not as a write
470+/// failure. MEASURED: 1234 bytes written through a path that LOOKS like a
471+/// stream file in a scratch directory but whose filesystem accepts every byte
472+/// and stores none returns `Ok`, and the file on disk is 0 bytes. So the length
473+/// is checked here once, from the same `bytes.len()` the writer used, and any
474+/// shortfall carries the path, both counts, and the OS error -- or, for the
475+/// write that reported success and left a short file, the plain statement that
476+/// there was no OS error, which is exactly the case that used to print nothing.
477+///
478+/// Returns the failure LINE rather than a bare bool, so the bail callers and any
479+/// panic caller all end on one format that cannot drift apart. The success path
480+/// is byte-identical to the old `fs::write`: same bytes, same path, truncate
481+/// then write.
482+fn pin_loud(site: &str, path: &std::path::Path, bytes: &[u8]) -> Result<(), String> {
483+ let expected = bytes.len();
484+ if let Err(e) = std::fs::write(path, bytes) {
485+ // The count here is the file's REAL length, not what the writer had
486+ // confirmed in hand: under a size cap the kernel stores everything up
487+ // to the cap and only THEN returns the error, and `fs::write` confirms
488+ // none of it.
489+ let on_disk = std::fs::metadata(path).map(|m| m.len() as usize).unwrap_or(0);
490+ return Err(short_line(
491+ site,
492+ path,
493+ on_disk,
494+ expected,
495+ &format!("the write failed: {e}"),
496+ ));
497+ }
498+ match std::fs::metadata(path) {
499+ Ok(m) if m.len() as usize == expected => Ok(()),
500+ Ok(m) => Err(short_line(
501+ site,
502+ path,
503+ m.len() as usize,
504+ expected,
505+ "the write reported success and the file on disk is still not that long (no OS error)",
506+ )),
507+ Err(e) => Err(short_line(
508+ site,
509+ path,
510+ 0,
511+ expected,
512+ &format!("the written file could not be stat'ed: {e}"),
513+ )),
514+ }
515+}
516+
517+/// The one failure line every short pin ends on: site, path, the bytes the file
518+/// holds vs the bytes owed, and the reason.
519+fn short_line(
520+ site: &str,
521+ path: &std::path::Path,
522+ on_disk: usize,
523+ expected: usize,
524+ why: &str,
525+) -> String {
526+ format!(
527+ "ec-h264 encode pin SHORT [{}] {}: file holds {on_disk} of {expected} bytes: {why}",
528+ site,
529+ path.display()
530+ )
531+}
532+
533+/// A pin whose shortfall is reported and then BAILED on, for a caller that
534+/// returns `None` today. Prints the same line [`pin_loud`] returns, so `None`
535+/// from here never reads as a plain "ffmpeg said no".
536+fn pin_or_bail(site: &str, path: &std::path::Path, bytes: &[u8]) -> Option<()> {
537+ pin_loud(site, path, bytes)
538+ .map_err(|why| eprintln!("{why}"))
539+ .ok()
540+}
541+
542+#[cfg(unix)]
543+#[test]
544+fn pin_loud_reds_on_an_ok_but_short_write() {
545+ // The shape the four sites left open: a write that reports success and
546+ // leaves a file of a different length. A symlink to /dev/null accepts every
547+ // byte and stores none, so `fs::write` returns Ok and the file is 0 bytes --
548+ // a stream path, silently empty.
549+ let dir = std::env::temp_dir().join(format!("ec-h264-pinloud-{}", std::process::id()));
550+ std::fs::create_dir_all(&dir).expect("scratch dir");
551+ let path = dir.join("ok-but-short.264");
552+ let _ = std::fs::remove_file(&path);
553+ std::os::unix::fs::symlink("/dev/null", &path).expect("symlink to /dev/null");
554+ let why = pin_loud("ok_but_short", &path, &[7u8; 1234]).unwrap_err();
555+ assert!(why.contains(&path.display().to_string()), "{why}");
556+ assert!(why.contains("file holds 0 of 1234 bytes"), "{why}");
557+ std::fs::remove_file(&path).ok();
558+
559+ // The control: the same call on a real file succeeds and leaves every byte.
560+ let good = dir.join("whole.264");
561+ let bytes = vec![7u8; 1234];
562+ pin_loud("control", &good, &bytes).expect("a whole write is not short");
563+ assert_eq!(std::fs::read(&good).expect("read back"), bytes);
564+ std::fs::remove_file(&good).ok();
565+ std::fs::remove_dir_all(&dir).ok();
566+}
567+
568+#[cfg(unix)]
569+#[test]
570+fn pin_loud_reports_what_landed_under_a_size_cap() {
571+ // The Err arm, driven for real: `ulimit -f` caps the file, the kernel stores
572+ // everything up to the cap and only then returns EFBIG. The line must carry
573+ // the bytes that actually LANDED (512 of a 1 KiB-block cap), not the count
574+ // the writer confirmed, which is zero.
575+ use std::process::Command;
576+ let Ok(exe) = std::env::current_exe() else {
577+ return;
578+ };
579+ // SIGXFSZ's default action would kill the child before it can print;
580+ // `trap '' XFSZ` sets SIG_IGN, which survives the exec.
581+ let script = format!(
582+ "ulimit -f 1; trap '' XFSZ; exec {} --exact pin_loud_cap_child --nocapture",
583+ exe.display()
584+ );
585+ let out = Command::new("sh")
586+ .args(["-c", &script])
587+ .env("EC_PINLOUD_CHILD", "1")
588+ .output()
589+ .expect("run the capped child");
590+ let text = format!(
591+ "{}{}",
592+ String::from_utf8_lossy(&out.stdout),
593+ String::from_utf8_lossy(&out.stderr)
594+ );
595+ assert!(!out.status.success(), "the capped write must fail: {text}");
596+ assert!(text.contains("file holds 512 of 4096 bytes"), "{text}");
597+ assert!(
598+ text.contains("EFBIG") || text.contains("File too large"),
599+ "{text}"
600+ );
601+}
602+
603+/// Child of [`pin_loud_reports_what_landed_under_a_size_cap`]: runs under
604+/// `ulimit -f 1` (a 1 KiB block cap) and pins 4096 bytes, so the write fails
605+/// partway. Inert unless the parent set `EC_PINLOUD_CHILD`.
606+#[test]
607+fn pin_loud_cap_child() {
608+ if std::env::var_os("EC_PINLOUD_CHILD").is_none() {
609+ return;
610+ }
611+ let dir = std::env::temp_dir().join(format!("ec-h264-pinloud-cap-{}", std::process::id()));
612+ std::fs::create_dir_all(&dir).expect("scratch dir");
613+ let path = dir.join("capped.264");
614+ let why = pin_loud("capped", &path, &[7u8; 4096])
615+ .expect_err("4096 bytes cannot fit a 1 KiB cap");
616+ std::fs::remove_file(&path).ok();
617+ std::fs::remove_dir_all(&dir).ok();
618+ panic!("{why}");
619+}
620+
462621 /// Decode an Annex B stream with ffmpeg, returning one I420 triple per picture.
463622 fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Vec<Planes>> {
464623 // Distinct per call, not per process: several #[test]s in this binary
@@ -472,7 +631,7 @@ fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Ve
472631 stream.len(),
473632 SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
474633 ));
475- std::fs::write(&path, stream).ok()?;
634+ pin_or_bail("ffmpeg_decode", &path, stream)?;
476635 let mut cmd = std::process::Command::new("ffmpeg");
477636 cmd.args(["-v", "error"]);
478637 cmd.args(extra);
@@ -1065,7 +1224,7 @@ fn x264_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32, gop: u32) ->
10651224 buf.extend_from_slice(u);
10661225 buf.extend_from_slice(v);
10671226 }
1068- std::fs::write(&raw, &buf).ok()?;
1227+ pin_or_bail("x264_encode_qp", &raw, &buf)?;
10691228 let status = std::process::Command::new("ffmpeg")
10701229 .args(["-v", "error", "-y"])
10711230 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
crates/ec-h265/tests/common/mod.rsmodified+93 -0
@@ -91,3 +91,96 @@ pub fn natural_frame(width: u32, height: u32, phase: u32) -> VideoFrame {
9191 )
9292 .expect("natural frame")
9393 }
94+
95+/// Write `bytes` to `path` and PROVE the file on disk is exactly that long.
96+///
97+/// lane-h26xpinloud: the encode gate's sites used `std::fs::write(..).ok()?`
98+/// and [`write_au`] used `File::create` + `write_all(..).expect(..)`, then all
99+/// three handed `path` to ffmpeg. Checking the `Result` closes only the ERROR
100+/// path. An Ok-but-short write -- a filesystem that reports success and stores
101+/// fewer bytes (ENOSPC on a full mount, EFBIG under a size cap, a quota, a
102+/// failed final flush) -- left ffmpeg decoding a truncated stream, and the
103+/// failure surfaced as a plausible-looking wrong pixel or a shifted PSNR
104+/// number, not as a write failure. MEASURED: 1234 bytes written through a path
105+/// that LOOKS like a stream file in a scratch directory but whose filesystem
106+/// accepts every byte and stores none returns `Ok`, and the file on disk is 0
107+/// bytes. So the length is checked here once, from the same `bytes.len()` the
108+/// writer used, and any shortfall carries the path, both counts, and the OS
109+/// error -- or, for the write that reported success and left a short file, the
110+/// plain statement that there was no OS error, which is exactly the case that
111+/// used to print nothing.
112+///
113+/// This is the ec-av1 `dumpio::LoudDump` idea replicated per crate: there is no
114+/// shared test-support crate here and none is being added for one function.
115+/// Returns the failure LINE rather than a bare bool, so the bail callers and the
116+/// panic caller all end on one format that cannot drift apart. The success path
117+/// is byte-identical to the old write: same bytes, same path, truncate then
118+/// write.
119+pub fn pin_loud(site: &str, path: &std::path::Path, bytes: &[u8]) -> Result<(), String> {
120+ let expected = bytes.len();
121+ if let Err(e) = std::fs::write(path, bytes) {
122+ // The count here is the file's REAL length, not what the writer had
123+ // confirmed in hand: under a size cap the kernel stores everything up
124+ // to the cap and only THEN returns the error, and the write confirms
125+ // none of it.
126+ let on_disk = std::fs::metadata(path).map(|m| m.len() as usize).unwrap_or(0);
127+ return Err(short_line(
128+ site,
129+ path,
130+ on_disk,
131+ expected,
132+ &format!("the write failed: {e}"),
133+ ));
134+ }
135+ match std::fs::metadata(path) {
136+ Ok(m) if m.len() as usize == expected => Ok(()),
137+ Ok(m) => Err(short_line(
138+ site,
139+ path,
140+ m.len() as usize,
141+ expected,
142+ "the write reported success and the file on disk is still not that long (no OS error)",
143+ )),
144+ Err(e) => Err(short_line(
145+ site,
146+ path,
147+ 0,
148+ expected,
149+ &format!("the written file could not be stat'ed: {e}"),
150+ )),
151+ }
152+}
153+
154+/// The one failure line every short pin ends on: site, path, the bytes the file
155+/// holds vs the bytes owed, and the reason.
156+fn short_line(
157+ site: &str,
158+ path: &std::path::Path,
159+ on_disk: usize,
160+ expected: usize,
161+ why: &str,
162+) -> String {
163+ format!(
164+ "ec-h265 test pin SHORT [{}] {}: file holds {on_disk} of {expected} bytes: {why}",
165+ site,
166+ path.display()
167+ )
168+}
169+
170+/// A pin whose shortfall is reported and then BAILED on, for a caller that
171+/// returns `None` today. Prints the same line [`pin_loud`] returns, so `None`
172+/// from here never reads as a plain "ffmpeg said no".
173+pub fn pin_or_bail(site: &str, path: &std::path::Path, bytes: &[u8]) -> Option<()> {
174+ pin_loud(site, path, bytes)
175+ .map_err(|why| eprintln!("{why}"))
176+ .ok()
177+}
178+
179+/// [`pin_loud`] with the shortfall PANICKING, for a caller that fails loudly
180+/// today. The panic message IS the failure line, so the two callers of this
181+/// shape cannot drift apart either.
182+pub fn pin_or_panic(site: &str, path: &std::path::Path, bytes: &[u8]) {
183+ if let Err(why) = pin_loud(site, path, bytes) {
184+ panic!("{why}");
185+ }
186+}
crates/ec-h265/tests/conformance.rsmodified+10 -4
@@ -6,10 +6,9 @@
66
77 mod common;
88
9-use common::{natural_frame, test_frame};
9+use common::{natural_frame, pin_or_panic, test_frame};
1010 use ec_core::frame::VideoFrame;
1111 use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl, TransformSkip};
12-use std::io::Write;
1312 use std::path::{Path, PathBuf};
1413 use std::process::Command;
1514
@@ -47,10 +46,17 @@ fn ffmpeg_decode(path: &Path) -> Result<Vec<u8>, String> {
4746 std::fs::read(&out).map_err(|e| e.to_string())
4847 }
4948
49+/// Pin one access unit as an Annex-B file for [`ffmpeg_decode`].
50+///
51+/// lane-h26xpinloud: this used `File::create(..).expect(..)` +
52+/// `write_all(..).expect("write bitstream")`, which closes only the ERROR path.
53+/// A write that reports success and leaves a short file put a truncated stream
54+/// at exactly the path ffmpeg then decoded, so the shortfall now carries the
55+/// path, both counts, and the OS error. Panic semantics kept: this caller
56+/// panicked before and still does, with the failure line as the message.
5057 fn write_au(name: &str, picture: &EncodedPicture) -> PathBuf {
5158 let path = scratch_dir().join(format!("{name}.265"));
52- let mut file = std::fs::File::create(&path).expect("create bitstream");
53- file.write_all(&picture.au).expect("write bitstream");
59+ pin_or_panic("write_au", &path, &picture.au);
5460 path
5561 }
5662
crates/ec-h265/tests/encode.rsmodified+84 -2
@@ -6,6 +6,9 @@
66 //! own reconstruction — and x265's psychovisual and adaptive tools are off so
77 //! the comparison is at matched features, not at matched marketing.
88
9+mod common;
10+
11+use common::{pin_loud, pin_or_bail};
912 use ec_core::frame::VideoFrame;
1013 use ec_h265::encoder::{Encoder, EncoderConfig, RateControl, TransformSkip};
1114
@@ -281,12 +284,91 @@ fn have_x265() -> bool {
281284 .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx265"))
282285 }
283286
287+#[cfg(unix)]
288+#[test]
289+fn pin_loud_reds_on_an_ok_but_short_write() {
290+ // The shape the two sites above left open: a write that reports success and
291+ // leaves a file of a different length. A symlink to /dev/null accepts every
292+ // byte and stores none, so `fs::write` returns Ok and the file is 0 bytes --
293+ // a stream path, silently empty.
294+ let dir = std::env::temp_dir().join(format!("ec-h265-pinloud-{}", std::process::id()));
295+ std::fs::create_dir_all(&dir).expect("scratch dir");
296+ let path = dir.join("ok-but-short.265");
297+ let _ = std::fs::remove_file(&path);
298+ std::os::unix::fs::symlink("/dev/null", &path).expect("symlink to /dev/null");
299+ let why = pin_loud("ok_but_short", &path, &[7u8; 1234]).unwrap_err();
300+ assert!(why.contains(&path.display().to_string()), "{why}");
301+ assert!(why.contains("file holds 0 of 1234 bytes"), "{why}");
302+ std::fs::remove_file(&path).ok();
303+
304+ // The control: the same call on a real file succeeds and leaves every byte.
305+ let good = dir.join("whole.265");
306+ let bytes = vec![7u8; 1234];
307+ pin_loud("control", &good, &bytes).expect("a whole write is not short");
308+ assert_eq!(std::fs::read(&good).expect("read back"), bytes);
309+ std::fs::remove_file(&good).ok();
310+ std::fs::remove_dir_all(&dir).ok();
311+}
312+
313+#[cfg(unix)]
314+#[test]
315+fn pin_loud_reports_what_landed_under_a_size_cap() {
316+ // The Err arm, driven for real: `ulimit -f` caps the file, the kernel stores
317+ // everything up to the cap and only then returns EFBIG. The line must carry
318+ // the bytes that actually LANDED (512 of a 1 KiB-block cap), not the count
319+ // the writer confirmed, which is zero.
320+ use std::process::Command;
321+ let Ok(exe) = std::env::current_exe() else {
322+ return;
323+ };
324+ // SIGXFSZ's default action would kill the child before it can print;
325+ // `trap '' XFSZ` sets SIG_IGN, which survives the exec.
326+ let script = format!(
327+ "ulimit -f 1; trap '' XFSZ; exec {} --exact pin_loud_cap_child --nocapture",
328+ exe.display()
329+ );
330+ let out = Command::new("sh")
331+ .args(["-c", &script])
332+ .env("EC_PINLOUD_CHILD", "1")
333+ .output()
334+ .expect("run the capped child");
335+ let text = format!(
336+ "{}{}",
337+ String::from_utf8_lossy(&out.stdout),
338+ String::from_utf8_lossy(&out.stderr)
339+ );
340+ assert!(!out.status.success(), "the capped write must fail: {text}");
341+ assert!(text.contains("file holds 512 of 4096 bytes"), "{text}");
342+ assert!(
343+ text.contains("EFBIG") || text.contains("File too large"),
344+ "{text}"
345+ );
346+}
347+
348+/// Child of [`pin_loud_reports_what_landed_under_a_size_cap`]: runs under
349+/// `ulimit -f 1` (a 1 KiB block cap) and pins 4096 bytes, so the write fails
350+/// partway. Inert unless the parent set `EC_PINLOUD_CHILD`.
351+#[test]
352+fn pin_loud_cap_child() {
353+ if std::env::var_os("EC_PINLOUD_CHILD").is_none() {
354+ return;
355+ }
356+ let dir = std::env::temp_dir().join(format!("ec-h265-pinloud-cap-{}", std::process::id()));
357+ std::fs::create_dir_all(&dir).expect("scratch dir");
358+ let path = dir.join("capped.265");
359+ let why = pin_loud("capped", &path, &[7u8; 4096])
360+ .expect_err("4096 bytes cannot fit a 1 KiB cap");
361+ std::fs::remove_file(&path).ok();
362+ std::fs::remove_dir_all(&dir).ok();
363+ panic!("{why}");
364+}
365+
284366 /// Decode an Annex-B stream with ffmpeg, returning one I420 triple per picture.
285367 fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Option<Vec<Planes>> {
286368 let dir = std::env::temp_dir().join(format!("ec-h265-enc-{}", std::process::id()));
287369 std::fs::create_dir_all(&dir).ok()?;
288370 let path = dir.join(format!("s{}.265", stream.len()));
289- std::fs::write(&path, stream).ok()?;
371+ pin_or_bail("ffmpeg_decode", &path, stream)?;
290372 let out = std::process::Command::new("ffmpeg")
291373 .args(["-v", "error"])
292374 .arg("-i")
@@ -338,7 +420,7 @@ fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec
338420 buf.extend_from_slice(u);
339421 buf.extend_from_slice(v);
340422 }
341- std::fs::write(&raw, &buf).ok()?;
423+ pin_or_bail("x265_encode_qp", &raw, &buf)?;
342424 // The param list is the h264 gate's x264 list translated to x265's option
343425 // names: psychovisual (psy-rd, psy-rdoq) and adaptive (aq-mode) tools off,
344426 // plus the in-loop filters x265 adds and x264 does not have (no-sao,
lanes/h26xpinloud.report.mdadded+159 -0
@@ -0,0 +1,159 @@
1+# lane/h26xpinloud — the h26x test pins fail loudly on an Ok-but-short write
2+
3+Base: `main` = `b8385c93`.
4+
5+`ec-av1` already owns this class: `crates/ec-av1/src/dumpio.rs` (`LoudDump`, and
6+`pin` / `pin_reporting` for the test-pin shape) declares the expected byte count,
7+writes, then stats the file's own length on disk and fails loudly on any
8+shortfall. The two h26x crates had no shared helper, so the four sites called
9+directly and the fix is per crate.
10+
11+## The four named sites
12+
13+| crate | site (pre-fix) | what it wrote | who read it |
14+|---|---|---|---|
15+| `ec-h264` | `tests/encode.rs:475` in `ffmpeg_decode` | our Annex B stream | `ffmpeg -i <path>` |
16+| `ec-h264` | `tests/encode.rs:1068` in `x264_encode_qp` | raw I420 for x264 | `ffmpeg -i <raw>` (x264 encode) |
17+| `ec-h265` | `tests/encode.rs:289` in `ffmpeg_decode` | our Annex B stream | `ffmpeg -i <path>` |
18+| `ec-h265` | `tests/encode.rs:341` in `x265_encode_qp` | raw I420 for x265 | `ffmpeg -i <raw>` (x265 encode) |
19+
20+All four were `std::fs::write(&path, bytes).ok()?`. The `Err` path was closed
21+(bail via `?`); the **Ok-but-short** path was not, and that is the one that
22+produces an artefact another tool then trusts.
23+
24+## Sweep of the two crates
25+
26+Every write-ish call in `crates/ec-h264` and `crates/ec-h265` (source + all test
27+binaries), filtered to the ones whose path an external reader takes:
28+
29+**Fixed — same shape:**
30+
31+- `ec-h264/tests/encode.rs:475`, `:1068` (the two named sites).
32+- `ec-h265/tests/encode.rs:289`, `:341` (the two named sites).
33+- `ec-h265/tests/conformance.rs:50` `write_au` — `File::create` +
34+ `write_all(&picture.au).expect("write bitstream")`, whose `path` is passed
35+ straight to `ffmpeg_decode` → `ffmpeg -i`. `write_all` returning `Ok` means the
36+ bytes were accepted by the write, not that the file holds them; the same
37+ on-disk stat is missing. **Not in the ticket's four, but the identical shape
38+ and the same crate, so it is fixed too.** It is the fifth site and the only
39+ one that fed a path written by `File::create`.
40+- `ec-h264/src/enc/mod.rs:747` `rd_trace_write` — `let _ = writeln!(out, ..)`
41+ into `$EC_H264_RD_TRACE` (feature `rd-ablation`). This one is an append-mode
42+ text table with **no knowable total**, so no length check is possible (the
43+ ec-av1 `append_unknown` case: `expected: None`). But discarding the write
44+ result leaves a silently short trace that an RD-attribution reader cannot
45+ distinguish from a complete one. Fixed as far as the shape allows: the write
46+ error is now fatal (`.expect("write EC_H264_RD_TRACE")`). The length check is
47+ deliberately absent, and the comment says why.
48+
49+**Swept and NOT the same shape (with the reason):**
50+
51+- `ec-h264/tests/conformance.rs` `x264_encode` / `x264_encode_gop` (and
52+ `extract_annexb`, ~1765) — these do not write the file themselves; **ffmpeg**
53+ writes the stream (`-f h264 <path>`, `h264_mp4toannexb`) and the harness reads
54+ it back with `fs::read`. There is no discarded write result of ours to check:
55+ ffmpeg's exit status is the only signal, and `run(...)` already discards
56+ everything but that boolean. Not this class.
57+- `ec-h264/tests/conformance.rs` `compare_sequence_streamed` (1693),
58+ `compare_container_streamed` (1815), `ffmpeg_all_frames` (226),
59+ `ffmpeg_first_frame` (144) — read-only paths into ffmpeg; no write of ours.
60+- `ec-h264/tests/conformance.rs` `scratch_dir` (694) `let _ = create_dir_all` and
61+ the many `let _ = remove_dir_all` — directory lifecycle, no bytes, no length to
62+ owe.
63+- `ec-h265/tests/common/mod.rs`, `decode.rs`, `perf.rs`, `rdoq_cache_hash.rs` —
64+ no file writes at all.
65+- `ec-h265/src/encoder.rs:769` `header.write(&mut writer, ..)` — an in-memory
66+ `BitWriter`, not a file.
67+
68+So: **every write in these two crates whose path is handed to ffmpeg now goes
69+through the loud pin** (five sites), and the one remaining write with a discarded
70+result (the append-mode RD trace) has its error made fatal because no length is
71+knowable.
72+
73+## Shape chosen: a per-crate helper, not four inline checks
74+
75+`pin_loud` (plus `short_line`, `pin_or_bail`, `pin_or_panic`), replicating
76+ec-av1's `dumpio` idea per crate — no cross-crate dependency, per contract.
77+
78+Why a helper and not inline checks: the four (now five) sites are the *same*
79+shape — write `bytes` to a `Path`, then hand `Path` to ffmpeg — so inline checks
80+would duplicate the failure-line format five times and let it drift, which is
81+precisely the ec-av1 hazard its shared `failure_line` exists to prevent. The
82+helper returns the **failure line as `Err(String)`** rather than panicking,
83+because three of the five sites `return None` on write failure today and
84+`:690` in ec-h264 turns `None` into a **SKIP**. Making it panic would have
85+changed a skip into a failure; instead the shortfall is printed in full and the
86+existing bail/skip semantics are preserved. Only `write_au` panicked before, so
87+only it gets `pin_or_panic` (the line *is* the panic message).
88+
89+Placement: `ec-h265` has a shared `tests/common/mod.rs` used by four test
90+binaries, and `write_au` lives in a different binary from `ffmpeg_decode`, so the
91+helper lives there. `ec-h264` has no `tests/common`; both of its sites are in
92+`tests/encode.rs`, so the helper is local to that file.
93+
94+## Proof the check bites
95+
96+Both crates carry two new non-vacuity tests.
97+
98+**1. Genuine Ok-but-short (`pin_loud_reds_on_an_ok_but_short_write`).** A
99+`/dev/null` symlink in a scratch dir is the shape: it *looks* like
100+`.../ok-but-short.264`, it accepts every byte, it stores none. Measured on this
101+box with a standalone `rustc` probe:
102+
103+```
104+fs::write -> Ok(()) | on-disk len = 0 | owed = 1234 # symlink to /dev/null
105+fs::write -> Ok(()) | on-disk len = 1234 | owed = 1234 # real file
106+```
107+
108+The test asserts the returned line contains the path and `file holds 0 of 1234
109+bytes`, then asserts the control — a real file of 1234 bytes succeeds and reads
110+back byte-identical.
111+
112+**Red-before proof (mutation).** Replacing the length check's short arm with
113+`Ok(())` (i.e. deleting the check) turns the test RED:
114+
115+```
116+---- pin_loud_reds_on_an_ok_but_short_write stdout ----
117+panicked at crates/ec-h264/tests/encode.rs:548:61:
118+called `Result::unwrap_err()` on an `Ok` value: ()
119+test result: FAILED. 0 passed; 1 failed
120+```
121+
122+Restored afterwards; `git diff --stat` confirms the helper is back.
123+
124+**2. The Err arm, driven for real (`pin_loud_reports_what_landed_under_a_size_cap`).**
125+A child process runs under `ulimit -f 1` (a 1 KiB block cap) with `SIGXFSZ`
126+ignored (`trap '' XFSZ`, which survives the exec) and pins 4096 bytes. The kernel
127+stores up to the cap and *then* returns `EFBIG`, so the acknowledged count is
128+zero while 512 bytes are on disk. Actual output from both binaries:
129+
130+```
131+ec-h264 encode pin SHORT [capped] /tmp/ec-h264-pinloud-cap-*/capped.264: file holds 512 of 4096 bytes: the write failed: File too large (os error 27)
132+ec-h265 test pin SHORT [capped] /tmp/ec-h265-pinloud-cap-*/capped.265: file holds 512 of 4096 bytes: the write failed: File too large (os error 27)
133+```
134+
135+The count on the line is the file's **real** length, not the writer's confirmed
136+count — which is the part the acked count gets wrong.
137+
138+## Scoped runs
139+
140+```
141+cargo check -p ec-h264 -p ec-h265 --tests # clean
142+cargo check -p ec-h264 --features rd-ablation # clean
143+cargo test -p ec-h264 --test encode pin_loud # 3 passed
144+cargo test -p ec-h265 --test encode pin_loud # 3 passed
145+```
146+
147+(The full `ec-av1` suite runs on the server; per contract these two crates were
148+checked and run locally, scoped.)
149+
150+## What did not change
151+
152+- The success path is byte-identical to the old `fs::write`: same bytes, same
153+ path, truncate-then-write. The `control` half of each test reads the file back
154+ and compares bytes.
155+- No assertion was weakened and no gate's printed output changed on the success
156+ path. The only new output is on the shortfall path, which previously printed
157+ nothing at all.
158+- No decode/encode logic touched: `ec-h264/src/enc/mod.rs` changed only inside the
159+ `rd-ablation`-gated trace writer's discarded result.
\ No newline at end of file