diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 92dbfb33..424c7a40 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -21465,7 +21465,11 @@ const MAX_LEGAL_SAMPLE: u16 = 4095; /// being impossible. `EC_AV1_PLANE_SENTINEL=1` -- the spelling every existing /// caller and gate uses, and `env_flag!`'s mere presence test -- keeps /// [`PLANE_SENTINEL`]. -fn plane_poison() -> u16 { +/// `pub(crate)` for lane-av1graincensus: `film_grain::uninit_plane` fills its +/// destination with the SAME poison `fresh_plane` does, and +/// [`census_unwritten_grained`] counts the same value. The fill and the census +/// must agree on both the value and the predicate, or a "0" means nothing. +pub(crate) fn plane_poison() -> u16 { static V: std::sync::LazyLock = std::sync::LazyLock::new(|| { let Ok(raw) = crate::envflags::var("EC_AV1_PLANE_SENTINEL") else { return PLANE_SENTINEL; @@ -21493,7 +21497,8 @@ thread_local! { } /// Whether freshly allocated planes are [`PLANE_SENTINEL`]-filled. -fn plane_sentinel_on() -> bool { +/// `pub(crate)` for the same reason as [`plane_poison`]. +pub(crate) fn plane_sentinel_on() -> bool { crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") || PLANE_SENTINEL_ON.with(std::cell::Cell::get) } @@ -21855,6 +21860,11 @@ pub fn take_final_census_scanned() -> usize { /// plane, how many samples still hold [`PLANE_SENTINEL`] once every filter has /// run, and records how many samples it LOOKED at in [`FINAL_CENSUS_SCANNED`]. /// +/// SCOPE, which lane-av1graincensus did not change but had to be true about: +/// this runs BEFORE `apply_grain`, over the PRE-grain planes. It does NOT and +/// never did measure the grained picture the caller receives -- that is +/// [`census_unwritten_grained`], a separate counter over a separate buffer. +/// /// Gated on [`plane_sentinel_on`] -- the SAME predicate as [`fresh_plane`] and as /// the pre-deblock [`census_unwritten`]: the env flag OR the thread-local /// [`set_plane_sentinel`] override. An earlier revision gated this on the raw env @@ -21862,19 +21872,86 @@ pub fn take_final_census_scanned() -> usize { /// the thread-local switch that the rest of the crate honours. The fill and both /// censuses must agree on when they are live, or a "0" means nothing. pub(crate) fn census_unwritten_final(y: &[u16], u: &[u16], v: &[u16]) { - if !plane_sentinel_on() { + let Some((scanned, total)) = census_sentinels(y, u, v) else { return; + }; + FINAL_CENSUS_SCANNED.fetch_add(scanned, std::sync::atomic::Ordering::SeqCst); + FINAL_UNWRITTEN_SAMPLES.fetch_add(total, std::sync::atomic::Ordering::SeqCst); +} + +/// The `(scanned, unwritten)` pair both output-point censuses accumulate, or +/// `None` when the sentinel fill is not live. +/// +/// Shared so the two censuses cannot drift into disagreeing about what counts +/// as unwritten -- the failure this crate's other paired counters exist to +/// prevent. `None` (rather than `(0, 0)`) is what keeps a caller from +/// publishing a meaningless zero when the fill was off. +fn census_sentinels(y: &[u16], u: &[u16], v: &[u16]) -> Option<(usize, usize)> { + if !plane_sentinel_on() { + return None; } - // The caller passes the frame's planes exactly as they are about to be - // stored into the reference slots, which are already cropped to the true - // extent (no padding past it reaches this point), so a flat count over - // each plane IS the true-extent count. + // Both callers pass planes cropped to the true extent (no padding past it + // reaches either point), so a flat count over each plane IS the + // true-extent count. let (scanned, total): (usize, usize) = [y, u, v] .iter() .map(|p| (p.len(), p.iter().filter(|&&s| s == plane_poison()).count())) .fold((0, 0), |(a, b), (c, d)| (a + c, b + d)); - FINAL_CENSUS_SCANNED.fetch_add(scanned, std::sync::atomic::Ordering::SeqCst); - FINAL_UNWRITTEN_SAMPLES.fetch_add(total, std::sync::atomic::Ordering::SeqCst); + Some((scanned, total)) +} + +/// lane-av1graincensus: samples still holding the poison after film grain, over +/// the picture [`crate::film_grain::apply_grain`] RETURNS -- i.e. the picture the +/// caller receives on a grained frame. +static GRAINED_UNWRITTEN_SAMPLES: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); + +/// The scanned half of the pairing for [`GRAINED_UNWRITTEN_SAMPLES`]. A gate +/// asserting only `== 0` passes on a build whose census call was deleted. +static GRAINED_CENSUS_SCANNED: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); + +/// Reads and clears [`GRAINED_UNWRITTEN_SAMPLES`]. +pub fn take_grained_unwritten_samples() -> usize { + GRAINED_UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst) +} + +/// Reads and clears [`GRAINED_CENSUS_SCANNED`]; the pairing is the reason it +/// exists, exactly as for [`take_final_census_scanned`]. +pub fn take_grained_census_scanned() -> usize { + GRAINED_CENSUS_SCANNED.swap(0, std::sync::atomic::Ordering::SeqCst) +} + +/// lane-av1graincensus: the SECOND output-point census -- the one +/// [`census_unwritten_final`] structurally cannot be. +/// +/// # WHY IT EXISTS +/// +/// `census_unwritten_final` runs at `stream.rs`'s `EC_AV1_FINAL_DUMP` site, which +/// is BEFORE `apply_grain`. Every filter (deblock/CDEF/LR/superres) writes in +/// place into the same buffer that census scanned, so those stages cannot open a +/// hole outside its extent. `apply_grain` is the ONE stage after it that +/// allocates a fresh picture -- `uninit_plane`, `Vec::with_capacity` + +/// `set_len`, no fill -- and whose soundness rests on a band row partition +/// rather than on the type system. Its destination therefore reaches the caller +/// having never been looked at by any census, and `lanes/unwritten-dep.report.md` +/// §6/§8 explicitly declines to claim otherwise. +/// +/// # WHAT IT IS WORTH ONLY IF THE FILL IS LIVE +/// +/// Counting `== plane_poison()` over an uninitialised buffer is a census that +/// can only ever report ~0: garbage is arbitrary, so a hole survives with +/// probability ~1/65536 rather than always. `uninit_plane` therefore fills with +/// the poison when [`plane_sentinel_on`] -- under the SAME predicate +/// [`fresh_plane`] honours -- so "the band copy wrote every sample" becomes a +/// measurement instead of an assumption. With the sentinel off (every shipped +/// build) nothing here runs and `uninit_plane` keeps its corner-cut. +pub(crate) fn census_unwritten_grained(y: &[u16], u: &[u16], v: &[u16]) { + let Some((scanned, total)) = census_sentinels(y, u, v) else { + return; + }; + GRAINED_CENSUS_SCANNED.fetch_add(scanned, std::sync::atomic::Ordering::SeqCst); + GRAINED_UNWRITTEN_SAMPLES.fetch_add(total, std::sync::atomic::Ordering::SeqCst); } /// Which closure [`fresh_plane`] applies to the allocation it hands back. @@ -38457,8 +38534,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // data lengths: this dump is the PADDED plane, not a crop, so the // writer's extent is `p.data` itself. let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let narrow = - |p: &PlaneBuf<'_>| -> Vec { p.data.iter().map(|&s| s as u8).collect() }; + let narrow = |p: &PlaneBuf<'_>| -> Vec { p.data.iter().map(|&s| s as u8).collect() }; crate::dumpio::write_planes( "EC_AV1_PREFILT_DUMP", format!("{path}.f{idx}"), @@ -56838,8 +56914,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // lane-av1dumploud: loud on a short write (see the key-frame twin // above -- same file, same shape, same three planes). let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let narrow = - |p: &PlaneBuf<'_>| -> Vec { p.data.iter().map(|&s| s as u8).collect() }; + let narrow = |p: &PlaneBuf<'_>| -> Vec { p.data.iter().map(|&s| s as u8).collect() }; crate::dumpio::write_planes( "EC_AV1_PREFILT_DUMP", format!("{path}.f{idx}"), diff --git a/crates/ec-av1/src/film_grain.rs b/crates/ec-av1/src/film_grain.rs index 09cb4678..0c5ee7b8 100644 --- a/crates/ec-av1/src/film_grain.rs +++ b/crates/ec-av1/src/film_grain.rs @@ -1281,12 +1281,28 @@ fn copy_clean_rows( /// [`crate::par::Shared`]'s disjointness is; the byte-exact 1-vs-4-thread /// gate is what checks it. Upgrade path: `Box<[MaybeUninit]>` plumbed /// through the kernels. +/// +/// # lane-av1graincensus: the fill under the census arm +/// +/// That corner-cut is also why the buffer must be POISONED, not merely +/// uninitialised, whenever the sentinel is live. Counting `== plane_poison()` +/// over ambient garbage is a census that can only ever report ~0: a hole +/// survives with probability ~1/65536 rather than always, so +/// [`crate::decode::census_unwritten_grained`] would report 0 whether or not +/// the band copy covered every row. Filling here makes "the band copy wrote +/// every sample" a measurement. It is the same predicate +/// [`crate::decode::fresh_plane`] honours, and with the sentinel off -- every +/// shipped build -- this is the `with_capacity` + `set_len` it always was, so +/// the corner-cut is untouched where it is paid for. #[allow(unsafe_code)] fn uninit_plane(n: usize) -> Vec { let mut v: Vec = Vec::with_capacity(n); // SAFETY: `u16` has no invalid bit pattern and no uninitialised sample is // read -- see the doc comment. unsafe { v.set_len(n) }; + if crate::decode::plane_sentinel_on() { + v.fill(crate::decode::plane_poison()); + } v } @@ -1338,7 +1354,12 @@ pub(crate) fn apply_grain( fctx: &crate::decode::FrameCtx, ) -> Picture { if !fg.apply_grain { - return picture.clone(); + let clean = picture.clone(); + // lane-av1graincensus: this exit censuses too, so "the picture + // `apply_grain` hands back is censused in its final form" is a property + // of the FUNCTION rather than of one branch. + crate::decode::census_unwritten_grained(&clean.y, &clean.u, &clean.v); + return clean; } fctx.grain_bit_depth.with(|c| c.set(bit_depth)); hit!(GRAIN_HITS); @@ -1992,6 +2013,16 @@ pub(crate) fn apply_grain( }); let _ = so; + // lane-av1graincensus: the post-grain census, at the point the caller takes + // the picture. `census_unwritten_final` runs in `stream.rs` BEFORE this + // function, over the clean planes, and every filter writes in place into + // that same buffer -- so the destination allocated above by `uninit_plane` + // is the ONLY picture between that census and the caller that no census has + // ever looked at. `lanes/unwritten-dep.report.md` §6/§8 declined to claim + // anything about it; this measures it. `uninit_plane` poisons the buffer + // under the same predicate, so the count is a measurement rather than a + // coin flip on ambient garbage. + crate::decode::census_unwritten_grained(&out.y, &out.u, &out.v); out } diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index eb980952..c01fd9b6 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -2246,12 +2246,20 @@ fn decode_frame( // census SEES it. // // So this second census is not a patch for a blind pre-deblock scan. It is - // the measurement taken where the output is taken, which covers the whole span - // from the tile walk to the caller's frame: anything a later stage could - // introduce (a filter, superres, a second pass) is inside its extent, where - // a scan taken before it would not be. It also runs before `apply_grain`, so - // the claim is over the PRE-GRAIN planes -- the bytes the reference bank - // stores and every later frame predicts from. + // the measurement taken where the reference-bank bytes are taken, which + // covers the whole span from the tile walk to those bytes: every filter + // writes IN PLACE into the very buffer this scans, so nothing a later + // filter does can open a hole outside its extent. + // + // lane-av1graincensus, the scope correction this comment needed: "to the + // caller's frame" was WRONG, and this call is not what makes it right. + // `apply_grain` runs after this and ALLOCATES a fresh picture + // (`film_grain::uninit_plane`, `with_capacity` + `set_len`, no fill), so + // that destination never passes through here. The claim over the PRE-GRAIN + // planes -- the bytes the reference bank stores and every later frame + // predicts from -- is what this line supports; the grained picture the + // caller receives is censused by `decode::census_unwritten_grained`, at + // `apply_grain`'s own return, over its own counters. decode::census_unwritten_final(&picture.y, &picture.u, &picture.v); if let Some(prefix) = final_dump { // lane-av1dumploud: this is the site that produced the 13 320 192-byte @@ -48658,10 +48666,17 @@ exit 0 /// `EC_AV1_FINAL_DUMP` writes, which is BEFORE `apply_grain`. The claim is /// therefore over the PRE-GRAIN planes -- which are also the bytes the /// reference bank stores and every later frame predicts from, the dependency - /// that matters. Whether `apply_grain` can itself introduce a hole is NOT - /// measured: the census never sees the planes `apply_grain` allocates. So the - /// claim is NOT "the caller's final grained picture has no hole", and nothing - /// here asserts that grain cannot introduce one. + /// that matters. Every filter writes IN PLACE into the buffer this scans, so + /// none of them can open a hole outside its extent. `apply_grain` is the one + /// stage after this scan that ALLOCATES a new picture, and this census never + /// sees it: the claim is NOT "the caller's final grained picture has no hole". + /// + /// lane-av1graincensus: that paragraph is still true of THIS gate and is not + /// weakened by the pointer below -- what changed is that the gap it names is + /// no longer UNMEASURED. + /// [`the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample`] + /// measures the grained picture `apply_grain` returns, over its own counters, + /// and is the gate that carries the post-grain claim. /// /// NON-VACUITY, the part that makes this gate worth having: a census is only a /// measurement if it CAN report non-zero. The control is a SYNTHETIC positive @@ -48787,6 +48802,165 @@ exit 0 } } + /// lane-av1graincensus: the picture the caller RECEIVES -- including film + /// grain -- carries no unwritten plane sample. + /// + /// # WHAT THIS GATE IS FOR, and the blind spot it closes + /// + /// [`the_frame_the_caller_receives_carries_no_unwritten_plane_sample`] scans + /// at `stream.rs`'s `EC_AV1_FINAL_DUMP` site, which is BEFORE `apply_grain`. + /// Every filter (deblock/CDEF/LR/superres) writes IN PLACE into the buffer it + /// scans, so none of them can open a hole outside its extent -- but + /// `apply_grain` is the one stage after that scan that ALLOCATES a fresh + /// picture: `film_grain::uninit_plane`, `Vec::with_capacity` + `set_len`, no + /// fill, with correctness resting on a band row partition rather than on the + /// type system. `lanes/unwritten-dep.report.md` §6 and §8 declined to claim + /// anything about that destination. This gate measures it. + /// + /// # WHY THE COUNT CAN BE NON-ZERO (the part that makes it a census) + /// + /// Counting `== plane_poison()` over an uninitialised buffer is a census that + /// reports ~0 either way: a hole survives with probability ~1/65536, not + /// always. `uninit_plane` therefore fills with the poison under the SAME + /// predicate `fresh_plane` honours. With the sentinel off -- every shipped + /// build -- `uninit_plane` is still `with_capacity` + `set_len`, so the + /// corner-cut it documents is untouched. + /// + /// # SCOPE, stated not implied + /// + /// The claim is over the picture the caller receives ON A GRAINED FRAME, in + /// its final form, after the noise. It is NOT a claim that the pre-grain + /// census already covered this -- that census never sees this buffer -- and it + /// is NOT a claim about a frame whose grain step does not run. + /// + /// # NON-VACUITY, two arms, both required + /// + /// 1. **synthetic, first, and with a DIFFERENT known count (5, not the + /// pre-grain arm's 7)** so a gate reading the wrong counter goes red. No + /// fixture involved, so no lane's refusal can redden it. + /// 2. **per-fixture `scanned > 0`** -- `unwritten == 0` is also what a build + /// with the census call deleted reports. `scanned > 0` is reachable only by + /// `apply_grain` actually running, so it is at once the + /// proof-that-grain-fired and the deletion control. + /// + /// Both mutations are in `lanes/av1graincensus.report.md`: deleting the + /// `census_unwritten_grained` call at `apply_grain`'s return reds arm 2, and + /// forcing ONE poison sample into a grained picture reds arm 2's count. + #[test] + fn the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample() { + const NAME: &str = + "the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample"; + let _gate_lock = lock_gate_counters(); + + let (syn, syn_scanned) = grain_census_synthetic(); + assert_eq!( + syn_scanned, 40, + "{NAME}: the synthetic control scanned {syn_scanned} samples, expected 40 \ + (16 + 16 + 8) -- the grained census did not look at what it was handed" + ); + assert_eq!( + syn, 5, + "{NAME}: the grained census reported {syn} for planes carrying exactly 5 sentinel \ + samples -- it is not measuring what it claims, so every zero below is \ + meaningless (class: census-silently-blind). Note 5, not the pre-grain arm's 7: \ + reading the wrong counter is the failure this number catches." + ); + + // Small and cheap: a 4:2:2 grain stream, a 4:2:0 one that also runs + // CDEF+LR, and the real 10-bit 3840x1608 hidden-alt-ref film whose height + // is not a multiple of the 32-pixel band row -- the shape where the band + // row partition has a tail. + for fixture in [ + "s422_grain_160x128", + "grain_cdef_lr_128x128", + "reelb_arf_witness", + ] { + let (n, scanned) = grain_census(fixture); + assert!( + scanned > 0, + "{NAME}: the grained census scanned 0 samples on {fixture} -- the call at \ + `apply_grain`'s return is not running (or grain never fired), so the {n} \ + below proves nothing (class: census-never-ran). Deleting the call in \ + apply_grain reproduces this." + ); + assert_eq!( + n, 0, + "{NAME}: {fixture} hands the caller a grained picture with {n} samples the \ + grain destination's band copy never wrote" + ); + } + } + + /// Runs the census child on `fixture` and returns the `GRAINCENSUS` line's + /// `(unwritten, scanned)` -- the POST-grain pair, over the picture + /// `apply_grain` returns. + fn grain_census(fixture: &str) -> (usize, usize) { + const NAME: &str = + "the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample"; + let exe = std::env::current_exe().expect("test binary path"); + let out = std::process::Command::new(exe) + .args([ + "--exact", + "stream::tests::uwdep_child_unwritten_census", + "--nocapture", + ]) + .env("UWDEP_CENSUS_FIXTURE", fixture) + .env("EC_AV1_PLANE_SENTINEL", "1") + .output() + .expect("running the census child"); + let text = format!( + "{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); + text.lines() + .find_map(|l| l.strip_prefix("GRAINCENSUS ")) + .and_then(parse_census_line) + .unwrap_or_else(|| { + panic!( + "{NAME}: the census child reported no grained count for {fixture} \ + (child said: {:?})", + text.trim() + ) + }) + } + + /// The synthetic non-vacuity control for the grained census: the child with + /// `UWDEP_CENSUS_FIXTURE` UNSET hands [`census_unwritten_grained`] planes + /// carrying 5 sentinel samples and reports what it counted. Function-level, + /// so no fixture's decode behaviour can change it. + fn grain_census_synthetic() -> (usize, usize) { + const NAME: &str = + "the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample"; + let exe = std::env::current_exe().expect("test binary path"); + let out = std::process::Command::new(exe) + .args([ + "--exact", + "stream::tests::uwdep_child_unwritten_census", + "--nocapture", + ]) + .env("EC_AV1_PLANE_SENTINEL", "1") + .env("UWDEP_CENSUS_SYNTHETIC", "1") + .env_remove("UWDEP_CENSUS_FIXTURE") + .output() + .expect("running the census child"); + let text = format!( + "{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); + text.lines() + .find_map(|l| l.strip_prefix("GRAINCENSUS ")) + .and_then(parse_census_line) + .unwrap_or_else(|| { + panic!( + "{NAME}: the census child reported no synthetic grained count (child said: \ + {:?})", + text.trim() + ) + }) + } + /// Parses the child's `UWDEP_CENSUS frames= scanned=` line /// into `(unwritten, scanned)`. The scanned count is what makes the fixture /// arms meaningful: `unwritten == 0` is also what a build with the census call @@ -48882,6 +49056,27 @@ exit 0 let n = decode::take_final_unwritten_samples(); let scanned = decode::take_final_census_scanned(); println!("UWDEP_CENSUS {n} synthetic=1 scanned={scanned}"); + // lane-av1graincensus: the grained census over the SAME planes but a + // DIFFERENT known count, 2 + 3 + 0 = 5. Deliberately not 7: a parent + // that read the pre-grain counter for the grained arm would see 7 and + // go red, so the two arms cannot be confused for one another. + for s in a.iter_mut().take(3) { + *s = 7; + } + for s in b.iter_mut().take(4) { + *s = 7; + } + for s in a.iter_mut().take(2) { + *s = S; + } + for s in b.iter_mut().take(3) { + *s = S; + } + let _ = decode::take_grained_unwritten_samples(); + decode::census_unwritten_grained(&a, &b, &c); + let gn = decode::take_grained_unwritten_samples(); + let gscanned = decode::take_grained_census_scanned(); + println!("GRAINCENSUS {gn} synthetic=1 scanned={gscanned}"); return; } let Ok(fixture) = std::env::var("UWDEP_CENSUS_FIXTURE") else { @@ -48894,10 +49089,23 @@ exit 0 let stream = std::fs::read(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display())); let _ = decode::take_final_unwritten_samples(); + // Both counters are drained BEFORE the decode: they are process-global + // and this child may inherit nothing, but a partial run must not be able + // to add its numbers to another test's. + let _ = decode::take_grained_unwritten_samples(); let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{fixture} refused: {e}")); let n = decode::take_final_unwritten_samples(); let scanned = decode::take_final_census_scanned(); println!("UWDEP_CENSUS {n} frames={} scanned={scanned}", frames.len()); + // lane-av1graincensus: the post-grain census, over the picture + // `apply_grain` returns. A different prefix from `UWDEP_CENSUS`, so + // neither parent can pick up the other's line. + let gn = decode::take_grained_unwritten_samples(); + let gscanned = decode::take_grained_census_scanned(); + println!( + "GRAINCENSUS {gn} frames={} scanned={gscanned}", + frames.len() + ); } /// lane-av1uballoc: the frame the caller receives does not depend on what @@ -48937,6 +49145,18 @@ exit 0 // 4:2:2 (12-bit key, inter, sb128 intrabc, 17-frame odd-size), 4:4:4 // (lossless sb64, intrabc rect4, 128-root mu), a padded odd size, an // off-tile chroma walk, and superres+CDEF+LR -- for ~1.3 s per arm. + // + // lane-av1graincensus adds FILM GRAIN. `apply_grain`'s `uninit_plane` is + // the crate's only OTHER `Vec::with_capacity` + `set_len` allocation, and + // before this row the only gate that can catch a READ of it had no grain + // fixture at all, so that `unsafe` had no coverage here. It matters: with + // the grain band's clean-row copy neutered, the noise kernels read the + // destination to build `avgLuma` and the picture's values then depend on + // whatever the buffer held -- a dependence the 0xDEAD-vs-0xBEEF arm + // exists to catch and the unwritten-sample census cannot (the read value + // is overwritten before the census runs). Measured in + // `lanes/av1graincensus.report.md` §5. `s422_grain_160x128` is the + // smallest grain fixture, so the arm grows by ~0.05 s. const FIXTURES: &[&str] = &[ "s422_12bit_160x128", "422_inter_160x128_3f", @@ -48948,6 +49168,7 @@ exit 0 "svt1-split-tx-pin", "mix176_offtile_chroma_clip", "superres_kf_cdef_lr_64x64", + "s422_grain_160x128", ]; let (a, b) = allocdet_synthetic(); diff --git a/lanes/av1graincensus.report.md b/lanes/av1graincensus.report.md new file mode 100644 index 00000000..fb4e55fd --- /dev/null +++ b/lanes/av1graincensus.report.md @@ -0,0 +1,271 @@ +# lane/av1graincensus — the unwritten-sample census was blind to `apply_grain` + +W1-2 of `lanes/refusal-plan.report.md` (`lane/refusalplan`). Base `5ba7a123`. + +`census_unwritten_final` is called in `stream.rs` **before** `apply_grain`. +`film_grain::uninit_plane` allocates the grained destination as *uninitialised* +memory — `Vec::with_capacity` + `set_len`, no fill — with correctness resting on +a band row partition rather than on the type system. `lanes/unwritten-dep.report.md` +§6 and §8 both say, in their own words, that "the caller's final grained picture +carries no unwritten plane sample" is **not claimed**, because the census never +sees that buffer. + +**This lane measures it.** Post-grain census at `apply_grain`'s return, its own +counter pair, two mutations proven red, and — because the census turned out to be +a strictly weaker instrument than the gap suggested — a second `unsafe` in the +same function brought under the gate that can actually see it (§5). + +--- + +## 1. What was wrong, precisely + +Two claims in the tree, both about the same buffer, neither true together: + +* `stream.rs`'s comment on the pre-grain call said the census "covers the whole + span from the tile walk to the caller's frame". Every filter (deblock, CDEF, + LR, superres) writes **in place** into the buffer that call scans, so that part + holds — but `apply_grain` runs *after* it and **allocates a new picture**. No + filter does that. So the comment's scope was one stage too wide. +* `film_grain::uninit_plane`'s SAFETY comment says the proof that no uninitialised + sample is read is "the band row partition at that call site, not the type + system … the byte-exact 1-vs-4-thread gate is what checks it". No gate with a + grain fixture existed to check it (§5). + +Neither sentence was false on its own terms; together they left the only picture +between the pre-grain census and the caller unmeasured and the only other +`set_len` allocation uncovered. + +--- + +## 2. The change + +### 2.1 `decode.rs` — a second census, its own counters + +`census_sentinels` is now the shared `(scanned, unwritten)` body, so +`census_unwritten_final` and the new `census_unwritten_grained` cannot drift into +disagreeing about what counts as unwritten. It returns `None` when the sentinel +fill is not live, so neither caller can publish a meaningless zero. + +```rust +static GRAINED_UNWRITTEN_SAMPLES: AtomicUsize; +static GRAINED_CENSUS_SCANNED: AtomicUsize; +pub fn take_grained_unwritten_samples() -> usize; +pub fn take_grained_census_scanned() -> usize; +pub(crate) fn census_unwritten_grained(y: &[u16], u: &[u16], v: &[u16]); +``` + +The `scanned`/`found` **pairing** is the same one the pre-deblock and pre-grain +censuses already use: `unwritten == 0` is also what a build with the call deleted +reports, so a gate that reads only the count passes vacuously. `scanned > 0` is +reachable only by `apply_grain` actually running. + +`plane_poison` and `plane_sentinel_on` became `pub(crate)` so `film_grain` fills +and counts the **same value under the same predicate** — the disagreement that +would make the count meaningless is now impossible by construction. + +### 2.2 `film_grain.rs` — poison under the census arm, census at the return + +```rust +fn uninit_plane(n: usize) -> Vec { + let mut v: Vec = Vec::with_capacity(n); + unsafe { v.set_len(n) }; + if crate::decode::plane_sentinel_on() { // NEW — census arm only + v.fill(crate::decode::plane_poison()); + } + v +} +``` + +Counting `== plane_poison()` over ambient garbage is **not a census**: a hole +survives with probability ~1/65536 rather than always, so the count would be ~0 +whether or not the band copy covered every row. The fill is what turns "the band +copy wrote every sample" from an assumption into a measurement. + +With the sentinel off — every shipped build, every byte-exact gate, every ffmpeg +comparison — `uninit_plane` is still `with_capacity` + `set_len`. **The corner-cut +it documents is untouched where it is actually paid for.** + +The census is called at **both** returns of `apply_grain`, so "the picture +`apply_grain` hands back is censused in its final form" is a property of the +function rather than of one branch. + +### 2.3 Why one call site and not four + +`stream.rs` synthesizes grain at four places (threaded decode, threaded +`show_existing_frame`, inline decode, inline `show_existing_frame`) and +`apply_grain` is the only one of them. One census inside `apply_grain` covers all +four; four census calls in `stream.rs` would cover the same pictures and drift. + +--- + +## 3. SCOPE, stated not implied + +* The new census covers **the picture the caller receives on a grained frame, in + its final form, after the noise**. That is its whole claim. +* It is **not** a claim that the pre-grain census already covered this. That + census never sees this buffer. `lanes/unwritten-dep.report.md` §6/§8 were + right, and the pre-grain gate's own doc comment now says so and points here. +* It is **not** a claim about a frame whose grain step does not run — for a + non-grained frame the caller receives the very bytes `census_unwritten_final` + scanned, and `EC_AV1_NO_GRAIN` makes the grained call not run at all. +* It is **not** a claim that grain cannot introduce a wrong VALUE (§5 is where + that question lives). + +**Out of scope, untouched:** the decode path, the reserved 4:2:0 group-tail +chroma SKIP arm, `decode_rect4_16_intrabc`, and the ffmpeg oracle helpers +(`assert_420_oracle_stream` and its callers). + +--- + +## 4. The gate + +`stream::tests::the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample` + +```text +$ cargo test -p ec-av1 --lib -- the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample +test stream::tests::the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample ... ok +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 837 filtered out; finished in 26.98s +``` + +Measured on the census child (`EC_AV1_PLANE_SENTINEL=1`, one process per +fixture), provenance-checked binary — only this worktree's paths appear in it: + +```text +fixture UWDEP_CENSUS (pre-grain) GRAINCENSUS (post-grain) +s422_grain_160x128 0 frames=3 scanned=122880 0 frames=3 scanned=122880 +grain_cdef_lr_128x128 0 frames=5 scanned=147456 0 frames=5 scanned=122880 +reelb_arf_witness 0 frames=37 scanned=370483200 0 frames=37 scanned=111144960 +synthetic 7 scanned=40 5 scanned=40 +``` + +Two things in that table are load-bearing: + +* **`scanned` is non-zero on every arm.** It is the only number that + distinguishes "scanned and found nothing" from "never scanned", and it is + reachable only by `apply_grain` having run. It is simultaneously the + proof-that-grain-fired and the deletion control. +* **The synthetic control counts 5, not 7.** The pre-grain arm's synthetic uses + 7 on the same planes. A gate that read the wrong counter for the grained arm + would see 7 and go red. The two arms cannot be confused for one another. + +The three fixtures are chosen for coverage, not for size: `s422_grain_160x128` is +4:2:2 (the per-axis chroma geometry), `grain_cdef_lr_128x128` is 4:2:0 running +CDEF and LR as well, and `reelb_arf_witness` is the real 10-bit 3840x1608 film with +hidden alt-refs whose height is **not** a multiple of the 32-pixel band row — the +shape where the row partition has a tail. + +Note `grain_cdef_lr_128x128`'s post-grain `scanned` (122880) is *smaller* than its +pre-grain `scanned` (147456): grain is synthesised for shown output only, and +hidden frames never reach the grained return. That asymmetry is the expected +result, not a gap in the census. + +--- + +## 5. Mutations + +| mutation | result | +|---|---| +| **A — the `census_unwritten_grained` call at `apply_grain`'s return DELETED** | **RED**: "the grained census scanned 0 samples on s422_grain_160x128 — the call at `apply_grain`'s return is not running (or grain never fired), so the 0 below proves nothing (class: census-never-ran)" | +| **B — one sentinel sample forced into the returned grained picture** (`out.y[0] = plane_poison()` before the census) | **RED**: "s422_grain_160x128 hands the caller a grained picture with **3** samples the grain destination's band copy never wrote" — exactly 3, because that fixture has 3 grained frames and the mutation fires once per frame | + +### 5.1 The measurement that changed the lane's conclusion + +I neutered `copy_clean_rows` — the grain band's clean-row copy, i.e. the code +whose correctness the `unsafe` rests on — leaving a destination written **only** +by the noise kernels, and re-ran the census: + +```text +s422_grain_160x128 GRAINCENSUS 0 frames=3 scanned=122880 +grain_cdef_lr_128x128 GRAINCENSUS 0 frames=5 scanned=122880 +``` + +**Still 0.** The census is not lying and is not broken: the noise kernels overwrite +every destination sample they read, so no poison survives to the return. "0 +unwritten samples in the caller's picture" is a *true* statement about a buffer +that was in fact filled with garbage. + +Which means the class **`census-of-unwritten-samples-cannot-see-a-read-of- +uninitialised-memory`** is real, and this lane's census does not cover it. The +gate that does is `the_frame_does_not_depend_on_the_plane_buffers_initial_content` +— the `0xDEAD`-vs-`0xBEEF` arm, which asks whether the *value* the buffer held +can reach the output. **Its fixture list had no grain fixture at all**, so +`uninit_plane`'s `unsafe` — the crate's only other `Vec::with_capacity` + +`set_len` — had no coverage there. + +**Class sweep, same lane:** added `s422_grain_160x128` to that gate's `FIXTURES` +(the smallest grain fixture; the arm grows ~0.05 s), and proved it bites by +re-running mutation D — `copy_clean_rows` neutered again: + +| mutation | result | +|---|---| +| **D — `copy_clean_rows` neutered, allocdet gate WITH the grain fixture** | **RED**: "s422_grain_160x128 decoded to a DIFFERENT picture depending on what the plane buffer held before the decode wrote it — sentinel-off-uninit gave `a1cafe984ea68d83`, the baseline arm gave `dfe426a3b9597432`" | +| **D′ — same mutation, unwritten-sample census** | **GREEN — correctly so** (§5.1). Two instruments, two different questions, and only one of them was pointed at this `unsafe`. | + +Before this lane the same mutation was invisible to both. + +--- + +## 6. Byte-exactness and the scoped sweep + +Film grain stays byte-exact against ffmpeg — `EC_AV1_REQUIRE_FFMPEG=1`, so no arm +can skip: + +```text +$ EC_AV1_REQUIRE_FFMPEG=1 cargo test -p ec-av1 --lib -- +test stream::tests::a_real_422_film_grain_stream_decodes_pixel_exact ... ok +test stream::tests::a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact ... ok +test stream::tests::a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact ... ok +test stream::tests::a_real_aomenc_stream_with_film_grain_decodes_pixel_exact ... ok +test stream::tests::real_aomenc_film_grain_streams_decode_pixel_exact ... ok +test stream::tests::the_frame_does_not_depend_on_the_plane_buffers_initial_content ... ok +test stream::tests::the_frame_the_caller_receives_carries_no_unwritten_plane_sample ... ok +test stream::tests::the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample ... ok + +test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 830 filtered out; finished in 111.39s +``` + +Every `uninit_plane` allocation in that run is provably unfilled: +`EC_AV1_PLANE_SENTINEL` is unset, `plane_sentinel_on()` is false, and each +allocation is the byte-identical `with_capacity` + `set_len` it was before. + +The full `ec-av1` suite is a server job (§8); this lane ran only scoped tests +locally, as the shared context requires. + +--- + +## 7. What this lane did not do + +* **It did not fix anything.** Every measured count was already 0. The defect was + in the *instrument*, not the decoder — the same class as + `lanes/unwritten-dep.report.md` §4's `dump_stage16`. +* **It did not make the census able to see a read of uninitialised memory.** + §5.1 says plainly that it cannot, and that the initial-content gate is the + instrument for that. §5 adds the grain coverage there; it does not pretend the + census grew a new sense. +* **It did not touch the reserved 4:2:0 group-tail chroma SKIP arm**, which is + reserved for its owning lane, nor `decode_rect4_16_intrabc`, nor the ffmpeg + oracle helpers. + +## 8. Open, filed + +* **Full-suite attribution is still owed.** The five grain gates, both census + gates and the initial-content gate are green locally; the whole `ec-av1` suite + is a server job and was not run by this lane. Whoever merges this should read the + server suite result for these eight test names. + +## 9. Commands + +```bash +cd /home/user/.cache/wt/av1graincensus +export CARGO_TARGET_DIR=/home/user/.cache/tgt/av1graincensus + +cargo test -p ec-av1 --lib --no-run +EC_AV1_REQUIRE_FFMPEG=1 cargo test -p ec-av1 --lib -- + +# the census child by hand, one process per fixture +B=$(ls -t $CARGO_TARGET_DIR/debug/deps/ec_av1-* | grep -v '\.d$' | head -1) +EC_AV1_PLANE_SENTINEL=1 UWDEP_CENSUS_FIXTURE=s422_grain_160x128 \ + $B --exact stream::tests::uwdep_child_unwritten_census --nocapture + +# mutations A, B, C, D: edit film_grain.rs, rebuild, run the gate named in §5 +```