diff --git a/crates/ec-av1/examples/alloc_timing.rs b/crates/ec-av1/examples/alloc_timing.rs new file mode 100644 index 00000000..52d284f3 --- /dev/null +++ b/crates/ec-av1/examples/alloc_timing.rs @@ -0,0 +1,105 @@ +//! Decode wall time and minor page faults for one `EC_AV1_PLANE_ALLOC` arm. +//! +//! The three closures lane-uballoc had to choose between (see +//! `lanes/av1uballoc.report.md`) are selected by `EC_AV1_PLANE_ALLOC` inside +//! the crate, not by a build flag -- see [`ec_av1`]'s `fresh_plane`. Measuring +//! them that way means all arms share one binary, one allocator state and one +//! machine, which three separate builds cannot do. +//! +//! ```text +//! EC_AV1_PLANE_ALLOC=zeroed cargo run -p ec-av1 --release --example alloc_timing -- s.obu +//! ``` +//! +//! One process does ONE decode and prints ONE line, so the harness interleaves +//! arms across processes instead of trusting one process's warm-up history: +//! +//! ```text +//! ALLOC_TIMING arm=zeroed frames=24 wall_ms=1234.567 minflt=61234 majflt=0 hash=8f2a... +//! ``` +//! +//! `hash` is FNV-1a over every picture's Y/U/V samples in decode order. It is +//! the cross-arm determinism evidence: identical `hash` on every arm means the +//! closure chosen does not move a single output sample. +use std::time::Instant; + +const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325; +const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; + +/// Minor/major faults from `/proc/self/stat` fields 10 and 12, read around the +/// decode. A zeroed-from-the-kernel allocation and an explicit memset differ in +/// how many pages they actually touch, and that is the only cheap proxy for it +/// that does not need `perf`. +fn faults() -> (u64, u64) { + let stat = std::fs::read_to_string("/proc/self/stat").unwrap_or_default(); + // Everything before the last ')' is pid + comm, and comm may hold spaces. + let Some(rest) = stat.rsplit_once(')').map(|(_, r)| r) else { + return (0, 0); + }; + let f: Vec<&str> = rest.split_whitespace().collect(); + // `rest` starts at field 3 (state); minflt is field 10, majflt field 12. + ( + f.get(7).and_then(|v| v.parse().ok()).unwrap_or(0), + f.get(9).and_then(|v| v.parse().ok()).unwrap_or(0), + ) +} + +fn fnv1a(mut h: u64, bytes: &[u8]) -> u64 { + for &b in bytes { + h ^= u64::from(b); + h = h.wrapping_mul(FNV_PRIME); + } + h +} + +fn main() { + let mut args = std::env::args().skip(1); + let Some(path) = args.next() else { + eprintln!("usage: alloc_timing "); + std::process::exit(2); + }; + let arm = std::env::var("EC_AV1_PLANE_ALLOC").unwrap_or_else(|_| "".into()); + let data = match std::fs::read(&path) { + Ok(d) => d, + Err(e) => { + eprintln!("{path}: {e}"); + std::process::exit(2); + } + }; + + // One warm-up decode is NOT done here on purpose: the plane allocations are + // freed back to the allocator between frames anyway, and a discarded decode + // would only hand one arm a warmer arena than another. The harness runs + // each arm many times and reports the median. + let (minflt0, majflt0) = faults(); + let t0 = Instant::now(); + let mut frames = 0usize; + let mut hash = FNV_OFFSET; + let r = ec_av1::stream::decode_stream_with(&data, |pic, _idx, shown| { + if !shown { + return Ok(()); + } + frames += 1; + for p in [&pic.y, &pic.u, &pic.v] { + let mut buf = Vec::with_capacity(p.len() * 2); + for &s in p.iter() { + buf.extend_from_slice(&s.to_le_bytes()); + } + hash = fnv1a(hash, &buf); + } + Ok(()) + }); + let wall = t0.elapsed(); + let (minflt1, majflt1) = faults(); + match r { + Ok(()) => println!( + "ALLOC_TIMING arm={arm} frames={frames} wall_ms={:.3} minflt={} majflt={} hash={hash:016x}", + wall.as_secs_f64() * 1e3, + minflt1.saturating_sub(minflt0), + majflt1.saturating_sub(majflt0), + ), + Err(e) => { + eprintln!("{path}: decode refused: {e}"); + std::process::exit(3); + } + } +} diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 7704d7cb..baea51a8 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -21269,9 +21269,9 @@ fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) { /// Enabled by `EC_AV1_PLANE_SENTINEL` (there is no separate flag for it): print /// an EXACT census of the samples the tile walk never wrote -- with it, every -/// plane still holding [`PLANE_SENTINEL`] at this point is a sample no block -/// reconstructed, and no legal sample can equal `0xDEAD` (reconstruction clamps -/// to `(1 << bit_depth) - 1`). +/// plane still holding [`plane_poison`] at this point is a sample no block +/// reconstructed, and no legal sample can equal the poison (reconstruction +/// clamps to `(1 << bit_depth) - 1`, at most 4095). /// /// Coverage, stated as the code has it: this census runs at TWO of the four /// 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<'_>) { /// `lane/av1422seed` census used: it replaces a wrong-sample diff (which says /// where the OUTPUT is wrong, not whether the block was written at all) with a /// direct count plus the coordinates of every hole, grouped into per-row -/// spans so a large hole stays readable. Scans each plane over its own -/// `true_width` x `true_height` extent, PER AXIS (`true_width.min(p.width)`), so -/// a 4:2:2 frame's chroma is scanned at its own `fw/2 x fh` shape rather than -/// the 4:2:0 `div_ceil(2)` crop the older [`dump_stage16`] used: past that -/// extent is the padded coding surface's invented tail, which no decoder ever -/// reads. +/// spans so a large hole stays readable. +/// +/// It scans TWO regions per plane, because they answer different questions and +/// the earlier revision only scanned one of them: +/// * the TRUE EXTENT -- each plane over its own `true_width` x `true_height`, +/// PER AXIS (`true_width.min(p.width)`), so a 4:2:2 frame's chroma is scanned +/// at its own `fw/2 x fh` shape rather than the 4:2:0 `div_ceil(2)` crop the +/// older [`dump_stage16`] used. A hole here can reach the caller, and it is +/// the region lane/av1unwritten's 224 samples sat in. +/// * the PADDED TAIL -- everything outside that extent, out to the block-aligned +/// coding surface -- counted separately into [`PAD_UNWRITTEN_SAMPLES`]. The +/// earlier revision's doc comment asserted "past that is the padded coding +/// surface's invented tail, which no decoder ever reads". That assertion is +/// exactly what a tail that is never written and never read looks like, so it +/// was self-certifying; the tail is now scanned and counted like any other +/// region. `EC_AV1_PLANE_ALLOC=padzero`/`extzero` attribute a read to one +/// side or the other (see [`fresh_plane`]). fn census_unwritten(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) { if !plane_sentinel_on() { return; } + let poison = plane_poison(); let idx = PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst); for (name, p) in [("Y", y), ("U", u), ("V", v)] { - let (w, h) = (p.true_width.min(p.width), p.true_height); + let (w, h) = (p.true_width.min(p.width), p.true_height.min(p.height)); let mut total = 0usize; let mut spans: Vec<(usize, usize, usize)> = Vec::new(); for row in 0..h { let mut run: Option<(usize, usize)> = None; for col in 0..w { - if p.data[row * p.width + col] == PLANE_SENTINEL { + if p.data[row * p.width + col] == poison { total += 1; run = Some(match run { None => (col, col), Some((a, _)) => (a, col), }); } - if run.is_some() - && (col + 1 == w || p.data[row * p.width + col + 1] != PLANE_SENTINEL) - { + if run.is_some() && (col + 1 == w || p.data[row * p.width + col + 1] != poison) { let (a, b) = run.take().expect("a run is open here"); spans.push((row, a, b)); } } } + // The padded tail: columns `w..width` on rows `0..h`, plus every column + // on rows `h..height`. + let mut pad_total = 0usize; + let mut pad_scanned = 0usize; + for row in 0..p.height { + let (from, to) = if row < h { (w, p.width) } else { (0, p.width) }; + if from >= to { + continue; + } + pad_scanned += to - from; + pad_total += p.data[row * p.width + from..row * p.width + to] + .iter() + .filter(|&&s| s == poison) + .count(); + } UNWRITTEN_SAMPLES.fetch_add(total, std::sync::atomic::Ordering::SeqCst); CENSUS_SCANNED.fetch_add(w * h, std::sync::atomic::Ordering::SeqCst); + PAD_UNWRITTEN_SAMPLES.fetch_add(pad_total, std::sync::atomic::Ordering::SeqCst); + PAD_CENSUS_SCANNED.fetch_add(pad_scanned, std::sync::atomic::Ordering::SeqCst); + eprintln!( + "SENTINEL_CENSUS idx={idx} plane={name} surface={}x{} extent={w}x{h} \ + pad_scanned={pad_scanned} unwritten={total} pad_unwritten={pad_total}", + p.width, p.height, + ); if total == 0 { - eprintln!("SENTINEL_CENSUS idx={idx} plane={name} extent={w}x{h} unwritten=0"); continue; } let body: Vec = spans @@ -21332,8 +21363,10 @@ fn census_unwritten(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) { .map(|&(r, a, b)| format!("y{r} x{a}..={b}")) .collect(); eprintln!( - "SENTINEL_CENSUS idx={idx} plane={name} extent={w}x{h} unwritten={total} \ - spans={}: {}", + "SENTINEL_CENSUS idx={idx} plane={name} surface={}x{} extent={w}x{h} \ + unwritten={total} spans={}: {}", + p.width, + p.height, spans.len(), body.join(" ") ); @@ -21376,6 +21409,67 @@ pub fn take_census_scanned() -> usize { CENSUS_SCANNED.swap(0, std::sync::atomic::Ordering::SeqCst) } +/// Samples in the PADDED TAIL -- every sample of each plane outside its own +/// `true_width` x `true_height` extent -- that still holds [`plane_poison`] at +/// the pre-deblock point. [`census_unwritten`] scans that region too, because +/// "past the true extent nothing is ever read" was an ASSUMPTION the tail's +/// census was built to avoid checking; this counter is the measurement. +static PAD_UNWRITTEN_SAMPLES: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); + +/// Samples [`census_unwritten`] scanned in the padded tail, paired with +/// [`PAD_UNWRITTEN_SAMPLES`] for the same reason as [`CENSUS_SCANNED`]. +static PAD_CENSUS_SCANNED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Reads and clears [`PAD_UNWRITTEN_SAMPLES`]. +pub fn take_pad_unwritten_samples() -> usize { + PAD_UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst) +} + +/// Reads and clears [`PAD_CENSUS_SCANNED`]. +pub fn take_pad_census_scanned() -> usize { + PAD_CENSUS_SCANNED.swap(0, std::sync::atomic::Ordering::SeqCst) +} + +/// The largest value reconstruction can produce, `(1 << 12) - 1`: the highest +/// bit depth this decoder carries is 12. A sentinel at or below this could be +/// a LEGAL sample, which would make the whole census vacuous -- every +/// unwritten sample would look like an ordinary one. +const MAX_LEGAL_SAMPLE: u16 = 4095; + +/// The value [`fresh_plane`] fills with when the sentinel is on. +/// +/// [`PLANE_SENTINEL`] unless `EC_AV1_PLANE_SENTINEL` names a different one in +/// hex. Two different poisons are what turns the sentinel from "did a hole +/// survive into the output" into "did the output depend on the buffer's +/// initial content": a hole whose value reaches the picture changes the hash +/// when the poison changes, and one that does not cannot have influenced +/// anything. A value at or below [`MAX_LEGAL_SAMPLE`] is REFUSED (falls back +/// to [`PLANE_SENTINEL`]) because the census's soundness rests on the sentinel +/// being impossible. `EC_AV1_PLANE_SENTINEL=1` -- the spelling every existing +/// caller and gate uses, and `env_flag!`'s mere presence test -- keeps +/// [`PLANE_SENTINEL`]. +fn plane_poison() -> u16 { + static V: std::sync::LazyLock = std::sync::LazyLock::new(|| { + let Ok(raw) = crate::envflags::var("EC_AV1_PLANE_SENTINEL") else { + return PLANE_SENTINEL; + }; + let t = raw.trim(); + if t.is_empty() || t == "1" { + return PLANE_SENTINEL; + } + let hex = t + .strip_prefix("0x") + .or_else(|| t.strip_prefix("0X")) + .unwrap_or(t); + match u16::from_str_radix(hex, 16) { + Ok(v) if v > MAX_LEGAL_SAMPLE => v, + _ => PLANE_SENTINEL, + } + }); + *V +} + thread_local! { /// The [`set_plane_sentinel`] override; `EC_AV1_PLANE_SENTINEL` is the /// process-wide default. @@ -21761,92 +21855,210 @@ pub(crate) fn census_unwritten_final(y: &[u16], u: &[u16], v: &[u16]) { // each plane IS the true-extent count. let (scanned, total): (usize, usize) = [y, u, v] .iter() - .map(|p| (p.len(), p.iter().filter(|&&s| s == PLANE_SENTINEL).count())) + .map(|p| (p.len(), p.iter().filter(|&&s| s == plane_poison()).count())) .fold((0, 0), |(a, b), (c, d)| (a + c, b + d)); FINAL_CENSUS_SCANNED.fetch_add(scanned, std::sync::atomic::Ordering::SeqCst); FINAL_UNWRITTEN_SAMPLES.fetch_add(total, std::sync::atomic::Ordering::SeqCst); } -/// A frame plane's own backing store, `n` samples, UNINITIALISED. +/// Which closure [`fresh_plane`] applies to the allocation it hands back. /// -/// (lane-picalloc) Replaced a `vec![0u16; n]` that zeroed the whole plane -/// buffer: ~3% of the frame thread's cycles at 4K, serially at the frame's head, -/// to initialise 25 MB the next pass overwrites. +/// # WHY AN ENV ARM, and what each arm is /// -/// # THE `unsafe` BELOW IS NOT FULLY JUSTIFIED -- read this before approving it +/// The closure was a filed choice with no number behind it +/// (`lanes/unwritten-dep.report.md` §12). lane-av1uballoc measured all of them +/// on one stream in ONE binary, because three separate builds cannot make the +/// comparison fair -- the allocator's recycled-arena state, the page-cache +/// state and the code layout all differ between them. `EC_AV1_PLANE_ALLOC` +/// (process-constant, read once -- see [`crate::envflags`]) picks the arm. +/// Numbers: `lanes/av1uballoc.report.md`. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum PlaneAlloc { + /// `vec![0u16; n]`, i.e. `alloc_zeroed`/`calloc`. **The default and the + /// shipped closure.** It removes the `unsafe` below from every build that + /// does not ask for a census arm. + /// + /// What it costs, measured on one stream in one binary + /// (`lanes/av1uballoc.report.md` §1): **+0.84%** of decode wall time at + /// 3840x2160 4:2:0 (96 frames, 6937.728 -> 6995.727 ms, mean 6995.769, + /// run-to-run spread of the arm 10.2 ms, so ~6 sigma), **+0.81%** at + /// 3840x2160 4:2:2, and **-1.63%** at 1920x1080 4:2:0 -- it is FASTER + /// there, reproducibly. The sign flip is not explained here; the numbers + /// are. + /// + /// What it is NOT is the "zero pages are free" story the arm's name + /// invites: glibc hands a RECYCLED arena block back from `calloc` with the + /// same memset an explicit fill does, which is why this arm and + /// [`PlaneAlloc::Fill`] land within 0.03% of each other at every size. + Zeroed, + /// The status quo this lane replaced: `Vec::with_capacity` + `set_len`, + /// nothing written. Kept as an arm because every number here is a delta + /// against it, and because `EC_AV1_PLANE_ALLOC=uninit` reproduces it. + Uninit, + /// An explicit zero-fill (`Vec::with_capacity` then `resize(n, 0)`) -- the + /// closure that costs the same as [`PlaneAlloc::Zeroed`]. Kept so the + /// "zero pages are free" hypothesis stays falsifiable from the outside. + Fill, + /// Census-only: zero the PADDED tail (everything outside the plane's true + /// extent) and leave the true extent uninitialised. Pairs with + /// [`PlaneAlloc::ExtZero`] to attribute a read to one region. + PadZero, + /// Census-only: the mirror of [`PlaneAlloc::PadZero`] -- zero the true + /// extent, leave the padded tail uninitialised. + ExtZero, +} + +/// `EC_AV1_PLANE_ALLOC`'s arm. Defaults to [`PlaneAlloc::Zeroed`], the shipped +/// closure; an unrecognised value is the default too, so a typo degrades to the +/// safe arm rather than back to the `unsafe` one. +fn plane_alloc() -> PlaneAlloc { + static ARM: std::sync::LazyLock = std::sync::LazyLock::new(|| { + match crate::envflags::var("EC_AV1_PLANE_ALLOC") + .ok() + .as_deref() + .map(str::trim) + { + Some("uninit") => PlaneAlloc::Uninit, + Some("fill") => PlaneAlloc::Fill, + Some("padzero") => PlaneAlloc::PadZero, + Some("extzero") => PlaneAlloc::ExtZero, + _ => PlaneAlloc::Zeroed, + } + }); + *ARM +} + +/// Zeroes a plane's PADDED tail -- the SB-aligned coding surface's invented +/// rows and columns outside `true_width` x `true_height` -- and leaves the +/// true extent alone. [`PlaneAlloc::PadZero`] only. +fn zero_pad(v: &mut [u16], width: usize, height: usize, true_width: usize, true_height: usize) { + for row in 0..height { + let base = row * width; + let first = if row < true_height { true_width } else { 0 }; + v[base + first..base + width].fill(0); + } +} + +/// Zeroes a plane's TRUE EXTENT and leaves the padded tail alone -- the mirror +/// of [`zero_pad`]. [`PlaneAlloc::ExtZero`] only. +fn zero_extent(v: &mut [u16], width: usize, true_width: usize, true_height: usize) { + for row in 0..true_height { + let base = row * width; + v[base..base + true_width].fill(0); + } +} + +/// A frame plane's own backing store, `n` samples. +/// +/// `true_width`/`true_height` are the plane's decodable extent in its own +/// units; `width`/`height` the block-aligned coding surface it is carved from +/// (`cols32 * 32`, so at most 31 px of margin per axis). They are what +/// [`zero_pad`]/[`zero_extent`] need and what the pad census reports against; +/// [`PlaneAlloc::Zeroed`] reads none of them. +/// +/// # WHAT CAN BE READ BEFORE IT IS WRITTEN -- the region list +/// +/// The premise an earlier revision of this comment carried -- "the SB-padded +/// surface is written sample-for-sample by the tile walk's reconstruction +/// before anything reads it" -- is RETRACTED by measurement +/// (`lanes/unwritten-dep.report.md` §12). What replaces it is this list, which +/// is checkable where a premise is not. TWO disjoint regions of the allocation +/// can hold a sample no block wrote: +/// +/// 1. THE PADDED TAIL -- every sample outside `true_width` x `true_height`, out +/// to the block-aligned surface. Unwritten BY CONSTRUCTION: no block lands +/// on it. Measured over all 128 committed fixtures at the pre-deblock point: +/// **4,676,128 unwritten of 22,787,296 scanned tail samples (20.5%)**, on 38 +/// fixtures. It is also **not read**: valgrind memcheck over the same 128 +/// fixtures, on the `uninit` arm, reports ZERO uninitialised-value uses -- +/// and the instrument is shown live by a deliberate tail read, which +/// produces 12 errors from 4 contexts (`lanes/av1uballoc.report.md` §2.4). +/// 2. THE TRUE EXTENT -- a sample inside `true_width` x `true_height` that the +/// tile walk skipped. This is where the withdrawn 224-sample demonstration +/// sat (`440_request_is_422`, U/V rows 36..63, whole 4x4 groups). Measured +/// over the same 127 fixtures at the pre-deblock point: **0 unwritten of +/// 1,466,581,280 scanned**, and 0 again at the output point. The one fixture +/// that demonstrated it is REFUSED on main, so nothing current reaches +/// region 2. /// -/// This comment previously claimed the SB-padded surface "is written -/// sample-for-sample by the tile walk's reconstruction before anything reads -/// it", and cited the sentinel gate as proof. **That claim is RETRACTED by -/// measurement.** The basis for the retraction is THIS LANE's own, not -/// second-hand: on `440_request_is_422` an exact u16 whole-plane census at the -/// pre-deblock point finds **112 unwritten samples per chroma plane, 224 total** -/// (U and V, 28 whole 4x4 groups each, rows 36..63) in a frame that is SHOWN -/// (`Key show=true`) and whose samples the caller receives. Uninitialised memory -/// that reaches the caller was read, or the read that produced it was. That is -/// the UB, and it needs no hash-variation claim to stand. +/// 3. THE WHOLE BUFFER, read-then-overwritten -- `pix_write` (`decode.rs:22073`, +/// called at 22294/22450/39014/39029) takes the destination sample's own +/// value as its `prev` argument, so on the first write to each sample it +/// READS the initial content. Unlike regions 1 and 2 this one FIRES on +/// every fixture and every store -- and neither census can see it, because +/// `prev` is consumed only inside `if *PIXPROBE_ON`, so it never reaches a +/// branch or a syscall. Confirmed: a DEBUG build under memcheck on the +/// `uninit` arm still reports 0 errors. It does not affect output, and it is +/// deleted by the shipped closure along with everything else. /// -/// A hash-variation observation also exists -- five plain runs of the same -/// witness giving two different output hashes (`lanes/av1unwritten.report.md`), -/// which would point the same way -- but it is SECOND-HAND and was NOT -/// reproduced here: five plain runs on `8d6998d7` gave one hash -/// (`a761118c8dd5c8d0`, `lanes/unwritten-dep.report.md` §10). It is not relied -/// on, and the ambient content a run happens to receive is machine-dependent, -/// so a stable value on one host and a varying one on another would be the same -/// defect either way. The 224-sample census is the basis; the hashes are aside. +/// The readers that could reach regions 1 and 2 are enumerated in +/// `lanes/av1uballoc.report.md` §2; all of them clamp to `true_width`/ +/// `true_height`, which is why region 1 never fires, and none of them is +/// reached on a current fixture, which is why region 2 does not either. /// -/// WHAT IS ACTUALLY ESTABLISHED, and it is weaker: +/// Those three measurements say no read of the initial content is reachable +/// from today's corpus. That is a statement about today's corpus, NOT a +/// licence for the `unsafe` below: a hostile file picks its own subsize values, +/// and the refusal that closes region 2 lives in the tile walk, not here -- +/// which is why it is a refusal and not a proof. So the shipped closure is +/// [`PlaneAlloc::Zeroed`] (+0.84% at 4K and -1.63% at 1080p, measured -- +/// `lanes/av1uballoc.report.md` §1), and the `unsafe` is reachable ONLY from +/// the `uninit`, `padzero` and `extzero` arms. /// -/// * The sentinel gate ([`census_unwritten_final`], -/// `the_frame_the_caller_receives_carries_no_unwritten_plane_sample`) proves -/// that no sample the tile walk never wrote SURVIVES into the frame the caller -/// receives, on the corpus measured. **It counts at the OUTPUT POINT ONLY -- -/// one census, one scan.** The pre-deblock census ([`census_unwritten`], -/// `take_unwritten_samples` / `take_census_scanned`) is a DIFFERENT instrument -/// and has NO committed reader anywhere in the crate on `main`, so it backs -/// nothing here; an earlier revision of this comment credited the gate with -/// both, which would have told a reviewer the premise is covered by two scans -/// when only one exists. It is measured SURVIVAL, not reads. -/// * It does NOT prove "every sample is written before it is read". A sample read -/// as a prediction or filter neighbour and overwritten a moment later is -/// invisible to that count. **No such read has been observed, and no -/// instrument here measures for one.** -/// * On `main` = `e45cc748` the one path where a read was demonstrated is -/// UNREACHABLE: lane/av1unwritten refuses the subsize before descending. +/// ONE ORDERING CONSTRAINT on the two census arms, because it changes what +/// they can be used for: the sentinel check comes FIRST, so +/// [`PlaneAlloc::PadZero`] and [`PlaneAlloc::ExtZero`] never run while +/// `EC_AV1_PLANE_SENTINEL` is set -- and that flag is what both census +/// functions require (each returns early when it is off). The census arms are +/// therefore meaningful only under **memcheck with the sentinel OFF**, where +/// the zeroed/uninitialised split between the two regions is exactly what +/// memcheck keys on. The order stays as it is: moving the sentinel check below +/// the match would let the region census scan a buffer the sentinel never +/// poisoned, which is the one thing it cannot recover from. /// -/// Honest status: a read-before-write is DEMONSTRATED on a path that is now -/// refused, UNMEASURED on every other path, and this `unsafe` is sound only under -/// the unproven "written before read" premise. Filed as an open UB-class item -/// (`lanes/unwritten-dep.report.md` §12) with two closures: (a) zero the -/// allocation -- the safe default, at the ~3% this removed; or (b) an instrument -/// counting reads-before-write per sample, so the premise can be proved rather -/// than assumed. -fn fresh_plane(n: usize) -> Vec { +/// What IS sound and unchanged in that block: `u16` has no invalid bit patterns +/// and no `Drop`, and the capacity was just reserved, so the vector validly +/// owns `n` slots. Creating a `Vec` over uninitialised memory is not itself +/// UB -- a READ of a slot in region 1, region 2 or region 3 is. +fn fresh_plane( + n: usize, + true_width: usize, + true_height: usize, + width: usize, + height: usize, +) -> Vec { if plane_sentinel_on() { - return vec![PLANE_SENTINEL; n]; + return vec![plane_poison(); n]; + } + match plane_alloc() { + PlaneAlloc::Zeroed => return vec![0u16; n], + PlaneAlloc::Fill => { + let mut v: Vec = Vec::with_capacity(n); + v.resize(n, 0); + return v; + } + PlaneAlloc::Uninit | PlaneAlloc::PadZero | PlaneAlloc::ExtZero => {} } let mut v: Vec = Vec::with_capacity(n); - // SAFETY, PARTIAL -- the premise is NOT established; see the block comment - // above ("THE `unsafe` BELOW IS NOT FULLY JUSTIFIED"). - // - // What IS sound: `u16` has no invalid bit patterns and no `Drop`, and the - // capacity was just reserved, so the vector owns `n` slots that are valid to - // OWN. Creating a `Vec` over uninitialised memory is not itself UB. - // - // What is NOT sound, and is the reason this is a filed item rather than a - // settled one: reading an uninitialised `u16` IS UB, and the only thing that - // makes the reads sound is the premise that reconstruction writes every - // sample before any read. That premise was RETRACTED by measurement (224 - // unwritten samples, output varying with initial content) on a path that is - // now refused, and is UNMEASURED everywhere else. The sentinel gate measures - // survival at the output point, not reads. The pre-deblock census is a - // separate instrument with no committed reader on main, so it adds nothing - // here. So this `unsafe` is sound under a premise no current instrument - // proves. + // SAFETY: OWNING `n` uninitialised `u16` slots is sound (`u16` has no + // invalid bit patterns and no `Drop`, and the capacity was just reserved). + // A READ of a slot in region 1, region 2 or region 3 above would not be, + // which is why the shipped arm returns above and never reaches here: this + // block is reachable only under `EC_AV1_PLANE_ALLOC=uninit|padzero|extzero` + // -- exactly the arms `plane_alloc()` lets fall through. `fill` is NOT one + // of them (it returns early at the `resize`), and an UNRECOGNISED value is + // not either: `plane_alloc()` maps it to `Zeroed`, so a typo picks the safe + // arm. The two region counts and the memcheck sweep are what make those + // arms' results readable; re-run them before believing a new "0". #[allow(unsafe_code)] unsafe { v.set_len(n); } + match plane_alloc() { + PlaneAlloc::PadZero => zero_pad(&mut v, width, height, true_width, true_height), + PlaneAlloc::ExtZero => zero_extent(&mut v, width, true_width, true_height), + _ => {} + } v } @@ -35892,7 +36104,13 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK); let mut y = PlaneBuf { - data: std::borrow::Cow::Owned(fresh_plane(width * height)), + data: std::borrow::Cow::Owned(fresh_plane( + width * height, + true_width, + true_height, + width, + height, + )), width, height, true_width, @@ -35906,7 +36124,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( let (cw, ch) = (width >> ss_x(fctx), height >> ss_y(fctx)); let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx)); let mut u = PlaneBuf { - data: std::borrow::Cow::Owned(fresh_plane(cw * ch)), + data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)), width: cw, height: ch, true_width: ctw, @@ -35918,7 +36136,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( plane: 1, }; let mut v = PlaneBuf { - data: std::borrow::Cow::Owned(fresh_plane(cw * ch)), + data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)), width: cw, height: ch, true_width: ctw, @@ -53657,7 +53875,13 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK); let mut y = PlaneBuf { - data: std::borrow::Cow::Owned(fresh_plane(width * height)), + data: std::borrow::Cow::Owned(fresh_plane( + width * height, + true_width, + true_height, + width, + height, + )), width, height, true_width, @@ -53671,7 +53895,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( let (cw, ch) = (width >> ss_x(fctx), height >> ss_y(fctx)); let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx)); let mut u = PlaneBuf { - data: std::borrow::Cow::Owned(fresh_plane(cw * ch)), + data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)), width: cw, height: ch, true_width: ctw, @@ -53683,7 +53907,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( plane: 1, }; let mut v = PlaneBuf { - data: std::borrow::Cow::Owned(fresh_plane(cw * ch)), + data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)), width: cw, height: ch, true_width: ctw, diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index f5ebc70c..5f5eaf5b 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -48557,6 +48557,239 @@ exit 0 println!("UWDEP_CENSUS {n} frames={} scanned={scanned}", frames.len()); } + /// lane-av1uballoc: the frame the caller receives does not depend on what + /// the plane buffer held before the decode wrote it. + /// + /// Four runs of the same fixtures, each in its own process (the fill and + /// the alloc closure are both process-constant env reads -- see + /// [`crate::envflags`] -- and this crate forbids `set_var`), must agree on + /// one hash per fixture: + /// + /// * `EC_AV1_PLANE_SENTINEL=0xDEAD` and `=0xBEEF` -- two DIFFERENT + /// impossible values for the same buffer. This is the arm that can + /// actually FAIL: if any reader's value reaches the picture, changing the + /// poison changes the output. Equal hashes are a statement about a READ, + /// which is what the `unsafe` in [`decode::fresh_plane`] needs and what no + /// census in the crate measures. + /// * the sentinel OFF with `EC_AV1_PLANE_ALLOC=uninit` and `=zeroed` -- the + /// status quo and the shipped closure, which must agree with each other + /// and with the poisoned runs. This is the "same with the sentinel off" + /// arm; on its own it is weak (the allocator may hand out the same + /// ambient bytes twice) and is here as the join between the two worlds. + /// + /// NON-VACUITY, first and synthetic: [`allocdet_synthetic`] hashes two + /// pictures that differ in ONE sample and asserts the hashes DIFFER. A hash + /// that cannot see a one-sample difference would make every equality below + /// vacuous, and it is the failure mode a "0 errors" style result has. + /// Second: every arm must report `frames>0`, so a child that decoded + /// nothing cannot agree with another child that decoded nothing. + #[test] + fn the_frame_does_not_depend_on_the_plane_buffers_initial_content() { + const NAME: &str = "the_frame_does_not_depend_on_the_plane_buffers_initial_content"; + let _gate_lock = lock_gate_counters(); + // Kept SMALL on purpose: the whole gate is 4 child processes x this + // list, and the suite runs it in a DEBUG build. A first revision used + // the 1920x792 film fixtures here and took 252 s, which is not a gate + // anyone keeps. These ten cover every shape the region list names -- + // 4:2:2 (12-bit key, inter, sb128 intrabc, 17-frame odd-size), 4:4:4 + // (lossless sb64, intrabc rect4, 128-root mu), a padded odd size, an + // off-tile chroma walk, and superres+CDEF+LR -- for ~1.3 s per arm. + const FIXTURES: &[&str] = &[ + "s422_12bit_160x128", + "422_inter_160x128_3f", + "422_intrabc_sb128_strip", + "s422_352x242_10b", + "ll444_sb64_1to4_lossless", + "444_intrabc_rect4_witness", + "444_intra_in_inter_128root_mu_chroma", + "svt1-split-tx-pin", + "mix176_offtile_chroma_clip", + "superres_kf_cdef_lr_64x64", + ]; + + let (a, b) = allocdet_synthetic(); + assert_ne!( + a, b, + "{NAME}: the content hash returned the same value for two pictures differing in one \ + sample, so every equality below is vacuous -- this gate would pass on any decoder, \ + including one that returns garbage (class: hash-cannot-see-content)" + ); + + let arms: [(&str, Option<&str>, &str); 4] = [ + ("poison-dead", Some("0xDEAD"), "uninit"), + ("poison-beef", Some("0xBEEF"), "uninit"), + ("sentinel-off-uninit", None, "uninit"), + ("alloc-zeroed", None, "zeroed"), + ]; + let mut baseline: Option> = None; + for (label, poison, alloc) in arms { + let rows = allocdet_child(FIXTURES, poison, alloc); + assert_eq!( + rows.len(), + FIXTURES.len(), + "{NAME}: the {label} arm reported {} of {} fixtures -- a run that decoded \ + nothing can agree with another run that decoded nothing", + rows.len(), + FIXTURES.len() + ); + for (f, frames, _) in &rows { + assert!( + *frames > 0, + "{NAME}: the {label} arm decoded 0 frames of {f}; the hashes it compared are \ + over nothing" + ); + } + match &baseline { + None => baseline = Some(rows), + Some(first) => { + for (i, (f, frames, h)) in rows.iter().enumerate() { + let (bf, bframes, bh) = &first[i]; + assert_eq!( + bf, f, + "{NAME}: arm {label} reported fixture {f} where the \ + baseline reported {bf} -- the arms are not comparable" + ); + assert_eq!( + bframes, frames, + "{NAME}: {f} decoded {frames} frames under \ + {label} and {bframes} under the baseline arm" + ); + assert_eq!( + bh, h, + "{NAME}: {f} decoded to a DIFFERENT picture depending on what the \ + plane buffer held before the decode wrote it -- {label} gave {h:016x}, \ + the baseline arm gave {bh:016x}. A read of uninitialised memory \ + reaches the caller's frame (see the SAFETY comment on \ + decode::fresh_plane)." + ); + } + } + } + } + } + + /// Runs [`allocdet_child_decode`] in a fresh process and parses its + /// `ALLOCDET frames= hash=` lines into + /// `(fixture, frames, hash)` in FIXTURES order. + fn allocdet_child( + fixtures: &[&str], + poison: Option<&str>, + alloc: &str, + ) -> Vec<(String, usize, u64)> { + const NAME: &str = "the_frame_does_not_depend_on_the_plane_buffers_initial_content"; + let exe = std::env::current_exe().expect("test binary path"); + let mut cmd = std::process::Command::new(exe); + cmd.args([ + "--exact", + "stream::tests::allocdet_child_decode", + "--nocapture", + ]) + .env("ALLOCDET_FIXTURES", fixtures.join(",")) + .env("EC_AV1_PLANE_ALLOC", alloc) + .env_remove("ALLOCDET_SYNTHETIC"); + match poison { + Some(p) => cmd.env("EC_AV1_PLANE_SENTINEL", p), + None => cmd.env_remove("EC_AV1_PLANE_SENTINEL"), + }; + let out = cmd.output().expect("running the allocdet child"); + let text = format!( + "{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); + let mut rows = Vec::new(); + for f in fixtures { + let line = text + .lines() + .find(|l| l.starts_with(&format!("ALLOCDET {f} "))) + .unwrap_or_else(|| { + panic!( + "{NAME}: the child reported nothing for {f} (child said: {:?})", + text.trim() + ) + }); + let mut parts = line.split_whitespace(); + assert_eq!(parts.next(), Some("ALLOCDET")); + assert_eq!(parts.next(), Some(*f)); + let frames = parts + .find_map(|p| p.strip_prefix("frames=")) + .and_then(|v| v.parse().ok()) + .unwrap_or_else(|| panic!("{NAME}: no frame count in {line:?}")); + let hash = parts + .find_map(|p| p.strip_prefix("hash=")) + .and_then(|v| u64::from_str_radix(v, 16).ok()) + .unwrap_or_else(|| panic!("{NAME}: no hash in {line:?}")); + rows.push(((*f).to_string(), frames, hash)); + } + rows + } + + /// The child half of + /// [`the_frame_does_not_depend_on_the_plane_buffers_initial_content`]: + /// decodes every fixture named in `ALLOCDET_FIXTURES` and prints one + /// `ALLOCDET` line each. + /// + /// With `ALLOCDET_SYNTHETIC` set it instead prints the two hashes the + /// non-vacuity control compares -- two pictures differing in ONE sample -- + /// and decodes nothing. + #[test] + fn allocdet_child_decode() { + if std::env::var_os("ALLOCDET_SYNTHETIC").is_some() { + let (a, b) = allocdet_synthetic(); + println!("ALLOCDET_SYNTHETIC {a:016x} {b:016x}"); + return; + } + let list = std::env::var("ALLOCDET_FIXTURES").expect("ALLOCDET_FIXTURES"); + let mut hash = 0xcbf2_9ce4_8422_2325u64; + for fixture in list.split(',').filter(|s| !s.is_empty()) { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join(format!("fixtures/{fixture}.obu")); + let stream = + std::fs::read(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display())); + let mut frames = 0usize; + decode_stream_with(&stream, |pic, _idx, shown| { + if !shown { + return Ok(()); + } + frames += 1; + for p in [&pic.y, &pic.u, &pic.v] { + for &s in p.iter() { + for b in s.to_le_bytes() { + hash ^= u64::from(b); + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); + } + } + } + Ok(()) + }) + .unwrap_or_else(|e| panic!("{fixture} refused: {e}")); + println!("ALLOCDET {fixture} frames={frames} hash={hash:016x}"); + } + } + + /// Two pictures identical except for ONE sample of ONE plane, hashed by the + /// same FNV-1a the child uses. Equal values here would make the gate's + /// equalities vacuous, so it is asserted to differ. + fn allocdet_synthetic() -> (u64, u64) { + const P: u64 = 0x0000_0100_0000_01b3; + let hash = |mut h: u64, samples: &[u16]| { + for &s in samples { + for b in s.to_le_bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(P); + } + } + h + }; + let a = vec![128u16; 4096]; + let mut b = a.clone(); + b[2048] = 129; + ( + hash(0xcbf2_9ce4_8422_2325, &a), + hash(0xcbf2_9ce4_8422_2325, &b), + ) + } + /// lane-t900 r6: the 128-superblock INTER witness. /// `crates/ec-av1/fixtures/reelc_sb128_inter_witness.obu`, 177773 bytes, /// sha256 `09d995946d27695ef4b7b1a24a4d7ad85f8e2c8176d58ee54e825efc061f9cbc`: diff --git a/lanes/av1uballoc.report.md b/lanes/av1uballoc.report.md new file mode 100644 index 00000000..1bf2c696 --- /dev/null +++ b/lanes/av1uballoc.report.md @@ -0,0 +1,414 @@ +# lane/av1uballoc — the plane allocation closure, decided with a number + +Started from base `2d8fa8a4`; **rebased onto `f01e9738` and re-measured there** +(§7). Target: `crates/ec-av1/src/decode.rs`'s `fresh_plane` and the +`unsafe { v.set_len(n) }` behind it. + +**Decision: ship closure (b), `vec![0u16; n]` (`alloc_zeroed`/`calloc`).** It +costs **+0.84%** of decode wall time at 3840x2160 4:2:0 and **+0.81%** at +3840x2160 4:2:2 (both ~6σ against a 6–10 ms run-to-run spread), and **−1.63%** +at 1920x1080 — it is *faster* there, reproducibly. It removes the `unsafe` +from every build that is not explicitly asking for a census arm. + +**No fixture on current main reaches an uninitialised read.** The reads-before- +write census below found zero, by two independent instruments, over all 128 +committed fixtures. The charter's stop condition did not fire. + +--- + +## 0. Two corrections to the charter before the numbers + +* **`EC_AV1_PERF*` does not exist** in this repository — not in `crates/ec-av1`, + not anywhere. The real decode-timing instruments are `EC_AV1_TIMELINE` + (`src/timeline.rs:1-13`, dumped by `stream.rs:1369`, read by + `scripts/av1-timeline-report.py`) and `EC_AV1_WAVE_STATS`. Neither buckets + decode into stages — they bucket a *frame's phases*, and the report script's + own doc says the per-phase sums exceed `wall` by construction, so they must + not be summed. Neither attributes a cost to an allocation, so this lane added + `examples/alloc_timing.rs`, which times the `decode_stream_with` call and + reads `minflt`/`majflt` from `/proc/self/stat` around it. It prints one + machine-readable line per process, which is what makes the interleaved + round-robin below possible. + +The closures are an **env arm inside the crate** (`EC_AV1_PLANE_ALLOC`), not a +build flag, so all three share one binary, one allocator state and one machine. +Three separate builds cannot make this comparison fair — the recycled-arena +state, the page-cache state and the code layout all differ between them. + +--- + +## 1. The table + +`cargo run -p ec-av1 --release --example alloc_timing -- `, arms +round-robined across processes so a drift hits every arm equally. Medians of 11 +runs each (`n=11` below). Linux 7.2.7, 12 cores, glibc, default allocator, +single-threaded decode (`EC_AV1_THREADS=1` is the crate default). + +### 3840x2160 4:2:0, 96 frames + +| arm | median ms | min ms | mean ms | stdev ms | Δ% | minflt | output hash | +|---|---|---|---|---|---|---|---| +| `uninit` — status quo, `set_len` | 6937.728 | 6926.888 | 6939.318 | 7.731 | +0.00 | 280 846 | `c93abb392857618d` | +| `fill` — closure (a), explicit zero-fill | 7001.420 | 6992.227 | 7001.984 | 6.448 | **+0.92** | 215 336 | `c93abb392857618d` | +| `zeroed` — closure (b), `alloc_zeroed` | 6995.727 | 6978.615 | 6995.769 | 10.201 | **+0.84** | 278 704 | `c93abb392857618d` | + +### 3840x2160 4:2:2, 48 frames + +| arm | median ms | min ms | mean ms | stdev ms | Δ% | minflt | output hash | +|---|---|---|---|---|---|---|---| +| `uninit` | 4709.657 | 4703.387 | 4716.928 | 16.443 | +0.00 | 204 348 | `1c8526888dc2285d` | +| `fill` | 4750.184 | 4741.289 | 4751.697 | 7.264 | **+0.86** | 142 987 | `1c8526888dc2285d` | +| `zeroed` | 4747.944 | 4740.307 | 4749.023 | 7.219 | **+0.81** | 202 410 | `1c8526888dc2285d` | + +### 1920x1080 4:2:0, 96 frames + +| arm | median ms | min ms | mean ms | stdev ms | Δ% | minflt | output hash | +|---|---|---|---|---|---|---|---| +| `uninit` | 1768.411 | 1767.167 | 1775.918 | 9.964 | +0.00 | 60 023 | `ba5f2444c2b60885` | +| `fill` | 1735.265 | 1731.097 | 1742.735 | 21.224 | **−1.87** | 47 018 | `ba5f2444c2b60885` | +| `zeroed` | 1739.516 | 1733.861 | 1743.644 | 10.109 | **−1.63** | 59 170 | `ba5f2444c2b60885` | + +**Every hash is identical within a stream.** The closure chosen moves not one +output sample. + +### What the table says, and what it does not + +* **(b) is not the free lunch the arm's name advertises.** `zeroed` and `fill` + land within 0.03 % of each other at every size. glibc hands a *recycled* + arena block back from `calloc` with the same memset an explicit fill does; the + "a page fault per page is the mechanism" story is wrong for a decoder that + frees and re-allocates the same plane every frame. +* **The cost is one extra pass over a buffer the decode immediately overwrites**: + +55 ms over 96 frames of 24.9 MB ≈ 42 GB/s of extra write bandwidth. The + `minflt` column is *not* the story — `fill` faults the fewest pages at 4K + (215 k vs 281 k) and is still the slowest arm, so page-fault count does not + explain the delta. +* **The 1080p sign flip is real and reproducible** (two independent 11-run + rounds: −1.59 %/−1.51 %, then −1.87 %/−1.63 %) and **is not explained here**. + I am reporting the number, not a story for it. It is the one result a + reviewer should re-run before trusting the 4K cost on their own hardware. + +--- + +## 2. Reads-before-write census — regions × readers × reachability + +### 2.1 The two regions + +`fresh_plane(n, true_width, true_height, width, height)` hands back `n = +width * height` slots. `width` is `block_grid(mi_cols) * 32` and +`true_width = mi_cols * 4`, so the plane is a **block-aligned coding surface** +with up to 31 px of margin per axis. `true_width`/`true_height` is the decodable +extent. That splits the allocation into two disjoint regions that can hold a +sample no block wrote: + +| # | region | definition | can a reader reach it? | +|---|---|---|---| +| 1 | **padded tail** | everything outside `true_width × true_height`, out to `width × height` | in principle; **not in practice** — see §2.3 | +| 2 | **true extent** | inside `true_width × true_height` that the tile walk skipped | yes — this is where the withdrawn 224-sample demonstration sat | + +The old `census_unwritten` scanned region 2 only, under a doc comment asserting +*"past that is the padded coding surface's invented tail, which no decoder ever +reads"*. That assertion is exactly what an unread tail looks like, so it was +self-certifying. This lane scans both and counts them separately +(`PAD_UNWRITTEN_SAMPLES` / `take_pad_unwritten_samples`), and the comment now +says what was measured. + +### 2.2 The readers + +Line numbers are `main` = `2d8fa8a4`. + +| reader class | sites | reads the CURRENT frame? | clamps to true extent? | reachable on a current fixture? | +|---|---|---|---|---| +| 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 | +| intra TX bound checks | `decode.rs:12630, 13007, 15179, 19411, 23202, 23736, 24428, 25031, 39153, 39341` (`if px >= true_width { continue }`) | yes | yes | no | +| CfL (chroma-from-luma) | via the TX store paths above | yes (luma block region) | yes | no | +| IntraBC / intrabc copy | `decode.rs:14451-14527, 15009-15074` | yes (the block's own luma) | yes | no | +| intra-in-inter | `decode.rs:18266-18387, 23062-23095` | yes | yes | no | +| deblock | `apply_deblock`, `decode.rs:33367-33370` (`tw = true_width.min(cw)`) | yes | yes | no | +| CDEF | `cdef_gather(..., true_width, true_height, ...)`, `decode.rs:34397-34484` | yes | yes | no | +| loop restoration | `restoration.rs:1053+`, driven with `true_width`/`true_height` (`decode.rs:35315-35319`) | yes | yes | no | +| superres upscale | `superres.rs:100-240`, over the mi-aligned margin, cropped to `true_width` | yes | yes | no | +| **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 | +| reference-frame materialisation | the crop at `decode.rs:38480-38548` | copies the true extent only | yes | n/a | +| `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 | + +The load-bearing structural fact: **every current-frame reader clamps to +`true_width`/`true_height`**, which is why region 1 never fires. The 224-sample +defect of `lanes/unwritten-dep.report.md` was in region 2 and needed no +clamp-bypass — it was the tile walk skipping samples, not a reader reaching +past the edge. + +### 2.3 Region census — measurement + +`EC_AV1_PLANE_SENTINEL=1 decode_probe `, summed over all 128 +committed fixtures, both regions, at the **pre-deblock** point +(`census_unwritten`, called at `decode.rs:38139` in +`decode_key_frame_tile_with_cdfs` and `56507` in the inter path — after +`flush_recon`, before `apply_deblock`): + +``` +TOTAL extent_scanned=1,466,581,280 EXT_HOLE=0 + pad_scanned = 22,787,296 PAD_HOLE=4,676,128 +fixtures with a nonzero hole in either region: 38 +``` + +* **Region 2 (true extent): 0 unwritten of 1.47 G scanned.** The withdrawn + defect is gone from the current corpus, and the one fixture that + demonstrated it is refused: + `440_request_is_422` → `REFUSED: unsupported: AV1 tile (a block size 4x8, + 8x16 or 16x4 (or 8x4 at 4:4:0) has no chroma plane block at this frame's + subsampling mode …)` (`decode.rs:21643`). +* **Region 1 (padded tail): 4.68 M unwritten of 22.8 M scanned (20.5 %)** on + 38 fixtures — unwritten *by construction*, since no block lands there. This + is the region whose "nobody reads it" claim had never been measured. +* On the generated 3840x2160 4:2:2 stream the tail is non-zero on the first + two frames and zero after (`pad_unwritten=4096/1024/1024` on frame 0, + `2048/512/512` on frame 1) out of 61 440/15 360/15 360 scanned per frame — + so a 4:2:2 frame does leave real unwritten tail behind at scale. + +### 2.4 Read census — measurement, and its non-vacuity + +The region census counts **unwritten** samples. It says nothing about reads, +which is the whole question. Two independent read instruments: + +**(a) valgrind memcheck, differential.** Every fixture decoded twice under +memcheck — once on `uninit` (the plane buffer is uninitialised, so any read of +it is a memcheck error) and once on `zeroed`. **128 fixtures × 2 arms = 256 +runs executed, zero uninitialised-value errors, identical error-signature sets +on all 128.** 126 of the fixtures decode; two refuse. The sweep was run in two +pieces — 127 fixtures on the pre-rebase tree, then the fixture that arrived +with `d16af6c3` (`422_header_edge16_walk.obu`, 128 bytes) run separately under +both arms on `f01e9738`: + +``` +422_header_edge16_walk.obu uninit 0 zeroed 0 CLEAN (identical) +raw, uninit arm: ERROR SUMMARY: 0 errors from 0 contexts +raw, zeroed arm: ERROR SUMMARY: 0 errors from 0 contexts +``` + +Those two runs are not vacuous, and that needed checking rather than assuming: +the fixture refuses, so "0 errors" could have meant "the decoder allocated +nothing". It did not. `EC_AV1_SUBSIZE_GUARD_TRACE=1` on it reports six +`note_subsize_guard` sites reached, with the refusal FIRING at +`decode.rs:37522` (`bsize=16x16 part=2 codable=false`) — that site is inside +the tile walk, which is downstream of the three `fresh_plane` calls at +`decode.rs:36007`/`36028`/`36040`. So the plane was allocated, partially +written, and abandoned mid-walk, and memcheck saw an `uninit` buffer with a +real partial write in it and still found nothing. +> +> One consequence for §2.3: this fixture prints **no** `SENTINEL_CENSUS` line, +> because the refusal short-circuits through `?` before the census at the tail +> of `decode_key_frame_tile_with_cdfs`. Its contribution is therefore 0 scanned +> and 0 holes, which is why the §2.3 totals are identical for 127 and for 128 +> files — and also why the census's `scanned` pairing cannot be dropped: a +> fixture that contributes nothing looks exactly like one never looked at. +> + +> **Non-vacuity, by mutation.** A temporary env-gated read of the plane's last +> slot (`v[n-1]`, added to `fresh_plane`, reverted before commit) makes the same +> binary on the same fixture report **12 errors from 4 contexts**: +> `Conditional jump or move depends on uninitialised value(s)` ×3, +> `Use of uninitialised value of size 8`. The instrument sees plane-sourced +> uninitialised reads when they exist. +> +> That run also shows the ambient-content hazard concretely: the luma plane +> (`n=30720`) errored and the two chroma planes (`n=7680`) happened to be handed +> already-zero memory and did not. A same-machine run is not proof; a +> *different* poison is. + +**(b) Differential poisoning.** Decode each fixture under two DIFFERENT +impossible values for the plane buffer and compare the output hash. A read +whose value reaches the picture changes the hash when the poison changes. + +| corpus | arms | result | +|---|---|---| +| 126 committed fixtures | `0xDEAD` / `0xBEEF` / `alloc_zeroed` | **126/126 byte-identical** | +| `440_request_is_422` | — | REFUSED (§2.3) | +| 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** | + +The last row needs a note on method. `plane_poison()` *refuses* a poison at or +below `MAX_LEGAL_SAMPLE` (4095), because a legal poison makes the region census +vacuous. To run the experiment anyway I temporarily removed that guard: the +**legal-range** poisons (`0x0001`, `0x0080`, `0x0FFF`, `0x1000`, `0x2000`) then +produce the same hash as the impossible ones. That matters because an +out-of-range poison can be hidden by a clamp — every legal sample is +`(1 << bit_depth) - 1` at most — while a legal-range poison is not. **No read +survives clamping, masking or branch selection.** The guard is restored. + +### 2.5 Verdict of the census + +* **Region 1 (padded tail):** exists (4.68 M samples), is never written, and is + **never read** — memcheck over 254 runs and 8 poisons agree. +* **Region 2 (true extent):** **0 holes** across 1.47 G samples on every current + fixture; the historical 224-sample case is behind a refusal. +* **A third category, which neither instrument can see: `pix_write`.** Its + `prev` argument is the destination sample's own value, read at four call + sites on **every** reconstruction store. When a block is the first to write + a sample, that read returns the buffer's initial content. It is still a read + of a `u16` that (on the `uninit` arm) was never written. + * Neither instrument reports it, and that is not a gap in them: `prev` is + only consumed inside `if *PIXPROBE_ON`, so the value never reaches a + branch, an address computation or a syscall — memcheck has nothing to + complain about, and no hash can move. Verified directly: a **debug** build + (no optimisation to dead-code-eliminate the load) under memcheck on the + `uninit` arm still reports `0 errors from 0 contexts`. + * So the honest reading is: the decoder provably does not *depend* on the + buffer's initial content, and `pix_write` is the one place it reads it + anyway. The shipped `Zeroed` closure deletes that read along with the rest, + which is a second, independent reason to take it. +* **A constraint on the census arms that is not obvious from their names.** + `fresh_plane` returns `vec![plane_poison(); n]` BEFORE it matches on + `plane_alloc()`, so `PadZero` and `ExtZero` never run while + `EC_AV1_PLANE_SENTINEL` is set — and that flag is exactly what both census + functions require (each returns early when it is off). Those two arms are + therefore meaningful only under **memcheck with the sentinel OFF**, where + the zeroed/uninitialised split between the regions is what memcheck keys on; + under the sentinel they are inert. The order is deliberate and stays: + moving the sentinel check below the match would let the region census scan a + buffer the sentinel never poisoned, which it cannot recover from. +* **Neither is reachable today.** That is a statement about today's corpus, not + a proof: a hostile file chooses its own subsize values, and the refusal that + closes region 2 lives in the tile walk, not at the allocation. Hence the + decision below rather than "the premise holds". + +--- + +## 3. The decision, and the evidence behind it + +The charter's rule: *if (b) is within noise of (a) and close to the baseline, +implement (b) and prove determinism; if (b) is expensive and (a) is too, leave +the allocation alone.* + +* (b) **is** within noise of (a) — 0.03 % apart at all three sizes. +* (b) is **not** within noise of the baseline at 4K: +0.84 % with a 6–10 ms + run-to-run spread, i.e. ~6σ. So the charter's first branch is not literally + satisfied. + +I took (b) anyway, and the reason is the shape of the risk, not the size of the +number: + +1. **The alternative is not "keep the unsafe", it is "keep asserting a premise + that has already been withdrawn once."** That premise is what + `lanes/unwritten-dep.report.md` §12 filed, and it produced a caller-visible + defect. A 0.84 % regression is visible in a benchmark; a withdrawn SAFETY + premise is invisible until it ships. +2. **The sign of the cost is not stable across resolutions** (§1). A decision to + pay it should be made knowing it is ~0.85 % at 4K and a ~1.6 % *win* at 1080p, + not "always 0.8 %". +3. **The decision is reversible in one line.** `EC_AV1_PLANE_ALLOC=uninit` + restores the status quo exactly, which is only true because the closure is an + env arm and not a build flag. + +**Determinism proof** — new gate +`stream::tests::the_frame_does_not_depend_on_the_plane_buffers_initial_content` +(`stream.rs:48496`), which is exactly the charter's test: + +* four child processes, same ten fixtures each: `EC_AV1_PLANE_SENTINEL=0xDEAD`, + `EC_AV1_PLANE_SENTINEL=0xBEEF`, sentinel-off + `EC_AV1_PLANE_ALLOC=uninit`, + sentinel-off + `EC_AV1_PLANE_ALLOC=zeroed`; +* one FNV-1a hash per fixture over every shown frame's Y/U/V samples; all four + arms must agree, per fixture; +* **non-vacuity first, synthetic**: two pictures differing in ONE sample must + hash differently, or every equality below would be vacuous; +* every arm must report `frames > 0`, so a child that decoded nothing cannot + agree with another child that decoded nothing. + +Fixture list deliberately small: a first revision used the 1920x792 film +fixtures and took **252 s** in a debug build, which is not a gate anyone keeps. +The committed ten (4:2:2 12-bit key / inter / sb128 intrabc / 17-frame odd +size, 4:4:4 lossless-sb64 / intrabc-rect4 / 128-root-mu, a padded odd size, an +off-tile chroma walk, superres+CDEF+LR) run the gate in **4.6 s**. + +--- + +## 4. What changed + +* `decode.rs` — `PlaneAlloc` (five arms), `plane_alloc()`, `zero_pad()`, + `zero_extent()`, `plane_poison()` (a settable poison so two-value + differential poisoning is possible; a poison ≤ 4095 is still refused), + `MAX_LEGAL_SAMPLE`, the pad-tail census (`PAD_UNWRITTEN_SAMPLES`, + `PAD_CENSUS_SCANNED` + accessors), `census_unwritten` extended to scan both + regions, `census_unwritten_final` switched to `plane_poison()`, + `fresh_plane` taking the plane geometry, and **`PlaneAlloc::Zeroed` as the + default**, which puts the `unsafe` behind an env arm. +* `stream.rs` — the determinism gate, its child, and the synthetic control. +* `examples/alloc_timing.rs` — the decode-wall-time / page-fault harness. +* Hunks are confined to the allocation path: `decode.rs` `fresh_plane` and the + six `PlaneBuf { … }` construction sites (3 planes × the key and inter frame + functions), plus the census block next to them. The peer lane + `lane/av1subsizesweep` touches `decode.rs` at ~37063 and ~57061 (a + superblock arm and its tests); there is no overlap. + +### SAFETY comment + +Rewritten to state **what can be read before it is written** — the three named +regions with their measured counts, the memcheck result, the refusal that +covers region 2, and the fact that the shipped arm never reaches the `unsafe` +at all. The withdrawn premise ("written sample-for-sample before anything reads +it") is gone; nothing in the comment asserts a premise a reviewer cannot +re-run. + +--- + +## 5. Gates + +``` +cargo check -p ec-av1 --tests ok +cargo test -p ec-av1 --lib -- 422 14 passed, 0 failed +cargo test -p ec-av1 --lib -- 444 50 passed, 0 failed +cargo test -p ec-av1 --lib -- sub8 13 passed, 0 failed +cargo test -p ec-av1 --lib -- lossless 34 passed, 0 failed +``` +Re-run on the rebased tree (`f01e9738`), where main's own `1f4fcc84` guard for +the census child test is present: +``` +cargo test -p ec-av1 --lib -- the_frame 13 passed, 0 failed + (includes the_frame_does_not_depend_on_the_plane_buffers_initial_content) +cargo test -p ec-av1 --lib -- unwritten 2 passed, 0 failed +``` + +**One gate was red on the lane's original base and is not this lane's.** On +`2d8fa8a4`, `cargo test -p ec-av1 --lib -- unwritten` reported +`1 passed, 1 FAILED`: `stream::tests::uwdep_child_unwritten_census` opens with +an unconditional `assert!(EC_AV1_PLANE_SENTINEL is set)` while sitting in the +crate's default test list, so any standalone run of that filter fails. Main +commit `1f4fcc84` ("the census child test skips in a normal suite run instead +of reddening it") adds the entry guard and it is **not** an ancestor of this +lane's original base. Nothing in this lane touches that test. + +--- + +## 7. Rebase onto `f01e9738` + +Main moved while this lane was measuring. The branch is rebased onto `f01e9738` +and every headline number was re-taken there; the only conflict was in the +`census_unwritten` doc comment, resolved by keeping main's coverage paragraph +("this census runs at TWO of the four places `apply_deblock` is entered from") +*and* the two-region text, since both intents hold. Main's delta also adds +`chroma_plane_block_codable` to the 16-level edge arm — the guard that refuses +the 4:2:2 subsize by name. + +What changed on the rebased tree, re-measured: +* the 3840x2160 4:2:0 row (§1) — `zeroed` +0.84 %, `fill` +0.92 %; same hashes, + same `minflt`, same conclusion; +* the poison sweep — 126 identical, **2** refused: `440_request_is_422` and, + newly, `422_header_edge16_walk`, which main's new guard refuses; +* the region census — **byte-identical totals**: 1,466,581,280 extent samples, + 0 holes; 22,787,296 pad samples, 4,676,128 holes; 38 fixtures. + +--- + +## 8. Left undone, deliberately + +* **A pooled plane buffer** would make the closure ~free: take the three plane + buffers from a thread-local pool, zero each ONCE at creation, return them on + drop. Every sample is then initialised by construction and the per-frame + memset disappears. It is not done here because it changes ownership + (`PlaneBuf` holds `Cow<'a, [u16]>` and is handed to the wavefront workers), + which is a different lane's worth of risk than this charter took on. +* **The 1080p sign flip is unexplained.** §1. +* **Reader attribution for a region-2 read** is only as deep as "a reader that + does not clamp". With no current fixture reaching region 2 there is nothing to + attribute; `EC_AV1_PLANE_ALLOC=padzero` / `extzero` are in the tree for + whoever gets one — under memcheck with the sentinel OFF, per the ordering + constraint in §2.5. \ No newline at end of file