forge
Explore
Log in

Don't you dare go Hollow

av1graincensus: census the grained picture, and cover uninit_plane's unsafe

Browse files at this commit

852b5e2580d3a0bbbd11eb129e556a08135d6019Ahmet Kaan GümüşParent: e4f7cf8
census_unwritten_final runs in stream.rs before apply_grain, and
apply_grain is the one stage after it that allocates a NEW picture:
film_grain::uninit_plane, Vec::with_capacity + set_len, no fill.
lanes/unwritten-dep.report.md sections 6 and 8 both decline to claim
anything about that buffer, so the picture the caller actually receives
was unmeasured.

- decode.rs: census_unwritten_grained at apply_grain's return, with its
  own GRAINED_UNWRITTEN_SAMPLES / GRAINED_CENSUS_SCANNED pair. The
  scanned/found pairing is the same one the other two censuses use, so a
  build with the call deleted cannot pass. census_sentinels is now the
  shared counting body, returning None when the fill is off, so neither
  caller can publish a meaningless zero. plane_poison and
  plane_sentinel_on become pub(crate) so the fill and the count cannot
  disagree about the value or the predicate.
- film_grain.rs: uninit_plane fills with that poison when
  plane_sentinel_on(). Counting == poison over ambient garbage is not a
  census -- a hole survives with probability ~1/65536, not always. With
  the sentinel off, every shipped build, the allocation is still
  with_capacity + set_len, so the documented corner-cut is untouched.
  Both returns of apply_grain census, so the property is the function's
  rather than one branch's.
- stream.rs: the gate, a synthetic control counting 5 rather than the
  pre-grain arm's 7 (so reading the wrong counter reds), and per-fixture
  scanned > 0, which is reachable only by grain having run.

Measured 0 unwritten on s422_grain_160x128, grain_cdef_lr_128x128 and
reelb_arf_witness. Mutations: deleting the call reds via scanned > 0; one
sentinel sample forced into a grained picture reds with exactly 3, the
fixture's 3 grained frames.

Class sweep, same lane: with copy_clean_rows neutered the census stays
correctly 0 -- the noise overwrites every sample it reads -- so it cannot
see a READ of uninitialised memory. That gate had no grain fixture at
all, leaving uninit_plane's unsafe uncovered; s422_grain_160x128 is added
and proven to bite (allocdet goes red on the same mutation, 0xDEAD vs
0xBEEF).

