forge
Explore
Log in

Don't you dare go Hollow

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

Browse files at this commit

3dd5d25c032e2d87e93ce3bab38c180d545f07d2Ahmet Kaan GümüşParent: fcbe2283aa53dd
ec-h264 and ec-h265 wrote their test pins with fs::write(..).ok()? and handed the path
straight to ffmpeg as decoder input. The Err path was closed (the helper bails), but a
write that returns Ok while leaving a short file was not -- ffmpeg would then read a
truncated stream and the test would report a wrong or missing comparison, not a failure.
The same silent-truncation class the ec-av1 dump and pin lanes closed, one hop removed.

A per-crate helper (not a cross-crate dependency) stats the file after the write and fails
loudly with the site, the path, the bytes on disk, the bytes owed, and the OS error -- or,
for the write that returned Ok and left a short file, the explicit statement that there was
no OS error. The failure semantics each site already had are kept: the callers bail, and
the one site that panicked before keeps a panicking twin. The sweep found a fifth
same-shape site (ec-h265's write_au) and fixed it too, and made the rd-trace write fatal
where a length check is impossible (append mode, no knowable total).

Proven with a real Ok-but-short write: a /dev/null symlink makes fs::write return Ok with
on-disk length 0 for 1234 bytes owed, and each crate's test asserts the failure line names
the path and the shortfall, then a whole-file control reads back byte-identical.
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,
744 for (addr, &(pre_luma, pre_chroma)) in pre.iter().enumerate() {744 for (addr, &(pre_luma, pre_chroma)) in pre.iter().enumerate() {
745 let (post_luma, post_chroma) = rd_trace_ssd(pic, src, addr % pic.mb_w, addr / pic.mb_w);745 let (post_luma, post_chroma) = rd_trace_ssd(pic, src, addr % pic.mb_w, addr / pic.mb_w);
746 let f = pic.mb_flags[addr];746 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!(
748 out,753 out,
749 "{frame} {addr} {} {} {} {} {pre_luma} {pre_chroma} {post_luma} {post_chroma}",754 "{frame} {addr} {} {} {} {} {pre_luma} {pre_chroma} {post_luma} {post_chroma}",
750 u8::from(f & FLAG_INTER == 0),755 u8::from(f & FLAG_INTER == 0),
751 u8::from(f & FLAG_TRANS8X8 != 0),756 u8::from(f & FLAG_TRANS8X8 != 0),
752 u8::from(f & FLAG_SKIP != 0),757 u8::from(f & FLAG_SKIP != 0),
753 pic.mb_qp[addr]758 pic.mb_qp[addr]
754- );759+ )
760+ .expect("write EC_H264_RD_TRACE");
755 }761 }
756 }762 }
757 763
crates/ec-h264/tests/encode.rsmodified+161 -2
@@ -459,6 +459,165 @@ fn require_fixture(path: &std::path::Path, generator: &str) -> bool {
459 present459 present
460 }460 }
461 461
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+
462 /// Decode an Annex B stream with ffmpeg, returning one I420 triple per picture.621 /// Decode an Annex B stream with ffmpeg, returning one I420 triple per picture.
463 fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Vec<Planes>> {622 fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Vec<Planes>> {
464 // Distinct per call, not per process: several #[test]s in this binary623 // 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
472 stream.len(),631 stream.len(),
473 SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)632 SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
474 ));633 ));
475- std::fs::write(&path, stream).ok()?;634+ pin_or_bail("ffmpeg_decode", &path, stream)?;
476 let mut cmd = std::process::Command::new("ffmpeg");635 let mut cmd = std::process::Command::new("ffmpeg");
477 cmd.args(["-v", "error"]);636 cmd.args(["-v", "error"]);
478 cmd.args(extra);637 cmd.args(extra);
@@ -1065,7 +1224,7 @@ fn x264_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32, gop: u32) ->
1065 buf.extend_from_slice(u);1224 buf.extend_from_slice(u);
1066 buf.extend_from_slice(v);1225 buf.extend_from_slice(v);
1067 }1226 }
1068- std::fs::write(&raw, &buf).ok()?;1227+ pin_or_bail("x264_encode_qp", &raw, &buf)?;
1069 let status = std::process::Command::new("ffmpeg")1228 let status = std::process::Command::new("ffmpeg")
1070 .args(["-v", "error", "-y"])1229 .args(["-v", "error", "-y"])
1071 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])1230 .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 {
91 )91 )
92 .expect("natural frame")92 .expect("natural frame")
93 }93 }
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 @@
6 6
7 mod common;7 mod common;
8 8
9-use common::{natural_frame, test_frame};9+use common::{natural_frame, pin_or_panic, test_frame};
10 use ec_core::frame::VideoFrame;10 use ec_core::frame::VideoFrame;
11 use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl, TransformSkip};11 use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl, TransformSkip};
12-use std::io::Write;
13 use std::path::{Path, PathBuf};12 use std::path::{Path, PathBuf};
14 use std::process::Command;13 use std::process::Command;
15 14
@@ -47,10 +46,17 @@ fn ffmpeg_decode(path: &Path) -> Result<Vec<u8>, String> {
47 std::fs::read(&out).map_err(|e| e.to_string())46 std::fs::read(&out).map_err(|e| e.to_string())
48 }47 }
49 48
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.
50 fn write_au(name: &str, picture: &EncodedPicture) -> PathBuf {57 fn write_au(name: &str, picture: &EncodedPicture) -> PathBuf {
51 let path = scratch_dir().join(format!("{name}.265"));58 let path = scratch_dir().join(format!("{name}.265"));
52- let mut file = std::fs::File::create(&path).expect("create bitstream");59+ pin_or_panic("write_au", &path, &picture.au);
53- file.write_all(&picture.au).expect("write bitstream");
54 path60 path
55 }61 }
56 62
crates/ec-h265/tests/encode.rsmodified+84 -2
@@ -6,6 +6,9 @@
6 //! own reconstruction — and x265's psychovisual and adaptive tools are off so6 //! own reconstruction — and x265's psychovisual and adaptive tools are off so
7 //! the comparison is at matched features, not at matched marketing.7 //! the comparison is at matched features, not at matched marketing.
8 8
9+mod common;
10+
11+use common::{pin_loud, pin_or_bail};
9 use ec_core::frame::VideoFrame;12 use ec_core::frame::VideoFrame;
10 use ec_h265::encoder::{Encoder, EncoderConfig, RateControl, TransformSkip};13 use ec_h265::encoder::{Encoder, EncoderConfig, RateControl, TransformSkip};
11 14
@@ -281,12 +284,91 @@ fn have_x265() -> bool {
281 .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx265"))284 .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx265"))
282 }285 }
283 286
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+
284 /// Decode an Annex-B stream with ffmpeg, returning one I420 triple per picture.366 /// Decode an Annex-B stream with ffmpeg, returning one I420 triple per picture.
285 fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Option<Vec<Planes>> {367 fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Option<Vec<Planes>> {
286 let dir = std::env::temp_dir().join(format!("ec-h265-enc-{}", std::process::id()));368 let dir = std::env::temp_dir().join(format!("ec-h265-enc-{}", std::process::id()));
287 std::fs::create_dir_all(&dir).ok()?;369 std::fs::create_dir_all(&dir).ok()?;
288 let path = dir.join(format!("s{}.265", stream.len()));370 let path = dir.join(format!("s{}.265", stream.len()));
289- std::fs::write(&path, stream).ok()?;371+ pin_or_bail("ffmpeg_decode", &path, stream)?;
290 let out = std::process::Command::new("ffmpeg")372 let out = std::process::Command::new("ffmpeg")
291 .args(["-v", "error"])373 .args(["-v", "error"])
292 .arg("-i")374 .arg("-i")
@@ -338,7 +420,7 @@ fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec
338 buf.extend_from_slice(u);420 buf.extend_from_slice(u);
339 buf.extend_from_slice(v);421 buf.extend_from_slice(v);
340 }422 }
341- std::fs::write(&raw, &buf).ok()?;423+ pin_or_bail("x265_encode_qp", &raw, &buf)?;
342 // The param list is the h264 gate's x264 list translated to x265's option424 // The param list is the h264 gate's x264 list translated to x265's option
343 // names: psychovisual (psy-rd, psy-rdoq) and adaptive (aq-mode) tools off,425 // names: psychovisual (psy-rd, psy-rdoq) and adaptive (aq-mode) tools off,
344 // plus the in-loop filters x265 adds and x264 does not have (no-sao,426 // 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\ No newline at end of file