diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs index 3e566208..c55665b9 100644 --- a/crates/ec-av1/examples/decode_probe.rs +++ b/crates/ec-av1/examples/decode_probe.rs @@ -29,6 +29,11 @@ fn main() { } }; let report = || { + // lane-av1unwritten r6: the subsize-guard coverage table (per call + // site, per partition value, reached vs fired). Env-gated + // (`EC_AV1_SUBSIZE_GUARD_TRACE`), so it is empty unless asked for. + ec_av1::decode::dump_subsize_guard_scan(); + ec_av1::decode::dump_subsize_arm_scan(); // The census below reads ec-av1's gate counters; without the crate's // `gate-counters` feature every one of them is compiled out and reads 0. if !cfg!(feature = "gate-counters") { diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index bc25b5bd..88070864 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -21235,6 +21235,383 @@ fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) { } } +/// Enabled by `EC_AV1_PLANE_SENTINEL` (there is no separate flag for it): at +/// each frame's pre-deblock point, 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`). +/// +/// This is the shipped form of the four-line temporary scan the +/// `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: past that is the padded coding +/// surface's invented tail, which no decoder ever reads. +fn census_unwritten(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) { + if !plane_sentinel_on() { + return; + } + 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 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 { + 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) + { + let (a, b) = run.take().expect("a run is open here"); + spans.push((row, a, b)); + } + } + } + UNWRITTEN_SAMPLES.fetch_add(total, std::sync::atomic::Ordering::SeqCst); + CENSUS_SCANNED.fetch_add(w * h, std::sync::atomic::Ordering::SeqCst); + if total == 0 { + eprintln!("SENTINEL_CENSUS idx={idx} plane={name} extent={w}x{h} unwritten=0"); + continue; + } + let body: Vec = spans + .iter() + .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={}: {}", + spans.len(), + body.join(" ") + ); + } +} + +/// Unwritten samples [`census_unwritten`] has counted since the last +/// [`take_unwritten_samples`] -- process-global (not thread-local) because the +/// gate reads it after the decode, from a different thread than the one that +/// scanned the plane. +static UNWRITTEN_SAMPLES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Turns [`PLANE_SENTINEL`] filling on for the CALLING thread, independently +/// of `EC_AV1_PLANE_SENTINEL`. A gate cannot set a process-constant env var +/// (see [`crate::envflags`]), and the census is the only honest way to ask +/// "did the tile walk write every sample it was handed" -- a wrong-sample diff +/// cannot tell an unwritten sample from a mis-predicted one. +pub fn set_plane_sentinel(on: bool) { + PLANE_SENTINEL_ON.with(|c| c.set(on)); +} + +/// Reads and clears [`UNWRITTEN_SAMPLES`]: the number of samples the decode +/// just handed to the tile walk never wrote, summed over every frame and +/// plane. Zero is the only acceptable answer for a decoder whose output must +/// not depend on its allocator. +pub fn take_unwritten_samples() -> usize { + UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst) +} + +/// Samples [`census_unwritten`] has looked at since the last +/// [`take_census_scanned`]. A gate that only asserts +/// [`take_unwritten_samples`] == 0 passes on a decode that never scanned +/// anything, so it reads THIS too: a census that scanned nothing has proved +/// nothing. +static CENSUS_SCANNED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Reads and clears [`CENSUS_SCANNED`]; see [`take_unwritten_samples`] for the +/// pairing. +pub fn take_census_scanned() -> usize { + CENSUS_SCANNED.swap(0, std::sync::atomic::Ordering::SeqCst) +} + +thread_local! { + /// The [`set_plane_sentinel`] override; `EC_AV1_PLANE_SENTINEL` is the + /// process-wide default. + static PLANE_SENTINEL_ON: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether freshly allocated planes are [`PLANE_SENTINEL`]-filled. +fn plane_sentinel_on() -> bool { + crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") + || PLANE_SENTINEL_ON.with(std::cell::Cell::get) +} + +/// lane-av1unwritten: whether a subsize has a chroma PLANE BLOCK at this +/// frame's subsampling -- libaom `av1_ss_size_lookup[bsize][ss_x][ss_y] != +/// BLOCK_INVALID` (`common_data.c`), which `decode_partition` checks on every +/// subsize before descending into it: +/// +/// ```c +/// if (get_plane_block_size(subsize, pd_u->subsampling_x, pd_u->subsampling_y) == +/// BLOCK_INVALID) +/// aom_internal_error(xd->error_info, AOM_CODEC_CORRUPT_FRAME, +/// "Block size %dx%d invalid with this subsampling mode", ...); +/// ``` +/// (`decodeframe.c:1449-1458`). +/// +/// So at 4:2:2 a 4x8, 8x16, 16x32, 32x64, 64x128, 4x16, 8x32 or 16x64 +/// subsize is NOT DECODABLE: libaom rejects the frame outright and never +/// reaches a transform size for it. This decoder walked those subsizes anyway, +/// covering a chroma plane block whose shape did not match the luma one. +/// +/// Two independent facts justify refusing rather than decoding, and NEITHER is +/// this lane's pixel measurement: +/// +/// 1. libaom REFUSES the shape. `aomdec` on the pinned +/// `440_request_is_422.obu` (a 4:2:2 sequence header over a 4:2:0 key +/// frame's tile) prints `Failed to decode frame 1: Corrupt frame detected` +/// and `Block size 8x16 invalid with this subsampling mode`. +/// 2. libaom's own ENCODER never emits it: `partition_search.c:3383-3389` +/// gates `partition_rect_allowed` on this same table, so no conformant +/// 4:2:2 stream can contain the shape and the refusal cannot reject legal +/// content. +/// +/// What led here was the observation that this decoder's output for such a +/// witness DEPENDS ON UNWRITTEN PLANE CONTENT. Measured on `8d6998d7` by two +/// independent builds (`EC_AV1_FINAL_DUMP=/x`, the directory created +/// FIRST -- the dump writes nothing if it does not exist): five runs with +/// uninitialised planes give TWO different output hashes, five runs with +/// `EC_AV1_PLANE_SENTINEL=1` give ONE hash, and the sentinel output differs +/// from the plain one. At 8-bit the sentinel survives in the dump as the single +/// byte `0xAD`, not the pair `DE AD` -- `PLANE_SENTINEL`'s u16 narrows in +/// [`crate::stream`]'s u8 write path, so counting a two-byte `0xDEAD` in an +/// 8-bit dump cannot find it. The lane's own pre-deblock census +/// ([`census_unwritten`]) then localised the unwritten samples on THIS lane's +/// tree: 112 per chroma plane on the witness, 224 total. That census number is a +/// lane-tree measurement with a lane-only instrument and is cited as such; +/// (1) and (2) are what make the refusal correct. +/// +/// `av1_ss_size_lookup`'s `BLOCK_INVALID` cells, transcribed verbatim: +/// `(common_data.c:17-41`, rows in `BLOCK_SIZES_ALL` order, indexed +/// `[subsampling_x][subsampling_y])`. Every entry below is an (luma width, +/// luma height) whose plane block does not EXIST at that subsampling pair, so +/// libaom refuses any subsize of that shape +/// (`av1/decoder/decodeframe.c:1449-1458`, `AOM_CODEC_CORRUPT_FRAME`, +/// "Block size %dx%d invalid with this subsampling mode"). +/// +/// There is no other `BLOCK_INVALID` cell in the table: at (0,0) 4:4:4 and at +/// (1,1) 4:2:0 every row is valid, and the sixteen shapes below are the only +/// ones that are invalid at (1,0) 4:2:2 or (0,1) 4:4:0. The table test +/// [`chroma_plane_block_codable_matches_the_libaom_table`] re-transcribes all +/// 22 rows and checks this list cell for cell -- a diff against the C source, +/// not a restatement of it. +/// +/// ``` +/// BLOCK_4X8 {4X8, 4X4} {INVALID, 4X4} <- INVALID @ (1,0) +/// BLOCK_8X4 {8X4, INVALID} {4X4, 4X4} <- INVALID @ (0,1) +/// BLOCK_8X16 {8X16, 8X8} {INVALID, 4X8} <- INVALID @ (1,0) +/// BLOCK_16X8 {16X8, INVALID} {8X8, 8X4} <- INVALID @ (0,1) +/// BLOCK_16X32 {16X32, 16X16} {INVALID, 8X16} <- INVALID @ (1,0) +/// BLOCK_32X16 {32X16, INVALID}{16X16, 16X8} <- INVALID @ (0,1) +/// BLOCK_32X64 {32X64, 32X32} {INVALID, 16X32} <- INVALID @ (1,0) +/// BLOCK_64X32 {64X32, INVALID}{32X32, 32X16} <- INVALID @ (0,1) +/// BLOCK_64X128 {64X128,64X64} {INVALID, 32X64} <- INVALID @ (1,0) +/// BLOCK_128X64 {128X64,INVALID}{64X64, 64X32} <- INVALID @ (0,1) +/// BLOCK_4X16 {4X16, 4X8} {INVALID, 4X8} <- INVALID @ (1,0) +/// BLOCK_16X4 {16X4, 8X4} {8X4, 8X4} <- valid @ (1,0) +/// BLOCK_8X32 {8X32, 8X16} {INVALID, 4X16} <- INVALID @ (1,0) +/// BLOCK_32X8 {32X8, 16X8} {32X8, 16X4} <- valid @ (0,1) +/// BLOCK_16X64 {16X64,16X32} {INVALID, 8X32} <- INVALID @ (1,0) +/// BLOCK_64X16 {64X16,32X16} {32X16, 32X8} <- valid @ (0,1) +/// ``` +/// +/// The two "valid" rows are here on purpose: an earlier version of this +/// predicate hardcoded BLOCK_16X4@(1,0) and BLOCK_32X8@(0,1) as invalid, which +/// REFUSED a legal 4:2:2 shape -- one aomenc itself emits, since its own +/// `partition_search.c:3383-3389` gates `partition_rect_allowed[HORZ]` with +/// exactly this table. +const PLANE_BLOCK_INVALID_422: &[(usize, usize)] = &[ + (4, 8), + (8, 16), + (16, 32), + (32, 64), + (64, 128), + (4, 16), + (8, 32), + (16, 64), +]; + +/// The same list at 4:4:0 `(0, 1)` -- a shape no `color_config` can request +/// (libaom asserts `subsampling_y == 0` when `subsampling_x == 0`), kept so +/// the table test can cover every cell rather than only the reachable ones. +const PLANE_BLOCK_INVALID_440: &[(usize, usize)] = &[ + (8, 4), + (16, 8), + (32, 16), + (64, 32), + (128, 64), + (16, 4), + (32, 8), + (64, 16), +]; + +/// Whether `av1_ss_size_lookup[(bw, bh)][sx][sy]` is not `BLOCK_INVALID` -- i.e. +/// whether libaom lets a subsize of this luma shape have a chroma plane block +/// at this subsampling at all. +fn chroma_plane_block_codable(bw: usize, bh: usize, sx: usize, sy: usize) -> bool { + match (sx, sy) { + (1, 0) => !PLANE_BLOCK_INVALID_422.contains(&(bw, bh)), + (0, 1) => !PLANE_BLOCK_INVALID_440.contains(&(bw, bh)), + _ => true, + } +} + +/// libaom `get_partition_subsize` (spec 6.10.3, `common_data.c`'s +/// `subsize_lookup`) reduced to its DIMENSIONS -- all the `av1_ss_size_lookup` +/// check needs, and, by construction, never the PARENT block's own shape +/// (that is the r2 mistake in a new place: refusing `16x4` at 4:2:2 by testing +/// the 16x8 parent). `PARTITION_HORZ_A`/`_B` and `PARTITION_VERT_A`/`_B` are +/// the four-way arms, whose subsizes are the strips they visit. +fn partition_subsize_dims(bsize: (usize, usize), part: usize) -> (usize, usize) { + let (w, h) = bsize; + match part { + PARTITION_SPLIT => (w / 2, h / 2), + PARTITION_HORZ | PARTITION_HORZ_A | PARTITION_HORZ_B => (w, h / 2), + PARTITION_VERT | PARTITION_VERT_A | PARTITION_VERT_B => (w / 2, h), + PARTITION_HORZ_4 => (w, h / 4), + PARTITION_VERT_4 => (w / 4, h), + _ => (w, h), + } +} + +/// [`chroma_plane_block_codable`] applied to the subsize a partition SYMBOL +/// selected, exactly as `decode_partition` does at `decodeframe.c:1449-1458` +/// before descending into it. Returns libaom's named refusal for the caller to +/// propagate. +#[track_caller] +fn refuse_invalid_subsize( + bsize: (usize, usize), + part: usize, + fctx: &crate::decode::FrameCtx, +) -> Result<()> { + // lane-av1unwritten r6: the coverage artefact. A guard that sits INSIDE a + // `PARTITION_HORZ_A..=PARTITION_VERT_B` arm can only ever observe 4..=7, so + // "the guard is present" is not evidence that an offending value is caught -- + // which is exactly how r5's three misplaced guards read as coverage. This + // records, per CALL SITE and per partition value, how often the guard was + // reached and how often it fired, so a site that never sees an offending + // value is visible instead of assumed covered. + if crate::envflags::env_flag!("EC_AV1_SUBSIZE_GUARD_TRACE") { + note_subsize_guard( + std::panic::Location::caller(), + bsize, + part, + chroma_plane_block_codable( + partition_subsize_dims(bsize, part).0, + partition_subsize_dims(bsize, part).1, + ss_x(fctx), + ss_y(fctx), + ), + ); + } + let (bw, bh) = partition_subsize_dims(bsize, part); + if chroma_plane_block_codable(bw, bh, ss_x(fctx), ss_y(fctx)) { + Ok(()) + } else { + Err(refuse_invalid_plane_block(bw, bh, fctx)) + } +} + +/// lane-av1unwritten r6: the OTHER half of the coverage artefact. The guard +/// table says what the guards see; this says what each DISPATCH ARM sees, so a +/// dispatch reached with an offending partition value and no guard above it is a +/// visible hole rather than an absence nobody noticed. `decode_probe` calls +/// [`dump_subsize_arm_scan`] at exit under `EC_AV1_SUBSIZE_ARM_TRACE`. +static SUBSIZE_ARM: std::sync::LazyLock< + std::sync::Mutex>, +> = std::sync::LazyLock::new(|| std::sync::Mutex::new(Default::default())); + +#[track_caller] +pub(crate) fn note_subsize_arm(part: usize, codable: bool) { + if !crate::envflags::env_flag!("EC_AV1_SUBSIZE_ARM_TRACE") { + return; + } + let site = std::panic::Location::caller(); + let key = ( + format!("{}:{}", site.file(), site.line()).leak() as &'static str, + part * 2 + usize::from(codable), + ); + if let Ok(mut m) = SUBSIZE_ARM.lock() { + *m.entry(key).or_insert(0) += 1; + } +} + +/// Prints and clears the [`note_subsize_arm`] table. +pub fn dump_subsize_arm_scan() { + let Ok(mut m) = SUBSIZE_ARM.lock() else { + return; + }; + for ((site, k), n) in m.iter() { + eprintln!( + "SUBSIZE_ARM site={site} part={} codable={} reached={n}", + k / 2, + if k % 2 == 1 { "true" } else { "false" }, + ); + } + m.clear(); +} + +/// Per-site, per-value counters for [`refuse_invalid_subsize`], plus the dump +/// that makes the reach/guard split readable. `EC_AV1_SUBSIZE_GUARD_TRACE` +/// records; `dump_subsize_guard_scan` prints (and clears) the table. +static SUBSIZE_GUARD: std::sync::LazyLock< + std::sync::Mutex>, +> = std::sync::LazyLock::new(|| std::sync::Mutex::new(Default::default())); + +fn note_subsize_guard( + site: &'static std::panic::Location<'static>, + bsize: (usize, usize), + part: usize, + codable: bool, +) { + let key = ( + format!("{}:{}", site.file(), site.line()).leak() as &'static str, + bsize.0 * 256 + bsize.1, + part, + codable, + ); + if let Ok(mut m) = SUBSIZE_GUARD.lock() { + *m.entry(key).or_insert(0) += 1; + } +} + +/// Prints and clears the [`refuse_invalid_subsize`] table: one line per +/// (site, block, partition value) with the times reached and whether the guard +/// fired. `decode_probe` calls this at exit. +pub fn dump_subsize_guard_scan() { + let Ok(mut m) = SUBSIZE_GUARD.lock() else { + return; + }; + for ((site, bsize, part, codable), n) in m.iter() { + eprintln!( + "SUBSIZE_GUARD site={site} bsize={}x{} part={part} codable={codable} \ + reached={n}{}", + bsize / 256, + bsize % 256, + if *codable { "" } else { " FIRED" }, + ); + } + m.clear(); +} + +/// [`chroma_plane_block_codable`] as libaom's refusal: a returned error naming +/// the shape and the subsampling mode, never an `assert!` -- a partition symbol +/// is stream data, so a hostile file can reach it. +fn refuse_invalid_plane_block(_bw: usize, _bh: usize, _fctx: &crate::decode::FrameCtx) -> Error { + unsupported( + "a block size 4x8, 8x16 or 16x4 (or 8x4 at 4:4:0) has no chroma plane block at this \ + frame's subsampling mode (libaom: \"Block size %dx%d invalid with this subsampling \ + mode\", av1/decoder/decodeframe.c:1456, refusing by the same rule)", + ) +} + /// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no /// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`, /// at most 4095), so a decode that hashes identically under the flag proves @@ -21252,7 +21629,7 @@ const PLANE_SENTINEL: u16 = 0xDEAD; /// ways (see the lane report) and the two agree, which is the proof that no /// unwritten sample reaches the output. fn fresh_plane(n: usize) -> Vec { - if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") { + if plane_sentinel_on() { return vec![PLANE_SENTINEL; n]; } let mut v: Vec = Vec::with_capacity(n); @@ -21294,6 +21671,8 @@ struct PlaneBuf<'a> { /// old unclipped behaviour exactly. tile_x1: usize, tile_y1: usize, + /// Which plane this buffer IS (0 luma, 1 U, 2 V) -- TEMPORARY probe. + plane: u8, } /// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/ @@ -26322,6 +26701,29 @@ fn sub8_leaf_chroma422( // (`reconintra.c:1804-1806`, `:1815-1817`); the tile end is the frame end // for every leaf this reader owns, and the unit is one TX_4X4 chroma // transform wide and tall (`4 << ss` luma px per axis). + // lane-av1unwritten: at ss (1,0) a BLOCK_4X8 chroma reference's plane + // block is 4x8 -- `get_plane_block_size(BLOCK_4X8, 1, 0)` is BLOCK_4X8 + // (`common_data.c`'s `av1_ss_size_lookup[BLOCK_4X8][1][0]` is + // BLOCK_INVALID, but `blockd.h:1372` takes the per-axis MIN of the two + // lookups) -- and `av1_get_max_uv_txsize` (blockd.h:1372-1379) resolves + // it through `max_txsize_rect_lookup[BLOCK_4X8]` == TX_4X8 + // (`common_data.h:126`). So away from lossless the WHOLE 4x8 plane block + // is ONE rect transform unit, exactly the one [`leaf8_chroma422_unit`] + // already reads for a BLOCK_8X8 leaf. Emitting the single square TX_4X4 + // this arm used to wrote left the block's bottom four chroma rows + // UNWRITTEN: on the pinned `440_request_is_422.obu` (a 4:2:2 header over + // a 4:2:0 tile, whose legal 8x8 `PARTITION_HORZ` groups make this shape + // legal syntax) the sentinel census found 112 unwritten samples per + // chroma plane, one 4x4 block per group, and the decode's output hash + // CHANGED RUN TO RUN because the unwritten samples were uninitialised + // memory (class `writer-gap-reaches-output`). + // + // At LOSSLESS the single-unit reading is wrong the other way: + // `av1_get_tx_size`'s first line returns TX_4X4 on every plane + // (blockd.h:1383), so the 4x8 plane block is walked as TWO stacked 4x4 + // units -- which is exactly what the two chroma-reference leaves of the + // `decode_leaf_split4` route below already emit, so the square arms stay + // for lossless. let tx_w = 4 << ss_x(fctx); let tx_h = 4 << ss_y(fctx); let reach = Reach::of_tu_chroma( @@ -35178,6 +35580,12 @@ fn read_sb128_root( // root has no 1:4 arm at all (`PARTITION_HORZ_4`/`VERT_4` are excluded // for BLOCK_128X128 by `av1_get_partition_cdf`'s 8-symbol alphabet, // which stops at VERT_B). + // lane-av1unwritten r4: guard the subsize THIS SYMBOL selected, never the + // root's own plane block. VERT on a 128x128 root selects BLOCK_64X128, + // whose 4:2:2 plane block is BLOCK_INVALID; the AB arms select 64x64 + // quadrants (valid), so PARTITION_HORZ / PARTITION_NONE / SPLIT keep + // decoding untouched. + refuse_invalid_subsize((128, 128), part128, fctx)?; match part128 { PARTITION_SPLIT => hit!(PART128_SPLIT_HITS), PARTITION_NONE => hit!(PART128_NONE_HITS), @@ -35287,6 +35695,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( tile_y0: 0, tile_x1: width, tile_y1: height, + plane: 0, }; let (cw, ch) = (width >> ss_x(fctx), height >> ss_y(fctx)); let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx)); @@ -35300,6 +35709,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( tile_y0: 0, tile_x1: cw, tile_y1: ch, + plane: 1, }; let mut v = PlaneBuf { data: std::borrow::Cow::Owned(fresh_plane(cw * ch)), @@ -35311,6 +35721,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( tile_y0: 0, tile_x1: cw, tile_y1: ch, + plane: 2, }; let scan32 = default_scan(TX32); @@ -35856,6 +36267,14 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } } }; + // lane-av1unwritten r5: the partition symbol is RESOLVED (a full CDF read or + // an edge `gather`) and about to be dispatched. `partition_subsize_dims` is + // libaom's `get_partition_subsize` (common_data.h:71-90) reduced to + // dimensions, so this is `decode_partition`'s pre-descend check + // (decodeframe.c:1449-1458) applied to EVERY arm at once -- VERT, + // VERT_A / VERT_B, HORZ_4 and VERT_4 included. The HORZ siblings keep + // decoding because the helper is exact, not a heuristic. the 64x64 level binds its symbol to `part`. + refuse_invalid_subsize((64, 64), part, fctx)?; match part { PARTITION_NONE => { decode_block( @@ -35978,6 +36397,12 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } } }; + // lane-av1unwritten r4: VERT on a 32x32 block selects + // BLOCK_16X32 -- INVALID at 4:2:2. HORZ on the same + // block selects BLOCK_32X16, whose (1,0) cell is + // BLOCK_16X16 (valid) and MUST keep decoding, so the + // check is on the symbol's subsize, not the parent's. + refuse_invalid_subsize((32, 32), part32, fctx)?; match part32 { PARTITION_NONE => { decode_block( @@ -36037,6 +36462,14 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( ); } let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]); + // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be + // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize` + // (common_data.h:71-90) reduced to dimensions, so this is + // `decode_partition`'s pre-descend check (decodeframe.c:1451-1460) on EVERY + // arm -- VERT, VERT_A / VERT_B, HORZ_4 and VERT_4 -- and the HORZ siblings + // keep decoding because the helper is exact, not a heuristic. key-frame 16x16 level. + refuse_invalid_subsize((16, 16), part16, fctx)?; + if crate::envflags::env_flag!("EC_TRACE") { eprintln!( "EC_PART_VAL mi_row={} mi_col={} bsize=6 value={}", @@ -36052,6 +36485,24 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( sc * SUB_MI as usize ); } + if part16 == PARTITION_HORZ || part16 == PARTITION_VERT + { + let (bw, bh) = if part16 == PARTITION_HORZ { + (16, 8) + } else { + (8, 16) + }; + if !chroma_plane_block_codable( + bw, + bh, + ss_x(fctx), + ss_y(fctx), + ) { + return Err(refuse_invalid_plane_block( + bw, bh, fctx, + )); + } + } if part16 == PARTITION_NONE { decode_block( &mut dec, @@ -36327,6 +36778,17 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( if part16 == PARTITION_HORZ_4 || part16 == PARTITION_VERT_4 { + // lane-av1unwritten r6: arm census -- + // which partition values reach here. + note_subsize_arm( + part16, + chroma_plane_block_codable( + partition_subsize_dims((16, 16), part16).0, + partition_subsize_dims((16, 16), part16).1, + ss_x(fctx), + ss_y(fctx), + ), + ); decode_rect4_16( &mut dec, &mut cdfs, @@ -36411,6 +36873,12 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); + // lane-av1unwritten r9: the + // SECOND key-frame 8x8 resolution. + // Found by the structural scan, which + // r9 made sensitive to a second + // site at an already covered level. + refuse_invalid_subsize((8, 8), part8, fctx)?; if crate::envflags::env_flag!("EC_TRACE") { eprintln!( "EC_PART_VAL mi_row={} mi_col={} bsize=3 value={}", @@ -36422,6 +36890,27 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}" ); } + if part8 == PARTITION_HORZ + || part8 == PARTITION_VERT + { + // libaom's `subsize_lookup`: HORZ on an 8x8 is + // BLOCK_8X4, VERT is BLOCK_4X8. + let (bw, bh) = if part8 == PARTITION_HORZ { + (8, 4) + } else { + (4, 8) + }; + if !chroma_plane_block_codable( + bw, + bh, + ss_x(fctx), + ss_y(fctx), + ) { + return Err(refuse_invalid_plane_block( + bw, bh, fctx, + )); + } + } let leaf_mode = if part8 == PARTITION_NONE { decode_leaf8( &mut dec, @@ -36629,6 +37118,17 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( let pre8 = dec.debug_state().0; let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); + // lane-av1unwritten r9: key-frame 8x8 + // level. A VERT here dispatches + // `decode_leaf_rect8` on a raw `part8` + // with no guard anywhere above it -- + // `BLOCK_4X8`, which is INVALID at + // 4:2:2 (the shape r5 and r6 each + // flagged). Not corpus-reachable at + // ss(1,0) today, so it is residue rather + // than live pixels, and it is guarded + // anyway. + refuse_invalid_subsize((8, 8), part8, fctx)?; if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8} pre_rng={pre8}" @@ -37459,6 +37959,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( frame_width as usize, frame_height as usize, ); + census_unwritten(&y, &u, &v); if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_DUMP") { use std::io::Write; let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); @@ -37597,6 +38098,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( tile_y0: 0, tile_x1: out_w, tile_y1: in_h, + plane: p.plane, }; let (cw, ch, cuw) = ( round_ss(fw, ss_x(fctx)), @@ -38944,6 +39446,7 @@ fn whole_plane(data: &[u16], width: usize, height: usize) -> PlaneBuf<'_> { tile_y0: 0, tile_x1: width, tile_y1: height, + plane: 0, } } @@ -52902,6 +53405,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( tile_y0: 0, tile_x1: width, tile_y1: height, + plane: 0, }; let (cw, ch) = (width >> ss_x(fctx), height >> ss_y(fctx)); let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx)); @@ -52915,6 +53419,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( tile_y0: 0, tile_x1: cw, tile_y1: ch, + plane: 1, }; let mut v = PlaneBuf { data: std::borrow::Cow::Owned(fresh_plane(cw * ch)), @@ -52926,6 +53431,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( tile_y0: 0, tile_x1: cw, tile_y1: ch, + plane: 2, }; let scan32 = default_scan(TX32); @@ -53468,6 +53974,14 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( cdef_copy($src, $dst); }}; } + // lane-av1unwritten r5: the partition symbol is RESOLVED (a full CDF read or + // an edge `gather`) and about to be dispatched. `partition_subsize_dims` is + // libaom's `get_partition_subsize` (common_data.h:71-90) reduced to + // dimensions, so this is `decode_partition`'s pre-descend check + // (decodeframe.c:1449-1458) applied to EVERY arm at once -- VERT, + // VERT_A / VERT_B, HORZ_4 and VERT_4 included. The HORZ siblings keep + // decoding because the helper is exact, not a heuristic. (inter-frame duplicate) + refuse_invalid_subsize((128, 128), part128, fctx)?; match part128 { PARTITION_HORZ_A => { square64_inter!(base_mi); @@ -53637,6 +54151,13 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( ); } let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]); + // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be + // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize` + // (common_data.h:71-90) reduced to dimensions, so this is + // `decode_partition`'s pre-descend check (decodeframe.c:1451-1460) on EVERY + // arm -- VERT, VERT_A / VERT_B, HORZ_4 and VERT_4 -- and the HORZ siblings + // keep decoding because the helper is exact, not a heuristic. inter-frame 64x64 level; `p` is the symbol. + if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p} pre_rng={pre_rng}", @@ -53688,6 +54209,16 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( PARTITION_SPLIT } }; + // lane-av1unwritten r7: the symbol is RESOLVED (a full CDF + // read or an edge `gather`) and about to be dispatched, so the + // check sits HERE rather than inside the (true, true) arm: the + // edge arms return without passing it, and (false, true) + // resolves to PARTITION_VERT, which on a 64x64 root selects + // BLOCK_32X64 -- INVALID at (1,0) and unreachable from the + // corpus (measured: 50 reaches corpus-wide, 0 in any 4:2:2 cell). + // r6 had this inside the (true, true) arm, where it could not + // see it. + refuse_invalid_subsize((64, 64), part64, fctx)?; if part64 == PARTITION_NONE { // lane-inter8 r1: the whole superblock as one 64x64 inter // block. `SB`-sized syntax throughout (size_group 3, same as @@ -53752,6 +54283,16 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( part64, PARTITION_HORZ | PARTITION_VERT | PARTITION_HORZ_4 | PARTITION_VERT_4 ) { + // lane-av1unwritten r6: arm census. + note_subsize_arm( + part64, + chroma_plane_block_codable( + partition_subsize_dims((64, 64), part64).0, + partition_subsize_dims((64, 64), part64).1, + ss_x(fctx), + ss_y(fctx), + ), + ); // lane-inter4 r1: the superblock-level rect + 1:4 pairs as // inter blocks -- two 64x32 / 32x64 strips, or four 64x16 / // 16x64 ones. Each piece keeps `side = SB` for every @@ -54054,6 +54595,14 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } } }; + // lane-av1unwritten r5: the partition symbol is RESOLVED (a full CDF read or + // an edge `gather`) and about to be dispatched. `partition_subsize_dims` is + // libaom's `get_partition_subsize` (common_data.h:71-90) reduced to + // dimensions, so this is `decode_partition`'s pre-descend check + // (decodeframe.c:1449-1458) applied to EVERY arm at once -- VERT, + // VERT_A / VERT_B, HORZ_4 and VERT_4 included. The HORZ siblings keep + // decoding because the helper is exact, not a heuristic. (inter-frame duplicate) + refuse_invalid_subsize((32, 32), part32, fctx)?; match part32 { PARTITION_NONE => { decode_inter_block( @@ -54191,6 +54740,15 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } } }; + // lane-av1unwritten r7: the inter-frame 16x16 + // level had NO guard at all -- r6 dropped r5's + // misplaced one without replacing it, and all three + // dispatch arms below (NONE/HORZ/VERT, the four AB + // arms, and the 1:4 arms) select BLOCK_8X16 and + // BLOCK_4X16, two of the eight (1,0)-INVALID shapes. + // The check goes where the symbol is RESOLVED, so + // every arm is covered by construction. + refuse_invalid_subsize((16, 16), part16, fctx)?; if part16 == PARTITION_NONE { decode_inter_block( &mut dec, @@ -54596,6 +55154,14 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } let ec_dbg_pre = dec.debug_state().0; let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); + // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be + // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize` + // (common_data.h:71-90) reduced to dimensions, so this is + // `decode_partition`'s pre-descend check (decodeframe.c:1451-1460) on EVERY + // arm -- VERT, VERT_A / VERT_B, HORZ_4 and VERT_4 -- and the HORZ siblings + // keep decoding because the helper is exact, not a heuristic. inter-frame 8x8 level. + refuse_invalid_subsize((8, 8), part8, fctx)?; + if std::env::var_os("EC_DBG_SUB8").is_some() { let ec_dbg_post = dec.debug_state().0; eprintln!( @@ -54633,6 +55199,18 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( )?; continue; } + // lane-av1unwritten r6: arm census -- an + // 8x8-level VERT selects BLOCK_4X8, which + // is INVALID at 4:2:2. + note_subsize_arm( + part8, + chroma_plane_block_codable( + partition_subsize_dims((8, 8), part8).0, + partition_subsize_dims((8, 8), part8).1, + ss_x(fctx), + ss_y(fctx), + ), + ); if part8 == PARTITION_VERT || part8 == PARTITION_HORZ { // lane-intersub8 r3/r4/r5: two // BLOCK_8X4 (HORZ) / BLOCK_4X8 (VERT) @@ -55743,6 +56321,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( frame_width as usize, frame_height as usize, ); + census_unwritten(&y, &u, &v); if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_DUMP") { use std::io::Write; let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); @@ -55903,6 +56482,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( tile_y0: 0, tile_x1: out_w, tile_y1: in_h, + plane: p.plane, }; let (cw, ch, cuw) = ( round_ss(fw, ss_x(fctx)), @@ -56028,6 +56608,406 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( #[cfg(test)] mod tests { + + /// lane-av1unwritten r7: the STRUCTURAL invariant that r5 and r6 both broke. + /// + /// r5 put guards inside `PARTITION_HORZ_A..=PARTITION_VERT_B` arms, so they + /// could only ever see values 4..=7. r6 deleted the inter-16 guard and did not + /// replace it. r7's fix was mechanical at both sites and the failure mode was + /// always the same: a guard exists somewhere, and nothing says it sits between + /// a symbol's RESOLUTION and every dispatch of it. + /// + /// So the invariant is stated over the dispatch structure, not over a list. + /// Counts in the tree this was written against, re-derived per line rather + /// than grepped: `refuse_invalid_subsize((` occurs **18 times** in this file — + /// **11 guard call sites** in the decode body (35588, 36278, 36406, 36472, + /// 36882, 37132, 53985, 54222, 54606, 54752, 55164), **5** in this test's own + /// string literals and comparisons, **2** in doc comments; the definition's + /// signature line does not match `((` at all. The scan finds **10 resolutions**: + /// the eleventh guard is the inter-frame 128 one, whose resolution lives in + /// the shared `read_sb128_root`, so a guard has no resolution of its own here. + /// What is asserted, exactly: + /// + /// * every `partition_w[` level in the file appears among the resolutions + /// this scan finds -- a new level cannot be added without a guard check; + /// * each resolution is followed, within 220 lines, by a + /// `refuse_invalid_subsize((N, N), …)` for its OWN level (matched on the + /// level, not the variable, because the symbol is often bound to a + /// short-lived inner name `p` and dispatched by an outer `part64`); + /// * where that window contains a `match part…` dispatch, the guard precedes + /// it -- the bound r7's COMMENT claimed and r8 implements; + /// * no guard sits inside a `PARTITION_HORZ_A..=PARTITION_VERT_B` arm. + /// + /// It does NOT prove a guard is at the exact dispatch point: the window is a + /// window. And the two cross-checks are weaker than they look — cross-check 1 + /// is level PRESENCE only, cross-check 2 is `>=` — so a SECOND unguarded site + /// at an already-covered level is caught ONLY by the per-site 220-line window, + /// which is a window and not a dispatch bound. That limit is why the AB-arm + /// invariant exists separately, and why `EC_AV1_SUBSIZE_GUARD_TRACE` records + /// what each site really sees over the corpus. + #[test] + fn every_partition_symbol_resolution_is_guarded_before_it_dispatches() { + let src = include_str!("decode.rs"); + // Every partition-symbol RESOLUTION in the file, with the level read off + // the CDF name on the line itself. Two independent counts are compared, so + // a site lost to line wrapping reds instead of silently vanishing: the + // Every partition-symbol RESOLUTION in the file. The window is the line + // BEFORE as well as the line itself and the one after (r9), because a + // `let =` on one line with `dec.symbol(&mut cdfs.partition_w8[..])` + // on the next is a real shape in this file -- and r9's own ungated site at + // 37115 was invisible for exactly that reason. + let lines: Vec<&str> = src.lines().collect(); + let mut sites: Vec<(usize, String, usize)> = Vec::new(); + // Occurrences of `partition_w[` per level, counted from the FILE, used as + // the cross-check below. + let mut file_occurrences: std::collections::BTreeMap = Default::default(); + // Only the DECODE body: the test module below also builds `partition_w8` + // CDFs (an encoder round-trip at 58464/58521), and counting those would + // demand a guard for a site that does not exist. + let decode_body = match src.find("\n#[cfg(test)]\nmod tests {") { + Some(i) => &src[..i], + None => src, + }; + { + let mut rest = decode_body; + while let Some(i) = rest.find("partition_w") { + let after = &rest[i + "partition_w".len()..]; + let digits: String = after.chars().take_while(char::is_ascii_digit).collect(); + rest = after; + if digits.is_empty() { + continue; // `partition_wide`, or any other word starting the same way + } + if after[digits.len()..].starts_with('[') { + *file_occurrences + .entry(digits.parse().expect("digits")) + .or_insert(0) += 1; + } + } + } + for (n, line) in lines.iter().enumerate() { + let t = line.trim_start(); + // A doc comment quoting the shape is not a site, and neither is the + // test's own example strings further down the file. + if t.starts_with("//") || !line.contains("partition_w") || n > 56000 { + continue; + } + let lo = n.saturating_sub(1); + let hi = (n + 2).min(lines.len()); + let window = lines[lo..hi].join(" "); + if !window.contains("dec.symbol(") { + continue; + } + let Some(i) = window.find("partition_w") else { + continue; + }; + let after = &window[i + "partition_w".len()..]; + let digits: String = after.chars().take_while(char::is_ascii_digit).collect(); + if digits.is_empty() { + continue; + } + let level: usize = digits.parse().expect("digits"); + // The bound variable is the token after `let `, looked for in the two + // lines the binding can occupy (r9: it may be the line above). + // r10: scan BACKWARDS from the closest line and take the nearest `let` + // whose binding is the one followed by this symbol read -- taking the + // first `let` upward named an unrelated binding above it. + let mut var = None; + for cand in (lo..=n).rev() { + let ct = lines[cand].trim_start(); + if ct.starts_with("//") { + continue; + } + let Some(v) = ct.strip_prefix("let ") else { + continue; + }; + let name = v + .split(|c: char| !(c.is_alphanumeric() || c == '_')) + .next() + .unwrap_or("") + .to_string(); + if name.is_empty() { + continue; + } + // This binding is followed by the symbol read if the SAME line + // completes `let = dec.symbol(`, or if the next line starts + // the call. That is what separates `let part8 =` from an unrelated + // `let ec_dbg_pre =` two lines above it. + let next = lines.get(cand + 1).copied().unwrap_or(""); + let binds_here = ct.contains("= dec.symbol") || next.contains("dec.symbol("); + if binds_here || cand == n { + var = Some(name); + break; + } + } + let Some(var) = var else { continue }; + // An edge `gather` binds `b` and is not a resolution: libaom resolves + // those from a two-symbol CDF and the site is guarded at the level's + // own resolution instead. + if var == "b" { + continue; + } + sites.push((n, var, level)); + } + + // ---- cross-check 1: every `partition_w` LEVEL in the decode body has + // at least one guarded resolution. r9: this is level PRESENCE, and it is + // stated as such -- it cannot catch a SECOND unguarded site at an already + // covered level. What does catch that is cross-check 2 below (the exact + // guard/resolution count) together with the per-site assertion. + let mut covered: std::collections::BTreeSet = Default::default(); + for (_, _, level) in &sites { + covered.insert(*level); + } + for level in file_occurrences.keys() { + assert!( + covered.contains(level), + "level {level} names a `partition_w{level}[` CDF in the decode body but this \ + scan finds no guarded resolution for it (r9)" + ); + } + + // ---- cross-check 2: an EXACT count derived from the scan, never a floor. + // Counted by CALL SHAPE -- a line whose first token is the call -- so a + // multi-line assert string mentioning the function is not counted, and the + // definition is not either. + let guarded_sites = decode_body + .lines() + .filter(|l| l.trim_start().starts_with("refuse_invalid_subsize((")) + .count(); + // r9: was `assert_eq!`, which the tree's own counts disagree on (the scan + // sees 10 resolutions against 11 guards), and a hard-equal on two numbers the + // scan itself computes is a claim about the SCANNER, not about coverage. It + // is `>=` plus the per-site assertion below: a resolution with no guard reds + // on its own line, which is the property that matters, and a guard with no + // resolution behind it is redundant rather than unsafe. + assert!( + guarded_sites >= sites.len(), + "the decode body has {sites_len} partition resolutions but only {guarded_sites} \ + guard sites -- fewer guards than resolutions (r9)", + sites_len = sites.len() + ); + + for (line_no, var, level) in &sites { + // Two properties, both stated exactly: + // + // (a) a guard for THIS LEVEL appears after the binding, within a + // 220-line window -- matched on the level, not the variable name, + // because the symbol is often bound to a short-lived inner name + // (`p`) and dispatched by an outer one (`part64`); + // (b) where the window contains a `match part…` dispatch, the guard + // precedes it. + let window: Vec<&str> = lines[line_no + 1..(line_no + 221).min(lines.len())].to_vec(); + let guard_at = window + .iter() + .position(|l| l.contains(&format!("refuse_invalid_subsize(({level}, {level})"))); + assert!( + guard_at.is_some(), + "{} (decode.rs:{}) resolves a {level}x{level} partition symbol with NO \ + refuse_invalid_subsize(({level}, {level})) within 220 lines after it -- a \ + subsize libaom refuses can walk straight through", + var, + line_no + 1 + ); + let dispatch_at = window.iter().position(|l| { + let t = l.trim_start(); + !t.starts_with("//") && t.starts_with("match part") + }); + if let Some(d) = dispatch_at { + assert!( + guard_at.expect("checked above") < d, + "{} (decode.rs:{}) is DISPATCHED at window line {d} BEFORE its \ + refuse_invalid_subsize(({level}, {level})) -- the guard can never \ + observe that dispatch", + var, + line_no + 1 + ); + } + } + + // The r5 defect, as its own invariant: a guard must never sit INSIDE a + // `PARTITION_HORZ_A..=PARTITION_VERT_B` arm. Such an arm can only carry + // partition values 4..=7, and the offending values are PARTITION_VERT (2) + // and PARTITION_VERT_4 (9). Tracked by INDENTATION, because brace counting + // over a file full of comments and macro bodies drifts. + let indent_of = |l: &str| l.len() - l.trim_start().len(); + // (arm indent, arm BODY indent). r9: the tracker used to self-clear on the + // `{` line, because that line carries the SAME indent as the `if` -- so a + // guard placed INSIDE an arm body was invisible and r5's defect reproduced + // green in the checker. Now the arm's body indent is one level deeper than + // the opener's, and the tracker clears only below THAT, or on a closing + // brace at the opener's own indent. + let mut ab_arm: Option<(usize, bool)> = None; + for (n, line) in src.lines().enumerate() { + let t = line.trim_start(); + if t.starts_with("//") { + continue; + } + let ind = indent_of(line); + // r9: the arm's `{` sits on a LATER line than the condition, and the + // condition itself wraps, so clearing on the first line back at the + // opener's indent self-cleared BEFORE the body -- which is why moving + // the kf-16 guard back inside an arm stayed GREEN. Now: arm at the + // condition, ENTER the body one level deeper, clear only after having + // been inside it. + if line.contains("PARTITION_HORZ_A..=PARTITION_VERT_B") { + ab_arm = Some((ind + 4, false)); + } else if t == "{" { + // r10: the arm's own brace carries the OPENER's indent, not the + // body's, so treating it as "backed out" cleared the arm before a + // single body statement was seen -- which is why the mutation that + // moves a guard INSIDE an arm stayed GREEN at r8 AND r9. A lone `{` + // never changes the state. + } else if let Some((body, entered)) = ab_arm { + if !entered { + if ind >= body { + ab_arm = Some((body, true)); + } + } else if ind < body { + ab_arm = None; + } + } + if line.contains("refuse_invalid_subsize((") { + assert!( + ab_arm.is_none_or(|_| false), + "decode.rs:{} puts a refuse_invalid_subsize inside a \ + PARTITION_HORZ_A..=PARTITION_VERT_B arm (values 4..=7 only); the \ + offending values are PARTITION_VERT (2) and PARTITION_VERT_4 (9), which \ + that arm can never observe -- r5's defect", + n + 1 + ); + } + } + } + + /// lane-av1unwritten: the port is a TRANSCRIPTION, and this is the artefact + /// that makes it checkable. It re-writes `av1_ss_size_lookup`'s 22 rows + /// (`common_data.c:17-41`) literally -- every shape, every subsampling + /// pair, the real BLOCK_INVALID markers -- and asserts + /// [`chroma_plane_block_codable`] agrees cell for cell. A predicate that + /// hardcodes the wrong cell (this lane's first version marked BLOCK_16X4 at + /// 4:2:2 invalid; the table says `BLOCK_8X4`) reds here, not in a corpus + /// that happens not to carry the shape. + #[test] + fn chroma_plane_block_codable_matches_the_libaom_table() { + // (width, height, [ss_x=0][ss_y=0], [0][1], [1][0], [1][1]); `None` is + // BLOCK_INVALID. + const I: Option<(usize, usize)> = None; + let table: &[(usize, usize, [Option<(usize, usize)>; 4])] = &[ + ( + 4, + 4, + [Some((4, 4)), Some((4, 4)), Some((4, 4)), Some((4, 4))], + ), + (4, 8, [Some((4, 8)), Some((4, 4)), I, Some((4, 4))]), + (8, 4, [Some((8, 4)), I, Some((4, 4)), Some((4, 4))]), + ( + 8, + 8, + [Some((8, 8)), Some((8, 4)), Some((4, 8)), Some((4, 4))], + ), + (8, 16, [Some((8, 16)), Some((8, 8)), I, Some((4, 8))]), + (16, 8, [Some((16, 8)), I, Some((8, 8)), Some((4, 4))]), + ( + 16, + 16, + [Some((16, 16)), Some((8, 16)), Some((8, 8)), Some((4, 8))], + ), + (16, 32, [Some((16, 32)), Some((16, 16)), I, Some((8, 16))]), + (32, 16, [Some((32, 16)), I, Some((16, 16)), Some((16, 8))]), + ( + 32, + 32, + [ + Some((32, 32)), + Some((16, 32)), + Some((16, 16)), + Some((16, 8)), + ], + ), + (32, 64, [Some((32, 64)), Some((32, 32)), I, Some((16, 32))]), + (64, 32, [Some((64, 32)), I, Some((32, 32)), Some((32, 16))]), + ( + 64, + 64, + [ + Some((64, 64)), + Some((32, 64)), + Some((32, 32)), + Some((32, 16)), + ], + ), + ( + 64, + 128, + [Some((64, 128)), Some((64, 64)), I, Some((32, 64))], + ), + ( + 128, + 64, + [Some((128, 64)), I, Some((64, 64)), Some((64, 32))], + ), + ( + 128, + 128, + [ + Some((128, 128)), + Some((64, 128)), + Some((64, 64)), + Some((64, 32)), + ], + ), + (4, 16, [Some((4, 16)), Some((4, 8)), I, Some((4, 8))]), + (16, 4, [Some((16, 4)), I, Some((8, 4)), Some((8, 4))]), + (8, 32, [Some((8, 32)), Some((8, 16)), I, Some((4, 16))]), + (32, 8, [Some((32, 8)), I, Some((16, 8)), Some((16, 4))]), + (16, 64, [Some((16, 64)), Some((16, 32)), I, Some((8, 32))]), + (64, 16, [Some((64, 16)), I, Some((32, 16)), Some((32, 8))]), + ( + 128, + 256, + [ + Some((128, 256)), + Some((64, 256)), + Some((64, 128)), + Some((64, 64)), + ], + ), + ( + 256, + 128, + [ + Some((256, 128)), + Some((128, 256)), + Some((128, 64)), + Some((128, 64)), + ], + ), + ]; + for &(w, h, cells) in table { + for sx in 0..2usize { + for sy in 0..2usize { + let want_codable = cells[sx * 2 + sy].is_some(); + assert_eq!( + chroma_plane_block_codable(w, h, sx, sy), + want_codable, + "av1_ss_size_lookup[{w}x{h}][{sx}][{sy}] is {:?} in libaom \ + (common_data.c) but our predicate says the opposite", + cells[sx * 2 + sy] + ); + } + } + } + // The two cells an earlier, hand-picked predicate got wrong: both are + // LEGAL at 4:2:2, and libaom's own encoder emits the 16x4 one. + assert!( + chroma_plane_block_codable(16, 4, 1, 0), + "16x4 at 4:2:2 is BLOCK_8X4" + ); + assert!( + !chroma_plane_block_codable(32, 8, 0, 1), + "32x8 at 4:4:0 is BLOCK_INVALID" + ); + } /// lane-av1chrtx: [`covering_leaf_tx_type`] resolves a chroma unit's /// `tx_type` from the luma leaf covering the unit's OWN quadrant, and /// reports "no leaf there" as `None` so the caller can fall back to the @@ -58297,6 +59277,7 @@ mod tests { tile_y0: 0, tile_x1: width, tile_y1: height, + plane: 0, }; let mut u = PlaneBuf { data: std::borrow::Cow::Owned(vec![0u16; (width / 2) * (height / 2)]), @@ -58308,6 +59289,7 @@ mod tests { tile_y0: 0, tile_x1: width / 2, tile_y1: height / 2, + plane: 1, }; let mut v = PlaneBuf { data: std::borrow::Cow::Owned(vec![0u16; (width / 2) * (height / 2)]), @@ -58319,6 +59301,7 @@ mod tests { tile_y0: 0, tile_x1: width / 2, tile_y1: height / 2, + plane: 2, }; let mut cdfs = Cdfs::new(q_ctx_of(100)); diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 09e48fa1..87b5db5a 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -2829,40 +2829,92 @@ pub(crate) mod tests { ever reads (0,1), a 4:4:0 cell became codable and this whole gate is wrong about the \ format." ); - // lane-av1422lift: the refusal is gone, and the replacement is NOT - // "it decodes". This pin's TILE is a 4:2:0 key frame's, byte for - // byte -- only the sequence header carries 4:2:2 -- so it is a - // header/tile mismatch and there is no oracle that can say what the - // right pixels are. What IS assertable, and is what the pin is for, - // is that the SEQUENCE HEADER alone decides the decode's geometry: - // the decoded chroma planes are half-width and FULL height, exactly - // the `round_ss(w, 1) x round_ss(h, 0)` shape a real 4:2:2 stream - // produces (see `a_real_422_key_frame_and_inter_sequence_decode_ - // pixel_exact` for the pixel claim on genuine 4:2:2 bytes), and that - // the 4:2:2 chroma walk really ran on it. A decoder that still - // allocated 4:2:0 planes here would give 32x32 chroma and red. - let frames = decode_stream(&pinned).unwrap_or_else(|e| { - panic!("{NAME}: a (1,0) header must decode now that 4:2:2 is admitted: {e}") + // lane-av1unwritten: lane-av1422lift replaced the old 4:2:2 header + // refusal with "it decodes, and the decoded chroma planes are 32x64". + // That was the wrong contract for THIS pin: its frame OBU is a 4:2:0 + // key frame's, so at 4:2:2 its partition symbols name subsizes with no + // chroma plane block, which libaom rejects as a corrupt frame + // ("Block size 8x16 invalid with this subsampling mode", + // decodeframe.c:1456) and `aomdec` does. The replacement is the + // REFUSAL, by that rule. + // + // The pin's remaining job is unchanged and still worth saying: it + // proves a 4:4:0 REQUEST at profile 2 lands on 4:2:2 (1,0), i.e. that + // `the_440_cell_is_not_a_codable_chroma_shape`'s claim is still true. + let err = decode_stream(&pinned).err().unwrap_or_else(|| { + panic!( + "{NAME}: the pin is a 4:2:2 header over a 4:2:0 tile -- libaom refuses it \ + (aomdec: \"Block size 8x16 invalid with this subsampling mode\"), and so \ + must we" + ) }); - assert_eq!( - frames.len(), - 1, - "{NAME}: the pin must decode exactly one frame" + assert!( + err.to_string() + .contains("invalid with this subsampling mode"), + "{NAME}: the refusal must name libaom's rule, got: {err}" ); - assert_eq!( - (frames[0].u.len(), frames[0].v.len()), - (32 * 64, 32 * 64), - "{NAME}: 64x64 4:2:2 is HALF WIDTH and FULL HEIGHT (32x64 chroma); {:?} means the \ - plane geometry still came from the TILE's 4:2:0 shape rather than the HEADER's", - (frames[0].u.len(), frames[0].v.len()) + // The pixels this pin never had: the sibling gate + // `a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt` + // pins the refusal plus a genuine 4:2:2 positive control, and every + // real 4:2:2 exactness claim lives on genuinely 4:2:2 pins in this + // file. + } + + /// lane-av1unwritten: this pin is a MISSING REFUSAL, not a pixel defect. + /// + /// `440_request_is_422.obu` is a 4:2:2 sequence header wrapped around a + /// 4:2:0 key frame's tile, so the tile's partition symbols make subsizes + /// (8x16 among them) that have NO chroma plane block at ss (1,0). libaom + /// refuses exactly that, before descending into the subsize: + /// + /// ```text + /// $ aomdec --rawvideo -o /dev/null fixtures/440_request_is_422.obu + /// Warning: Failed to decode frame 1: Corrupt frame detected + /// Warning: Additional information: Block size 8x16 invalid with this subsampling mode + /// ``` + /// + /// (`av1/decoder/decodeframe.c:1449-1458`, + /// `get_plane_block_size(subsize, ss_x, ss_y) == BLOCK_INVALID` -> + /// `AOM_CODEC_CORRUPT_FRAME`.) We walked those subsizes instead, and the + /// first version of this lane misread the downstream symptom -- a chroma + /// plane block covered by a square unit, whole 4x4 blocks left unwritten, + /// and a `EC_AV1_FINAL_DUMP` hash that CHANGED RUN TO RUN because the + /// unwritten samples were uninitialised plane memory. + /// + /// The contract pinned here is the one libaom has: the pin REFUSES, by a + /// named error that says which shape and which subsampling mode. The + /// positive control is a genuinely 4:2:2 pin, which must still decode -- + /// so this gate cannot pass by refusing everything. + #[test] + fn a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt() { + const NAME: &str = "a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt"; + let _gate_lock = lock_gate_counters(); + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join("440_request_is_422.obu"); + let pinned = read_pin(&path, 2014, 0x98a1378df976253d, NAME); + let err = decode_stream(&pinned) + .err() + .unwrap_or_else(|| panic!("{NAME}: the pin must be REFUSED, not decoded")); + let msg = err.to_string(); + assert!( + msg.contains("invalid with this subsampling mode"), + "{NAME}: the refusal must name the rule it refuses by (libaom's own wording), got: \ + {msg}" ); + // Positive control: a real 4:2:2 stream must still decode, so the gate + // cannot pass by refusing everything. + let ok_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join("422_key_64x64.obu"); + let ok = decode_stream(&std::fs::read(&ok_path).expect("the 4:2:2 control fixture")) + .unwrap_or_else(|e| panic!("{NAME}: a genuine 4:2:2 pin must still decode: {e}")); assert!( - crate::decode::census_nonsub_units()[1] > 0 - && crate::decode::census_nonsub_units()[2] > 0, - "{NAME}: the pin walked zero 4:2:2 chroma coefficient units -- the per-axis walk never \ - ran on it" + !ok.is_empty(), + "{NAME}: the 4:2:2 control decoded no frames" ); } + /// lane-av1-422bigblock: the two witnessed 4:2:2 big-block defects, pinned /// as fixtures (`git add -f`; `fixtures/` is gitignored). /// diff --git a/lanes/av1unwritten.report.md b/lanes/av1unwritten.report.md new file mode 100644 index 00000000..b90ace20 --- /dev/null +++ b/lanes/av1unwritten.report.md @@ -0,0 +1,697 @@ +# lane/av1unwritten — a MISSING REFUSAL, not an unwritten chroma unit + +**Outcome in one line: `440_request_is_422.obu` is a 4:2:2 sequence header over a +4:2:0 tile, so its partition symbols name subsizes (8x16 among them) with NO +chroma plane block at ss (1,0) — libaom calls that `AOM_CODEC_CORRUPT_FRAME` +("Block size 8x16 invalid with this subsampling mode") and `aomdec` refuses the +file outright, and libaom's own encoder never emits such a shape; we walked those +subsizes anyway, and our output for that witness depends on unwritten plane +content. The fix mirrors libaom's check and returns a named refusal; the sentinel +census that led here is kept as the instrument.** + +Branch `lane/av1unwritten`, base `main` = `8d6998d7`. No push. + +> **r3 correction, on top of r2.** The r2 predicate was a four-cell hand-picked +> `match`, and it was wrong in BOTH directions. It refused `(16, 4)` at ss (1,0), +> where `av1_ss_size_lookup[BLOCK_16X4][1][0]` is `BLOCK_8X4` — a LEGAL 4:2:2 +> shape, and one libaom's own encoder emits (`partition_search.c:3383-3389` +> gates `partition_rect_allowed[HORZ]` with this very table), so we were refusing +> a stream aomenc produces. And it covered only two of the eight shapes libaom +> refuses at 4:2:2. r3 replaces the `match` with a verbatim transcription of +> the table's `BLOCK_INVALID` cells (§3.1) and adds +> `chroma_plane_block_codable_matches_the_libaom_table`, which re-writes all 22 +> rows x 4 subsampling pairs from `common_data.c:17-41` and checks the predicate +> cell for cell. The corpus sweep CANNOT see the false positive — no committed +> fixture carries a 16x8 block split `PARTITION_HORZ` at 4:2:2 — and that table +> test is what covers that direction. +> +> **r5, on top of r4.** Main: "a found defect is swept whole, not partly." +> r4 guarded only the plain `VERT` arm at four sites and named six more. r5 +> makes every guard UNCONDITIONAL on the resolved symbol — because +> `partition_subsize_dims` is exact, passing the symbol covers `VERT`, +> `VERT_A`/`VERT_B`, `HORZ_4` and `VERT_4` in one call, and the HORZ siblings +> pass through — and adds the three inter-frame duplicates plus the 64x64 key-frame +> level that binds its symbol to `part` rather than `part64`. One intermediate +> attempt inserted `refuse_invalid_subsize(..., PARTITION_VERT_4, ...)` INSIDE a +> `PARTITION_HORZ_4 | PARTITION_VERT_4 =>` arm, which fired for HORZ_4 too and +> refused nine real 4:2:2 gates; the unconditional form is what shipped. +> +> **r4, on top of r3.** Main: "a found defect is swept whole, not partly." +> r3 named the six remaining sites instead of installing them. r4 installs four +> of them, via a helper that takes the PARTITION SYMBOL and maps it to its +> subsize dimensions (`partition_subsize_dims`, spec 6.10.3 +> `get_partition_subsize`) so the check can never be applied to a parent's own +> shape -- the r2 mistake in a new place. The sites, their subsize, the cell +> they guard, and the SIBLING that must keep decoding are in §3.2. Two are still +> open and named (the inter-frame duplicate of the 64-level match, and the +> `decode_rect4_16_intrabc` exception, which is another lane's charter). +> +> **This report was rewritten once before. The first version of this lane claimed a libaom +> `TX_4X8` chroma unit for a `BLOCK_4X8` subsize and landed a port of it. The +> refutation pass (Agent03-5, verified first-hand by Main) showed that port does +> not exist: `get_plane_block_size` is a single indexed return +> (`av1_ss_size_lookup[bsize][ss_x][ss_y]`, `blockd.h:1186-1193`), BLOCK_4X8 at +> ss (1,0) is `BLOCK_INVALID`, and libaom never reaches +> `max_txsize_rect_lookup` for that shape because it refuses the frame first. +> The `TX_4X8` arm, its chroma-extent derivation and its gate are all GONE; what +> follows is the corrected lane. The corrected findings are in §1–§2 and the +> correction itself is recorded here rather than quietly edited in. + +--- + +## 1. The oracle decides this, not our reasoning + +``` +$ ~/.cache/aom-oracle/build/aomdec --rawvideo -o /dev/null \ + crates/ec-av1/fixtures/440_request_is_422.obu +Warning: Failed to decode frame 1: Corrupt frame detected +Warning: Additional information: Block size 8x16 invalid with this subsampling mode +``` + +We decoded it. That is the defect. + +`av1/decoder/decodeframe.c:1449-1458`, in `decode_partition`, before it descends +into any subsize: + +```c +const struct macroblockd_plane *const pd_u = &xd->plane[1]; +if (get_plane_block_size(subsize, pd_u->subsampling_x, pd_u->subsampling_y) == + BLOCK_INVALID) { + xd->mi_row = mi_row; + aom_internal_error(xd->error_info, AOM_CODEC_CORRUPT_FRAME, + "Block size %dx%d invalid with this subsampling mode", + block_size_wide[subsize], block_size_high[subsize]); +} +``` + +`get_plane_block_size` (`blockd.h:1186-1193`) is a **single indexed return**, +`av1_ss_size_lookup[bsize][subsampling_x][subsampling_y]` — no per-axis MIN. The +`BLOCK_INVALID` cells in that table (`common_data.c:20-26`) are: + +| subsize | ss (0,0) 4:4:4 | ss (0,1) | ss (1,0) 4:2:2 | ss (1,1) 4:2:0 | +|---|---|---|---|---| +| 4x8 | 4x8 | 4x4 | **INVALID** | 4x4 | +| 8x4 | 8x4 | **INVALID** | 4x4 | 4x4 | +| 8x16 | 8x16 | 8x8 | **INVALID** | 4x8 | +| 16x4 | 16x4 | **INVALID** | 8x8 | 4x4 | + +So at 4:2:2 a **4x8, 8x16 or 16x4** subsize is not decodable at all. It is not a +"the chroma unit is 4x8" case: libaom never computes a transform size for it. +(The earlier `8x16` in the oracle's message is the first such subsize the +witness's 4:2:0 tile presents; 4x8 and 16x4 are in the same class.) + +`PARTITION_HORZ` on an 8x8 is `subsize_lookup[HORZ][BLOCK_8X8] = BLOCK_8X4`, +whose 4:2:2 plane block is BLOCK_4X4 — the square unit, which is why the +`(4, 8)` chroma path itself was never wrong. `BLOCK_4X8` leaves come from +`PARTITION_VERT`, i.e. from `decode_leaf_rect8(vert = true)`, and that subsize is +exactly one of the four libaom refuses. + +--- + +## 2. What led here, and what it is worth + +### 2.1 The observation (on `8d6998d7`, by two independent builds) + +``` +$ mkdir -p /tmp/wt_aw/same # the dump writes NOTHING if the directory + # does not exist -- create it first +$ for i in 1 2 3 4 5; do EC_AV1_FINAL_DUMP=/tmp/wt_aw/same/x \ + ./target/debug/examples/decode_probe crates/ec-av1/fixtures/440_request_is_422.obu \ + >/dev/null 2>&1; sha256sum /tmp/wt_aw/same/x.f0; done +727ea647b2362b22520de232c2f6a0ce541dbfa90f02495f572af4aa2297116d +ba2957e1709507b8336e53cd908b7dfe2a59dc2064b1f5eb4bea9b3149a4653d +2e245bcc6abb2ef81e80254711fe042cadd3409c622faa46b9ee393dd14ffa96 +``` + +Two distinct output hashes from one file with uninitialised planes; and with +`EC_AV1_PLANE_SENTINEL=1` five runs give ONE hash, and that hash differs from the +plain one -- both dumps are 8192 bytes, and the sentinel dump carries 65 bytes +equal to `0xAD` against a 33-byte baseline in the plain dump. (An earlier draft of +this line said "differs by 1984 bytes"; that byte count does not reproduce, and the +`0xAD` counts are the correct form. A per-byte diff of the two dumps is not +stable, because one sentinel sample propagates through the loop filters into its +neighbours -- which is itself the reason the dependence matters.) Reproduced +independently on a fresh `8d6998d7` worktree with +its own target dir (Main: `d35d59cce59cfa2b` / `5b38d5079a6578a8` plain, +`3a2ae6dbec390f26` sentinel x5). + +**Provenance note, because it nearly inverted this section.** The first +counter-measurement said main was deterministic; that reading came from a binary +whose embedded source paths pointed at THIS worktree, not at main -- the +stale-binary class. Provenance has to come from the binary's own strings, not +from what `cargo build` last reported. With a path-verified build the +nondeterminism is real, and this is the observation that started the lane. + +**Byte width matters for the census.** `EC_AV1_FINAL_DUMP` writes **u8** for an +8-bit stream, so `PLANE_SENTINEL = 0xDEAD` narrows to the single byte `0xAD`: +65 such bytes in a sentinel dump against a 33 baseline in a plain one. Counting +a two-byte `0xDEAD` in an 8-bit dump cannot find it. + +### 2.2 The census, on this lane's tree + +`census_unwritten` at each frame's pre-deblock point, on the lane tree at r1: +**112 unwritten samples per chroma plane, 224 total**, in whole 4x4 chroma +blocks, each the lower half of a plane block whose luma subsize is one §1 says +is not decodable. That number is a lane-tree measurement with a lane-only +instrument and is cited as such; the fix does not rest on it. + +### 2.3 Why refusing is the right contract + +Neither of these is this lane's pixel measurement: + +1. **libaom refuses the shape.** `aomdec --rawvideo` on the pin prints + `Failed to decode frame 1: Corrupt frame detected` / `Block size 8x16 invalid + with this subsampling mode` (`decodeframe.c:1449-1458`). +2. **libaom's encoder never emits it.** `partition_search.c:3383-3389` gates + `partition_rect_allowed` on this same table, so no conformant 4:2:2 stream + can contain the shape and the refusal cannot reject legal content. + +§2.1 explains why anyone looked; §2.3 is why the fix is right. + +The instrument is **kept**: env-gated, off by default, and the only way to ask +"did the tile walk write every sample it was handed" (a wrong-sample diff cannot +tell an unwritten sample from a mis-predicted one). + +## 3. The fix + +`crates/ec-av1/src/decode.rs`: + +* `chroma_plane_block_codable(bw, bh, ss_x, ss_y)` — a verbatim transcription + of `av1_ss_size_lookup`'s `BLOCK_INVALID` cells, in two const lists so a + reader can diff them against `common_data.c` line by line: + + | subsampling | INVALID luma shapes | + |---|---| + | 4:2:2 `(1,0)` | 4x8, 8x16, 16x32, 32x64, 64x128, 4x16, 8x32, 16x64 | + | 4:4:0 `(0,1)` | 8x4, 16x8, 32x16, 64x32, 128x64, 16x4, 32x8, 64x16 | + | 4:4:4 `(0,0)`, 4:2:0 `(1,1)` | none | + + Checked by `chroma_plane_block_codable_matches_the_libaom_table`, which + transcribes all 22 rows x 4 pairs literally from `common_data.c:17-41`. +* `refuse_invalid_plane_block(...)` — a **returned** error (never an + `assert!`: a partition symbol is stream data, so hostile bytes reach it), + carrying libaom's own wording so the message names the rule: + `"... has no chroma plane block at this frame's subsampling mode (libaom: + \"Block size %dx%d invalid with this subsampling mode\", + av1/decoder/decodeframe.c:1456, refusing by the same rule)"`. +* Installed at every place a partition symbol is turned into a **strip** subsize + with a chroma plane block: + * `partition_w8` → `PARTITION_HORZ` = 8x4, `PARTITION_VERT` = 4x8 + (`subsize_lookup[PARTITION_*][BLOCK_8X8]`); + * `partition_w16` → `PARTITION_HORZ` = 16x8, `PARTITION_VERT` = 8x16. + +``` +$ ./target/debug/examples/decode_probe crates/ec-av1/fixtures/440_request_is_422.obu 2>&1 | head -4 +TILING: 1 frame headers parsed +SEQ: use_128x128_superblock=true bit_depth=8 mono_chrome=false max_frame=64x64 +TILING: cols=1 rows=1 uniform_spacing=true context_update_tile_id=0 +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 (libaom: "Block size %dx%d invalid with this +subsampling mode", av1/decoder/decodeframe.c:1456, refusing by the same rule)) +``` + +Same refusal class as the oracle, same rule, same shape named. + +### 3.3 The r5 site table + +Every site below is guarded UNCONDITIONALLY: the symbol is passed to +`refuse_invalid_subsize`, and because `partition_subsize_dims` is exact, every +arm of the dispatch is covered at once — `VERT`, `VERT_A`/`VERT_B`, `HORZ_4` and +`VERT_4` — while the HORZ siblings pass through. That replaced r4's narrower +`matches!(sym, PARTITION_VERT)` guards, which covered only the plain `VERT` arm. + +| site (key frame unless noted) | subsize it can select | guarded cell | sibling that must keep decoding | +|---|---|---|---| +| 128 root, `match part128` | `VERT`/`VERT_A`/`VERT_B` -> 64x128 | `(1,0)` INVALID | `HORZ`/`HORZ_A`/`HORZ_B` -> 128x64, `(1,0)` = 64x64 valid | +| 64 level, `match part` (symbol bound to `part`) | `VERT`/`VERT_A`/`VERT_B` -> 32x64; `VERT_4` -> 16x64 | `(1,0)` INVALID | `HORZ*` -> 64x32 `(1,0)` = 32x32 valid; `HORZ_4` -> 64x16 `(1,0)` = 32x16 valid | +| 32 level, `match part32` | `VERT*` -> 16x32; `VERT_4` -> 8x32 | `(1,0)` INVALID | `HORZ*` -> 32x16 `(1,0)` = 16x16 valid; `HORZ_4` -> 32x8 `(1,0)` = 16x8 valid | +| 16x16 level, `match part16` | `VERT_4` -> 4x16 | `(1,0)` INVALID | `HORZ_4` -> 16x4, `(1,0)` = **8x4 valid** — the shape r2 refused | +| 8 level, `partition_w8` arms (r3) | `VERT` -> 4x8 | `(1,0)` INVALID | `HORZ` -> 8x4, `(1,0)` = 4x4 valid | +| **inter** 128 root, `match part128` | 64x128 | `(1,0)` INVALID | as key | +| **inter** 64 level, `match part64` | 32x64; `VERT_4` -> 16x64 | `(1,0)` INVALID | as key | +| **inter** 32 level, `match part32` | 16x32; `VERT_4` -> 8x32 | `(1,0)` INVALID | as key | +| **inter** 16x16 level, `match part16` | 4x16 | `(1,0)` INVALID | `HORZ_4` -> 16x4 valid | + +`decode_rect4_16_intrabc` remains the declared exception (another lane's +charter). The 8x16 / 16x8 `VERT_4` case is covered by the level-16 guard, whose +symbol is the same `PARTITION_VERT_4`; the shape it selects is the four-way child +`4x16` at that level, not the `16x4` r2 wrongly refused. + +**Still open:** none of the four items in r5's list. Each is a one-line call +behind the existing helper and all four landed. + +### 3.2 The r4 site table + +| site | subsize it can select | cell it guards | sibling that must keep decoding | +|---|---|---|---| +| 128 root, `PARTITION_VERT` (`decode.rs`, `match part128`) | 64x128 | `(1,0)` INVALID | `PARTITION_HORZ` -> 128x64, `(1,0)` = 64x64 valid | +| 64-level, `PARTITION_VERT` (`match part64`) | 32x64 | `(1,0)` INVALID | `PARTITION_HORZ` -> 64x32, `(1,0)` = 32x32 valid | +| 32-level, `PARTITION_VERT` (`match part32`) | 16x32 | `(1,0)` INVALID | `PARTITION_HORZ` -> 32x16, `(1,0)` = 16x16 valid | +| 16x16-level, `PARTITION_VERT_4` (`match part16`) | 4x16 | `(1,0)` INVALID | `PARTITION_HORZ_4` -> 16x4, `(1,0)` = 8x4 **valid** -- the exact shape r2 refused, and the one libaom's encoder emits | +| 16-level, `PARTITION_HORZ`/`VERT` | 16x8 / 8x16 | 8x16 `(1,0)` INVALID | `PARTITION_HORZ` -> 16x8, `(1,0)` = 8x8 valid | +| 8-level, `PARTITION_HORZ`/`VERT` | 8x4 / 4x8 | 4x8 `(1,0)` INVALID | `PARTITION_HORZ` -> 8x4, `(1,0)` = 4x4 valid | + +The sibling column is the r2 lesson turned into a rule: at every site the +opposite-axis branch of the SAME dispatch must keep decoding, and the table test +plus these guards are what prove it. `decode_rect4_16_intrabc` is the declared +exception (another lane's charter). + +### 3.1 Sites found, and the ones proven not to need it + +| site | subsizes it can produce | needs the check? | +|---|---|---| +| `partition_w8` (2 sites, 36549 / 36767 region) | 8x4, 4x8 | **yes**, installed | +| `partition_w16` intra (36175 region) | 16x8, 8x16 | **yes**, installed | +| `partition_w16` edge split (`VERT_ALIKE`/`HORZ_ALIKE` gather) | same two, reached only when `has_cols16`/`has_rows16` is false | covered by the same rule at the sibling site; the edge arm's two-symbol gather can only choose SPLIT vs the matching strip | +| `PARTITION_VERT_4` at the 16x16 level | 4x16 — INVALID at 4:2:2 | **yes, r4, installed** | +| `partition_w32` `PARTITION_VERT` | 16x32 — INVALID at 4:2:2 | **yes, r4, installed** | +| `partition_w64` `PARTITION_VERT` | 32x64 — INVALID at 4:2:2 | **yes, r4, installed** | +| 128 root `PARTITION_VERT` | 64x128 — INVALID at 4:2:2 | **yes, r4, installed** | +| the four-way vertical splits (`VERT_A` / `VERT_B`) at 16/32/64 | 8x32, 16x64 — both INVALID at 4:2:2 | **still open, named** | +| `VERT_4` on 8x16 / 16x8 (`decode_rect_split`) | 8x32 — INVALID at 4:2:2 | **still open, named** | +| the inter-frame duplicate of the 64-level match | 32x64 | **still open, named** | +| `decode_rect4_16_intrabc` | 4x16 / 8x32 | **out of scope** — another lane's charter | +| 32/64/128 roots' OWN plane blocks, the AB partitions, `PARTITION_SPLIT` | BLOCK_32X32 (16X32), BLOCK_64X64 (32X32), BLOCK_128X128 (64X64), all valid | no — a PARENT row being valid says nothing about its children, which is exactly what r2 got wrong; the child rows are the four rows above | +| 4:4:4 square leaves, `decode_leaf8`, `decode_leaf_split4` | BLOCK_4X4 / BLOCK_8X8 / BLOCK_16X16 | no: `(0,0)` column is non-INVALID for all of them | + +So r3 installs the check at two sites and NAMES the other six rather than +claiming them covered. The predicate is now correct for every shape, so each +remaining site is a one-line call at a dispatch that is already written; none of +them is reachable by a committed fixture (§4 shows the corpus cannot see even +the false-positive direction), which is why they are a declared gap and not a +claim. + +The 1:4 sites were already the honest gap: `PARTITION_HORZ_4` on an 8x16 yields a 4x16, +whose 4:2:2 plane block is `BLOCK_INVALID`, and this lane did not install the +check there. `decode_rect4_16_intrabc` is on another lane's charter and was not +touched; the neighbouring non-intrabc `decode_rect4_16_strip` site is where the +next step belongs. No committed fixture reaches it (see §4), and the census +instrument is what would show it if one ever did. + +--- + +## 4. Regression evidence + +* **Corpus, both trees.** Every fixture decoded with `EC_AV1_FINAL_DUMP`, every + `.f*` hashed. Pre-fix vs post-fix the **126 valid fixtures are byte-identical** + and **none newly refuses**; the witness is the only difference and it now + refuses. Re-run on the r6 predicate (guards relocated): `differing: + ['440_request_is_422']`, 126 fixtures emitting dumps, and exactly one fixture + whose output contains `REFUSED` — the witness. **The sweep cannot see the + (16,4)-at-4:2:2 false positive**: no committed fixture carries a 16x8 block + split `PARTITION_HORZ` at 4:2:2, which is why r2's over-refusal passed 126/126 + unnoticed. That direction is covered by + `chroma_plane_block_codable_matches_the_libaom_table`, not by the sweep. +* **Sentinel sweep** (127 fixtures, `EC_AV1_PLANE_SENTINEL=1`): pre-fix exactly + one fixture had a non-empty census (the witness, 112+112); post-fix the census + is empty on all 127 — the witness decodes nothing at all now, and the other 126 + are unchanged. **This is NOT a corpus-wide claim that no fixture's output + depends on unwritten plane memory.** The census is a PRE-DEBLOCK scan of the + three planes, so it cannot see a dependence produced at a later stage or in a + region it does not cover. Measured on `8d6998d7` with a provenance-verified + probe (Main, after r5), a sentinel-vs-plain output diff finds at least two + further fixtures whose output DOES depend on unwritten content — + `reelb_rect64_intra16x4_witness.obu` (34 frames) and `reelb_arf_witness.obu` (40 + frames) — both of which this census calls clean. One of the two instruments has + a blind spot; `Agent01-9` owns finding which (`lane/unwritten-dep`). Every number + above is this lane's own tree and instrument. +* **Scoped tests.** `cargo test -p ec-av1 --features gate-counters --lib -- 422 + 440 chroma422` → 15 passed (including six real-4:2:2 byte-exact gates: + `a_real_422_key_frame_and_inter_sequence_decode_pixel_exact`, + `a_real_422_12bit_and_superres_stream_decode_pixel_exact`, + `a_real_422_film_grain_stream_decodes_pixel_exact`, + `the_pinned_422_palette_intra_in_inter_cell_window_is_byte_exact`, + `the_pinned_422_lossless_inter_witnesses_decode_pixel_exact`, + `the_pinned_422_bigblock_witnesses_decode_pixel_exact`); + `-- sub8 decode::tests` → 53 passed. The 15-test set also covers the + pre-existing `the_440_cell_is_not_a_codable_chroma_shape`, whose tail arm + lane-av1422lift had amended to "the pin decodes"; that arm is now the refusal + assertion above and the rest of the gate (the 4:4:0-request-lands-on-4:2:2 + claim) is untouched. + `-- sub8 picalloc sentinel` → 13 passed; `-- decode::tests` → 40 passed. + +--- + +## 5. The gate + +`crates/ec-av1/src/stream.rs`, +`a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt`: + +1. pins `440_request_is_422.obu` through the existing `read_pin` (2014 bytes, + fnv1a64 `0x98a1378df976253d`); +2. asserts the decode is an **error**, and that the message contains libaom's + own `"invalid with this subsampling mode"` — so a gate cannot pass on any + other refusal; +3. **positive control**: `422_key_64x64.obu`, a genuine 4:2:2 pin, must still + decode to at least one frame — the gate cannot pass by refusing everything. + +``` +$ cargo test -p ec-av1 --features gate-counters --lib -- refuses_the_subsize +test stream::tests::a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt ... ok +test result: ok. 1 passed; 0 failed; ... +``` + +**The pin.** The witness no longer produces output at all — it refuses, which is +the contract libaom has (§2.3). §2.1 records the observation that made the +stream worth looking at (varying output with uninitialised planes, one hash +under the sentinel); it is reported, not gated, because the gate's job is the +contract and the contract is the refusal. The determinism is then a consequence +of the refusal, not a second assertion. + +**Mutation.** Deleting any one `refuse_invalid_subsize` call the witness passes +through (the 128 root's, the key 64's, ...) puts the witness back to +`OK: 1 frames decoded` and the gate's `unwrap_or_else` panics +with "the pin must be REFUSED, not decoded"; replacing the message text so it no +longer contains libaom's wording reds the second assertion; pointing the positive +control at the witness reds the third. + +--- + +## 6. What this lane did not do + +* The `PARTITION_HORZ_4` / `VERT_4` 1:4 subsize sites (4x16 / 16x4) are not + checked — §3.1 names them and where the next step belongs. No committed + fixture reaches them. +* No pixel claim is made or unmade for the witness: it is not a decodable 4:2:2 + stream and `aomdec` says so. +* `film_grain.rs`, the reserved 4:2:0 group-tail chroma SKIP arm and + `decode_rect4_16_intrabc` untouched — the cause is not in them. + +--- + +## 7. Traps this lane paid for + +* **`EC_AV1_FINAL_DUMP` writes NOTHING when the prefix's directory does not + exist** — silence, not an error, so a run that "produced no dump" reads as a + decode that produced no frame. Create the directory first. This cost a + measurement round here and one for Main. +* **At 8-bit the dump is u8, so `PLANE_SENTINEL = 0xDEAD` survives only as the + single byte `0xAD`.** Counting a two-byte `0xDEAD` in an 8-bit dump cannot find + it (65 such bytes against a 33 baseline is what a sentinel dump actually + carries here). Use a 0xAD count at 8-bit, or a 10-bit fixture where the dump is + u16 LE. +* **A binary's provenance comes from its own embedded source paths**, not from + what `cargo build` last reported. A probe built from this worktree was read as + a measurement of `main` here and inverted a whole section of the report until + `strings` was checked. + +--- + +## 8. r6 — the guards were not where the values are decided + +**r5 claimed complete coverage and did not have it.** The refutation pass +(Agent03-5) showed that three of the eight `refuse_invalid_subsize` calls sat +**inside `PARTITION_HORZ_A..=PARTITION_VERT_B` arms**, so they could only ever +observe partition values 4..=7 — and the arms that DO see the offending values +had no guard above them: + +| unguarded arm | value | subsize | corpus hits | +|---|---|---|---| +| kf 16-level `decode_rect4_16` | `part16 = 9` (VERT_4) | `BLOCK_4X16` | 538 | +| inter 64-level rect / 1:4 arm | `part64 = 2` (VERT) | `BLOCK_32X64` | 887 | +| inter 64-level rect / 1:4 arm | `part64 = 9` (VERT_4) | `BLOCK_16X64` | 280 | +| inter `w8` arm | `part8 = 2` (VERT) | `BLOCK_4X8` | 3476 | + +All four are `BLOCK_INVALID` at `av1_ss_size_lookup[..][1][0]` — exactly what +libaom refuses at `decodeframe.c:1451-1460`. + +### 8.1 The fix + +Every guard now sits where the partition symbol is **RESOLVED**, before any +dispatch arm — one guard per level per path, so it can see every value that level +produces: + +| site | level | values seen (corpus scan) | +|---|---|---| +| `decode.rs:35584` kf 128 root | 128x128 | 0,1,2,3 | +| `decode.rs:36274` kf 64 | 64x64 | 0,1,2,3,4,5,6,7,8,9 | +| `decode.rs:36402` kf 32 | 32x32 | 0,1,2,3,4,5,6,7,8,9 | +| `decode.rs:36468` kf 16 | 16x16 | 0,1,2,3,4,5,6,7,8,9 — **part=7 FIRED 68x** | +| `decode.rs:54140` inter 64 | 64x64 | 0,1,2,3,4,5,7,8,9 | +| `decode.rs:54576` inter 32 | 32x32 | 0,1,2,3,4,5,6,7,8,9 | +| `decode.rs:55125` inter 8 | 8x8 | 0,1,2,3 | + +The only guard that fires over the corpus is the key-frame 16-level one, on +`PARTITION_VERT_B` (subsize `BLOCK_8X16`, INVALID at 4:2:2) — 68 times, in +`reelb_*`-class streams. Every other corpus stream is 4:2:0 / 4:4:4, where the same +values are legal, so "passed" is the correct reading and **the sweep is what +proves the legal siblings still decode**. + +### 8.2 The coverage artefact (this is what made the failure visible) + +Two env-gated scans, both printed by `decode_probe` and both committed, because +prose about coverage is not evidence of coverage: + +* `EC_AV1_SUBSIZE_GUARD_TRACE=1` — per **guard call site**, per partition value: + times reached and whether the guard fired. A site that never sees an offending + value is then visible instead of assumed covered. That is exactly the defect + r5 shipped: three sites whose reachable value set was 4..=7 only. +* `EC_AV1_SUBSIZE_ARM_TRACE=1` — per **unguarded dispatch arm**, which partition + values actually reach it and whether their subsize is codable at this frame's + subsampling. + +Both are off by default and cost nothing when unset. + +``` +$ for f in crates/ec-av1/fixtures/*.obu; do EC_AV1_SUBSIZE_GUARD_TRACE=1 EC_AV1_SUBSIZE_ARM_TRACE=1 ./target/debug/examples/decode_probe "$f" 2>&1 >/dev/null | grep -E '^SUBSIZE_(GUARD|ARM)'; done > /tmp/gt.txt +$ wc -l /tmp/gt.txt +2346 /tmp/gt.txt +``` + +### 8.3 Residue + +* **`decode_rect4_16_intrabc` is the declared exception and was NOT audited.** It + is another lane's charter. Everything above covers the intra and inter paths + this lane owns. +* No other subsize-selecting dispatch lacks a guard above it: the arm scan finds + no dispatch reached with a non-codable subsize and no `refuse_invalid_subsize` + call between it and the symbol's resolution. + +--- + +## 9. r7 — two more gaps, and the structural change that stops the third + +r6 was also partial. The refutation found two surviving holes and named the +pattern that kept producing them. + +**Gap 1 — inter 64 edge arm.** r6's guard sat inside the `(true, true)` arm of +`let part64 = match (has_cols, has_rows)`. The edge arms return without passing +it, and `(false, true)` resolves to `PARTITION_VERT`, which at a 64x64 root +selects `BLOCK_32X64` — INVALID at (1,0). Measured: `inter64_rect` is reached with +`part64=2, has_cols=false, has_rows=true` **50 times corpus-wide and 0 times in +any 4:2:2 cell**, so the corpus cannot see it. Fixed by hoisting one +`refuse_invalid_subsize((64, 64), part64, fctx)?` to just after the `match` closes. + +**Gap 2 — the inter-frame 16x16 level had no guard at all.** r6 deleted r5's +misplaced one without replacing it, and all three dispatch arms there (NONE/HORZ/ +VERT, the four AB arms, and the 1:4 arms) select `BLOCK_8X16` and `BLOCK_4X16` — +two more of the eight (1,0)-INVALID shapes. Fixed by adding the guard where the +inter-16 symbol is resolved, before any arm. + +### 9.1 The structural change (this is the part that matters) + +Both r5 and r6 failures had the same shape: **a guard existed somewhere and +nothing said it sat between a symbol's resolution and every dispatch of it.** A +hand-maintained site list cannot fix that — it is a list, and lists drift. So the +invariant is now stated over the dispatch structure itself: + +`every_partition_symbol_resolution_is_guarded_before_it_dispatches` scans +`decode.rs` for every binding of the form `let = dec.symbol(...partition_w[...])` +— the resolutions, derived from the code, not from memory — and asserts each is +followed by a `refuse_invalid_subsize((N, N), …)` for its own level. It also +asserts the r5 defect cannot come back: **no `refuse_invalid_subsize` call may +sit inside a `PARTITION_HORZ_A..=PARTITION_VERT_B` arm** (values 4..=7 only; the +offending values are 2 and 9), tracked by indentation. + +Mutation, to show it bites: + +``` +$ # delete the inter-16 guard +panicked: part16 (decode.rs:54671) resolves a 16x16 partition symbol with NO +refuse_invalid_subsize((16, 16)) anywhere after it -- a subsize libaom refuses +can walk straight through (r6 shipped exactly this on the inter-frame 16x16 level) +``` + +This is why `EC_AV1_SUBSIZE_ARM_TRACE` hand-listing three arms was not enough: +its site list was itself a hand-maintained list, and r6's "no unguarded arm" +reading was a limit of the instrument. The scan above cannot have a hole of that +kind — a new level appears as a new binding and the test fails until it is +guarded. + +### 9.2 Residue, corrected + +**At least three sites, not one.** `decode_rect4_16_intrabc` is **not** the only +exception any more, and the earlier "still open: none" was wrong: + +| residue | status | +|---|---| +| inter-64 edge arm (`part64=2` via `(false, true)`) | **fixed in r7** | +| inter-16 level's two shapes (`BLOCK_8X16`, `BLOCK_4X16`) | **fixed in r7** | +| `decode_rect4_16_intrabc` | **out of scope and NOT audited** — another lane's charter | + +Beyond those, the structural scan reports every `partition_w*` resolution in the +file guarded at its own level, so no further subsize-selecting dispatch in the +paths this lane owns lacks a guard above it. That is a statement about the +`partition_w*` resolutions; a dispatch that selects a subsize WITHOUT reading a +`partition_w*` symbol would not be caught by it, and I did not find one, but I am +not claiming the scan proves none exists. + +--- + +## 10. r8 — the test claimed more than it proved + +Maine's r7 read found three honesty gaps in the structural gate. All three were +in what the test SAID, not what the decode does; none changed a decode path. + +1. **"BEFORE the first dispatch on the variable" was in the comment only.** r7 + checked that a guard for the level appears somewhere in the next 220 lines. + r8 IMPLEMENTS the bound: where the window contains a `match part…` dispatch, + the guard must precede it. +2. **The binding pattern was formatting-sensitive and failed silently.** A + resolution whose `dec.symbol(` is wrapped onto the next line used to vanish + from the list with nothing red. r8 reads the level and the symbol read from a + two-line window, so a wrapped site resolves instead of disappearing, and the + remaining cross-check is over **levels**, which a reformat cannot lose: every + `partition_w[` in the file must appear among the resolutions found. +3. **`var` was parsed as the text BEFORE `let `**, so it was always empty and the + diagnostic read `(decode.rs:1234) resolves…` with no name — exactly where the + name matters. r8 takes the token after `let `. + +### 10.1 Coverage, stated so a reader can tell it from a floor + +**Today: 10 partition-symbol resolutions, 13 `refuse_invalid_subsize((` +occurrences**, of which 9 are guards at 9 resolutions and the rest are the +function definition, its doc comment and this test's own example strings. + +What is asserted, exactly: + +* every `partition_w[` level in the file appears among the resolutions found — + a new level cannot be added without a guard check; +* each resolution is followed, within 220 lines, by a + `refuse_invalid_subsize((N, N), …)` for its own level, matched on the LEVEL + rather than the variable (the symbol is often bound to a short-lived `p` and + dispatched by an outer `part64`); +* where that window contains a `match part…` dispatch, the guard precedes it; +* no guard sits inside a `PARTITION_HORZ_A..=PARTITION_VERT_B` arm. + +What is NOT claimed: the test does not prove a guard is at the exact dispatch +point — the window is a window. That limit is why the AB-arm invariant is a +separate assertion and why `EC_AV1_SUBSIZE_GUARD_TRACE` records what each site +really sees over the corpus. + +Two mutations, both red: + +``` +$ # delete the inter-16 guard +part16 (decode.rs:36465) resolves a 16x16 partition symbol with NO +refuse_invalid_subsize((16, 16)) within 220 lines after it + +$ # move the inter-64 guard inside a PARTITION_HORZ_A..=PARTITION_VERT_B arm +p (decode.rs:54137) resolves a 64x64 partition symbol with NO +refuse_invalid_subsize((64, 64)) within 220 lines after it +``` + +--- + +## 11. r9 — a real residue site, and a checker that was weaker than its comment + +The third pass confirmed r7's decode path (all 9 guard sites top-level, seeing +every value; the corpus census reproducing exactly; all 20 genuine 4:2:2 fixtures +decoding). The FAIL was in the checker plus one real residue. + +### 11.1 The residue: a second key-frame 8x8 resolution, unguarded + +`decode.rs:37115` is a key-frame `partition_w8` resolution dispatching +`decode_leaf_rect8` on a raw `part8` with no `refuse_invalid_subsize` anywhere +after it — `BLOCK_4X8` at 4:2:2, the shape r5 and r6 each flagged. Guarded. The +fixed scan then immediately found a **second** one at `36876`, which no earlier +round had seen. Both are residue rather than live pixels: neither is corpus- +reachable at ss (1,0) today. Guarded anyway. + +### 11.2 Three checker gaps, all closed + +1. **The scan's window started AT the `partition_w` line**, so a binding whose + `let` is on the line above was dropped — which is exactly why `37115` was + invisible. r9 searches the line BEFORE as well. +2. **The level cross-check was per-level PRESENCE**, so a second unguarded site + at an already covered level passed — which is how `37115` survived with level 8 + covered by the inter-8 site. r9 keeps presence as presence and says so, and + adds the exact guard-vs-resolution count. +3. **`sites.len() >= 9` was a floor the tree already satisfied with 10.** Replaced + with a count derived from the scan: the decode body has **11 guard sites** and + the scan finds **10 resolutions** — the eleventh guard is the inter-frame 128 + one at `53985`, whose resolution lives in the shared `read_sb128_root` and so + has no resolution of its own here. That is exactly the redundancy the `>=` + exists to allow, so the counts are reported as 11 guards against 10 + resolutions and the reason is named. + +Plus the one the refutation demonstrated green: the AB-arm tracker **self-cleared +on the `{` line**, because that line carries the same indent as the `if` — moving +the kf-32 guard back inside an arm stayed GREEN. r9 arms at the condition, +*enters* the body one level deeper, and clears only after having been inside it. +That mutation now reds: + +``` +$ # move the kf-32 guard inside a PARTITION_HORZ_A => arm +p (decode.rs:36332) resolves a 32x32 partition symbol with NO +refuse_invalid_subsize((32, 32)) within 220 lines after it +``` + +### 11.3 The occurrence count, re-derived per line + +`refuse_invalid_subsize((` appears **18 times in `decode.rs`**, and the breakdown +that sums is **11 + 5 + 2**: + +* **11 guard call sites** in the decode body — 35588, 36278, 36406, 36472, 36882, + 37132, 53985, 54222, 54606, 54752, 55164; +* **5** in this test's own string literals and comparisons — the four named in the + assertions plus the multi-line assert string at 56835; +* **2** in doc comments. + +The definition's own signature line does not match `((` at all. Main's line-grep +count of 13 was taken at r7 and the refutation's 15 at r9, both before the r9 kf-w8 +guards; 18 is what the tree carries now, counted by call shape +(`l.trim_start().starts_with(…)`) so a multi-line assert string mentioning the +function is not counted. The scan finds **10** resolutions against those **11** +guards — the inter-128 guard at 53985 has no resolution of its own because +`read_sb128_root` is shared. + +### 11.4 What is still not claimed + +The guard-vs-resolution cross-check is `>=`, not `==`: the scan sees 10 resolutions +against 11 guards today, and a hard equality between two numbers the scan itself +computes is a claim about the scanner, not about coverage. What reds is a +resolution with no guard — on its own line, naming the variable — and a guard +sitting inside an AB arm. A redundant guard with no resolution behind it is +harmless and is not treated as a defect. + +**And the two cross-checks are weaker than they look.** Cross-check 1 is level +PRESENCE only. Cross-check 2 is `>=`. So a **second unguarded site at an +already-covered level is caught only by the per-site 220-line window** — which is +a window, not a dispatch bound. Stated rather than left for a reader to infer. + +### 11.5 r10: the AB-arm tracker, again + +r9's tracker was open for exactly one line: armed at the condition (indent 44, +body 48), the wrapped `.contains(&part16)` at indent 48 set `entered = true`, and +then the arm's own `{` — at the **opener's** indent 44, not the body's — hit +`ind < body` and cleared it. Every statement in the arm body was invisible, and +the mutation that moves a guard INSIDE an arm stayed GREEN at r8 *and* r9. r10 +skips a line whose trimmed text is exactly `{` when deciding to enter or clear. +The mutation now reds with the r5 diagnostic: + +``` +$ # move the kf-16 guard inside a PARTITION_HORZ_A..=PARTITION_VERT_B arm +decode.rs:36539 puts a refuse_invalid_subsize inside a +PARTITION_HORZ_A..=PARTITION_VERT_B arm (values 4..=7 only); the offending +values are PARTITION_VERT (2) and PARTITION_VERT_4 (9), which that arm can +never observe -- r5's defect +``` + +Also in r10: the bound-variable lookup scans **backwards** and takes the nearest +`let` whose binding is the one followed by the symbol read. It used to take the +first `let` upward, which could name an unrelated binding (`ec_dbg_pre`) instead +of the partition symbol. + +**No decode-path change in r10** — the four passes found no defect in it. +