Report: lanes/av1graincensus.report.md
crates/ec-av1/src/decode.rsmodified+88 -13
@@ -21465,7 +21465,11 @@ const MAX_LEGAL_SAMPLE: u16 = 4095;
2146521465 /// being impossible. `EC_AV1_PLANE_SENTINEL=1` -- the spelling every existing
2146621466 /// caller and gate uses, and `env_flag!`'s mere presence test -- keeps
2146721467 /// [`PLANE_SENTINEL`].
21468-fn plane_poison() -> u16 {
21468+/// `pub(crate)` for lane-av1graincensus: `film_grain::uninit_plane` fills its
21469+/// destination with the SAME poison `fresh_plane` does, and
21470+/// [`census_unwritten_grained`] counts the same value. The fill and the census
21471+/// must agree on both the value and the predicate, or a "0" means nothing.
21472+pub(crate) fn plane_poison() -> u16 {
2146921473 static V: std::sync::LazyLock<u16> = std::sync::LazyLock::new(|| {
2147021474 let Ok(raw) = crate::envflags::var("EC_AV1_PLANE_SENTINEL") else {
2147121475 return PLANE_SENTINEL;
@@ -21493,7 +21497,8 @@ thread_local! {
2149321497 }
2149421498
2149521499 /// Whether freshly allocated planes are [`PLANE_SENTINEL`]-filled.
21496-fn plane_sentinel_on() -> bool {
21500+/// `pub(crate)` for the same reason as [`plane_poison`].
21501+pub(crate) fn plane_sentinel_on() -> bool {
2149721502 crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL")
2149821503 || PLANE_SENTINEL_ON.with(std::cell::Cell::get)
2149921504 }
@@ -21855,6 +21860,11 @@ pub fn take_final_census_scanned() -> usize {
2185521860 /// plane, how many samples still hold [`PLANE_SENTINEL`] once every filter has
2185621861 /// run, and records how many samples it LOOKED at in [`FINAL_CENSUS_SCANNED`].
2185721862 ///
21863+/// SCOPE, which lane-av1graincensus did not change but had to be true about:
21864+/// this runs BEFORE `apply_grain`, over the PRE-grain planes. It does NOT and
21865+/// never did measure the grained picture the caller receives -- that is
21866+/// [`census_unwritten_grained`], a separate counter over a separate buffer.
21867+///
2185821868 /// Gated on [`plane_sentinel_on`] -- the SAME predicate as [`fresh_plane`] and as
2185921869 /// the pre-deblock [`census_unwritten`]: the env flag OR the thread-local
2186021870 /// [`set_plane_sentinel`] override. An earlier revision gated this on the raw env
@@ -21862,19 +21872,86 @@ pub fn take_final_census_scanned() -> usize {
2186221872 /// the thread-local switch that the rest of the crate honours. The fill and both
2186321873 /// censuses must agree on when they are live, or a "0" means nothing.
2186421874 pub(crate) fn census_unwritten_final(y: &[u16], u: &[u16], v: &[u16]) {
21865- if !plane_sentinel_on() {
21875+ let Some((scanned, total)) = census_sentinels(y, u, v) else {
2186621876 return;
21877+ };
21878+ FINAL_CENSUS_SCANNED.fetch_add(scanned, std::sync::atomic::Ordering::SeqCst);
21879+ FINAL_UNWRITTEN_SAMPLES.fetch_add(total, std::sync::atomic::Ordering::SeqCst);
21880+}
21881+
21882+/// The `(scanned, unwritten)` pair both output-point censuses accumulate, or
21883+/// `None` when the sentinel fill is not live.
21884+///
21885+/// Shared so the two censuses cannot drift into disagreeing about what counts
21886+/// as unwritten -- the failure this crate's other paired counters exist to
21887+/// prevent. `None` (rather than `(0, 0)`) is what keeps a caller from
21888+/// publishing a meaningless zero when the fill was off.
21889+fn census_sentinels(y: &[u16], u: &[u16], v: &[u16]) -> Option<(usize, usize)> {
21890+ if !plane_sentinel_on() {
21891+ return None;
2186721892 }
21868- // The caller passes the frame's planes exactly as they are about to be
21869- // stored into the reference slots, which are already cropped to the true
21870- // extent (no padding past it reaches this point), so a flat count over
21871- // each plane IS the true-extent count.
21893+ // Both callers pass planes cropped to the true extent (no padding past it
21894+ // reaches either point), so a flat count over each plane IS the
21895+ // true-extent count.
2187221896 let (scanned, total): (usize, usize) = [y, u, v]
2187321897 .iter()
2187421898 .map(|p| (p.len(), p.iter().filter(|&&s| s == plane_poison()).count()))
2187521899 .fold((0, 0), |(a, b), (c, d)| (a + c, b + d));
21876- FINAL_CENSUS_SCANNED.fetch_add(scanned, std::sync::atomic::Ordering::SeqCst);
21877- FINAL_UNWRITTEN_SAMPLES.fetch_add(total, std::sync::atomic::Ordering::SeqCst);
21900+ Some((scanned, total))
21901+}
21902+
21903+/// lane-av1graincensus: samples still holding the poison after film grain, over
21904+/// the picture [`crate::film_grain::apply_grain`] RETURNS -- i.e. the picture the
21905+/// caller receives on a grained frame.
21906+static GRAINED_UNWRITTEN_SAMPLES: std::sync::atomic::AtomicUsize =
21907+ std::sync::atomic::AtomicUsize::new(0);
21908+
21909+/// The scanned half of the pairing for [`GRAINED_UNWRITTEN_SAMPLES`]. A gate
21910+/// asserting only `== 0` passes on a build whose census call was deleted.
21911+static GRAINED_CENSUS_SCANNED: std::sync::atomic::AtomicUsize =
21912+ std::sync::atomic::AtomicUsize::new(0);
21913+
21914+/// Reads and clears [`GRAINED_UNWRITTEN_SAMPLES`].
21915+pub fn take_grained_unwritten_samples() -> usize {
21916+ GRAINED_UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst)
21917+}
21918+
21919+/// Reads and clears [`GRAINED_CENSUS_SCANNED`]; the pairing is the reason it
21920+/// exists, exactly as for [`take_final_census_scanned`].
21921+pub fn take_grained_census_scanned() -> usize {
21922+ GRAINED_CENSUS_SCANNED.swap(0, std::sync::atomic::Ordering::SeqCst)
21923+}
21924+
21925+/// lane-av1graincensus: the SECOND output-point census -- the one
21926+/// [`census_unwritten_final`] structurally cannot be.
21927+///
21928+/// # WHY IT EXISTS
21929+///
21930+/// `census_unwritten_final` runs at `stream.rs`'s `EC_AV1_FINAL_DUMP` site, which
21931+/// is BEFORE `apply_grain`. Every filter (deblock/CDEF/LR/superres) writes in
21932+/// place into the same buffer that census scanned, so those stages cannot open a
21933+/// hole outside its extent. `apply_grain` is the ONE stage after it that
21934+/// allocates a fresh picture -- `uninit_plane`, `Vec::with_capacity` +
21935+/// `set_len`, no fill -- and whose soundness rests on a band row partition
21936+/// rather than on the type system. Its destination therefore reaches the caller
21937+/// having never been looked at by any census, and `lanes/unwritten-dep.report.md`
21938+/// §6/§8 explicitly declines to claim otherwise.
21939+///
21940+/// # WHAT IT IS WORTH ONLY IF THE FILL IS LIVE
21941+///
21942+/// Counting `== plane_poison()` over an uninitialised buffer is a census that
21943+/// can only ever report ~0: garbage is arbitrary, so a hole survives with
21944+/// probability ~1/65536 rather than always. `uninit_plane` therefore fills with
21945+/// the poison when [`plane_sentinel_on`] -- under the SAME predicate
21946+/// [`fresh_plane`] honours -- so "the band copy wrote every sample" becomes a
21947+/// measurement instead of an assumption. With the sentinel off (every shipped
21948+/// build) nothing here runs and `uninit_plane` keeps its corner-cut.
21949+pub(crate) fn census_unwritten_grained(y: &[u16], u: &[u16], v: &[u16]) {
21950+ let Some((scanned, total)) = census_sentinels(y, u, v) else {
21951+ return;
21952+ };
21953+ GRAINED_CENSUS_SCANNED.fetch_add(scanned, std::sync::atomic::Ordering::SeqCst);
21954+ GRAINED_UNWRITTEN_SAMPLES.fetch_add(total, std::sync::atomic::Ordering::SeqCst);
2187821955 }
2187921956
2188021957 /// Which closure [`fresh_plane`] applies to the allocation it hands back.
@@ -38457,8 +38534,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
3845738534 // data lengths: this dump is the PADDED plane, not a crop, so the
3845838535 // writer's extent is `p.data` itself.
3845938536 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
38460- let narrow =
38461- |p: &PlaneBuf<'_>| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
38537+ let narrow = |p: &PlaneBuf<'_>| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
3846238538 crate::dumpio::write_planes(
3846338539 "EC_AV1_PREFILT_DUMP",
3846438540 format!("{path}.f{idx}"),
@@ -56838,8 +56914,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
5683856914 // lane-av1dumploud: loud on a short write (see the key-frame twin
5683956915 // above -- same file, same shape, same three planes).
5684056916 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
56841- let narrow =
56842- |p: &PlaneBuf<'_>| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
56917+ let narrow = |p: &PlaneBuf<'_>| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
5684356918 crate::dumpio::write_planes(
5684456919 "EC_AV1_PREFILT_DUMP",
5684556920 format!("{path}.f{idx}"),
crates/ec-av1/src/film_grain.rsmodified+32 -1
@@ -1281,12 +1281,28 @@ fn copy_clean_rows(
12811281 /// [`crate::par::Shared`]'s disjointness is; the byte-exact 1-vs-4-thread
12821282 /// gate is what checks it. Upgrade path: `Box<[MaybeUninit<u16>]>` plumbed
12831283 /// through the kernels.
1284+///
1285+/// # lane-av1graincensus: the fill under the census arm
1286+///
1287+/// That corner-cut is also why the buffer must be POISONED, not merely
1288+/// uninitialised, whenever the sentinel is live. Counting `== plane_poison()`
1289+/// over ambient garbage is a census that can only ever report ~0: a hole
1290+/// survives with probability ~1/65536 rather than always, so
1291+/// [`crate::decode::census_unwritten_grained`] would report 0 whether or not
1292+/// the band copy covered every row. Filling here makes "the band copy wrote
1293+/// every sample" a measurement. It is the same predicate
1294+/// [`crate::decode::fresh_plane`] honours, and with the sentinel off -- every
1295+/// shipped build -- this is the `with_capacity` + `set_len` it always was, so
1296+/// the corner-cut is untouched where it is paid for.
12841297 #[allow(unsafe_code)]
12851298 fn uninit_plane(n: usize) -> Vec<u16> {
12861299 let mut v: Vec<u16> = Vec::with_capacity(n);
12871300 // SAFETY: `u16` has no invalid bit pattern and no uninitialised sample is
12881301 // read -- see the doc comment.
12891302 unsafe { v.set_len(n) };
1303+ if crate::decode::plane_sentinel_on() {
1304+ v.fill(crate::decode::plane_poison());
1305+ }
12901306 v
12911307 }
12921308
@@ -1338,7 +1354,12 @@ pub(crate) fn apply_grain(
13381354 fctx: &crate::decode::FrameCtx,
13391355 ) -> Picture {
13401356 if !fg.apply_grain {
1341- return picture.clone();
1357+ let clean = picture.clone();
1358+ // lane-av1graincensus: this exit censuses too, so "the picture
1359+ // `apply_grain` hands back is censused in its final form" is a property
1360+ // of the FUNCTION rather than of one branch.
1361+ crate::decode::census_unwritten_grained(&clean.y, &clean.u, &clean.v);
1362+ return clean;
13421363 }
13431364 fctx.grain_bit_depth.with(|c| c.set(bit_depth));
13441365 hit!(GRAIN_HITS);
@@ -1992,6 +2013,16 @@ pub(crate) fn apply_grain(
19922013 });
19932014 let _ = so;
19942015
2016+ // lane-av1graincensus: the post-grain census, at the point the caller takes
2017+ // the picture. `census_unwritten_final` runs in `stream.rs` BEFORE this
2018+ // function, over the clean planes, and every filter writes in place into
2019+ // that same buffer -- so the destination allocated above by `uninit_plane`
2020+ // is the ONLY picture between that census and the caller that no census has
2021+ // ever looked at. `lanes/unwritten-dep.report.md` §6/§8 declined to claim
2022+ // anything about it; this measures it. `uninit_plane` poisons the buffer
2023+ // under the same predicate, so the count is a measurement rather than a
2024+ // coin flip on ambient garbage.
2025+ crate::decode::census_unwritten_grained(&out.y, &out.u, &out.v);
19952026 out
19962027 }
19972028
crates/ec-av1/src/stream.rsmodified+231 -10
@@ -2246,12 +2246,20 @@ fn decode_frame(
22462246 // census SEES it.
22472247 //
22482248 // So this second census is not a patch for a blind pre-deblock scan. It is
2249- // the measurement taken where the output is taken, which covers the whole span
2250- // from the tile walk to the caller's frame: anything a later stage could
2251- // introduce (a filter, superres, a second pass) is inside its extent, where
2252- // a scan taken before it would not be. It also runs before `apply_grain`, so
2253- // the claim is over the PRE-GRAIN planes -- the bytes the reference bank
2254- // stores and every later frame predicts from.
2249+ // the measurement taken where the reference-bank bytes are taken, which
2250+ // covers the whole span from the tile walk to those bytes: every filter
2251+ // writes IN PLACE into the very buffer this scans, so nothing a later
2252+ // filter does can open a hole outside its extent.
2253+ //
2254+ // lane-av1graincensus, the scope correction this comment needed: "to the
2255+ // caller's frame" was WRONG, and this call is not what makes it right.
2256+ // `apply_grain` runs after this and ALLOCATES a fresh picture
2257+ // (`film_grain::uninit_plane`, `with_capacity` + `set_len`, no fill), so
2258+ // that destination never passes through here. The claim over the PRE-GRAIN
2259+ // planes -- the bytes the reference bank stores and every later frame
2260+ // predicts from -- is what this line supports; the grained picture the
2261+ // caller receives is censused by `decode::census_unwritten_grained`, at
2262+ // `apply_grain`'s own return, over its own counters.
22552263 decode::census_unwritten_final(&picture.y, &picture.u, &picture.v);
22562264 if let Some(prefix) = final_dump {
22572265 // lane-av1dumploud: this is the site that produced the 13 320 192-byte
@@ -48658,10 +48666,17 @@ exit 0
4865848666 /// `EC_AV1_FINAL_DUMP` writes, which is BEFORE `apply_grain`. The claim is
4865948667 /// therefore over the PRE-GRAIN planes -- which are also the bytes the
4866048668 /// reference bank stores and every later frame predicts from, the dependency
48661- /// that matters. Whether `apply_grain` can itself introduce a hole is NOT
48662- /// measured: the census never sees the planes `apply_grain` allocates. So the
48663- /// claim is NOT "the caller's final grained picture has no hole", and nothing
48664- /// here asserts that grain cannot introduce one.
48669+ /// that matters. Every filter writes IN PLACE into the buffer this scans, so
48670+ /// none of them can open a hole outside its extent. `apply_grain` is the one
48671+ /// stage after this scan that ALLOCATES a new picture, and this census never
48672+ /// sees it: the claim is NOT "the caller's final grained picture has no hole".
48673+ ///
48674+ /// lane-av1graincensus: that paragraph is still true of THIS gate and is not
48675+ /// weakened by the pointer below -- what changed is that the gap it names is
48676+ /// no longer UNMEASURED.
48677+ /// [`the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample`]
48678+ /// measures the grained picture `apply_grain` returns, over its own counters,
48679+ /// and is the gate that carries the post-grain claim.
4866548680 ///
4866648681 /// NON-VACUITY, the part that makes this gate worth having: a census is only a
4866748682 /// measurement if it CAN report non-zero. The control is a SYNTHETIC positive
@@ -48787,6 +48802,165 @@ exit 0
4878748802 }
4878848803 }
4878948804
48805+ /// lane-av1graincensus: the picture the caller RECEIVES -- including film
48806+ /// grain -- carries no unwritten plane sample.
48807+ ///
48808+ /// # WHAT THIS GATE IS FOR, and the blind spot it closes
48809+ ///
48810+ /// [`the_frame_the_caller_receives_carries_no_unwritten_plane_sample`] scans
48811+ /// at `stream.rs`'s `EC_AV1_FINAL_DUMP` site, which is BEFORE `apply_grain`.
48812+ /// Every filter (deblock/CDEF/LR/superres) writes IN PLACE into the buffer it
48813+ /// scans, so none of them can open a hole outside its extent -- but
48814+ /// `apply_grain` is the one stage after that scan that ALLOCATES a fresh
48815+ /// picture: `film_grain::uninit_plane`, `Vec::with_capacity` + `set_len`, no
48816+ /// fill, with correctness resting on a band row partition rather than on the
48817+ /// type system. `lanes/unwritten-dep.report.md` §6 and §8 declined to claim
48818+ /// anything about that destination. This gate measures it.
48819+ ///
48820+ /// # WHY THE COUNT CAN BE NON-ZERO (the part that makes it a census)
48821+ ///
48822+ /// Counting `== plane_poison()` over an uninitialised buffer is a census that
48823+ /// reports ~0 either way: a hole survives with probability ~1/65536, not
48824+ /// always. `uninit_plane` therefore fills with the poison under the SAME
48825+ /// predicate `fresh_plane` honours. With the sentinel off -- every shipped
48826+ /// build -- `uninit_plane` is still `with_capacity` + `set_len`, so the
48827+ /// corner-cut it documents is untouched.
48828+ ///
48829+ /// # SCOPE, stated not implied
48830+ ///
48831+ /// The claim is over the picture the caller receives ON A GRAINED FRAME, in
48832+ /// its final form, after the noise. It is NOT a claim that the pre-grain
48833+ /// census already covered this -- that census never sees this buffer -- and it
48834+ /// is NOT a claim about a frame whose grain step does not run.
48835+ ///
48836+ /// # NON-VACUITY, two arms, both required
48837+ ///
48838+ /// 1. **synthetic, first, and with a DIFFERENT known count (5, not the
48839+ /// pre-grain arm's 7)** so a gate reading the wrong counter goes red. No
48840+ /// fixture involved, so no lane's refusal can redden it.
48841+ /// 2. **per-fixture `scanned > 0`** -- `unwritten == 0` is also what a build
48842+ /// with the census call deleted reports. `scanned > 0` is reachable only by
48843+ /// `apply_grain` actually running, so it is at once the
48844+ /// proof-that-grain-fired and the deletion control.
48845+ ///
48846+ /// Both mutations are in `lanes/av1graincensus.report.md`: deleting the
48847+ /// `census_unwritten_grained` call at `apply_grain`'s return reds arm 2, and
48848+ /// forcing ONE poison sample into a grained picture reds arm 2's count.
48849+ #[test]
48850+ fn the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample() {
48851+ const NAME: &str =
48852+ "the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample";
48853+ let _gate_lock = lock_gate_counters();
48854+
48855+ let (syn, syn_scanned) = grain_census_synthetic();
48856+ assert_eq!(
48857+ syn_scanned, 40,
48858+ "{NAME}: the synthetic control scanned {syn_scanned} samples, expected 40 \
48859+ (16 + 16 + 8) -- the grained census did not look at what it was handed"
48860+ );
48861+ assert_eq!(
48862+ syn, 5,
48863+ "{NAME}: the grained census reported {syn} for planes carrying exactly 5 sentinel \
48864+ samples -- it is not measuring what it claims, so every zero below is \
48865+ meaningless (class: census-silently-blind). Note 5, not the pre-grain arm's 7: \
48866+ reading the wrong counter is the failure this number catches."
48867+ );
48868+
48869+ // Small and cheap: a 4:2:2 grain stream, a 4:2:0 one that also runs
48870+ // CDEF+LR, and the real 10-bit 3840x1608 hidden-alt-ref film whose height
48871+ // is not a multiple of the 32-pixel band row -- the shape where the band
48872+ // row partition has a tail.
48873+ for fixture in [
48874+ "s422_grain_160x128",
48875+ "grain_cdef_lr_128x128",
48876+ "reelb_arf_witness",
48877+ ] {
48878+ let (n, scanned) = grain_census(fixture);
48879+ assert!(
48880+ scanned > 0,
48881+ "{NAME}: the grained census scanned 0 samples on {fixture} -- the call at \
48882+ `apply_grain`'s return is not running (or grain never fired), so the {n} \
48883+ below proves nothing (class: census-never-ran). Deleting the call in \
48884+ apply_grain reproduces this."
48885+ );
48886+ assert_eq!(
48887+ n, 0,
48888+ "{NAME}: {fixture} hands the caller a grained picture with {n} samples the \
48889+ grain destination's band copy never wrote"
48890+ );
48891+ }
48892+ }
48893+
48894+ /// Runs the census child on `fixture` and returns the `GRAINCENSUS` line's
48895+ /// `(unwritten, scanned)` -- the POST-grain pair, over the picture
48896+ /// `apply_grain` returns.
48897+ fn grain_census(fixture: &str) -> (usize, usize) {
48898+ const NAME: &str =
48899+ "the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample";
48900+ let exe = std::env::current_exe().expect("test binary path");
48901+ let out = std::process::Command::new(exe)
48902+ .args([
48903+ "--exact",
48904+ "stream::tests::uwdep_child_unwritten_census",
48905+ "--nocapture",
48906+ ])
48907+ .env("UWDEP_CENSUS_FIXTURE", fixture)
48908+ .env("EC_AV1_PLANE_SENTINEL", "1")
48909+ .output()
48910+ .expect("running the census child");
48911+ let text = format!(
48912+ "{}{}",
48913+ String::from_utf8_lossy(&out.stdout),
48914+ String::from_utf8_lossy(&out.stderr),
48915+ );
48916+ text.lines()
48917+ .find_map(|l| l.strip_prefix("GRAINCENSUS "))
48918+ .and_then(parse_census_line)
48919+ .unwrap_or_else(|| {
48920+ panic!(
48921+ "{NAME}: the census child reported no grained count for {fixture} \
48922+ (child said: {:?})",
48923+ text.trim()
48924+ )
48925+ })
48926+ }
48927+
48928+ /// The synthetic non-vacuity control for the grained census: the child with
48929+ /// `UWDEP_CENSUS_FIXTURE` UNSET hands [`census_unwritten_grained`] planes
48930+ /// carrying 5 sentinel samples and reports what it counted. Function-level,
48931+ /// so no fixture's decode behaviour can change it.
48932+ fn grain_census_synthetic() -> (usize, usize) {
48933+ const NAME: &str =
48934+ "the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample";
48935+ let exe = std::env::current_exe().expect("test binary path");
48936+ let out = std::process::Command::new(exe)
48937+ .args([
48938+ "--exact",
48939+ "stream::tests::uwdep_child_unwritten_census",
48940+ "--nocapture",
48941+ ])
48942+ .env("EC_AV1_PLANE_SENTINEL", "1")
48943+ .env("UWDEP_CENSUS_SYNTHETIC", "1")
48944+ .env_remove("UWDEP_CENSUS_FIXTURE")
48945+ .output()
48946+ .expect("running the census child");
48947+ let text = format!(
48948+ "{}{}",
48949+ String::from_utf8_lossy(&out.stdout),
48950+ String::from_utf8_lossy(&out.stderr),
48951+ );
48952+ text.lines()
48953+ .find_map(|l| l.strip_prefix("GRAINCENSUS "))
48954+ .and_then(parse_census_line)
48955+ .unwrap_or_else(|| {
48956+ panic!(
48957+ "{NAME}: the census child reported no synthetic grained count (child said: \
48958+ {:?})",
48959+ text.trim()
48960+ )
48961+ })
48962+ }
48963+
4879048964 /// Parses the child's `UWDEP_CENSUS <unwritten> frames=<n> scanned=<n>` line
4879148965 /// into `(unwritten, scanned)`. The scanned count is what makes the fixture
4879248966 /// arms meaningful: `unwritten == 0` is also what a build with the census call
@@ -48882,6 +49056,27 @@ exit 0
4888249056 let n = decode::take_final_unwritten_samples();
4888349057 let scanned = decode::take_final_census_scanned();
4888449058 println!("UWDEP_CENSUS {n} synthetic=1 scanned={scanned}");
49059+ // lane-av1graincensus: the grained census over the SAME planes but a
49060+ // DIFFERENT known count, 2 + 3 + 0 = 5. Deliberately not 7: a parent
49061+ // that read the pre-grain counter for the grained arm would see 7 and
49062+ // go red, so the two arms cannot be confused for one another.
49063+ for s in a.iter_mut().take(3) {
49064+ *s = 7;
49065+ }
49066+ for s in b.iter_mut().take(4) {
49067+ *s = 7;
49068+ }
49069+ for s in a.iter_mut().take(2) {
49070+ *s = S;
49071+ }
49072+ for s in b.iter_mut().take(3) {
49073+ *s = S;
49074+ }
49075+ let _ = decode::take_grained_unwritten_samples();
49076+ decode::census_unwritten_grained(&a, &b, &c);
49077+ let gn = decode::take_grained_unwritten_samples();
49078+ let gscanned = decode::take_grained_census_scanned();
49079+ println!("GRAINCENSUS {gn} synthetic=1 scanned={gscanned}");
4888549080 return;
4888649081 }
4888749082 let Ok(fixture) = std::env::var("UWDEP_CENSUS_FIXTURE") else {
@@ -48894,10 +49089,23 @@ exit 0
4889449089 let stream =
4889549090 std::fs::read(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display()));
4889649091 let _ = decode::take_final_unwritten_samples();
49092+ // Both counters are drained BEFORE the decode: they are process-global
49093+ // and this child may inherit nothing, but a partial run must not be able
49094+ // to add its numbers to another test's.
49095+ let _ = decode::take_grained_unwritten_samples();
4889749096 let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{fixture} refused: {e}"));
4889849097 let n = decode::take_final_unwritten_samples();
4889949098 let scanned = decode::take_final_census_scanned();
4890049099 println!("UWDEP_CENSUS {n} frames={} scanned={scanned}", frames.len());
49100+ // lane-av1graincensus: the post-grain census, over the picture
49101+ // `apply_grain` returns. A different prefix from `UWDEP_CENSUS`, so
49102+ // neither parent can pick up the other's line.
49103+ let gn = decode::take_grained_unwritten_samples();
49104+ let gscanned = decode::take_grained_census_scanned();
49105+ println!(
49106+ "GRAINCENSUS {gn} frames={} scanned={gscanned}",
49107+ frames.len()
49108+ );
4890149109 }
4890249110
4890349111 /// lane-av1uballoc: the frame the caller receives does not depend on what
@@ -48937,6 +49145,18 @@ exit 0
4893749145 // 4:2:2 (12-bit key, inter, sb128 intrabc, 17-frame odd-size), 4:4:4
4893849146 // (lossless sb64, intrabc rect4, 128-root mu), a padded odd size, an
4893949147 // off-tile chroma walk, and superres+CDEF+LR -- for ~1.3 s per arm.
49148+ //
49149+ // lane-av1graincensus adds FILM GRAIN. `apply_grain`'s `uninit_plane` is
49150+ // the crate's only OTHER `Vec::with_capacity` + `set_len` allocation, and
49151+ // before this row the only gate that can catch a READ of it had no grain
49152+ // fixture at all, so that `unsafe` had no coverage here. It matters: with
49153+ // the grain band's clean-row copy neutered, the noise kernels read the
49154+ // destination to build `avgLuma` and the picture's values then depend on
49155+ // whatever the buffer held -- a dependence the 0xDEAD-vs-0xBEEF arm
49156+ // exists to catch and the unwritten-sample census cannot (the read value
49157+ // is overwritten before the census runs). Measured in
49158+ // `lanes/av1graincensus.report.md` §5. `s422_grain_160x128` is the
49159+ // smallest grain fixture, so the arm grows by ~0.05 s.
4894049160 const FIXTURES: &[&str] = &[
4894149161 "s422_12bit_160x128",
4894249162 "422_inter_160x128_3f",
@@ -48948,6 +49168,7 @@ exit 0
4894849168 "svt1-split-tx-pin",
4894949169 "mix176_offtile_chroma_clip",
4895049170 "superres_kf_cdef_lr_64x64",
49171+ "s422_grain_160x128",
4895149172 ];
4895249173
4895349174 let (a, b) = allocdet_synthetic();
lanes/av1graincensus.report.mdadded+271 -0
@@ -0,0 +1,271 @@
1+# lane/av1graincensus — the unwritten-sample census was blind to `apply_grain`
2+
3+W1-2 of `lanes/refusal-plan.report.md` (`lane/refusalplan`). Base `5ba7a123`.
4+
5+`census_unwritten_final` is called in `stream.rs` **before** `apply_grain`.
6+`film_grain::uninit_plane` allocates the grained destination as *uninitialised*
7+memory — `Vec::with_capacity` + `set_len`, no fill — with correctness resting on
8+a band row partition rather than on the type system. `lanes/unwritten-dep.report.md`
9+§6 and §8 both say, in their own words, that "the caller's final grained picture
10+carries no unwritten plane sample" is **not claimed**, because the census never
11+sees that buffer.
12+
13+**This lane measures it.** Post-grain census at `apply_grain`'s return, its own
14+counter pair, two mutations proven red, and — because the census turned out to be
15+a strictly weaker instrument than the gap suggested — a second `unsafe` in the
16+same function brought under the gate that can actually see it (§5).
17+
18+---
19+
20+## 1. What was wrong, precisely
21+
22+Two claims in the tree, both about the same buffer, neither true together:
23+
24+* `stream.rs`'s comment on the pre-grain call said the census "covers the whole
25+ span from the tile walk to the caller's frame". Every filter (deblock, CDEF,
26+ LR, superres) writes **in place** into the buffer that call scans, so that part
27+ holds — but `apply_grain` runs *after* it and **allocates a new picture**. No
28+ filter does that. So the comment's scope was one stage too wide.
29+* `film_grain::uninit_plane`'s SAFETY comment says the proof that no uninitialised
30+ sample is read is "the band row partition at that call site, not the type
31+ system … the byte-exact 1-vs-4-thread gate is what checks it". No gate with a
32+ grain fixture existed to check it (§5).
33+
34+Neither sentence was false on its own terms; together they left the only picture
35+between the pre-grain census and the caller unmeasured and the only other
36+`set_len` allocation uncovered.
37+
38+---
39+
40+## 2. The change
41+
42+### 2.1 `decode.rs` — a second census, its own counters
43+
44+`census_sentinels` is now the shared `(scanned, unwritten)` body, so
45+`census_unwritten_final` and the new `census_unwritten_grained` cannot drift into
46+disagreeing about what counts as unwritten. It returns `None` when the sentinel
47+fill is not live, so neither caller can publish a meaningless zero.
48+
49+```rust
50+static GRAINED_UNWRITTEN_SAMPLES: AtomicUsize;
51+static GRAINED_CENSUS_SCANNED: AtomicUsize;
52+pub fn take_grained_unwritten_samples() -> usize;
53+pub fn take_grained_census_scanned() -> usize;
54+pub(crate) fn census_unwritten_grained(y: &[u16], u: &[u16], v: &[u16]);
55+```
56+
57+The `scanned`/`found` **pairing** is the same one the pre-deblock and pre-grain
58+censuses already use: `unwritten == 0` is also what a build with the call deleted
59+reports, so a gate that reads only the count passes vacuously. `scanned > 0` is
60+reachable only by `apply_grain` actually running.
61+
62+`plane_poison` and `plane_sentinel_on` became `pub(crate)` so `film_grain` fills
63+and counts the **same value under the same predicate** — the disagreement that
64+would make the count meaningless is now impossible by construction.
65+
66+### 2.2 `film_grain.rs` — poison under the census arm, census at the return
67+
68+```rust
69+fn uninit_plane(n: usize) -> Vec<u16> {
70+ let mut v: Vec<u16> = Vec::with_capacity(n);
71+ unsafe { v.set_len(n) };
72+ if crate::decode::plane_sentinel_on() { // NEW — census arm only
73+ v.fill(crate::decode::plane_poison());
74+ }
75+ v
76+}
77+```
78+
79+Counting `== plane_poison()` over ambient garbage is **not a census**: a hole
80+survives with probability ~1/65536 rather than always, so the count would be ~0
81+whether or not the band copy covered every row. The fill is what turns "the band
82+copy wrote every sample" from an assumption into a measurement.
83+
84+With the sentinel off — every shipped build, every byte-exact gate, every ffmpeg
85+comparison — `uninit_plane` is still `with_capacity` + `set_len`. **The corner-cut
86+it documents is untouched where it is actually paid for.**
87+
88+The census is called at **both** returns of `apply_grain`, so "the picture
89+`apply_grain` hands back is censused in its final form" is a property of the
90+function rather than of one branch.
91+
92+### 2.3 Why one call site and not four
93+
94+`stream.rs` synthesizes grain at four places (threaded decode, threaded
95+`show_existing_frame`, inline decode, inline `show_existing_frame`) and
96+`apply_grain` is the only one of them. One census inside `apply_grain` covers all
97+four; four census calls in `stream.rs` would cover the same pictures and drift.
98+
99+---
100+
101+## 3. SCOPE, stated not implied
102+
103+* The new census covers **the picture the caller receives on a grained frame, in
104+ its final form, after the noise**. That is its whole claim.
105+* It is **not** a claim that the pre-grain census already covered this. That
106+ census never sees this buffer. `lanes/unwritten-dep.report.md` §6/§8 were
107+ right, and the pre-grain gate's own doc comment now says so and points here.
108+* It is **not** a claim about a frame whose grain step does not run — for a
109+ non-grained frame the caller receives the very bytes `census_unwritten_final`
110+ scanned, and `EC_AV1_NO_GRAIN` makes the grained call not run at all.
111+* It is **not** a claim that grain cannot introduce a wrong VALUE (§5 is where
112+ that question lives).
113+
114+**Out of scope, untouched:** the decode path, the reserved 4:2:0 group-tail
115+chroma SKIP arm, `decode_rect4_16_intrabc`, and the ffmpeg oracle helpers
116+(`assert_420_oracle_stream` and its callers).
117+
118+---
119+
120+## 4. The gate
121+
122+`stream::tests::the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample`
123+
124+```text
125+$ cargo test -p ec-av1 --lib -- the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample
126+test stream::tests::the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample ... ok
127+test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 837 filtered out; finished in 26.98s
128+```
129+
130+Measured on the census child (`EC_AV1_PLANE_SENTINEL=1`, one process per
131+fixture), provenance-checked binary — only this worktree's paths appear in it:
132+
133+```text
134+fixture UWDEP_CENSUS (pre-grain) GRAINCENSUS (post-grain)
135+s422_grain_160x128 0 frames=3 scanned=122880 0 frames=3 scanned=122880
136+grain_cdef_lr_128x128 0 frames=5 scanned=147456 0 frames=5 scanned=122880
137+reelb_arf_witness 0 frames=37 scanned=370483200 0 frames=37 scanned=111144960
138+synthetic 7 scanned=40 5 scanned=40
139+```
140+
141+Two things in that table are load-bearing:
142+
143+* **`scanned` is non-zero on every arm.** It is the only number that
144+ distinguishes "scanned and found nothing" from "never scanned", and it is
145+ reachable only by `apply_grain` having run. It is simultaneously the
146+ proof-that-grain-fired and the deletion control.
147+* **The synthetic control counts 5, not 7.** The pre-grain arm's synthetic uses
148+ 7 on the same planes. A gate that read the wrong counter for the grained arm
149+ would see 7 and go red. The two arms cannot be confused for one another.
150+
151+The three fixtures are chosen for coverage, not for size: `s422_grain_160x128` is
152+4:2:2 (the per-axis chroma geometry), `grain_cdef_lr_128x128` is 4:2:0 running
153+CDEF and LR as well, and `reelb_arf_witness` is the real 10-bit 3840x1608 film with
154+hidden alt-refs whose height is **not** a multiple of the 32-pixel band row — the
155+shape where the row partition has a tail.
156+
157+Note `grain_cdef_lr_128x128`'s post-grain `scanned` (122880) is *smaller* than its
158+pre-grain `scanned` (147456): grain is synthesised for shown output only, and
159+hidden frames never reach the grained return. That asymmetry is the expected
160+result, not a gap in the census.
161+
162+---
163+
164+## 5. Mutations
165+
166+| mutation | result |
167+|---|---|
168+| **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)" |
169+| **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 |
170+
171+### 5.1 The measurement that changed the lane's conclusion
172+
173+I neutered `copy_clean_rows` — the grain band's clean-row copy, i.e. the code
174+whose correctness the `unsafe` rests on — leaving a destination written **only**
175+by the noise kernels, and re-ran the census:
176+
177+```text
178+s422_grain_160x128 GRAINCENSUS 0 frames=3 scanned=122880
179+grain_cdef_lr_128x128 GRAINCENSUS 0 frames=5 scanned=122880
180+```
181+
182+**Still 0.** The census is not lying and is not broken: the noise kernels overwrite
183+every destination sample they read, so no poison survives to the return. "0
184+unwritten samples in the caller's picture" is a *true* statement about a buffer
185+that was in fact filled with garbage.
186+
187+Which means the class **`census-of-unwritten-samples-cannot-see-a-read-of-
188+uninitialised-memory`** is real, and this lane's census does not cover it. The
189+gate that does is `the_frame_does_not_depend_on_the_plane_buffers_initial_content`
190+— the `0xDEAD`-vs-`0xBEEF` arm, which asks whether the *value* the buffer held
191+can reach the output. **Its fixture list had no grain fixture at all**, so
192+`uninit_plane`'s `unsafe` — the crate's only other `Vec::with_capacity` +
193+`set_len` — had no coverage there.
194+
195+**Class sweep, same lane:** added `s422_grain_160x128` to that gate's `FIXTURES`
196+(the smallest grain fixture; the arm grows ~0.05 s), and proved it bites by
197+re-running mutation D — `copy_clean_rows` neutered again:
198+
199+| mutation | result |
200+|---|---|
201+| **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`" |
202+| **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`. |
203+
204+Before this lane the same mutation was invisible to both.
205+
206+---
207+
208+## 6. Byte-exactness and the scoped sweep
209+
210+Film grain stays byte-exact against ffmpeg — `EC_AV1_REQUIRE_FFMPEG=1`, so no arm
211+can skip:
212+
213+```text
214+$ EC_AV1_REQUIRE_FFMPEG=1 cargo test -p ec-av1 --lib -- <grain + census gates>
215+test stream::tests::a_real_422_film_grain_stream_decodes_pixel_exact ... ok
216+test stream::tests::a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact ... ok
217+test stream::tests::a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact ... ok
218+test stream::tests::a_real_aomenc_stream_with_film_grain_decodes_pixel_exact ... ok
219+test stream::tests::real_aomenc_film_grain_streams_decode_pixel_exact ... ok
220+test stream::tests::the_frame_does_not_depend_on_the_plane_buffers_initial_content ... ok
221+test stream::tests::the_frame_the_caller_receives_carries_no_unwritten_plane_sample ... ok
222+test stream::tests::the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample ... ok
223+
224+test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 830 filtered out; finished in 111.39s
225+```
226+
227+Every `uninit_plane` allocation in that run is provably unfilled:
228+`EC_AV1_PLANE_SENTINEL` is unset, `plane_sentinel_on()` is false, and each
229+allocation is the byte-identical `with_capacity` + `set_len` it was before.
230+
231+The full `ec-av1` suite is a server job (§8); this lane ran only scoped tests
232+locally, as the shared context requires.
233+
234+---
235+
236+## 7. What this lane did not do
237+
238+* **It did not fix anything.** Every measured count was already 0. The defect was
239+ in the *instrument*, not the decoder — the same class as
240+ `lanes/unwritten-dep.report.md` §4's `dump_stage16`.
241+* **It did not make the census able to see a read of uninitialised memory.**
242+ §5.1 says plainly that it cannot, and that the initial-content gate is the
243+ instrument for that. §5 adds the grain coverage there; it does not pretend the
244+ census grew a new sense.
245+* **It did not touch the reserved 4:2:0 group-tail chroma SKIP arm**, which is
246+ reserved for its owning lane, nor `decode_rect4_16_intrabc`, nor the ffmpeg
247+ oracle helpers.
248+
249+## 8. Open, filed
250+
251+* **Full-suite attribution is still owed.** The five grain gates, both census
252+ gates and the initial-content gate are green locally; the whole `ec-av1` suite
253+ is a server job and was not run by this lane. Whoever merges this should read the
254+ server suite result for these eight test names.
255+
256+## 9. Commands
257+
258+```bash
259+cd /home/user/.cache/wt/av1graincensus
260+export CARGO_TARGET_DIR=/home/user/.cache/tgt/av1graincensus
261+
262+cargo test -p ec-av1 --lib --no-run
263+EC_AV1_REQUIRE_FFMPEG=1 cargo test -p ec-av1 --lib -- <grain + census gates>
264+
265+# the census child by hand, one process per fixture
266+B=$(ls -t $CARGO_TARGET_DIR/debug/deps/ec_av1-* | grep -v '\.d$' | head -1)
267+EC_AV1_PLANE_SENTINEL=1 UWDEP_CENSUS_FIXTURE=s422_grain_160x128 \
268+ $B --exact stream::tests::uwdep_child_unwritten_census --nocapture
269+
270+# mutations A, B, C, D: edit film_grain.rs, rebuild, run the gate named in §5
271+```