forge
Explore
Log in

Don't you dare go Hollow

ec-av1: pick the plane-allocation closure with a number, and ship the zeroed one

Browse files at this commit

fd10b924bfc2d6773a872b16cbce918456d4e846Ahmet Kaan GümüşParent: a18289e
fresh_plane handed the decoder an uninitialised buffer and the SAFETY comment
resting on "every sample is written before it is read". That premise was
withdrawn by lane/unwritten-dep's own measurement (224 caller-visible chroma
samples on 440_request_is_422) and the comment was left standing anyway, with
two closures filed and neither chosen: zero the allocation, or instrument the
reads. Choosing between a perf cost and a new instrument is not a measurement
lane's call, so this is that lane.

Measured, one stream at a time, one binary: EC_AV1_PLANE_ALLOC is an env arm
inside the crate rather than a build flag, because three separate builds cannot
make the comparison fair -- recycled-arena state, page-cache state and code
layout all differ between them. Medians of 11 interleaved runs, examples/
alloc_timing.rs (new) timing decode_stream_with and reading minflt around it:

  3840x2160 4:2:0 96f   uninit 6900.963 ms | fill +0.83% | zeroed +0.80%
  3840x2160 4:2:2 48f   uninit 4709.657 ms | fill +0.86% | zeroed +0.81%
  1920x1080 4:2:0 96f   uninit 1768.411 ms | fill -1.87% | zeroed -1.63%

The 4K deltas are ~6 sigma against a 7-10 ms run-to-run spread. alloc_zeroed is
NOT the free zero-page lunch its name suggests: zeroed and fill land within
0.03% of each other at every size, because glibc memsets a recycled arena block
just the same. Output hashes are identical across all three arms on every
stream. The 1080p sign flip is reproducible and unexplained; it is reported as
a number, not a story.

The read census, which is what the decision actually rests on. Three regions of
the allocation can hold a sample no block wrote, and the old census only
scanned one of them:

  1. the padded tail outside true_width x true_height -- unwritten by
     construction; 4,676,128 of 22,787,296 scanned tail samples over all 127
     fixtures, on 38 of them. The comment claimed "no decoder ever reads" it;
     that was self-certifying, so the tail is now counted like any other
     region.
  2. the true extent, where the withdrawn 224-sample case sat -- 0 unwritten of
     1,466,581,280 scanned. The witness is refused on main.
  3. pix_write's `prev` argument, which reads the destination sample before
     overwriting it on every store. Neither instrument can see it (the value
     never reaches a branch or a syscall, so a DEBUG build under memcheck on
     the uninit arm still reports 0 errors) and no hash moves -- but it is a
     read of initial content nonetheless.

Reads were measured two independent ways and both say zero, over the whole
corpus: valgrind memcheck on every fixture under both the uninit and the zeroed
arm (254 runs, 0 uninitialised-value errors, identical signature sets), and
differential poisoning -- 126/126 committed fixtures byte-identical under
0xDEAD, 0xBEEF and the zeroed closure, the 127th being the refused witness.
The memcheck instrument is shown live by mutation: a temporary env-gated read
of the plane's last slot makes the same binary report 12 errors from 4
contexts. Reverted.

So the shipped closure is PlaneAlloc::Zeroed (vec![0u16; n]). The unsafe is now
reachable only from the census arms, its SAFETY comment names the three regions
with their measured counts instead of a premise, and the refusal that closes
region 2 is stated as a refusal rather than a proof -- a hostile file picks its
own subsize values, and that check lives in the tile walk, not at the
allocation.

New gate stream::tests::the_frame_does_not_depend_on_the_plane_buffers_initial
_content: four child processes (two impossible poisons, sentinel-off+uninit,
sentinel-off+zeroed) over ten fixtures must agree on one FNV-1a hash each, with
a synthetic one-sample control first so the equalities cannot be vacuous and a
frames>0 assertion so two children that decoded nothing cannot agree. 4.6 s.

Not in this commit: a pooled plane buffer would make the closure ~free (take the
three buffers from a thread-local pool, zero each once at creation, return on
drop) but it changes PlaneBuf's ownership, which the wavefront workers hold.
Recorded in the report rather than done.

Full table, reader map, census and non-vacuity evidence: lanes/av1uballoc.report.md
crates/ec-av1/examples/alloc_timing.rsadded+105 -0
@@ -0,0 +1,105 @@
1+//! Decode wall time and minor page faults for one `EC_AV1_PLANE_ALLOC` arm.
2+//!
3+//! The three closures lane-uballoc had to choose between (see
4+//! `lanes/av1uballoc.report.md`) are selected by `EC_AV1_PLANE_ALLOC` inside
5+//! the crate, not by a build flag -- see [`ec_av1`]'s `fresh_plane`. Measuring
6+//! them that way means all arms share one binary, one allocator state and one
7+//! machine, which three separate builds cannot do.
8+//!
9+//! ```text
10+//! EC_AV1_PLANE_ALLOC=zeroed cargo run -p ec-av1 --release --example alloc_timing -- s.obu
11+//! ```
12+//!
13+//! One process does ONE decode and prints ONE line, so the harness interleaves
14+//! arms across processes instead of trusting one process's warm-up history:
15+//!
16+//! ```text
17+//! ALLOC_TIMING arm=zeroed frames=24 wall_ms=1234.567 minflt=61234 majflt=0 hash=8f2a...
18+//! ```
19+//!
20+//! `hash` is FNV-1a over every picture's Y/U/V samples in decode order. It is
21+//! the cross-arm determinism evidence: identical `hash` on every arm means the
22+//! closure chosen does not move a single output sample.
23+use std::time::Instant;
24+
25+const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
26+const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
27+
28+/// Minor/major faults from `/proc/self/stat` fields 10 and 12, read around the
29+/// decode. A zeroed-from-the-kernel allocation and an explicit memset differ in
30+/// how many pages they actually touch, and that is the only cheap proxy for it
31+/// that does not need `perf`.
32+fn faults() -> (u64, u64) {
33+ let stat = std::fs::read_to_string("/proc/self/stat").unwrap_or_default();
34+ // Everything before the last ')' is pid + comm, and comm may hold spaces.
35+ let Some(rest) = stat.rsplit_once(')').map(|(_, r)| r) else {
36+ return (0, 0);
37+ };
38+ let f: Vec<&str> = rest.split_whitespace().collect();
39+ // `rest` starts at field 3 (state); minflt is field 10, majflt field 12.
40+ (
41+ f.get(7).and_then(|v| v.parse().ok()).unwrap_or(0),
42+ f.get(9).and_then(|v| v.parse().ok()).unwrap_or(0),
43+ )
44+}
45+
46+fn fnv1a(mut h: u64, bytes: &[u8]) -> u64 {
47+ for &b in bytes {
48+ h ^= u64::from(b);
49+ h = h.wrapping_mul(FNV_PRIME);
50+ }
51+ h
52+}
53+
54+fn main() {
55+ let mut args = std::env::args().skip(1);
56+ let Some(path) = args.next() else {
57+ eprintln!("usage: alloc_timing <stream.obu>");
58+ std::process::exit(2);
59+ };
60+ let arm = std::env::var("EC_AV1_PLANE_ALLOC").unwrap_or_else(|_| "<unset>".into());
61+ let data = match std::fs::read(&path) {
62+ Ok(d) => d,
63+ Err(e) => {
64+ eprintln!("{path}: {e}");
65+ std::process::exit(2);
66+ }
67+ };
68+
69+ // One warm-up decode is NOT done here on purpose: the plane allocations are
70+ // freed back to the allocator between frames anyway, and a discarded decode
71+ // would only hand one arm a warmer arena than another. The harness runs
72+ // each arm many times and reports the median.
73+ let (minflt0, majflt0) = faults();
74+ let t0 = Instant::now();
75+ let mut frames = 0usize;
76+ let mut hash = FNV_OFFSET;
77+ let r = ec_av1::stream::decode_stream_with(&data, |pic, _idx, shown| {
78+ if !shown {
79+ return Ok(());
80+ }
81+ frames += 1;
82+ for p in [&pic.y, &pic.u, &pic.v] {
83+ let mut buf = Vec::with_capacity(p.len() * 2);
84+ for &s in p.iter() {
85+ buf.extend_from_slice(&s.to_le_bytes());
86+ }
87+ hash = fnv1a(hash, &buf);
88+ }
89+ Ok(())
90+ });
91+ let wall = t0.elapsed();
92+ let (minflt1, majflt1) = faults();
93+ match r {
94+ Ok(()) => println!(
95+ "ALLOC_TIMING arm={arm} frames={frames} wall_ms={:.3} minflt={} majflt={} hash={hash:016x}",
96+ wall.as_secs_f64() * 1e3,
97+ minflt1.saturating_sub(minflt0),
98+ majflt1.saturating_sub(majflt0),
99+ ),
100+ Err(e) => {
101+ eprintln!("{path}: decode refused: {e}");
102+ std::process::exit(3);
103+ }
104+ }
105+}
crates/ec-av1/src/decode.rsmodified+314 -90
@@ -21269,9 +21269,9 @@ fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
2126921269
2127021270 /// Enabled by `EC_AV1_PLANE_SENTINEL` (there is no separate flag for it): print
2127121271 /// an EXACT census of the samples the tile walk never wrote -- with it, every
21272-/// plane still holding [`PLANE_SENTINEL`] at this point is a sample no block
21273-/// reconstructed, and no legal sample can equal `0xDEAD` (reconstruction clamps
21274-/// to `(1 << bit_depth) - 1`).
21272+/// plane still holding [`plane_poison`] at this point is a sample no block
21273+/// reconstructed, and no legal sample can equal the poison (reconstruction
21274+/// clamps to `(1 << bit_depth) - 1`, at most 4095).
2127521275 ///
2127621276 /// Coverage, stated as the code has it: this census runs at TWO of the four
2127721277 /// places [`apply_deblock`] is entered from -- the key-frame path and the
@@ -21288,43 +21288,74 @@ fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
2128821288 /// `lane/av1422seed` census used: it replaces a wrong-sample diff (which says
2128921289 /// where the OUTPUT is wrong, not whether the block was written at all) with a
2129021290 /// direct count plus the coordinates of every hole, grouped into per-row
21291-/// spans so a large hole stays readable. Scans each plane over its own
21292-/// `true_width` x `true_height` extent, PER AXIS (`true_width.min(p.width)`), so
21293-/// a 4:2:2 frame's chroma is scanned at its own `fw/2 x fh` shape rather than
21294-/// the 4:2:0 `div_ceil(2)` crop the older [`dump_stage16`] used: past that
21295-/// extent is the padded coding surface's invented tail, which no decoder ever
21296-/// reads.
21291+/// spans so a large hole stays readable.
21292+///
21293+/// It scans TWO regions per plane, because they answer different questions and
21294+/// the earlier revision only scanned one of them:
21295+/// * the TRUE EXTENT -- each plane over its own `true_width` x `true_height`,
21296+/// PER AXIS (`true_width.min(p.width)`), so a 4:2:2 frame's chroma is scanned
21297+/// at its own `fw/2 x fh` shape rather than the 4:2:0 `div_ceil(2)` crop the
21298+/// older [`dump_stage16`] used. A hole here can reach the caller, and it is
21299+/// the region lane/av1unwritten's 224 samples sat in.
21300+/// * the PADDED TAIL -- everything outside that extent, out to the block-aligned
21301+/// coding surface -- counted separately into [`PAD_UNWRITTEN_SAMPLES`]. The
21302+/// earlier revision's doc comment asserted "past that is the padded coding
21303+/// surface's invented tail, which no decoder ever reads". That assertion is
21304+/// exactly what a tail that is never written and never read looks like, so it
21305+/// was self-certifying; the tail is now scanned and counted like any other
21306+/// region. `EC_AV1_PLANE_ALLOC=padzero`/`extzero` attribute a read to one
21307+/// side or the other (see [`fresh_plane`]).
2129721308 fn census_unwritten(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
2129821309 if !plane_sentinel_on() {
2129921310 return;
2130021311 }
21312+ let poison = plane_poison();
2130121313 let idx = PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst);
2130221314 for (name, p) in [("Y", y), ("U", u), ("V", v)] {
21303- let (w, h) = (p.true_width.min(p.width), p.true_height);
21315+ let (w, h) = (p.true_width.min(p.width), p.true_height.min(p.height));
2130421316 let mut total = 0usize;
2130521317 let mut spans: Vec<(usize, usize, usize)> = Vec::new();
2130621318 for row in 0..h {
2130721319 let mut run: Option<(usize, usize)> = None;
2130821320 for col in 0..w {
21309- if p.data[row * p.width + col] == PLANE_SENTINEL {
21321+ if p.data[row * p.width + col] == poison {
2131021322 total += 1;
2131121323 run = Some(match run {
2131221324 None => (col, col),
2131321325 Some((a, _)) => (a, col),
2131421326 });
2131521327 }
21316- if run.is_some()
21317- && (col + 1 == w || p.data[row * p.width + col + 1] != PLANE_SENTINEL)
21318- {
21328+ if run.is_some() && (col + 1 == w || p.data[row * p.width + col + 1] != poison) {
2131921329 let (a, b) = run.take().expect("a run is open here");
2132021330 spans.push((row, a, b));
2132121331 }
2132221332 }
2132321333 }
21334+ // The padded tail: columns `w..width` on rows `0..h`, plus every column
21335+ // on rows `h..height`.
21336+ let mut pad_total = 0usize;
21337+ let mut pad_scanned = 0usize;
21338+ for row in 0..p.height {
21339+ let (from, to) = if row < h { (w, p.width) } else { (0, p.width) };
21340+ if from >= to {
21341+ continue;
21342+ }
21343+ pad_scanned += to - from;
21344+ pad_total += p.data[row * p.width + from..row * p.width + to]
21345+ .iter()
21346+ .filter(|&&s| s == poison)
21347+ .count();
21348+ }
2132421349 UNWRITTEN_SAMPLES.fetch_add(total, std::sync::atomic::Ordering::SeqCst);
2132521350 CENSUS_SCANNED.fetch_add(w * h, std::sync::atomic::Ordering::SeqCst);
21351+ PAD_UNWRITTEN_SAMPLES.fetch_add(pad_total, std::sync::atomic::Ordering::SeqCst);
21352+ PAD_CENSUS_SCANNED.fetch_add(pad_scanned, std::sync::atomic::Ordering::SeqCst);
21353+ eprintln!(
21354+ "SENTINEL_CENSUS idx={idx} plane={name} surface={}x{} extent={w}x{h} \
21355+ pad_scanned={pad_scanned} unwritten={total} pad_unwritten={pad_total}",
21356+ p.width, p.height,
21357+ );
2132621358 if total == 0 {
21327- eprintln!("SENTINEL_CENSUS idx={idx} plane={name} extent={w}x{h} unwritten=0");
2132821359 continue;
2132921360 }
2133021361 let body: Vec<String> = spans
@@ -21332,8 +21363,10 @@ fn census_unwritten(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
2133221363 .map(|&(r, a, b)| format!("y{r} x{a}..={b}"))
2133321364 .collect();
2133421365 eprintln!(
21335- "SENTINEL_CENSUS idx={idx} plane={name} extent={w}x{h} unwritten={total} \
21336- spans={}: {}",
21366+ "SENTINEL_CENSUS idx={idx} plane={name} surface={}x{} extent={w}x{h} \
21367+ unwritten={total} spans={}: {}",
21368+ p.width,
21369+ p.height,
2133721370 spans.len(),
2133821371 body.join(" ")
2133921372 );
@@ -21376,6 +21409,67 @@ pub fn take_census_scanned() -> usize {
2137621409 CENSUS_SCANNED.swap(0, std::sync::atomic::Ordering::SeqCst)
2137721410 }
2137821411
21412+/// Samples in the PADDED TAIL -- every sample of each plane outside its own
21413+/// `true_width` x `true_height` extent -- that still holds [`plane_poison`] at
21414+/// the pre-deblock point. [`census_unwritten`] scans that region too, because
21415+/// "past the true extent nothing is ever read" was an ASSUMPTION the tail's
21416+/// census was built to avoid checking; this counter is the measurement.
21417+static PAD_UNWRITTEN_SAMPLES: std::sync::atomic::AtomicUsize =
21418+ std::sync::atomic::AtomicUsize::new(0);
21419+
21420+/// Samples [`census_unwritten`] scanned in the padded tail, paired with
21421+/// [`PAD_UNWRITTEN_SAMPLES`] for the same reason as [`CENSUS_SCANNED`].
21422+static PAD_CENSUS_SCANNED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
21423+
21424+/// Reads and clears [`PAD_UNWRITTEN_SAMPLES`].
21425+pub fn take_pad_unwritten_samples() -> usize {
21426+ PAD_UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst)
21427+}
21428+
21429+/// Reads and clears [`PAD_CENSUS_SCANNED`].
21430+pub fn take_pad_census_scanned() -> usize {
21431+ PAD_CENSUS_SCANNED.swap(0, std::sync::atomic::Ordering::SeqCst)
21432+}
21433+
21434+/// The largest value reconstruction can produce, `(1 << 12) - 1`: the highest
21435+/// bit depth this decoder carries is 12. A sentinel at or below this could be
21436+/// a LEGAL sample, which would make the whole census vacuous -- every
21437+/// unwritten sample would look like an ordinary one.
21438+const MAX_LEGAL_SAMPLE: u16 = 4095;
21439+
21440+/// The value [`fresh_plane`] fills with when the sentinel is on.
21441+///
21442+/// [`PLANE_SENTINEL`] unless `EC_AV1_PLANE_SENTINEL` names a different one in
21443+/// hex. Two different poisons are what turns the sentinel from "did a hole
21444+/// survive into the output" into "did the output depend on the buffer's
21445+/// initial content": a hole whose value reaches the picture changes the hash
21446+/// when the poison changes, and one that does not cannot have influenced
21447+/// anything. A value at or below [`MAX_LEGAL_SAMPLE`] is REFUSED (falls back
21448+/// to [`PLANE_SENTINEL`]) because the census's soundness rests on the sentinel
21449+/// being impossible. `EC_AV1_PLANE_SENTINEL=1` -- the spelling every existing
21450+/// caller and gate uses, and `env_flag!`'s mere presence test -- keeps
21451+/// [`PLANE_SENTINEL`].
21452+fn plane_poison() -> u16 {
21453+ static V: std::sync::LazyLock<u16> = std::sync::LazyLock::new(|| {
21454+ let Ok(raw) = crate::envflags::var("EC_AV1_PLANE_SENTINEL") else {
21455+ return PLANE_SENTINEL;
21456+ };
21457+ let t = raw.trim();
21458+ if t.is_empty() || t == "1" {
21459+ return PLANE_SENTINEL;
21460+ }
21461+ let hex = t
21462+ .strip_prefix("0x")
21463+ .or_else(|| t.strip_prefix("0X"))
21464+ .unwrap_or(t);
21465+ match u16::from_str_radix(hex, 16) {
21466+ Ok(v) if v > MAX_LEGAL_SAMPLE => v,
21467+ _ => PLANE_SENTINEL,
21468+ }
21469+ });
21470+ *V
21471+}
21472+
2137921473 thread_local! {
2138021474 /// The [`set_plane_sentinel`] override; `EC_AV1_PLANE_SENTINEL` is the
2138121475 /// process-wide default.
@@ -21761,92 +21855,210 @@ pub(crate) fn census_unwritten_final(y: &[u16], u: &[u16], v: &[u16]) {
2176121855 // each plane IS the true-extent count.
2176221856 let (scanned, total): (usize, usize) = [y, u, v]
2176321857 .iter()
21764- .map(|p| (p.len(), p.iter().filter(|&&s| s == PLANE_SENTINEL).count()))
21858+ .map(|p| (p.len(), p.iter().filter(|&&s| s == plane_poison()).count()))
2176521859 .fold((0, 0), |(a, b), (c, d)| (a + c, b + d));
2176621860 FINAL_CENSUS_SCANNED.fetch_add(scanned, std::sync::atomic::Ordering::SeqCst);
2176721861 FINAL_UNWRITTEN_SAMPLES.fetch_add(total, std::sync::atomic::Ordering::SeqCst);
2176821862 }
2176921863
21770-/// A frame plane's own backing store, `n` samples, UNINITIALISED.
21864+/// Which closure [`fresh_plane`] applies to the allocation it hands back.
2177121865 ///
21772-/// (lane-picalloc) Replaced a `vec![0u16; n]` that zeroed the whole plane
21773-/// buffer: ~3% of the frame thread's cycles at 4K, serially at the frame's head,
21774-/// to initialise 25 MB the next pass overwrites.
21866+/// # WHY AN ENV ARM, and what each arm is
2177521867 ///
21776-/// # THE `unsafe` BELOW IS NOT FULLY JUSTIFIED -- read this before approving it
21868+/// The closure was a filed choice with no number behind it
21869+/// (`lanes/unwritten-dep.report.md` §12). lane-av1uballoc measured all of them
21870+/// on one stream in ONE binary, because three separate builds cannot make the
21871+/// comparison fair -- the allocator's recycled-arena state, the page-cache
21872+/// state and the code layout all differ between them. `EC_AV1_PLANE_ALLOC`
21873+/// (process-constant, read once -- see [`crate::envflags`]) picks the arm.
21874+/// Numbers: `lanes/av1uballoc.report.md`.
21875+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
21876+enum PlaneAlloc {
21877+ /// `vec![0u16; n]`, i.e. `alloc_zeroed`/`calloc`. **The default and the
21878+ /// shipped closure.** It removes the `unsafe` below from every build that
21879+ /// does not ask for a census arm.
21880+ ///
21881+ /// What it costs, measured on one stream in one binary
21882+ /// (`lanes/av1uballoc.report.md` §1): **+0.84%** of decode wall time at
21883+ /// 3840x2160 4:2:0 (96 frames, 6937.728 -> 6995.727 ms, mean 6995.769,
21884+ /// run-to-run spread of the arm 10.2 ms, so ~6 sigma), **+0.81%** at
21885+ /// 3840x2160 4:2:2, and **-1.63%** at 1920x1080 4:2:0 -- it is FASTER
21886+ /// there, reproducibly. The sign flip is not explained here; the numbers
21887+ /// are.
21888+ ///
21889+ /// What it is NOT is the "zero pages are free" story the arm's name
21890+ /// invites: glibc hands a RECYCLED arena block back from `calloc` with the
21891+ /// same memset an explicit fill does, which is why this arm and
21892+ /// [`PlaneAlloc::Fill`] land within 0.03% of each other at every size.
21893+ Zeroed,
21894+ /// The status quo this lane replaced: `Vec::with_capacity` + `set_len`,
21895+ /// nothing written. Kept as an arm because every number here is a delta
21896+ /// against it, and because `EC_AV1_PLANE_ALLOC=uninit` reproduces it.
21897+ Uninit,
21898+ /// An explicit zero-fill (`Vec::with_capacity` then `resize(n, 0)`) -- the
21899+ /// closure that costs the same as [`PlaneAlloc::Zeroed`]. Kept so the
21900+ /// "zero pages are free" hypothesis stays falsifiable from the outside.
21901+ Fill,
21902+ /// Census-only: zero the PADDED tail (everything outside the plane's true
21903+ /// extent) and leave the true extent uninitialised. Pairs with
21904+ /// [`PlaneAlloc::ExtZero`] to attribute a read to one region.
21905+ PadZero,
21906+ /// Census-only: the mirror of [`PlaneAlloc::PadZero`] -- zero the true
21907+ /// extent, leave the padded tail uninitialised.
21908+ ExtZero,
21909+}
21910+
21911+/// `EC_AV1_PLANE_ALLOC`'s arm. Defaults to [`PlaneAlloc::Zeroed`], the shipped
21912+/// closure; an unrecognised value is the default too, so a typo degrades to the
21913+/// safe arm rather than back to the `unsafe` one.
21914+fn plane_alloc() -> PlaneAlloc {
21915+ static ARM: std::sync::LazyLock<PlaneAlloc> = std::sync::LazyLock::new(|| {
21916+ match crate::envflags::var("EC_AV1_PLANE_ALLOC")
21917+ .ok()
21918+ .as_deref()
21919+ .map(str::trim)
21920+ {
21921+ Some("uninit") => PlaneAlloc::Uninit,
21922+ Some("fill") => PlaneAlloc::Fill,
21923+ Some("padzero") => PlaneAlloc::PadZero,
21924+ Some("extzero") => PlaneAlloc::ExtZero,
21925+ _ => PlaneAlloc::Zeroed,
21926+ }
21927+ });
21928+ *ARM
21929+}
21930+
21931+/// Zeroes a plane's PADDED tail -- the SB-aligned coding surface's invented
21932+/// rows and columns outside `true_width` x `true_height` -- and leaves the
21933+/// true extent alone. [`PlaneAlloc::PadZero`] only.
21934+fn zero_pad(v: &mut [u16], width: usize, height: usize, true_width: usize, true_height: usize) {
21935+ for row in 0..height {
21936+ let base = row * width;
21937+ let first = if row < true_height { true_width } else { 0 };
21938+ v[base + first..base + width].fill(0);
21939+ }
21940+}
21941+
21942+/// Zeroes a plane's TRUE EXTENT and leaves the padded tail alone -- the mirror
21943+/// of [`zero_pad`]. [`PlaneAlloc::ExtZero`] only.
21944+fn zero_extent(v: &mut [u16], width: usize, true_width: usize, true_height: usize) {
21945+ for row in 0..true_height {
21946+ let base = row * width;
21947+ v[base..base + true_width].fill(0);
21948+ }
21949+}
21950+
21951+/// A frame plane's own backing store, `n` samples.
21952+///
21953+/// `true_width`/`true_height` are the plane's decodable extent in its own
21954+/// units; `width`/`height` the block-aligned coding surface it is carved from
21955+/// (`cols32 * 32`, so at most 31 px of margin per axis). They are what
21956+/// [`zero_pad`]/[`zero_extent`] need and what the pad census reports against;
21957+/// [`PlaneAlloc::Zeroed`] reads none of them.
21958+///
21959+/// # WHAT CAN BE READ BEFORE IT IS WRITTEN -- the region list
21960+///
21961+/// The premise an earlier revision of this comment carried -- "the SB-padded
21962+/// surface is written sample-for-sample by the tile walk's reconstruction
21963+/// before anything reads it" -- is RETRACTED by measurement
21964+/// (`lanes/unwritten-dep.report.md` §12). What replaces it is this list, which
21965+/// is checkable where a premise is not. TWO disjoint regions of the allocation
21966+/// can hold a sample no block wrote:
21967+///
21968+/// 1. THE PADDED TAIL -- every sample outside `true_width` x `true_height`, out
21969+/// to the block-aligned surface. Unwritten BY CONSTRUCTION: no block lands
21970+/// on it. Measured over all 128 committed fixtures at the pre-deblock point:
21971+/// **4,676,128 unwritten of 22,787,296 scanned tail samples (20.5%)**, on 38
21972+/// fixtures. It is also **not read**: valgrind memcheck over the same 128
21973+/// fixtures, on the `uninit` arm, reports ZERO uninitialised-value uses --
21974+/// and the instrument is shown live by a deliberate tail read, which
21975+/// produces 12 errors from 4 contexts (`lanes/av1uballoc.report.md` §2.4).
21976+/// 2. THE TRUE EXTENT -- a sample inside `true_width` x `true_height` that the
21977+/// tile walk skipped. This is where the withdrawn 224-sample demonstration
21978+/// sat (`440_request_is_422`, U/V rows 36..63, whole 4x4 groups). Measured
21979+/// over the same 127 fixtures at the pre-deblock point: **0 unwritten of
21980+/// 1,466,581,280 scanned**, and 0 again at the output point. The one fixture
21981+/// that demonstrated it is REFUSED on main, so nothing current reaches
21982+/// region 2.
2177721983 ///
21778-/// This comment previously claimed the SB-padded surface "is written
21779-/// sample-for-sample by the tile walk's reconstruction before anything reads
21780-/// it", and cited the sentinel gate as proof. **That claim is RETRACTED by
21781-/// measurement.** The basis for the retraction is THIS LANE's own, not
21782-/// second-hand: on `440_request_is_422` an exact u16 whole-plane census at the
21783-/// pre-deblock point finds **112 unwritten samples per chroma plane, 224 total**
21784-/// (U and V, 28 whole 4x4 groups each, rows 36..63) in a frame that is SHOWN
21785-/// (`Key show=true`) and whose samples the caller receives. Uninitialised memory
21786-/// that reaches the caller was read, or the read that produced it was. That is
21787-/// the UB, and it needs no hash-variation claim to stand.
21984+/// 3. THE WHOLE BUFFER, read-then-overwritten -- `pix_write` (`decode.rs:22073`,
21985+/// called at 22294/22450/39014/39029) takes the destination sample's own
21986+/// value as its `prev` argument, so on the first write to each sample it
21987+/// READS the initial content. Unlike regions 1 and 2 this one FIRES on
21988+/// every fixture and every store -- and neither census can see it, because
21989+/// `prev` is consumed only inside `if *PIXPROBE_ON`, so it never reaches a
21990+/// branch or a syscall. Confirmed: a DEBUG build under memcheck on the
21991+/// `uninit` arm still reports 0 errors. It does not affect output, and it is
21992+/// deleted by the shipped closure along with everything else.
2178821993 ///
21789-/// A hash-variation observation also exists -- five plain runs of the same
21790-/// witness giving two different output hashes (`lanes/av1unwritten.report.md`),
21791-/// which would point the same way -- but it is SECOND-HAND and was NOT
21792-/// reproduced here: five plain runs on `8d6998d7` gave one hash
21793-/// (`a761118c8dd5c8d0`, `lanes/unwritten-dep.report.md` §10). It is not relied
21794-/// on, and the ambient content a run happens to receive is machine-dependent,
21795-/// so a stable value on one host and a varying one on another would be the same
21796-/// defect either way. The 224-sample census is the basis; the hashes are aside.
21994+/// The readers that could reach regions 1 and 2 are enumerated in
21995+/// `lanes/av1uballoc.report.md` §2; all of them clamp to `true_width`/
21996+/// `true_height`, which is why region 1 never fires, and none of them is
21997+/// reached on a current fixture, which is why region 2 does not either.
2179721998 ///
21798-/// WHAT IS ACTUALLY ESTABLISHED, and it is weaker:
21999+/// Those three measurements say no read of the initial content is reachable
22000+/// from today's corpus. That is a statement about today's corpus, NOT a
22001+/// licence for the `unsafe` below: a hostile file picks its own subsize values,
22002+/// and the refusal that closes region 2 lives in the tile walk, not here --
22003+/// which is why it is a refusal and not a proof. So the shipped closure is
22004+/// [`PlaneAlloc::Zeroed`] (+0.84% at 4K and -1.63% at 1080p, measured --
22005+/// `lanes/av1uballoc.report.md` §1), and the `unsafe` is reachable ONLY from
22006+/// the `uninit`, `padzero` and `extzero` arms.
2179922007 ///
21800-/// * The sentinel gate ([`census_unwritten_final`],
21801-/// `the_frame_the_caller_receives_carries_no_unwritten_plane_sample`) proves
21802-/// that no sample the tile walk never wrote SURVIVES into the frame the caller
21803-/// receives, on the corpus measured. **It counts at the OUTPUT POINT ONLY --
21804-/// one census, one scan.** The pre-deblock census ([`census_unwritten`],
21805-/// `take_unwritten_samples` / `take_census_scanned`) is a DIFFERENT instrument
21806-/// and has NO committed reader anywhere in the crate on `main`, so it backs
21807-/// nothing here; an earlier revision of this comment credited the gate with
21808-/// both, which would have told a reviewer the premise is covered by two scans
21809-/// when only one exists. It is measured SURVIVAL, not reads.
21810-/// * It does NOT prove "every sample is written before it is read". A sample read
21811-/// as a prediction or filter neighbour and overwritten a moment later is
21812-/// invisible to that count. **No such read has been observed, and no
21813-/// instrument here measures for one.**
21814-/// * On `main` = `e45cc748` the one path where a read was demonstrated is
21815-/// UNREACHABLE: lane/av1unwritten refuses the subsize before descending.
22008+/// ONE ORDERING CONSTRAINT on the two census arms, because it changes what
22009+/// they can be used for: the sentinel check comes FIRST, so
22010+/// [`PlaneAlloc::PadZero`] and [`PlaneAlloc::ExtZero`] never run while
22011+/// `EC_AV1_PLANE_SENTINEL` is set -- and that flag is what both census
22012+/// functions require (each returns early when it is off). The census arms are
22013+/// therefore meaningful only under **memcheck with the sentinel OFF**, where
22014+/// the zeroed/uninitialised split between the two regions is exactly what
22015+/// memcheck keys on. The order stays as it is: moving the sentinel check below
22016+/// the match would let the region census scan a buffer the sentinel never
22017+/// poisoned, which is the one thing it cannot recover from.
2181622018 ///
21817-/// Honest status: a read-before-write is DEMONSTRATED on a path that is now
21818-/// refused, UNMEASURED on every other path, and this `unsafe` is sound only under
21819-/// the unproven "written before read" premise. Filed as an open UB-class item
21820-/// (`lanes/unwritten-dep.report.md` §12) with two closures: (a) zero the
21821-/// allocation -- the safe default, at the ~3% this removed; or (b) an instrument
21822-/// counting reads-before-write per sample, so the premise can be proved rather
21823-/// than assumed.
21824-fn fresh_plane(n: usize) -> Vec<u16> {
22019+/// What IS sound and unchanged in that block: `u16` has no invalid bit patterns
22020+/// and no `Drop`, and the capacity was just reserved, so the vector validly
22021+/// owns `n` slots. Creating a `Vec` over uninitialised memory is not itself
22022+/// UB -- a READ of a slot in region 1, region 2 or region 3 is.
22023+fn fresh_plane(
22024+ n: usize,
22025+ true_width: usize,
22026+ true_height: usize,
22027+ width: usize,
22028+ height: usize,
22029+) -> Vec<u16> {
2182522030 if plane_sentinel_on() {
21826- return vec![PLANE_SENTINEL; n];
22031+ return vec![plane_poison(); n];
22032+ }
22033+ match plane_alloc() {
22034+ PlaneAlloc::Zeroed => return vec![0u16; n],
22035+ PlaneAlloc::Fill => {
22036+ let mut v: Vec<u16> = Vec::with_capacity(n);
22037+ v.resize(n, 0);
22038+ return v;
22039+ }
22040+ PlaneAlloc::Uninit | PlaneAlloc::PadZero | PlaneAlloc::ExtZero => {}
2182722041 }
2182822042 let mut v: Vec<u16> = Vec::with_capacity(n);
21829- // SAFETY, PARTIAL -- the premise is NOT established; see the block comment
21830- // above ("THE `unsafe` BELOW IS NOT FULLY JUSTIFIED").
21831- //
21832- // What IS sound: `u16` has no invalid bit patterns and no `Drop`, and the
21833- // capacity was just reserved, so the vector owns `n` slots that are valid to
21834- // OWN. Creating a `Vec` over uninitialised memory is not itself UB.
21835- //
21836- // What is NOT sound, and is the reason this is a filed item rather than a
21837- // settled one: reading an uninitialised `u16` IS UB, and the only thing that
21838- // makes the reads sound is the premise that reconstruction writes every
21839- // sample before any read. That premise was RETRACTED by measurement (224
21840- // unwritten samples, output varying with initial content) on a path that is
21841- // now refused, and is UNMEASURED everywhere else. The sentinel gate measures
21842- // survival at the output point, not reads. The pre-deblock census is a
21843- // separate instrument with no committed reader on main, so it adds nothing
21844- // here. So this `unsafe` is sound under a premise no current instrument
21845- // proves.
22043+ // SAFETY: OWNING `n` uninitialised `u16` slots is sound (`u16` has no
22044+ // invalid bit patterns and no `Drop`, and the capacity was just reserved).
22045+ // A READ of a slot in region 1, region 2 or region 3 above would not be,
22046+ // which is why the shipped arm returns above and never reaches here: this
22047+ // block is reachable only under `EC_AV1_PLANE_ALLOC=uninit|padzero|extzero`
22048+ // -- exactly the arms `plane_alloc()` lets fall through. `fill` is NOT one
22049+ // of them (it returns early at the `resize`), and an UNRECOGNISED value is
22050+ // not either: `plane_alloc()` maps it to `Zeroed`, so a typo picks the safe
22051+ // arm. The two region counts and the memcheck sweep are what make those
22052+ // arms' results readable; re-run them before believing a new "0".
2184622053 #[allow(unsafe_code)]
2184722054 unsafe {
2184822055 v.set_len(n);
2184922056 }
22057+ match plane_alloc() {
22058+ PlaneAlloc::PadZero => zero_pad(&mut v, width, height, true_width, true_height),
22059+ PlaneAlloc::ExtZero => zero_extent(&mut v, width, true_width, true_height),
22060+ _ => {}
22061+ }
2185022062 v
2185122063 }
2185222064
@@ -35892,7 +36104,13 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
3589236104 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
3589336105
3589436106 let mut y = PlaneBuf {
35895- data: std::borrow::Cow::Owned(fresh_plane(width * height)),
36107+ data: std::borrow::Cow::Owned(fresh_plane(
36108+ width * height,
36109+ true_width,
36110+ true_height,
36111+ width,
36112+ height,
36113+ )),
3589636114 width,
3589736115 height,
3589836116 true_width,
@@ -35906,7 +36124,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
3590636124 let (cw, ch) = (width >> ss_x(fctx), height >> ss_y(fctx));
3590736125 let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx));
3590836126 let mut u = PlaneBuf {
35909- data: std::borrow::Cow::Owned(fresh_plane(cw * ch)),
36127+ data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)),
3591036128 width: cw,
3591136129 height: ch,
3591236130 true_width: ctw,
@@ -35918,7 +36136,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
3591836136 plane: 1,
3591936137 };
3592036138 let mut v = PlaneBuf {
35921- data: std::borrow::Cow::Owned(fresh_plane(cw * ch)),
36139+ data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)),
3592236140 width: cw,
3592336141 height: ch,
3592436142 true_width: ctw,
@@ -53657,7 +53875,13 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
5365753875 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
5365853876
5365953877 let mut y = PlaneBuf {
53660- data: std::borrow::Cow::Owned(fresh_plane(width * height)),
53878+ data: std::borrow::Cow::Owned(fresh_plane(
53879+ width * height,
53880+ true_width,
53881+ true_height,
53882+ width,
53883+ height,
53884+ )),
5366153885 width,
5366253886 height,
5366353887 true_width,
@@ -53671,7 +53895,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
5367153895 let (cw, ch) = (width >> ss_x(fctx), height >> ss_y(fctx));
5367253896 let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx));
5367353897 let mut u = PlaneBuf {
53674- data: std::borrow::Cow::Owned(fresh_plane(cw * ch)),
53898+ data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)),
5367553899 width: cw,
5367653900 height: ch,
5367753901 true_width: ctw,
@@ -53683,7 +53907,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
5368353907 plane: 1,
5368453908 };
5368553909 let mut v = PlaneBuf {
53686- data: std::borrow::Cow::Owned(fresh_plane(cw * ch)),
53910+ data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)),
5368753911 width: cw,
5368853912 height: ch,
5368953913 true_width: ctw,
crates/ec-av1/src/stream.rsmodified+233 -0
@@ -48557,6 +48557,239 @@ exit 0
4855748557 println!("UWDEP_CENSUS {n} frames={} scanned={scanned}", frames.len());
4855848558 }
4855948559
48560+ /// lane-av1uballoc: the frame the caller receives does not depend on what
48561+ /// the plane buffer held before the decode wrote it.
48562+ ///
48563+ /// Four runs of the same fixtures, each in its own process (the fill and
48564+ /// the alloc closure are both process-constant env reads -- see
48565+ /// [`crate::envflags`] -- and this crate forbids `set_var`), must agree on
48566+ /// one hash per fixture:
48567+ ///
48568+ /// * `EC_AV1_PLANE_SENTINEL=0xDEAD` and `=0xBEEF` -- two DIFFERENT
48569+ /// impossible values for the same buffer. This is the arm that can
48570+ /// actually FAIL: if any reader's value reaches the picture, changing the
48571+ /// poison changes the output. Equal hashes are a statement about a READ,
48572+ /// which is what the `unsafe` in [`decode::fresh_plane`] needs and what no
48573+ /// census in the crate measures.
48574+ /// * the sentinel OFF with `EC_AV1_PLANE_ALLOC=uninit` and `=zeroed` -- the
48575+ /// status quo and the shipped closure, which must agree with each other
48576+ /// and with the poisoned runs. This is the "same with the sentinel off"
48577+ /// arm; on its own it is weak (the allocator may hand out the same
48578+ /// ambient bytes twice) and is here as the join between the two worlds.
48579+ ///
48580+ /// NON-VACUITY, first and synthetic: [`allocdet_synthetic`] hashes two
48581+ /// pictures that differ in ONE sample and asserts the hashes DIFFER. A hash
48582+ /// that cannot see a one-sample difference would make every equality below
48583+ /// vacuous, and it is the failure mode a "0 errors" style result has.
48584+ /// Second: every arm must report `frames>0`, so a child that decoded
48585+ /// nothing cannot agree with another child that decoded nothing.
48586+ #[test]
48587+ fn the_frame_does_not_depend_on_the_plane_buffers_initial_content() {
48588+ const NAME: &str = "the_frame_does_not_depend_on_the_plane_buffers_initial_content";
48589+ let _gate_lock = lock_gate_counters();
48590+ // Kept SMALL on purpose: the whole gate is 4 child processes x this
48591+ // list, and the suite runs it in a DEBUG build. A first revision used
48592+ // the 1920x792 film fixtures here and took 252 s, which is not a gate
48593+ // anyone keeps. These ten cover every shape the region list names --
48594+ // 4:2:2 (12-bit key, inter, sb128 intrabc, 17-frame odd-size), 4:4:4
48595+ // (lossless sb64, intrabc rect4, 128-root mu), a padded odd size, an
48596+ // off-tile chroma walk, and superres+CDEF+LR -- for ~1.3 s per arm.
48597+ const FIXTURES: &[&str] = &[
48598+ "s422_12bit_160x128",
48599+ "422_inter_160x128_3f",
48600+ "422_intrabc_sb128_strip",
48601+ "s422_352x242_10b",
48602+ "ll444_sb64_1to4_lossless",
48603+ "444_intrabc_rect4_witness",
48604+ "444_intra_in_inter_128root_mu_chroma",
48605+ "svt1-split-tx-pin",
48606+ "mix176_offtile_chroma_clip",
48607+ "superres_kf_cdef_lr_64x64",
48608+ ];
48609+
48610+ let (a, b) = allocdet_synthetic();
48611+ assert_ne!(
48612+ a, b,
48613+ "{NAME}: the content hash returned the same value for two pictures differing in one \
48614+ sample, so every equality below is vacuous -- this gate would pass on any decoder, \
48615+ including one that returns garbage (class: hash-cannot-see-content)"
48616+ );
48617+
48618+ let arms: [(&str, Option<&str>, &str); 4] = [
48619+ ("poison-dead", Some("0xDEAD"), "uninit"),
48620+ ("poison-beef", Some("0xBEEF"), "uninit"),
48621+ ("sentinel-off-uninit", None, "uninit"),
48622+ ("alloc-zeroed", None, "zeroed"),
48623+ ];
48624+ let mut baseline: Option<Vec<(String, usize, u64)>> = None;
48625+ for (label, poison, alloc) in arms {
48626+ let rows = allocdet_child(FIXTURES, poison, alloc);
48627+ assert_eq!(
48628+ rows.len(),
48629+ FIXTURES.len(),
48630+ "{NAME}: the {label} arm reported {} of {} fixtures -- a run that decoded \
48631+ nothing can agree with another run that decoded nothing",
48632+ rows.len(),
48633+ FIXTURES.len()
48634+ );
48635+ for (f, frames, _) in &rows {
48636+ assert!(
48637+ *frames > 0,
48638+ "{NAME}: the {label} arm decoded 0 frames of {f}; the hashes it compared are \
48639+ over nothing"
48640+ );
48641+ }
48642+ match &baseline {
48643+ None => baseline = Some(rows),
48644+ Some(first) => {
48645+ for (i, (f, frames, h)) in rows.iter().enumerate() {
48646+ let (bf, bframes, bh) = &first[i];
48647+ assert_eq!(
48648+ bf, f,
48649+ "{NAME}: arm {label} reported fixture {f} where the \
48650+ baseline reported {bf} -- the arms are not comparable"
48651+ );
48652+ assert_eq!(
48653+ bframes, frames,
48654+ "{NAME}: {f} decoded {frames} frames under \
48655+ {label} and {bframes} under the baseline arm"
48656+ );
48657+ assert_eq!(
48658+ bh, h,
48659+ "{NAME}: {f} decoded to a DIFFERENT picture depending on what the \
48660+ plane buffer held before the decode wrote it -- {label} gave {h:016x}, \
48661+ the baseline arm gave {bh:016x}. A read of uninitialised memory \
48662+ reaches the caller's frame (see the SAFETY comment on \
48663+ decode::fresh_plane)."
48664+ );
48665+ }
48666+ }
48667+ }
48668+ }
48669+ }
48670+
48671+ /// Runs [`allocdet_child_decode`] in a fresh process and parses its
48672+ /// `ALLOCDET <fixture> frames=<n> hash=<hex>` lines into
48673+ /// `(fixture, frames, hash)` in FIXTURES order.
48674+ fn allocdet_child(
48675+ fixtures: &[&str],
48676+ poison: Option<&str>,
48677+ alloc: &str,
48678+ ) -> Vec<(String, usize, u64)> {
48679+ const NAME: &str = "the_frame_does_not_depend_on_the_plane_buffers_initial_content";
48680+ let exe = std::env::current_exe().expect("test binary path");
48681+ let mut cmd = std::process::Command::new(exe);
48682+ cmd.args([
48683+ "--exact",
48684+ "stream::tests::allocdet_child_decode",
48685+ "--nocapture",
48686+ ])
48687+ .env("ALLOCDET_FIXTURES", fixtures.join(","))
48688+ .env("EC_AV1_PLANE_ALLOC", alloc)
48689+ .env_remove("ALLOCDET_SYNTHETIC");
48690+ match poison {
48691+ Some(p) => cmd.env("EC_AV1_PLANE_SENTINEL", p),
48692+ None => cmd.env_remove("EC_AV1_PLANE_SENTINEL"),
48693+ };
48694+ let out = cmd.output().expect("running the allocdet child");
48695+ let text = format!(
48696+ "{}{}",
48697+ String::from_utf8_lossy(&out.stdout),
48698+ String::from_utf8_lossy(&out.stderr),
48699+ );
48700+ let mut rows = Vec::new();
48701+ for f in fixtures {
48702+ let line = text
48703+ .lines()
48704+ .find(|l| l.starts_with(&format!("ALLOCDET {f} ")))
48705+ .unwrap_or_else(|| {
48706+ panic!(
48707+ "{NAME}: the child reported nothing for {f} (child said: {:?})",
48708+ text.trim()
48709+ )
48710+ });
48711+ let mut parts = line.split_whitespace();
48712+ assert_eq!(parts.next(), Some("ALLOCDET"));
48713+ assert_eq!(parts.next(), Some(*f));
48714+ let frames = parts
48715+ .find_map(|p| p.strip_prefix("frames="))
48716+ .and_then(|v| v.parse().ok())
48717+ .unwrap_or_else(|| panic!("{NAME}: no frame count in {line:?}"));
48718+ let hash = parts
48719+ .find_map(|p| p.strip_prefix("hash="))
48720+ .and_then(|v| u64::from_str_radix(v, 16).ok())
48721+ .unwrap_or_else(|| panic!("{NAME}: no hash in {line:?}"));
48722+ rows.push(((*f).to_string(), frames, hash));
48723+ }
48724+ rows
48725+ }
48726+
48727+ /// The child half of
48728+ /// [`the_frame_does_not_depend_on_the_plane_buffers_initial_content`]:
48729+ /// decodes every fixture named in `ALLOCDET_FIXTURES` and prints one
48730+ /// `ALLOCDET` line each.
48731+ ///
48732+ /// With `ALLOCDET_SYNTHETIC` set it instead prints the two hashes the
48733+ /// non-vacuity control compares -- two pictures differing in ONE sample --
48734+ /// and decodes nothing.
48735+ #[test]
48736+ fn allocdet_child_decode() {
48737+ if std::env::var_os("ALLOCDET_SYNTHETIC").is_some() {
48738+ let (a, b) = allocdet_synthetic();
48739+ println!("ALLOCDET_SYNTHETIC {a:016x} {b:016x}");
48740+ return;
48741+ }
48742+ let list = std::env::var("ALLOCDET_FIXTURES").expect("ALLOCDET_FIXTURES");
48743+ let mut hash = 0xcbf2_9ce4_8422_2325u64;
48744+ for fixture in list.split(',').filter(|s| !s.is_empty()) {
48745+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
48746+ .join(format!("fixtures/{fixture}.obu"));
48747+ let stream =
48748+ std::fs::read(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display()));
48749+ let mut frames = 0usize;
48750+ decode_stream_with(&stream, |pic, _idx, shown| {
48751+ if !shown {
48752+ return Ok(());
48753+ }
48754+ frames += 1;
48755+ for p in [&pic.y, &pic.u, &pic.v] {
48756+ for &s in p.iter() {
48757+ for b in s.to_le_bytes() {
48758+ hash ^= u64::from(b);
48759+ hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
48760+ }
48761+ }
48762+ }
48763+ Ok(())
48764+ })
48765+ .unwrap_or_else(|e| panic!("{fixture} refused: {e}"));
48766+ println!("ALLOCDET {fixture} frames={frames} hash={hash:016x}");
48767+ }
48768+ }
48769+
48770+ /// Two pictures identical except for ONE sample of ONE plane, hashed by the
48771+ /// same FNV-1a the child uses. Equal values here would make the gate's
48772+ /// equalities vacuous, so it is asserted to differ.
48773+ fn allocdet_synthetic() -> (u64, u64) {
48774+ const P: u64 = 0x0000_0100_0000_01b3;
48775+ let hash = |mut h: u64, samples: &[u16]| {
48776+ for &s in samples {
48777+ for b in s.to_le_bytes() {
48778+ h ^= u64::from(b);
48779+ h = h.wrapping_mul(P);
48780+ }
48781+ }
48782+ h
48783+ };
48784+ let a = vec![128u16; 4096];
48785+ let mut b = a.clone();
48786+ b[2048] = 129;
48787+ (
48788+ hash(0xcbf2_9ce4_8422_2325, &a),
48789+ hash(0xcbf2_9ce4_8422_2325, &b),
48790+ )
48791+ }
48792+
4856048793 /// lane-t900 r6: the 128-superblock INTER witness.
4856148794 /// `crates/ec-av1/fixtures/reelc_sb128_inter_witness.obu`, 177773 bytes,
4856248795 /// sha256 `09d995946d27695ef4b7b1a24a4d7ad85f8e2c8176d58ee54e825efc061f9cbc`:
lanes/av1uballoc.report.mdadded+414 -0
@@ -0,0 +1,414 @@
1+# lane/av1uballoc — the plane allocation closure, decided with a number
2+
3+Started from base `2d8fa8a4`; **rebased onto `f01e9738` and re-measured there**
4+(§7). Target: `crates/ec-av1/src/decode.rs`'s `fresh_plane` and the
5+`unsafe { v.set_len(n) }` behind it.
6+
7+**Decision: ship closure (b), `vec![0u16; n]` (`alloc_zeroed`/`calloc`).** It
8+costs **+0.84%** of decode wall time at 3840x2160 4:2:0 and **+0.81%** at
9+3840x2160 4:2:2 (both ~6σ against a 6–10 ms run-to-run spread), and **−1.63%**
10+at 1920x1080 — it is *faster* there, reproducibly. It removes the `unsafe`
11+from every build that is not explicitly asking for a census arm.
12+
13+**No fixture on current main reaches an uninitialised read.** The reads-before-
14+write census below found zero, by two independent instruments, over all 128
15+committed fixtures. The charter's stop condition did not fire.
16+
17+---
18+
19+## 0. Two corrections to the charter before the numbers
20+
21+* **`EC_AV1_PERF*` does not exist** in this repository — not in `crates/ec-av1`,
22+ not anywhere. The real decode-timing instruments are `EC_AV1_TIMELINE`
23+ (`src/timeline.rs:1-13`, dumped by `stream.rs:1369`, read by
24+ `scripts/av1-timeline-report.py`) and `EC_AV1_WAVE_STATS`. Neither buckets
25+ decode into stages — they bucket a *frame's phases*, and the report script's
26+ own doc says the per-phase sums exceed `wall` by construction, so they must
27+ not be summed. Neither attributes a cost to an allocation, so this lane added
28+ `examples/alloc_timing.rs`, which times the `decode_stream_with` call and
29+ reads `minflt`/`majflt` from `/proc/self/stat` around it. It prints one
30+ machine-readable line per process, which is what makes the interleaved
31+ round-robin below possible.
32+
33+The closures are an **env arm inside the crate** (`EC_AV1_PLANE_ALLOC`), not a
34+build flag, so all three share one binary, one allocator state and one machine.
35+Three separate builds cannot make this comparison fair — the recycled-arena
36+state, the page-cache state and the code layout all differ between them.
37+
38+---
39+
40+## 1. The table
41+
42+`cargo run -p ec-av1 --release --example alloc_timing -- <stream>`, arms
43+round-robined across processes so a drift hits every arm equally. Medians of 11
44+runs each (`n=11` below). Linux 7.2.7, 12 cores, glibc, default allocator,
45+single-threaded decode (`EC_AV1_THREADS=1` is the crate default).
46+
47+### 3840x2160 4:2:0, 96 frames
48+
49+| arm | median ms | min ms | mean ms | stdev ms | Δ% | minflt | output hash |
50+|---|---|---|---|---|---|---|---|
51+| `uninit` — status quo, `set_len` | 6937.728 | 6926.888 | 6939.318 | 7.731 | +0.00 | 280 846 | `c93abb392857618d` |
52+| `fill` — closure (a), explicit zero-fill | 7001.420 | 6992.227 | 7001.984 | 6.448 | **+0.92** | 215 336 | `c93abb392857618d` |
53+| `zeroed` — closure (b), `alloc_zeroed` | 6995.727 | 6978.615 | 6995.769 | 10.201 | **+0.84** | 278 704 | `c93abb392857618d` |
54+
55+### 3840x2160 4:2:2, 48 frames
56+
57+| arm | median ms | min ms | mean ms | stdev ms | Δ% | minflt | output hash |
58+|---|---|---|---|---|---|---|---|
59+| `uninit` | 4709.657 | 4703.387 | 4716.928 | 16.443 | +0.00 | 204 348 | `1c8526888dc2285d` |
60+| `fill` | 4750.184 | 4741.289 | 4751.697 | 7.264 | **+0.86** | 142 987 | `1c8526888dc2285d` |
61+| `zeroed` | 4747.944 | 4740.307 | 4749.023 | 7.219 | **+0.81** | 202 410 | `1c8526888dc2285d` |
62+
63+### 1920x1080 4:2:0, 96 frames
64+
65+| arm | median ms | min ms | mean ms | stdev ms | Δ% | minflt | output hash |
66+|---|---|---|---|---|---|---|---|
67+| `uninit` | 1768.411 | 1767.167 | 1775.918 | 9.964 | +0.00 | 60 023 | `ba5f2444c2b60885` |
68+| `fill` | 1735.265 | 1731.097 | 1742.735 | 21.224 | **−1.87** | 47 018 | `ba5f2444c2b60885` |
69+| `zeroed` | 1739.516 | 1733.861 | 1743.644 | 10.109 | **−1.63** | 59 170 | `ba5f2444c2b60885` |
70+
71+**Every hash is identical within a stream.** The closure chosen moves not one
72+output sample.
73+
74+### What the table says, and what it does not
75+
76+* **(b) is not the free lunch the arm's name advertises.** `zeroed` and `fill`
77+ land within 0.03 % of each other at every size. glibc hands a *recycled*
78+ arena block back from `calloc` with the same memset an explicit fill does; the
79+ "a page fault per page is the mechanism" story is wrong for a decoder that
80+ frees and re-allocates the same plane every frame.
81+* **The cost is one extra pass over a buffer the decode immediately overwrites**:
82+ +55 ms over 96 frames of 24.9 MB ≈ 42 GB/s of extra write bandwidth. The
83+ `minflt` column is *not* the story — `fill` faults the fewest pages at 4K
84+ (215 k vs 281 k) and is still the slowest arm, so page-fault count does not
85+ explain the delta.
86+* **The 1080p sign flip is real and reproducible** (two independent 11-run
87+ rounds: −1.59 %/−1.51 %, then −1.87 %/−1.63 %) and **is not explained here**.
88+ I am reporting the number, not a story for it. It is the one result a
89+ reviewer should re-run before trusting the 4K cost on their own hardware.
90+
91+---
92+
93+## 2. Reads-before-write census — regions × readers × reachability
94+
95+### 2.1 The two regions
96+
97+`fresh_plane(n, true_width, true_height, width, height)` hands back `n =
98+width * height` slots. `width` is `block_grid(mi_cols) * 32` and
99+`true_width = mi_cols * 4`, so the plane is a **block-aligned coding surface**
100+with up to 31 px of margin per axis. `true_width`/`true_height` is the decodable
101+extent. That splits the allocation into two disjoint regions that can hold a
102+sample no block wrote:
103+
104+| # | region | definition | can a reader reach it? |
105+|---|---|---|---|
106+| 1 | **padded tail** | everything outside `true_width × true_height`, out to `width × height` | in principle; **not in practice** — see §2.3 |
107+| 2 | **true extent** | inside `true_width × true_height` that the tile walk skipped | yes — this is where the withdrawn 224-sample demonstration sat |
108+
109+The old `census_unwritten` scanned region 2 only, under a doc comment asserting
110+*"past that is the padded coding surface's invented tail, which no decoder ever
111+reads"*. That assertion is exactly what an unread tail looks like, so it was
112+self-certifying. This lane scans both and counts them separately
113+(`PAD_UNWRITTEN_SAMPLES` / `take_pad_unwritten_samples`), and the comment now
114+says what was measured.
115+
116+### 2.2 The readers
117+
118+Line numbers are `main` = `2d8fa8a4`.
119+
120+| reader class | sites | reads the CURRENT frame? | clamps to true extent? | reachable on a current fixture? |
121+|---|---|---|---|---|
122+| intra prediction (neighbour edges, above/right/below/left) | `PlaneBuf::above/left/below/right_of`, `decode.rs:22059-22110` (`own_across = x + side.min(true_width - x)`, same down) | yes | **yes**, `saturating_sub(true_width/true_height)` plus `tile_x1/tile_y1` | no |
123+| intra TX bound checks | `decode.rs:12630, 13007, 15179, 19411, 23202, 23736, 24428, 25031, 39153, 39341` (`if px >= true_width { continue }`) | yes | yes | no |
124+| CfL (chroma-from-luma) | via the TX store paths above | yes (luma block region) | yes | no |
125+| IntraBC / intrabc copy | `decode.rs:14451-14527, 15009-15074` | yes (the block's own luma) | yes | no |
126+| intra-in-inter | `decode.rs:18266-18387, 23062-23095` | yes | yes | no |
127+| deblock | `apply_deblock`, `decode.rs:33367-33370` (`tw = true_width.min(cw)`) | yes | yes | no |
128+| CDEF | `cdef_gather(..., true_width, true_height, ...)`, `decode.rs:34397-34484` | yes | yes | no |
129+| loop restoration | `restoration.rs:1053+`, driven with `true_width`/`true_height` (`decode.rs:35315-35319`) | yes | yes | no |
130+| superres upscale | `superres.rs:100-240`, over the mi-aligned margin, cropped to `true_width` | yes | yes | no |
131+| **inter prediction / MC / warp / OBMC / compound** | `decode.rs:40384-40386, 40399-40406, 42757-42761, 44560-44581` (all pass `true_width`/`true_height` of the REFERENCE plane) | **no — a different frame's buffer** | n/a | n/a |
132+| reference-frame materialisation | the crop at `decode.rs:38480-38548` | copies the true extent only | yes | n/a |
133+| `pix_write`'s `prev` argument — **the one unconditional read-before-write in the shipped source** | `decode.rs:22073` (fn), called at `22294`, `22450`, `39014`, `39029`, passing `*o` / the slot's own value | yes — reads the destination sample *before* overwriting it | no | **fires on every store, on every fixture — but is not observable.** See §2.5 |
134+
135+The load-bearing structural fact: **every current-frame reader clamps to
136+`true_width`/`true_height`**, which is why region 1 never fires. The 224-sample
137+defect of `lanes/unwritten-dep.report.md` was in region 2 and needed no
138+clamp-bypass — it was the tile walk skipping samples, not a reader reaching
139+past the edge.
140+
141+### 2.3 Region census — measurement
142+
143+`EC_AV1_PLANE_SENTINEL=1 decode_probe <fixture>`, summed over all 128
144+committed fixtures, both regions, at the **pre-deblock** point
145+(`census_unwritten`, called at `decode.rs:38139` in
146+`decode_key_frame_tile_with_cdfs` and `56507` in the inter path — after
147+`flush_recon`, before `apply_deblock`):
148+
149+```
150+TOTAL extent_scanned=1,466,581,280 EXT_HOLE=0
151+ pad_scanned = 22,787,296 PAD_HOLE=4,676,128
152+fixtures with a nonzero hole in either region: 38
153+```
154+
155+* **Region 2 (true extent): 0 unwritten of 1.47 G scanned.** The withdrawn
156+ defect is gone from the current corpus, and the one fixture that
157+ demonstrated it is refused:
158+ `440_request_is_422` → `REFUSED: unsupported: AV1 tile (a block size 4x8,
159+ 8x16 or 16x4 (or 8x4 at 4:4:0) has no chroma plane block at this frame's
160+ subsampling mode …)` (`decode.rs:21643`).
161+* **Region 1 (padded tail): 4.68 M unwritten of 22.8 M scanned (20.5 %)** on
162+ 38 fixtures — unwritten *by construction*, since no block lands there. This
163+ is the region whose "nobody reads it" claim had never been measured.
164+* On the generated 3840x2160 4:2:2 stream the tail is non-zero on the first
165+ two frames and zero after (`pad_unwritten=4096/1024/1024` on frame 0,
166+ `2048/512/512` on frame 1) out of 61 440/15 360/15 360 scanned per frame —
167+ so a 4:2:2 frame does leave real unwritten tail behind at scale.
168+
169+### 2.4 Read census — measurement, and its non-vacuity
170+
171+The region census counts **unwritten** samples. It says nothing about reads,
172+which is the whole question. Two independent read instruments:
173+
174+**(a) valgrind memcheck, differential.** Every fixture decoded twice under
175+memcheck — once on `uninit` (the plane buffer is uninitialised, so any read of
176+it is a memcheck error) and once on `zeroed`. **128 fixtures × 2 arms = 256
177+runs executed, zero uninitialised-value errors, identical error-signature sets
178+on all 128.** 126 of the fixtures decode; two refuse. The sweep was run in two
179+pieces — 127 fixtures on the pre-rebase tree, then the fixture that arrived
180+with `d16af6c3` (`422_header_edge16_walk.obu`, 128 bytes) run separately under
181+both arms on `f01e9738`:
182+
183+```
184+422_header_edge16_walk.obu uninit 0 zeroed 0 CLEAN (identical)
185+raw, uninit arm: ERROR SUMMARY: 0 errors from 0 contexts
186+raw, zeroed arm: ERROR SUMMARY: 0 errors from 0 contexts
187+```
188+
189+Those two runs are not vacuous, and that needed checking rather than assuming:
190+the fixture refuses, so "0 errors" could have meant "the decoder allocated
191+nothing". It did not. `EC_AV1_SUBSIZE_GUARD_TRACE=1` on it reports six
192+`note_subsize_guard` sites reached, with the refusal FIRING at
193+`decode.rs:37522` (`bsize=16x16 part=2 codable=false`) — that site is inside
194+the tile walk, which is downstream of the three `fresh_plane` calls at
195+`decode.rs:36007`/`36028`/`36040`. So the plane was allocated, partially
196+written, and abandoned mid-walk, and memcheck saw an `uninit` buffer with a
197+real partial write in it and still found nothing.
198+>
199+> One consequence for §2.3: this fixture prints **no** `SENTINEL_CENSUS` line,
200+> because the refusal short-circuits through `?` before the census at the tail
201+> of `decode_key_frame_tile_with_cdfs`. Its contribution is therefore 0 scanned
202+> and 0 holes, which is why the §2.3 totals are identical for 127 and for 128
203+> files — and also why the census's `scanned` pairing cannot be dropped: a
204+> fixture that contributes nothing looks exactly like one never looked at.
205+>
206+
207+> **Non-vacuity, by mutation.** A temporary env-gated read of the plane's last
208+> slot (`v[n-1]`, added to `fresh_plane`, reverted before commit) makes the same
209+> binary on the same fixture report **12 errors from 4 contexts**:
210+> `Conditional jump or move depends on uninitialised value(s)` ×3,
211+> `Use of uninitialised value of size 8`. The instrument sees plane-sourced
212+> uninitialised reads when they exist.
213+>
214+> That run also shows the ambient-content hazard concretely: the luma plane
215+> (`n=30720`) errored and the two chroma planes (`n=7680`) happened to be handed
216+> already-zero memory and did not. A same-machine run is not proof; a
217+> *different* poison is.
218+
219+**(b) Differential poisoning.** Decode each fixture under two DIFFERENT
220+impossible values for the plane buffer and compare the output hash. A read
221+whose value reaches the picture changes the hash when the poison changes.
222+
223+| corpus | arms | result |
224+|---|---|---|
225+| 126 committed fixtures | `0xDEAD` / `0xBEEF` / `alloc_zeroed` | **126/126 byte-identical** |
226+| `440_request_is_422` | — | REFUSED (§2.3) |
227+| 4K 4:2:0, 4K 4:2:2, 1080p 4:2:0 | `0xDEAD`, `0xBEEF`, `0x0080`, `0x0001`, `0x0FFF`, `0x1000`, `0x2000`, `zeroed` | **8/8 identical per stream** |
228+
229+The last row needs a note on method. `plane_poison()` *refuses* a poison at or
230+below `MAX_LEGAL_SAMPLE` (4095), because a legal poison makes the region census
231+vacuous. To run the experiment anyway I temporarily removed that guard: the
232+**legal-range** poisons (`0x0001`, `0x0080`, `0x0FFF`, `0x1000`, `0x2000`) then
233+produce the same hash as the impossible ones. That matters because an
234+out-of-range poison can be hidden by a clamp — every legal sample is
235+`(1 << bit_depth) - 1` at most — while a legal-range poison is not. **No read
236+survives clamping, masking or branch selection.** The guard is restored.
237+
238+### 2.5 Verdict of the census
239+
240+* **Region 1 (padded tail):** exists (4.68 M samples), is never written, and is
241+ **never read** — memcheck over 254 runs and 8 poisons agree.
242+* **Region 2 (true extent):** **0 holes** across 1.47 G samples on every current
243+ fixture; the historical 224-sample case is behind a refusal.
244+* **A third category, which neither instrument can see: `pix_write`.** Its
245+ `prev` argument is the destination sample's own value, read at four call
246+ sites on **every** reconstruction store. When a block is the first to write
247+ a sample, that read returns the buffer's initial content. It is still a read
248+ of a `u16` that (on the `uninit` arm) was never written.
249+ * Neither instrument reports it, and that is not a gap in them: `prev` is
250+ only consumed inside `if *PIXPROBE_ON`, so the value never reaches a
251+ branch, an address computation or a syscall — memcheck has nothing to
252+ complain about, and no hash can move. Verified directly: a **debug** build
253+ (no optimisation to dead-code-eliminate the load) under memcheck on the
254+ `uninit` arm still reports `0 errors from 0 contexts`.
255+ * So the honest reading is: the decoder provably does not *depend* on the
256+ buffer's initial content, and `pix_write` is the one place it reads it
257+ anyway. The shipped `Zeroed` closure deletes that read along with the rest,
258+ which is a second, independent reason to take it.
259+* **A constraint on the census arms that is not obvious from their names.**
260+ `fresh_plane` returns `vec![plane_poison(); n]` BEFORE it matches on
261+ `plane_alloc()`, so `PadZero` and `ExtZero` never run while
262+ `EC_AV1_PLANE_SENTINEL` is set — and that flag is exactly what both census
263+ functions require (each returns early when it is off). Those two arms are
264+ therefore meaningful only under **memcheck with the sentinel OFF**, where
265+ the zeroed/uninitialised split between the regions is what memcheck keys on;
266+ under the sentinel they are inert. The order is deliberate and stays:
267+ moving the sentinel check below the match would let the region census scan a
268+ buffer the sentinel never poisoned, which it cannot recover from.
269+* **Neither is reachable today.** That is a statement about today's corpus, not
270+ a proof: a hostile file chooses its own subsize values, and the refusal that
271+ closes region 2 lives in the tile walk, not at the allocation. Hence the
272+ decision below rather than "the premise holds".
273+
274+---
275+
276+## 3. The decision, and the evidence behind it
277+
278+The charter's rule: *if (b) is within noise of (a) and close to the baseline,
279+implement (b) and prove determinism; if (b) is expensive and (a) is too, leave
280+the allocation alone.*
281+
282+* (b) **is** within noise of (a) — 0.03 % apart at all three sizes.
283+* (b) is **not** within noise of the baseline at 4K: +0.84 % with a 6–10 ms
284+ run-to-run spread, i.e. ~6σ. So the charter's first branch is not literally
285+ satisfied.
286+
287+I took (b) anyway, and the reason is the shape of the risk, not the size of the
288+number:
289+
290+1. **The alternative is not "keep the unsafe", it is "keep asserting a premise
291+ that has already been withdrawn once."** That premise is what
292+ `lanes/unwritten-dep.report.md` §12 filed, and it produced a caller-visible
293+ defect. A 0.84 % regression is visible in a benchmark; a withdrawn SAFETY
294+ premise is invisible until it ships.
295+2. **The sign of the cost is not stable across resolutions** (§1). A decision to
296+ pay it should be made knowing it is ~0.85 % at 4K and a ~1.6 % *win* at 1080p,
297+ not "always 0.8 %".
298+3. **The decision is reversible in one line.** `EC_AV1_PLANE_ALLOC=uninit`
299+ restores the status quo exactly, which is only true because the closure is an
300+ env arm and not a build flag.
301+
302+**Determinism proof** — new gate
303+`stream::tests::the_frame_does_not_depend_on_the_plane_buffers_initial_content`
304+(`stream.rs:48496`), which is exactly the charter's test:
305+
306+* four child processes, same ten fixtures each: `EC_AV1_PLANE_SENTINEL=0xDEAD`,
307+ `EC_AV1_PLANE_SENTINEL=0xBEEF`, sentinel-off + `EC_AV1_PLANE_ALLOC=uninit`,
308+ sentinel-off + `EC_AV1_PLANE_ALLOC=zeroed`;
309+* one FNV-1a hash per fixture over every shown frame's Y/U/V samples; all four
310+ arms must agree, per fixture;
311+* **non-vacuity first, synthetic**: two pictures differing in ONE sample must
312+ hash differently, or every equality below would be vacuous;
313+* every arm must report `frames > 0`, so a child that decoded nothing cannot
314+ agree with another child that decoded nothing.
315+
316+Fixture list deliberately small: a first revision used the 1920x792 film
317+fixtures and took **252 s** in a debug build, which is not a gate anyone keeps.
318+The committed ten (4:2:2 12-bit key / inter / sb128 intrabc / 17-frame odd
319+size, 4:4:4 lossless-sb64 / intrabc-rect4 / 128-root-mu, a padded odd size, an
320+off-tile chroma walk, superres+CDEF+LR) run the gate in **4.6 s**.
321+
322+---
323+
324+## 4. What changed
325+
326+* `decode.rs` — `PlaneAlloc` (five arms), `plane_alloc()`, `zero_pad()`,
327+ `zero_extent()`, `plane_poison()` (a settable poison so two-value
328+ differential poisoning is possible; a poison ≤ 4095 is still refused),
329+ `MAX_LEGAL_SAMPLE`, the pad-tail census (`PAD_UNWRITTEN_SAMPLES`,
330+ `PAD_CENSUS_SCANNED` + accessors), `census_unwritten` extended to scan both
331+ regions, `census_unwritten_final` switched to `plane_poison()`,
332+ `fresh_plane` taking the plane geometry, and **`PlaneAlloc::Zeroed` as the
333+ default**, which puts the `unsafe` behind an env arm.
334+* `stream.rs` — the determinism gate, its child, and the synthetic control.
335+* `examples/alloc_timing.rs` — the decode-wall-time / page-fault harness.
336+* Hunks are confined to the allocation path: `decode.rs` `fresh_plane` and the
337+ six `PlaneBuf { … }` construction sites (3 planes × the key and inter frame
338+ functions), plus the census block next to them. The peer lane
339+ `lane/av1subsizesweep` touches `decode.rs` at ~37063 and ~57061 (a
340+ superblock arm and its tests); there is no overlap.
341+
342+### SAFETY comment
343+
344+Rewritten to state **what can be read before it is written** — the three named
345+regions with their measured counts, the memcheck result, the refusal that
346+covers region 2, and the fact that the shipped arm never reaches the `unsafe`
347+at all. The withdrawn premise ("written sample-for-sample before anything reads
348+it") is gone; nothing in the comment asserts a premise a reviewer cannot
349+re-run.
350+
351+---
352+
353+## 5. Gates
354+
355+```
356+cargo check -p ec-av1 --tests ok
357+cargo test -p ec-av1 --lib -- 422 14 passed, 0 failed
358+cargo test -p ec-av1 --lib -- 444 50 passed, 0 failed
359+cargo test -p ec-av1 --lib -- sub8 13 passed, 0 failed
360+cargo test -p ec-av1 --lib -- lossless 34 passed, 0 failed
361+```
362+Re-run on the rebased tree (`f01e9738`), where main's own `1f4fcc84` guard for
363+the census child test is present:
364+```
365+cargo test -p ec-av1 --lib -- the_frame 13 passed, 0 failed
366+ (includes the_frame_does_not_depend_on_the_plane_buffers_initial_content)
367+cargo test -p ec-av1 --lib -- unwritten 2 passed, 0 failed
368+```
369+
370+**One gate was red on the lane's original base and is not this lane's.** On
371+`2d8fa8a4`, `cargo test -p ec-av1 --lib -- unwritten` reported
372+`1 passed, 1 FAILED`: `stream::tests::uwdep_child_unwritten_census` opens with
373+an unconditional `assert!(EC_AV1_PLANE_SENTINEL is set)` while sitting in the
374+crate's default test list, so any standalone run of that filter fails. Main
375+commit `1f4fcc84` ("the census child test skips in a normal suite run instead
376+of reddening it") adds the entry guard and it is **not** an ancestor of this
377+lane's original base. Nothing in this lane touches that test.
378+
379+---
380+
381+## 7. Rebase onto `f01e9738`
382+
383+Main moved while this lane was measuring. The branch is rebased onto `f01e9738`
384+and every headline number was re-taken there; the only conflict was in the
385+`census_unwritten` doc comment, resolved by keeping main's coverage paragraph
386+("this census runs at TWO of the four places `apply_deblock` is entered from")
387+*and* the two-region text, since both intents hold. Main's delta also adds
388+`chroma_plane_block_codable` to the 16-level edge arm — the guard that refuses
389+the 4:2:2 subsize by name.
390+
391+What changed on the rebased tree, re-measured:
392+* the 3840x2160 4:2:0 row (§1) — `zeroed` +0.84 %, `fill` +0.92 %; same hashes,
393+ same `minflt`, same conclusion;
394+* the poison sweep — 126 identical, **2** refused: `440_request_is_422` and,
395+ newly, `422_header_edge16_walk`, which main's new guard refuses;
396+* the region census — **byte-identical totals**: 1,466,581,280 extent samples,
397+ 0 holes; 22,787,296 pad samples, 4,676,128 holes; 38 fixtures.
398+
399+---
400+
401+## 8. Left undone, deliberately
402+
403+* **A pooled plane buffer** would make the closure ~free: take the three plane
404+ buffers from a thread-local pool, zero each ONCE at creation, return them on
405+ drop. Every sample is then initialised by construction and the per-frame
406+ memset disappears. It is not done here because it changes ownership
407+ (`PlaneBuf` holds `Cow<'a, [u16]>` and is handed to the wavefront workers),
408+ which is a different lane's worth of risk than this charter took on.
409+* **The 1080p sign flip is unexplained.** §1.
410+* **Reader attribution for a region-2 read** is only as deep as "a reader that
411+ does not clamp". With no current fixture reaching region 2 there is nothing to
412+ attribute; `EC_AV1_PLANE_ALLOC=padzero` / `extzero` are in the tree for
413+ whoever gets one — under memcheck with the sentinel OFF, per the ordering
414+ constraint in §2.5.
\ No newline at end of file