diff --git a/crates/ec-av1/src/gate_coverage.rs b/crates/ec-av1/src/gate_coverage.rs index 891cfbd3..1aaf14a9 100644 --- a/crates/ec-av1/src/gate_coverage.rs +++ b/crates/ec-av1/src/gate_coverage.rs @@ -1699,3 +1699,782 @@ mod tests { ); } } + +/// lane-av1pins5 r5: the PIN INVENTORY. +/// +/// The r3 inventory this replaces matched only two call shapes -- +/// `crate_pin("X")` and `pin_dir().join("X")` -- both SINGLE-NAME. A gate that +/// reads a whole DIRECTORY of pins through a `concat!` literal and then formats +/// a name at runtime (`format!("{fixtures}/{n}.obu")`) matched neither, so +/// `pinned_warp_stream_decodes_pixel_exact` and its 14 uncommitted pins were +/// invisible to it, and r3 reported "the machine-local-pin population is zero". +/// It was not. This enumerator resolves all four shapes. +/// +/// Ownership, stated because two lanes touch this: THIS scanner owns the +/// ENUMERATION (which gates read which pins, from source). The fixture-preflight +/// lane owns the FILE INVENTORY on a runner (does each referenced path exist on +/// the box). Different questions; both must agree, and this one is the stricter of +/// the two because it fails on an uncommitted pin whether or not some runner +/// happens to have a copy. +#[cfg(test)] +mod pin_inventory { + /// One pin a gate reads, and where it came from. + pub struct PinRead { + pub gate: String, + pub file: String, + pub shape: &'static str, + } + + /// Split `src` into `(fn_name, body)` for every `fn name(` at the gate indent. + fn gate_bodies(src: &str) -> Vec<(String, &'static str)> { + let mut out = Vec::new(); + let mut cur: Option<(String, usize)> = None; + for (i, line) in src.lines().enumerate() { + let t = line.trim_start(); + if let Some(rest) = t.strip_prefix("fn ") { + if let Some(name) = rest.split('(').next() { + if !name.contains(' ') { + cur = Some((name.to_string(), i)); + } + } + } + // A `#[test]`/`#[ignore]` line is never a closing brace, so the fn + // ends at the first line that is exactly four-space `}`. + if let Some((name, start)) = &cur { + if i > *start && line == " }" { + let body = src + .lines() + .skip(*start) + .take(i - *start + 1) + .collect::>() + .join("\n"); + out.push((name.clone(), &*Box::leak(body.into_boxed_str()))); + cur = None; + } + } + } + out + } + + /// Every pin every gate reads, across all four shapes. + pub fn pins_read(src: &str) -> Vec { + let mut out = Vec::new(); + for (gate, body) in gate_bodies(src) { + // (a) crate_pin("X") and (b) pin_dir().join("X") -- single name. + for m in body.match_indices("crate_pin(\"") { + let rest = &body[m.0 + 11..]; + if let Some(e) = rest.find('"') { + out.push(PinRead { + gate: gate.clone(), + file: rest[..e].to_string(), + shape: "crate_pin", + }); + } + } + for m in body.match_indices("pin_dir().join(\"") { + let rest = &body[m.0 + 16..]; + if let Some(e) = rest.find('"') { + out.push(PinRead { + gate: gate.clone(), + file: rest[..e].to_string(), + shape: "pin_dir_machine_local", + }); + } + } + // (c) a whole-file concat! literal to a named pin: + // concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/X.obu") + for m in body.match_indices("/../../fixtures/") { + let rest = &body[m.0 + 16..]; + if let Some(e) = rest.find('"') { + out.push(PinRead { + gate: gate.clone(), + file: rest[..e].to_string(), + shape: "concat_literal_machine_local", + }); + } + } + // (d) the shape that hid 14 pins: a DIRECTORY literal bound to a + // local, plus a runtime `format!("{var}/{n}.ext")` over a + // literal name array. Resolve the array's names. + for (vi, line) in body.lines().enumerate() { + let tl = line.trim(); + // `let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");` + // -> the bound name is whatever sits between `let ` and the `=`. + let var = match ( + tl.find("concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/../../fixtures\")"), + tl.find('='), + ) { + (Some(a), Some(eq)) if eq < a => tl[4..eq].trim().to_string(), + _ => continue, + }; + if var.is_empty() { + continue; + } + // `format!("{fixtures}/{n}.obu")` -- built by concatenation, not + // by `format!`: escaping `{{`/`}}` to emit literal braces here is + // exactly the bug that made this shape resolve to 0 pins on the + // first run of the scanner. + let marker = ["format!(\"", "{", &var, "}/{n}"].concat(); + let Some(pos) = body.find(&marker) else { + continue; + }; + // Walk back from the format! to the `[ ... ].iter()` array and + // take every quoted name in it. + let head = &body[..pos]; + let Some(bracket) = head.rfind('[') else { + continue; + }; + let names: Vec = head[bracket..] + .split('"') + .skip(1) + .step_by(2) + .filter(|s| !s.is_empty() && !s.contains(' ') && *s != "]") + .map(|s| s.to_string()) + .collect(); + // `.obu` -- SLICE up to the closing quote. (Stringifying the + // `find` index instead produced names like `warp-mismatch4`.) + let tail = &body[pos + marker.len()..]; + let ext = tail + .find('"') + .map(|e| tail[..e].to_string()) + .unwrap_or_default(); + for n in names { + out.push(PinRead { + gate: gate.clone(), + file: format!("{n}{ext}"), + shape: "concat_dir_runtime_name", + }); + } + let _ = vi; + } + // (e) the shape this very fix INTRODUCED: + // `.map(|n| crate_pin(&format!("{n}.obu")))`. Rewriting the + // directory literal as a committed-path lookup made the gate + // correct and simultaneously invisible -- `crate_pin("` no + // longer appears, so shape (a) found nothing and the + // enumerator reported a CLEAN tree while 14 pins were read. A + // false pass is worse than the original gap: the original at + // least showed up in a filesystem audit. Caught here by the + // `reads.len()` floor in the invariant test. + for m in body.match_indices("crate_pin(&format!(") { + let rest = &body[m.0 + 19..]; + let Some(close) = rest.find(')') else { + continue; + }; + let call = &rest[..close]; + if !call.contains('"') { + continue; + } + let head = &body[..m.0]; + let Some(bracket) = head.rfind('[') else { + continue; + }; + let names: Vec = head[bracket..] + .split('"') + .skip(1) + .step_by(2) + .filter(|x| !x.is_empty() && !x.contains(' ') && *x != "]") + .map(|x| x.to_string()) + .collect(); + // the literal inside the format!, e.g. `{n}.obu` + let lit = call.split('"').nth(1).unwrap_or(""); + let ext = lit + .split_once("}") + .map(|(_, e)| e.to_string()) + .unwrap_or_default(); + for n in names { + out.push(PinRead { + gate: gate.clone(), + file: format!("{n}{ext}"), + shape: "crate_pin_runtime_name", + }); + } + } + } + out + } + + /// Does this shape resolve through `crate_pin`, i.e. the COMMITTED + /// crate-local copy? Both the literal form and the runtime-name form do -- + /// only the two `pin_dir`/root-`concat!` forms are machine-local. + pub fn resolves_committed(shape: &str) -> bool { + matches!(shape, "crate_pin" | "crate_pin_runtime_name") + } + + /// Is `file` present as a committed crate-local fixture? + pub fn is_committed(file: &str) -> bool { + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join(file) + .is_file() + } +} + +#[cfg(test)] +mod pin_inventory_tests { + use super::pin_inventory::{is_committed, pins_read}; + + /// The scanner must be able to SEE the directory-literal shape. Run over a + /// SYNTHETIC source, not the live tree: r5 removed that shape from + /// `pinned_warp_stream_decodes_pixel_exact`, so a test that asserted it + /// against the live file would rot the moment the fix landed -- which is + /// precisely how a scanner loses its edge and reports a clean tree again. + /// A capability test must have its own input. + #[test] + fn the_pin_scanner_sees_the_directory_literal_shape() { + let synthetic = r#" + #[test] + fn a_gate_using_the_old_shape() { + let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures"); + let paths: Vec = match std::env::var("EC_AV1_GATE_DUMP_PIN") { + Ok(p) => vec![p], + Err(_) => [ + "warp-mismatch", + "ii-flake-1", + "rect-flake-3", + ] + .iter() + .map(|n| format!("{fixtures}/{n}.obu")) + .collect(), + }; + for path in paths { + check(&path); + } + } +"#; + let reads = pins_read(synthetic); + let names: Vec<&str> = reads.iter().map(|r| r.file.as_str()).collect(); + assert_eq!( + names, + vec!["warp-mismatch.obu", "ii-flake-1.obu", "rect-flake-3.obu"], + "the directory-literal + runtime-name shape resolved to {names:?} -- a scanner \ + that cannot see this shape is how 14 uncommitted pins survived three rounds" + ); + assert!( + reads.iter().all(|r| r.shape == "concat_dir_runtime_name"), + "the synthetic pins were attributed to the wrong shape: {:?}", + reads.iter().map(|r| r.shape).collect::>() + ); + } + + /// The other three shapes resolve too -- same reasoning, same synthetic input, + /// so the capability survives the tree being fixed. + #[test] + fn the_pin_scanner_sees_every_shape() { + let synthetic = r#" + #[test] + fn shapes() { + let a = crate_pin("golden3-pin.obu"); + let b = pin_dir().join("sbpart-pin.obu"); + let c = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/x.obu")); + } +"#; + let mut names: Vec = pins_read(synthetic) + .iter() + .map(|r| format!("{}|{}", r.file, r.shape)) + .collect(); + names.sort(); + assert_eq!( + names, + vec![ + "golden3-pin.obu|crate_pin", + "sbpart-pin.obu|pin_dir_machine_local", + "x.obu|concat_literal_machine_local", + ], + "shape coverage changed: {names:?}" + ); + } + + /// THE INVARIANT, on the live tree: every pin a gate reads is a COMMITTED + /// crate-local copy, and NO gate reads through a machine-local shape. This is + /// the check the r3 manifest could not express. + #[test] + fn every_pin_a_gate_reads_is_committed_under_the_crate() { + let src = include_str!("stream.rs"); + let reads = pins_read(src); + assert!( + reads.len() >= 20, + "the enumerator found only {} pin reads in stream.rs -- it has lost a shape, \ + which is the failure mode that let 14 pins go unseen", + reads.len() + ); + let uncommitted: Vec = reads + .iter() + .filter(|r| !is_committed(&r.file)) + .map(|r| format!("{}:{} ({})", r.gate, r.file, r.shape)) + .collect(); + assert!( + uncommitted.is_empty(), + "{} pin(s) a gate reads have no committed copy under \ + crates/ec-av1/fixtures/ -- each resolves only on a machine whose \ + gitignored root fixtures/ happens to be populated, so a clean checkout \ + silently skips or panics:\n {}", + uncommitted.len(), + uncommitted.join("\n ") + ); + let machine_local: Vec = reads + .iter() + .filter(|r| !super::pin_inventory::resolves_committed(r.shape)) + .map(|r| format!("{} reads {} via {}", r.gate, r.file, r.shape)) + .collect(); + assert!( + machine_local.is_empty(), + "{} pin read(s) still resolve through a machine-local shape instead of \ + `crate_pin` (the committed crate-local copy), so they break on a clean \ + checkout:\n {}", + machine_local.len(), + machine_local.join("\n ") + ); + } +} + +/// lane-av1pins5 r5: the COUNT-VACUITY enumerator. +/// +/// Passing OUR OWN decode's length as the ORACLE's expected frame count +/// (`ffmpeg_decode_sequence(&stream, w, h, ours.len())`) is a real defect, but +/// NOT the one r4 claimed. MEASURED, by calling +/// `ffmpeg_decode_sequence(&stream, 192, 128, 0)` on a real pinned stream under +/// `catch_unwind`: it PANICS at `stream.rs:5110` with +/// `expected 0 4:2:0 frames, ffmpeg said: `. The helper asserts +/// `out.stdout.len() == frame_bytes * frames` unconditionally, so a wrong count +/// cannot pass silently -- it reds, with a message that blames FFMPEG for a +/// count OUR decoder chose. +/// +/// TWO DEFECT CLASSES, DO NOT CONFLATE THEM (lane-av1pins5 r6): +/// * MISATTRIBUTED RED -- a wrong count reds, and the old message blamed +/// ffmpeg for a number OUR decoder chose. This is what these sites are. +/// `ffmpeg_decode_sequence`'s `stdout.len() == frame_bytes * frames` assert +/// is unconditional, so it cannot pass silently. +/// * SILENT PASS -- the compare is skipped or truncated and the gate reports +/// green. A DIFFERENT defect with a DIFFERENT fix, and r4 mislabelled these +/// sites as belonging to it. If you are reading this to decide what to fix, +/// fix the message and the count SOURCE; do not go looking for a silent pass. +/// +/// r4 reported this shape as "a vacuous pass" and told Main so. That was wrong. +/// The consequence is a MISATTRIBUTED RED. The fix r4 shipped is still right (the +/// count now comes from the fixture, so the red names the real cause), but the +/// justification was wrong, and a sweep that repeats it would send the next +/// reader after a silent-pass bug that does not exist. +/// +/// This enumerator finds every such site and classifies it, so the class is +/// visible and cannot shrink unnoticed. +#[cfg(test)] +mod count_vacuity { + /// One oracle call whose expected frame count is locally derived. + pub struct Site { + pub line: usize, + pub gate: String, + pub count_expr: String, + /// An independent count assertion on the same binding, within a few + /// lines above: that is what makes the count a SPEC rather than a + /// self-fulfilling number. + pub pinned_by: Option, + /// Does this gate actually COMPARE PIXELS (so a wrong count would + /// corrupt a verdict), or is it a report-only probe? + pub pixel_comparing: bool, + /// The fix bucket, by READING the gate (r7). `Some(b)` where + /// a = pinned stream on disk -> take the count from the PIN + /// b = live aomenc encode -> take it from the ENCODE's frame count; + /// our decode's length is the thing + /// UNDER TEST and must never be the + /// expected value + /// c = census/probe -> report only, never fix + /// `None` = could not classify, and the reason is in `bucket_reason`. + pub bucket: Option<&'static str>, + pub bucket_reason: String, + /// The numeric frame count found in this gate's own encode call, when + /// one is visible -- the value the compare should assert instead. + pub candidate: Option, + /// A frame count already in scope that is a SPEC rather than a + /// self-fulfilling number -- e.g. the `FRAMES` the gate encoded, or a + /// count asserted on the pinned stream. `Some(..)` means the fix is a + /// one-line swap at this site. + pub fixable_from: Option, + } + + /// A census/probe/diagnostic gate: it reports, it does not assert a verdict. + fn is_probe(gate: &str) -> bool { + [ + "census", + "probe", + "sweep", + "first_diff", + "scratch", + "rectx", + "diagnostic", + ] + .iter() + .any(|m| gate.contains(m)) + } + + /// Encode helpers a gate can drive INDIRECTLY. The r7 extraction found 21 of + /// the 25 bucket-b gates encode through one of these, not through + /// `aomenc_path()` directly -- which is why a first pass that only looked for + /// `aomenc_path()` classified 6 gates "unclassified" that plainly encode. + fn enc_helpers(body: &str) -> Vec<&'static str> { + const NAMES: &[&str] = &[ + "encode_aomenc_stream", + "screen_intrabc_stream_at_depth", + "screen_intrabc_stream_with", + "libaom_encode_with", + "libaom_encode", + "run_multi_tile_gate", + "edge32_gate", + "rect_tx_tool_gate", + "the_chroma_rect_gates", + "restore_gate", + "cdef_gate", + "warp_gate", + "superres_gate", + "grain_gate", + "sgate", + ]; + NAMES + .iter() + .copied() + .filter(|n| body.contains(&format!("{n}("))) + .collect() + } + + pub fn sites(src: &str) -> Vec { + let mut out = Vec::new(); + let lines: Vec<&str> = src.lines().collect(); + // LINE index -> BYTE offset. The body walk indexes `src.as_bytes()`, so + // handing it a line number walks from the wrong place entirely and every + // body-dependent classification reads "unclassified". Same bug I hit in + // the Python classifier one step earlier. + let mut offsets: Vec = Vec::with_capacity(lines.len()); + { + let mut o = 0usize; + for l in &lines { + offsets.push(o); + o += l.len() + 1; + } + } + let mut gate = String::new(); + let mut fn_start = 0usize; + for (i, line) in lines.iter().enumerate() { + let t = line.trim_start(); + if let Some(rest) = t.strip_prefix("fn ") { + if let Some(n) = rest.split('(').next() { + if !n.contains(' ') { + gate = n.to_string(); + fn_start = offsets[i]; + } + } + } + for callee in [ + "ffmpeg_decode_sequence(", + "ffmpeg_decode_sequence_10bit(", + "ffmpeg_decode_sequence_444(", + ] { + let Some(at) = line.find(callee) else { + continue; + }; + let args = &line[at + callee.len()..]; + // DEPTH-AWARE close: `args.find(')')` stops at the `)` of + // `pictures.len()` and truncates the arg list mid-expression, + // which silently yielded zero sites on the first run. + let mut depth = 1usize; + let mut close = None; + for (k, ch) in args.char_indices() { + match ch { + '(' => depth += 1, + ')' => { + depth -= 1; + if depth == 0 { + close = Some(k); + break; + } + } + _ => {} + } + } + let Some(close) = close else { continue }; + let arglist = &args[..close]; + let last = arglist.rsplit(',').next().unwrap_or("").trim(); + if !(last.ends_with(".len()") || last.ends_with(".count()")) { + continue; + } + // Is the SAME binding count-asserted against a literal/const + // within the preceding 12 lines? That is the difference between + // a spec and a self-fulfilling number. + let binding = last.trim_end_matches(".len()").trim_end_matches(".count()"); + // Match the assertion across a LINE BREAK: rustfmt puts + // assert_eq!( + // frames.len(), + // so requiring `assert_eq!(frames.len()` on one line missed + // every multi-line spelling and inflated the unpinned count. + let want = format!("{binding}.len()"); + let mut pinned = None; + for back in 1..=14usize { + if i < back { + break; + } + let prev = lines[i - back].trim_start(); + if !prev.starts_with("assert") || !prev.contains('(') { + continue; + } + // rustfmt splits `assert_eq!(` from its first argument, so + // the binding is on THIS line or the NEXT one. + let here = prev.contains(&want); + let next = lines + .get(i - back + 1) + .map(|l| l.trim_start().contains(&want)) + .unwrap_or(false); + if here || next { + pinned = Some(prev.chars().take(60).collect()); + break; + } + } + // Pixel-comparing? A gate that compares planes is the only + // place a wrong count corrupts a verdict; a report-only probe + // just prints. + // Bound to THIS fn only. Slicing to EOF matched a later gate's + // `const FRAMES` and its `assert_eq!(got.y`, which reported all + // 48 sites as pixel-comparing with a spec in scope -- the same + // over-broad-scope bug the class keeps teaching. + // Brace-depth walk, not `find("\n }")`: a gate with an + // early 4-space `}` (a bare block, a `match` arm tail) truncated + // the slice and made the compare-detection read false. + // STRING-AWARE brace walk. Counting raw bytes counts a `}` + // inside a format string as a closing brace, which truncated the + // body and made every compare-detection read false -- the same + // trap that made stream.rs look 2 braces short in the first + // review of this wave. + let bytes = src.as_bytes(); + let mut depth = 0i32; + let mut started = false; + let mut fn_end = src.len(); + let mut in_str = false; + let mut in_line_comment = false; + let mut k = fn_start; + while k < bytes.len() { + let c = bytes[k]; + if in_line_comment { + if c == b'\n' { + in_line_comment = false; + } + k += 1; + continue; + } + if in_str { + if c == b'\\' { + k += 2; + continue; + } + if c == b'"' { + in_str = false; + } + k += 1; + continue; + } + match c { + b'"' => in_str = true, + b'/' if bytes.get(k + 1) == Some(&b'/') => { + in_line_comment = true; + k += 1; + } + b'{' => { + depth += 1; + started = true; + } + b'}' => { + depth -= 1; + if started && depth == 0 { + fn_end = k + 1; + break; + } + } + _ => {} + } + k += 1; + } + let body = &src[fn_start..fn_end]; + // APPROXIMATE, and known to be so: the body slice is a + // hand-rolled brace walk, and this crate's compare idioms vary + // enough that the column under-reports. The LINE, GATE and + // COUNT EXPR columns are exact (line-based scan, no body + // slicing); treat `pixel_comparing` as a hint, not a verdict. + // Idiom-tolerant: this crate spells the compare every which way + // (`assert_eq!(got.y, want.y)`, `assert_eq!(g, w)`, + // `let ok = ours.y == ref_f.y`, `ours.y, want.y`), so match the + // PLANE inside an assertion, not one fixed spelling. + let pixel_comparing = body.contains("assert") + && (body.contains(".y,") + || body.contains(".y ==") + || body.contains(".y)") + || body.contains("vs ffmpeg")); + // A SPEC already in scope for this gate? + let mut fixable = None; + for cand in ["FRAMES", "frame_count", "NFRAMES", "frames_expected"] { + if body.contains(&format!("const {cand}")) + || body.contains(&format!("let {cand}")) + { + fixable = Some(cand.to_string()); + break; + } + } + // Bucket by READING the gate. A census/probe reports and never + // asserts, so its count is not a verdict and is left alone. A + // gate that drives aomenc takes the count from the ENCODE -- our + // decode's length is what is under test, so using it as the + // expected value is circular. A gate that reads a stream from + // disk takes it from that stream. + // The candidate fix: the numeric frame count in this gate's own + // encode call. For bucket (b) that number IS the encoder's frame + // count, so it is the spec the compare should assert. + let candidate = enc_helpers(body).first().and_then(|h| { + let at = body.find(&format!("{h}("))?; + let open = at + h.len() + 1; + let seg = &body[open..(open + 400).min(body.len())]; + let close = seg.find(';')?; + let nums: Vec<&str> = seg[..close] + .split(',') + .map(|x| x.trim()) + .filter(|x| !x.is_empty() && x.chars().all(|c| c.is_ascii_digit())) + .collect(); + nums.last().map(|x| x.to_string()) + }); + let (bucket, bucket_reason) = if is_probe(&gate) { + ( + Some("c"), + "census/probe: reports, does not assert a verdict".to_string(), + ) + } else if body.contains("aomenc_path()") || !enc_helpers(body).is_empty() { + ( + Some("b"), + "live aomenc encode: count belongs to the encoder".to_string(), + ) + } else if body.contains("fs::read") || body.contains("crate_pin") { + ( + Some("a"), + "stream read from disk: count belongs to the pin".to_string(), + ) + } else { + ( + None, + "unclassified: no aomenc drive, no disk read, and not a probe -- \ + needs a reader" + .to_string(), + ) + }; + out.push(Site { + line: i + 1, + gate: gate.clone(), + count_expr: last.to_string(), + pinned_by: pinned, + pixel_comparing, + fixable_from: fixable, + bucket, + bucket_reason, + candidate, + }); + } + } + out + } +} + +#[cfg(test)] +mod count_vacuity_tests { + use super::count_vacuity::sites; + + /// The shape is real and widespread; this pins the FLOOR so the sweep cannot + /// silently stop finding sites. Measured count is well above this. + #[test] + fn the_count_vacuity_sweep_finds_the_known_sites() { + let src = include_str!("stream.rs"); + let s = sites(src); + assert!( + s.len() >= 40, + "the count-vacuity sweep found only {} site(s); expected 40+ -- it has lost a \ + shape", + s.len() + ); + // r7: the first reported site (3895, `pictures.len()`) is FIXED -- it now + // asserts `ENCODED_FRAMES`, the encode's own count. The anchor therefore + // moved from "the site is still there" to "the fix is still in place AND + // the dominant remaining shape is still found", so the sweep cannot go + // quiet by either route. + // The GENERAL rule, not the one literal r7 fixed. Every decode-derived + // count expression is banned at the gate r7 fixed, so a future edit that + // reintroduces the shape under a different binding name is caught, and so + // the guard does not go quiet as the OTHER sites are fixed later. + const DECODE_DERIVED: &[&str] = &["pictures.len()", "decoded.len()", "frames.len()"]; + assert!( + !s.iter().any(|x| x.gate + == "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact" + && DECODE_DERIVED.contains(&x.count_expr.as_str())), + "the r7 fix regressed: {} is passing a decode-derived count as the oracle's \ + expected count again -- our decode's length is the thing UNDER TEST and \ + must never be the expected value", + "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact" + ); + // A CEILING on the unpinned population, so a NEW site cannot be added + // silently. Lower it as sites are fixed; a fix that does not lower it is + // still a fix, but a NEW site is an immediate red. + let unpinned = s.iter().filter(|x| x.pinned_by.is_none()).count(); + const UNPINNED_CEILING: usize = 43; + assert!( + unpinned <= UNPINNED_CEILING, + "{unpinned} unpinned count site(s), ceiling is {UNPINNED_CEILING} -- a new one \ + was added (lower the ceiling only when a site is actually fixed)" + ); + assert!( + s.iter().any(|x| x.count_expr == "frames.len()"), + "the dominant `frames.len()` shape is no longer found -- the sweep has lost a \ + shape, not gained a fix" + ); + } + + /// Report, per site: does the count come from a SPEC or from our own decode? + /// Prints the table the r5 report carries. The assertion is the FLOOR above, + /// not "zero unpinned" -- the residual unpinned sites are handed to another + /// lane with this table, and forcing them all here would be an unbounded + /// change dressed as a fix. + #[test] + fn every_locally_derived_oracle_count_is_reported() { + let src = include_str!("stream.rs"); + let s = sites(src); + let unpinned: Vec = s + .iter() + .filter(|x| x.pinned_by.is_none()) + .map(|x| { + format!( + "stream.rs:{} | {} | {} | NOT SPEC-PINNED", + x.line, x.gate, x.count_expr + ) + }) + .collect(); + let pinned = s.len() - unpinned.len(); + eprintln!( + "count-vacuity sweep: {} site(s); {} spec-pinned by a prior assert, {} not", + s.len(), + pinned, + unpinned.len() + ); + for line in unpinned.iter() { + eprintln!(" {line}"); + } + // The table Main asked for, as columns the guard itself computes. + for x in s.iter().filter(|x| x.pinned_by.is_none()) { + eprintln!( + "ROW {} | {} | {} | bucket={} | candidate={} | spec_in_scope={} | {} | \ + pixel_comparing={}", + x.line, + x.gate, + x.count_expr, + x.bucket.unwrap_or("?"), + x.candidate.clone().unwrap_or_else(|| "-".into()), + x.fixable_from.clone().unwrap_or_else(|| "-".into()), + x.bucket_reason, + x.pixel_comparing + ); + } + assert!( + !s.is_empty() && s.iter().all(|x| !x.gate.is_empty()), + "a site has no owning gate -- the sweep's gate attribution is broken" + ); + } +} diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 8f4b2cc7..e344ee19 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -3856,7 +3856,10 @@ pub(crate) mod tests { ("film mandelbrot", "mandelbrot", 192, 128), ]; for (arm, source, width, height) in &arms { - let stream = encode_aomenc_stream(source, *width, *height, 40, &extra); + // r7: the ENCODE's frame count, bound so the compare below asserts a + // spec rather than our own decode's length. + const ENCODED_FRAMES: usize = 40; + let stream = encode_aomenc_stream(source, *width, *height, ENCODED_FRAMES, &extra); // Premise: the shape under test really arrived -- segmentation on // every frame, the map both coded and inherited, and real ALT_Q // tables. An aomenc drift that dropped any of these would make @@ -3904,7 +3907,11 @@ pub(crate) mod tests { "{arm}: every block dequantized at the same qindex ({lo}) -- SEG_LVL_ALT_Q \ never changed any block's quantizer" ); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, *width, *height, pictures.len()); + // `ENCODED_FRAMES`, not `pictures.len()`: our decode's length is the + // thing UNDER TEST, so using it as the oracle's expected count is + // circular -- a decode that dropped a frame would ask ffmpeg for the + // same short count and the compare would silently shrink. + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, *width, *height, ENCODED_FRAMES); for (i, (ours, theirs)) in pictures.iter().zip(&ffmpeg_frames).enumerate() { assert_eq!(ours.y, theirs.y, "{NAME} {arm}: frame {i} luma vs ffmpeg"); assert_eq!(ours.u, theirs.u, "{NAME} {arm}: frame {i} U vs ffmpeg"); @@ -5290,6 +5297,57 @@ pub(crate) mod tests { } /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream. + /// The frame-count diagnostic shared by the three `ffmpeg_decode_sequence*` + /// helpers (lane-av1pins5 r6). + /// + /// Before this, a caller that passed its OWN decode's length as the expected + /// count got `expected N 4:2:0 frames, ffmpeg said: ` -- with an EMPTY tail, + /// because ffmpeg ran at `-v error` and succeeded. The message named ffmpeg, + /// said nothing about where `N` came from, and sent the next reader hunting + /// ffmpeg for a count ffmpeg never chose. + /// + /// The class is MISATTRIBUTED RED, not silent pass: the helper's + /// `out.stdout.len() == frame_bytes * frames` assert fires unconditionally, so + /// a wrong count cannot pass -- it just fails while blaming the wrong + /// component. (Measured: `ffmpeg_decode_sequence(&s, 192, 128, 0)` panics + /// here, not silently.) Naming the real cause is the whole fix; no caller has + /// to change to benefit. + fn frame_count_diagnosis( + format: &str, + frames: usize, + width: usize, + height: usize, + frame_bytes: usize, + got: usize, + stderr: &[u8], + ) -> String { + let actual = if frame_bytes == 0 { + 0 + } else { + got / frame_bytes + }; + let leftover = if frame_bytes == 0 { + got + } else { + got % frame_bytes + }; + format!( + "FRAME COUNT MISMATCH ({format} {width}x{height}): the caller passed \ + `frames={frames}`, ffmpeg produced {actual} frame(s) ({got} bytes, \ + {leftover} byte(s) not a whole frame, at {frame_bytes} B/frame).\n\ + `frames` is the EXPECTED count the CALLER asserted -- it is NOT measured \ + from ffmpeg, so it never had ffmpeg's agreement. If it came from our own \ + decode_stream(), this is OUR decoder disagreeing with ffmpeg about how many \ + frames the stream holds, and the fix is on OUR side, not ffmpeg's. ffmpeg \ + itself exited cleanly{}.", + if stderr.is_empty() { + " with no diagnostics (`-v error`)" + } else { + "" + } + ) + } + fn ffmpeg_decode_sequence( stream: &[u8], width: usize, @@ -5312,8 +5370,16 @@ pub(crate) mod tests { assert_eq!( out.stdout.len(), frame_bytes * frames, - "expected {frames} 4:2:0 frames, ffmpeg said: {}", - String::from_utf8_lossy(&out.stderr) + "{}", + frame_count_diagnosis( + "4:2:0", + frames, + width, + height, + frame_bytes, + out.stdout.len(), + &out.stderr + ) ); (0..frames) .map(|i| { @@ -5406,8 +5472,16 @@ pub(crate) mod tests { assert_eq!( out.stdout.len(), frame_bytes * frames, - "expected {frames} 4:2:0 10-bit frames, ffmpeg said: {}", - String::from_utf8_lossy(&out.stderr) + "{}", + frame_count_diagnosis( + "4:2:0 10-bit", + frames, + width, + height, + frame_bytes, + out.stdout.len(), + &out.stderr + ) ); fn le16(bytes: &[u8]) -> Vec { bytes @@ -6811,8 +6885,16 @@ pub(crate) mod tests { assert_eq!( out.stdout.len(), frame_bytes * frames, - "expected {frames} 4:4:4 frames, ffmpeg said: {}", - String::from_utf8_lossy(&out.stderr) + "{}", + frame_count_diagnosis( + "4:4:4", + frames, + width, + height, + frame_bytes, + out.stdout.len(), + &out.stderr + ) ); (0..frames) .map(|i| { diff --git a/lanes/av1pins.report.md b/lanes/av1pins.report.md index b7125208..ea9b34a8 100644 --- a/lanes/av1pins.report.md +++ b/lanes/av1pins.report.md @@ -559,3 +559,515 @@ Follow-on handed back rather than folded in: the 14 `pinned_warp` pins, which ar the same defect as r3's four and want the same `crate_pin` + committed-copy treatment. Not verified: a full `cargo test -p ec-av1` run (project-wide validation is Main's). + +--- + +# r5 — the scanner, the 14 pins, and a correction to r4 + +Branch `lane-av1pins5`, forked from the r4 tip `2e5509e9`. Commits `e200fede` +(the 14 pins), `3eb90648` (scanner + sweep), plus this report. Tests and test +helpers only. Not pushed; main untouched. + +**Authoritative location, as the batch-close audit asked:** this lane lives in +`~/.cache/wt/av1pins5` (branch `lane-av1pins5`). It is **not** a stale duplicate of +`~/.cache/wt/av1pinslive` — `av1pinslive` sits at the same tip `2e5509e9` but does +**not** carry the 14 pins; they were only ever in `av1pins5`. All 14 were verified +byte-identical in three independent locations (this worktree's staged copy, a +local `/tmp` copy, and the runner library) before committing: **14/14 identical, +0 mismatches**. They are now committed, so no worktree holds the only copy. + +## 1. The scanner + +`pin_inventory` in `gate_coverage.rs` resolves **five** shapes: + +| # | shape | example | +|---|---|---| +| (a) | single-name committed | `crate_pin("golden3-pin.obu")` | +| (b) | single-name machine-local | `pin_dir().join("x.obu")` | +| (c) | whole-file `concat!` literal | `concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/x.obu")` | +| (d) | directory literal + runtime name | `let fixtures = concat!(...); … format!("{fixtures}/{n}.obu")` | +| (e) | committed + runtime name | `crate_pin(&format!("{n}.obu"))` | + +### Scanner before/after on the live tree + +``` +BEFORE (r3 inventory): gate=pinned_warp_stream_decodes_pixel_exact reads=0 +AFTER (r5 inventory): 14 pin(s) a gate reads have no committed copy under + crates/ec-av1/fixtures/: + pinned_warp_stream_decodes_pixel_exact:warp-mismatch.obu (concat_dir_runtime_name) + … all 14 named, then 0 after the fix landed. +``` + +### Shape (e) is the finding worth reading + +Rewriting the directory literal as a committed-path lookup made the gate +**correct and simultaneously invisible**: `crate_pin("` no longer appears, shape +(a) found nothing, and the enumerator reported a **clean tree while 14 pins were +read**. A false pass is worse than the original gap — the original at least +surfaced in a filesystem audit, which is exactly how the batch-close audit found +it. It was caught by the `reads.len() >= 20` floor in the invariant test. That +floor exists for this and I would not remove it. + +**The general lesson:** fixing a shape can blind the check that was watching it. + +### Two scanner bugs, both found by the capability tests + +* A `format!` brace escape emitted `{n` instead of `{n}`, so the marker never + matched and shape (d) resolved 0 pins. +* `args.find(')')` stopped at the `)` of `pictures.len()`, truncating the argument + list and yielding **zero** sites overall — the sweep reported a clean tree. + +Capability tests therefore use **synthetic source**, never the live file. Asserting +against the live tree would rot the moment the fix lands, which is precisely how a +scanner loses its edge. + +**Ownership, stated because two lanes touch this:** the scanner owns the +**enumeration** (which gates read which pins, from source). The fixture-preflight +lane owns the **file inventory on a runner** (does each path exist on the box). +The scanner is the stricter of the two — it fails on an uncommitted pin whether or +not some runner happens to have a copy. + +## 2. The 14 pins — provenance `recovered-original` + +Fetched byte-for-byte from the runner library. **Not regenerated**: these are the +actual historical mismatch witnesses, and a re-encode would be a different stream +that must not be called the pin. + +| pin | size | sha256 | +|---|---|---| +| warp-mismatch.obu | 621 B | `24cca5beb41c1078f8109d8fa7e35f10cc1eefb67c6d1d1ea248a0b6842287bb` | +| warp-flake-5.obu | 602 B | `1a99f9e5b257eed0ebae055441904d6c40962a26c0c2d63c3e051732569ff0a0` | +| warp-flake-7.obu | 723 B | `c2f8b93f5a59c56b1c4453ea789e0fc955557ed9b63c0e2cb8683fa483eff2b5` | +| ii-flake-1.obu | 579 B | `700ded3e61e15bc3573d339d7fcc6ab94500adb796c30021094d354306662238` | +| ii-flake-2.obu | 581 B | `edc4ad3a6c00c6bc909c626fa24433ef31a88ed519ed57403f5373a160e590af` | +| ii-flake-3.obu | 670 B | `994bfbdc952ecef18ae1560d5e7f121ba1000172e0bc2ad05e5b8cfaa17b15cb` | +| ii-flake-5.obu | 681 B | `f43fe77ea0e8ddd9c1524b642e09f935921cb0d00c4a60061a52d2260af38b9a` | +| ii-flake-6.obu | 632 B | `84a1f60011dfdb77ede98ce95a25d247d270b0af1cff2c44aa1e6b311ca63dce` | +| ii-flake-7.obu | 654 B | `61ba4d114aa55ebcf95ae691abbce3307146a2d969c0627ea3ceea02f3875574` | +| ii-flake-8.obu | 635 B | `f19d3d80ed564850cec02a26cfe7ab00e282afa7896821c535a117f5541bef5d` | +| ii-flake-9.obu | 690 B | `0df4874737cc615258c0fdfb4bcb157c9a3663127cbf0a896af44d4deb83c653` | +| rect-flake-1.obu | 607 B | `a3869b5d2bd8a8bc5413e0d039d5e3375a48601cdeb2edb8d4b732402926d357` | +| rect-flake-2.obu | 601 B | `c780ddee1adf25cf63a6ba70ff449820f6f4474b23ef16615c1e843ad0c86adb` | +| rect-flake-3.obu | 572 B | `3b23d204549b7bcfbd7166b1b3e2920580236c78de12e8f23f7fb64c1864f3e6` | + +`.gitignore`'s `!crates/*/fixtures/**` negation means a plain `git add` suffices — +verified with `git check-ignore -q` (returns 1) and by staging with no `-f`. + +## 3. The gate is live + +`pinned_warp_stream_decodes_pixel_exact` reads all 14 from +`crates/ec-av1/fixtures/`, via `crate_pin`, with `require_pin` in the helper. +Plain run (no `--ignored`): **1 passed; 0 failed; 0 ignored; 744 filtered out; +1.47 s**, printing each `pin: …/crates/ec-av1/fixtures/`. + +The asserts live in `check_pinned_warp_stream`, which this gate delegates to — +stated in the gate's doc comment, because a body-only scan reads as assert-free, +which is how the r4 audit got it wrong. `#[ignore]` **36 → 35**. + +## 4. The count-vacuity sweep — and a CORRECTION to r4 + +`count_vacuity` enumerates every site passing a locally-derived count as the +oracle's expected frame count: **61 sites, 13 spec-pinned by a prior assert, 48 +not**. The floor (`>= 40`) stops the sweep silently shrinking. + +**r4 reported this shape as a "vacuous pass" and I told Main so. That was wrong.** +Measured, by calling `ffmpeg_decode_sequence(&stream, 192, 128, 0)` on a real +pinned stream under `catch_unwind`: + +``` +panicked at crates/ec-av1/src/stream.rs:5110:9: +expected 0 4:2:0 frames, ffmpeg said: +``` + +The helper asserts `out.stdout.len() == frame_bytes * frames` unconditionally, so +a wrong count **cannot pass silently** — it REDS, with a message that blames +FFmpeg for a count our decoder chose. The consequence is a **misattributed red**, +not a silent pass. + +r4's *fix* still stands (the count now comes from the fixture, so the red names the +real cause). The *justification* was wrong, and a sweep repeating it would send +the next reader after a bug that does not exist. + +| column | meaning | +|---|---| +| `stream.rs:3895` | `a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact` — `pictures.len()`, not spec-pinned: a wrong count reds, blaming ffmpeg | +| `stream.rs:5355` | `an_svt_screen_palette_block_with_a_split_transform_decodes_exactly` — `decoded.len()`, not spec-pinned | +| `stream.rs:10287/10289` | `rect_tx_tool_gate` — `decoded.len()`, not spec-pinned | +| … 48 total | full list printed by the test; the floor pins the count | + +**All 48 are reported, none fixed.** That is an unbounded change across gates this +lane does not own, and dressing it as a fix would be dishonest. The pin-class gates +are clean: **0** unpinned count sites in `pinned_lr_sgr`, +`check_pinned_warp_stream`, `pinned_golden3`, `pinned_sbpart` and the film-grain +gate. + +## 5. State + +`lane-av1pins5`, three commits on top of `2e5509e9`. `cargo check -p ec-av1 +--all-targets` clean, **0 warnings**. `gate_coverage` **15 passed** (10 pre-existing ++ 5 new scanner tests), `refusal_inventory` 15 passed. Not verified: a full +`cargo test -p ec-av1` run (project-wide validation is Main's). + +The rule this lane earns, on top of r3's: **a fix can blind the check that was +watching the shape it changed.** The pin inventory went from blind, to correct, to +blind-again-in-a-new-guise, across three commits in three rounds. The floor and the +synthetic capability tests are what make that survivable. + +--- + +# r6 — name the real cause, classify the defect, and report the 44 + +Branch `lane-av1pins5`. Commit `02c8e7a8`. Tests and test helpers only. Not +pushed; main untouched. + +**Canonical branch: `lane-av1pins5`.** `av1pinslive` is a **stale duplicate** at +`2e5509e9` with no work of its own beyond r4; every r5/r6 commit is here only. +`av1pinslive` can be dropped. No pins are at risk either way — all 18 recovered +pins are committed. + +## 1. The change that matters: the failure now names the real cause + +Before, a caller passing our own decode's length got: + +``` +expected N 4:2:0 frames, ffmpeg said: +``` + +Empty tail, because ffmpeg runs at `-v error` and succeeds. It named ffmpeg, said +nothing about where `N` came from, and sent the reader hunting ffmpeg for a count +ffmpeg never chose. + +All three helpers (`ffmpeg_decode_sequence`, `_10bit`, `_444`) now share +`frame_count_diagnosis`. Measured with the same probe r5 used: + +``` +FRAME COUNT MISMATCH (4:2:0 192x128): the caller passed `frames=0`, ffmpeg produced +1 frame(s) (36864 bytes, 0 byte(s) not a whole frame, at 36864 B/frame). +`frames` is the EXPECTED count the CALLER asserted -- it is NOT measured from ffmpeg, +so it never had ffmpeg's agreement. If it came from our own decode_stream(), this is +OUR decoder disagreeing with ffmpeg about how many frames the stream holds, and the +fix is on OUR side, not ffmpeg's. ffmpeg itself exited cleanly with no diagnostics. +``` + +**This converts most of the 44 from confusing to diagnosable without touching a +single caller** — which is exactly the de-risking Main asked for, since "48 edits +of unclear value" was the risk. + +## 2. Two defect classes, named so r4 is not repeated + +The sweep's doc comment now states: + +* **MISATTRIBUTED RED** — a wrong count reds, and the old message blamed ffmpeg. + **This is what these sites are.** The `stdout.len() == frame_bytes * frames` + assert is unconditional, so a wrong count cannot pass silently. +* **SILENT PASS** — the compare is skipped or truncated and the gate reports green. + A *different* defect with a *different* fix. **These sites are not that.** + +## 3. The sweep: 61 sites, 17 spec-pinned, 44 not, 30 distinct gates + +Two detection bugs of mine, both inflating the number: + +* `assert_eq!` is split across lines by rustfmt (`assert_eq!(` then + `frames.len(),`), so a one-line containment check missed every multi-line + spelling. Now matched over a two-line window: **13 → 17** spec-pinned. +* The body slice used to classify each gate is a hand-rolled brace walk, and raw + byte counting treats a `}` inside a format string as a closing brace — the same + trap that made `stream.rs` look two braces short in the first review of this wave. + +**The `pixel_comparing` column is APPROXIMATE and under-reports, and I am not +building the 44-row table on it.** I sampled three gates it marks `false` and all +three plainly compare planes (`a_real_aomenc_stream_with_rect_palette…` 4 +plane-compare lines, `…palette_stream_with_8x8_leaves…` 5, +`a_16x4_intrabc_pair_strip…` 1). The column's `line`, `gate` and `count_expr` +are exact — a line-based scan with no body slicing — but whether a gate +pixel-compares needs a reader, not a regex. + +## 4. The table — 44 sites, exact columns + +`file:line | gate | count source before | fixture's own count known? | status` + +| file:line | gate | count source before → after | fixture count known? | status | +|---|---|---|---|---| +| stream.rs:3895 | `a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact` | `pictures.len()` → unchanged | no (live aomenc; use the encode's frame count) | reported | +| stream.rs:5414 | `an_svt_screen_palette_block_with_a_split_transform_decodes_exactly` | `decoded.len()` → unchanged | no (SVT stream read from a file) | reported | +| stream.rs:10135 | `a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact` | `frames.len()` → unchanged | yes (the gate's own `frames` const) | reported | +| stream.rs:10354, :10356 | `rect_tx_tool_gate` | `decoded.len()` ×2 → unchanged | yes (encode frame count) | reported | +| stream.rs:10834 | `a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips` | `frames.len()` → unchanged | yes | reported | +| stream.rs:11005 | `a_16x4_intrabc_pair_strip_decodes_pixel_exact` | `frames.len()` → unchanged | yes (pinned fixture) | reported | +| stream.rs:11077 | `a_lossless_16x4_chroma_pair_repairs_the_measured_site` | `frames.len()` → unchanged | yes (pinned fixture) | reported | +| stream.rs:11465, :11608 | `a_coded_rect_intrabc_block_reconstructs_in_both_orientations` | `frames.len()` ×2 → unchanged | yes | reported | +| stream.rs:11851, :11853 | `an_sb128_screen_stream_with_intrabc_decodes_pixel_exact` | `frames.len()` ×2 → unchanged | yes | reported | +| stream.rs:12239 | `a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal` | `frames.len()` → unchanged | n/a (census/probe) | report-only | +| stream.rs:12314 | `an_intrabc_vartx_census_measures_the_mixed_leaf_refusal` | `frames.len()` → unchanged | n/a (census/probe) | report-only | +| stream.rs:12418 | `a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal` | `frames.len()` → unchanged | no (live aomenc) | reported | +| stream.rs:12720 | `an_intrabc_block_under_tx_mode_select_decodes_pixel_exact` | `frames.len()` → unchanged | yes | reported | +| stream.rs:12781 | `a_real_aomenc_stream_with_cdf_update_disabled_decodes_pixel_exact` | `frames.len()` → unchanged | no (live aomenc) | reported | +| stream.rs:12987, :12989 | `a_real_aomenc_stream_with_rect_strip_palette_decodes_pixel_exact` | `frames.len()` ×2 → unchanged | no (live aomenc) | reported | +| stream.rs:15126 | `first_diff` (helper) | `decoded.len()` → unchanged | n/a (diagnostic helper) | report-only | +| … 27 more across 15 gates | — | `frames.len()` / `decoded.len()` | mixed | reported | + +The full 44-line list is printed by `every_locally_derived_oracle_count_is_reported` +on every run, so it cannot drift from the source. + +**None fixed in this commit beyond r4's.** The per-site fix is to derive each count +from the fixture — a recorded frame count, a parsed OBU frame count, a length +assert on the pinned stream — or, for a live-aomenc gate, from **the encoder's own +frame count**, not from our decode. That is 30 gates of real work and it is the +next lane. + +## 5. State + +`lane-av1pins5`, four commits on top of `2e5509e9`. `cargo check -p ec-av1 +--all-targets` clean, **0 warnings**. `gate_coverage` 15 passed, +`refusal_inventory` 15, `count_vacuity` 2, `pin_inventory` 3, `pinned_golden3` +green. `#[ignore]` unchanged at 34. Not verified: a full `cargo test -p ec-av1` +run (project-wide validation is Main's). + +The rule r6 adds, on top of r3's and r5's: **a scanner's own columns are only as +trustworthy as the slice it parsed, and a column that is "approximately right" is +worse than no column** — because a 44-row table built on it would send a lane +after the wrong gates. Two of the four bugs in this lane's scanners were exactly +this: a slice that stopped at `len()`'s own paren, and a brace count that did not +skip string literals. + +--- + +# r7 — classify by reading, fix the first, hand back 38 + +Branch `lane-av1pins5`. Commit `71afc8c9`. Tests and test helpers only. Not +pushed. **Canonical branch: `lane-av1pins5`**; `av1pinslive` is dropped. + +## 1. The classification, printed per site so it is auditable + +The sweep now emits, on every run: + +``` +ROW | | | bucket | candidate | spec_in_scope | | pixel_comparing +``` + +| bucket | sites | rule | +|---|---|---| +| **b** | 37 | live aomenc encode → the count belongs to the **encoder** | +| **a** | 1 | stream read from disk → the count belongs to the **pin** | +| **c** | 4 | census/probe → report only, never fix | +| **?** | 1 | unclassified, **with the reason printed** rather than a guess | + +Each gate is classified from its own body, over a **string-aware** extent. Two +details that changed the answer: 21 of the bucket-b gates encode through a +*helper* (`screen_intrabc_stream_at_depth`, `run_multi_tile_gate`, `edge32_gate`, +`rect_tx_tool_gate`, …) rather than calling `aomenc_path()` directly, so a first +pass that only looked for `aomenc_path()` called six plainly-encoding gates +"unclassified". + +**A third offset bug, same family as the two r6 caught.** The sweep handed its +body-walk a **line index** where a **byte offset** was required, so every +body-dependent classification read "unclassified" — 40 of 44, all looking like a +legitimate result. It is the third time in this lane that a line/byte or +slice-boundary confusion has silently produced a plausible clean output. + +## 2. Fixed: `stream.rs:3895` + +`a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact`: +`ffmpeg_decode_sequence(..., pictures.len())` → `ENCODED_FRAMES` (40), the count +its own `encode_aomenc_stream(source, w, h, 40, &extra)` call encodes. Our +decode's length is the thing **under test**, so using it as the oracle's expected +count was circular. Gate green, 2.05 s, now comparing 40 frames against ffmpeg's +40 rather than a self-fulfilling number. + +**The sweep's "known site" anchor moved with the fix.** It used to assert that +`pictures.len()` was still present, which went red the moment the fix landed — a +guard that punishes the fix. It now asserts the *opposite* (no site may pass +`pictures.len()` again) **and** that the dominant `frames.len()` shape is still +found, so the sweep cannot go quiet by either route. + +## 3. NOT DONE: 38 of the 39 fixable sites + +The sweep prints a `candidate` — the numeric frame count in the gate's own encode +call — and it resolves for exactly **one** gate. The rest encode inside loops or +through per-gate helpers whose frame-count argument has to be read per gate, and +only 3 of 44 are a clean one-line swap to something already in scope. + +I am handing those back with the method rather than editing 38 call sites on a +guess, for the same reason r6 refused the 44-row table on an untrustworthy column: +a plausible-looking bulk edit built on a heuristic I have now shown wrong three +times in this lane would send the next reader after the wrong lines. + +Per-gate recipe for whoever takes it: + +* **bucket b** — bind the encoder's frame count to a named const at the encode + call (`const ENCODED_FRAMES: usize = ;`) and pass that to + `ffmpeg_decode_sequence`, exactly as `stream.rs:3895` now does. Where the + encode is inside a loop over `cq`/`depth`, the count is the helper's frame-count + argument and must be read from that call. +* **bucket a** — the count is the pinned stream's; take it from the pin's recorded + frame count or a length assert on the pinned bytes, not from `decode_stream`. +* **bucket c** — leave. A census reports; it asserts no verdict, so a wrong count + there is not a wrong count. + +The sweep prints the full 44-row table on every run, so the ledger cannot drift +from the source, and the `>= 40` floor plus the two-direction anchor stop the +class from quietly shrinking or from being "fixed" away. + +## 4. State + +`lane-av1pins5`, five commits on top of `2e5509e9`. `cargo check -p ec-av1 +--all-targets` clean, **0 warnings**. `gate_coverage` 15, `refusal_inventory` 15, +`count_vacuity` 2, `pin_inventory` 3, and the fixed gate all green. `#[ignore]` +unchanged at 34. Lane-scoped `CARGO_TARGET_DIR` with touch-first, per the +observation that the shared target dir served another worktree's binary. + +Not verified: a full `cargo test -p ec-av1` run (project-wide validation is +Main's). + +The rule r7 adds: **a scanner that classifies by reading must print its +reasoning per row.** Every unclassifiable row in this table carries the sentence +that disqualified it, so a reader can disagree with a bucket instead of +inheriting it — and the one `?` in the table is more useful than a confident +guess would have been. + +--- + +# r7 closeout — rebased onto main, ledger handed forward + +Rebased onto main `97b4ee04`. **One conflict worth recording:** the fixture-preflight +lane had, independently, already landed the r5 work — the 14 pins are committed +under `crates/ec-av1/fixtures/` and `pinned_warp_stream_decodes_pixel_exact` was +rewired to `crate_pin` with **string literals**, which is a better shape than my +`crate_pin(&format!("{n}.ext"))`: a literal is resolvable name-by-name, so it does +not create the shape-(e) blind spot at all. All three conflicted hunks resolved to +main's side; my duplicate pin commit became a no-op. + +**Ownership, settled:** main's `scripts/pin-gate-audit.py` owns the standalone +census (a human/agent runs it); `pin_inventory` in `gate_coverage.rs` owns the +CI-enforced invariant (it fails the suite when a pin is uncommitted). Different +jobs, same question, both run. + +`git diff main --stat`: **3 files, 1215 insertions, 8 deletions** — pure additions. +`gate_coverage` 18, `refusal_inventory` 19, `count_vacuity` 2, `pin_inventory` 3, +`cargo check --all-targets` **0 warnings**. + +## 1. Merge readiness + +| | | +|---|---| +| branch | `lane-av1pins5` (canonical), rebased onto main `97b4ee04` | +| diff vs main | 3 files, +1215 / −8 — additions only | +| test-count delta | branch carries +5 CI tests over main (pin_inventory 3, count_vacuity 2); the 18/19 gate_coverage/refusal_inventory totals include the preflight lane's | +| sweep floor | holds: 61 sites ≥ 40; unpinned ceiling 43 holds | +| warnings | 0 | + +## 2. The class note — stop the next reader chasing a nonexistent bug + +**A wrong count here cannot pass silently.** `ffmpeg_decode_sequence`'s +`out.stdout.len() == frame_bytes * frames` assert is unconditional, so a wrong +count REDS. The defect is a **misattributed red**: the old message +(`expected N 4:2:0 frames, ffmpeg said: `) named ffmpeg for a count ffmpeg +never chose. `frame_count_diagnosis` — the class-level fix — reports the caller's +count, ffmpeg's actual count, the byte arithmetic, and states that the fix is on +OUR side. That single change converts the class from confusing to diagnosable +without touching a caller. **This, not the 38 sites, is what the branch is for.** + +## 3. The three detection bugs, each of which produced a plausible clean output + +1. **A line index handed to a byte-offset walk** (r7). The sweep computed each + gate's body by indexing `src.as_bytes()` with a LINE number. 40 of 44 rows read + "unclassified" — and "unclassified" looks like a finding, not a bug. +2. **`assert_eq!` split by rustfmt** (r6). The lookback required + `assert_eq!(frames.len()` on one line, but rustfmt emits `assert_eq!(` then + `frames.len(),` on the next. Every multi-line spelling was missed, inflating the + unpinned count 48 → 44 once a two-line window was used. +3. **A `}` inside a format string counted as a closing brace** (r6). The body walk + counted raw bytes, so a brace in a message truncated the slice and every + compare-detection read false. Same trap that made `stream.rs` look two braces + short in the first review of this wave. + +Each was caught by a floor or a synthetic-input capability test, and each would +have survived an honest-looking table. The rules they earn: **walk offsets in the +units you index; match a call across the line breaks rustfmt introduces; and never +count braces without skipping string literals.** A scanner column derived from a +hand-rolled slice is a hypothesis, not a measurement. + +## 4. The ledger — 43 sites, handed forward + +| file:line | gate | count expr before | bucket | candidate | spec_in_scope | disposition | +|---|---|---|---|---|---|---| +| stream.rs:5631 | `an_svt_screen_palette_block_with_a_split_transform_decodes_exactly` | `decoded.len()` | a | candidate=- | spec_in_scope=- | deferred(bucket a first: count from the PIN) | +| stream.rs:10513 | `a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:10732 | `rect_tx_tool_gate` | `decoded.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:10734 | `rect_tx_tool_gate` | `decoded.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:11212 | `a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:11383 | `a_16x4_intrabc_pair_strip_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:11455 | `a_lossless_16x4_chroma_pair_repairs_the_measured_site` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:11838 | `a_coded_rect_intrabc_block_reconstructs_in_both_orientations` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:11981 | `a_coded_rect_intrabc_block_reconstructs_in_both_orientations` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:12224 | `an_sb128_screen_stream_with_intrabc_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:12226 | `an_sb128_screen_stream_with_intrabc_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:12612 | `a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal` | `frames.len()` | c | candidate=- | spec_in_scope=- | report-only (census/probe asserts no verdict) | +| stream.rs:12687 | `an_intrabc_vartx_census_measures_the_mixed_leaf_refusal` | `frames.len()` | c | candidate=- | spec_in_scope=- | report-only (census/probe asserts no verdict) | +| stream.rs:12791 | `a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:13093 | `an_intrabc_block_under_tx_mode_select_decodes_pixel_exact` | `frames.len()` | ? | candidate=- | spec_in_scope=- | UNCLASSIFIED - needs a reader | +| stream.rs:13154 | `a_real_aomenc_stream_with_cdf_update_disabled_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:13360 | `a_real_aomenc_rect_strip_palette_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:13362 | `a_real_aomenc_rect_strip_palette_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:15497 | `first_diff` | `decoded.len()` | c | candidate=- | spec_in_scope=- | report-only (census/probe asserts no verdict) | +| stream.rs:27636 | `a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:27764 | `a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:27933 | `a_real_aomenc_stream_whose_chroma_edge_filter_reads_a_sub16_neighbours_uv_mode_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:27935 | `a_real_aomenc_stream_whose_chroma_edge_filter_reads_a_sub16_neighbours_uv_mode_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:28129 | `a_real_aomenc_sb128_stream_whose_skipped_cfl_and_1to4_chroma_pairs_decode_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:28131 | `a_real_aomenc_sb128_stream_whose_skipped_cfl_and_1to4_chroma_pairs_decode_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:28456 | `a_real_aomenc_stream_with_ab_partitions_below_16x16_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:28458 | `a_real_aomenc_stream_with_ab_partitions_below_16x16_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:28609 | `sweep_rectx_recipes` | `frames.len()` | c | candidate=- | spec_in_scope=- | report-only (census/probe asserts no verdict) | +| stream.rs:29212 | `a_real_aomenc_stream_with_a_32_level_ab_partition_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:30646 | `a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly` | `pics.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:30744 | `a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly` | `pics.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:38033 | `edge32_gate` | `decoded.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:38035 | `edge32_gate` | `decoded.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:41761 | `a_real_aomenc_stream_with_a_coded_strip_whose_chroma_is_a_4to1_or_sub8_rect_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:41763 | `a_real_aomenc_stream_with_a_coded_strip_whose_chroma_is_a_4to1_or_sub8_rect_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:41998 | `the_chroma_rect_gates_excluded_seed_46_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:42000 | `the_chroma_rect_gates_excluded_seed_46_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:42167 | `a_real_aomenc_band_stream_seed46_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:42169 | `a_real_aomenc_band_stream_seed46_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:42376 | `a_real_aomenc_stream_whose_frame_edge_partition_bit_is_horz_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:42378 | `a_real_aomenc_stream_whose_frame_edge_partition_bit_is_horz_decodes_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=- | deferred(bucket b: count from the ENCODER) | +| stream.rs:42602 | `a_real_aomenc_rect_inter_block_predicts_chroma_with_the_narrow_kernel_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=FRAMES | deferred(bucket b: count from the ENCODER) | +| stream.rs:42604 | `a_real_aomenc_rect_inter_block_predicts_chroma_with_the_narrow_kernel_pixel_exact` | `frames.len()` | b | candidate=- | spec_in_scope=FRAMES | deferred(bucket b: count from the ENCODER) | + +TOTALS: a=1 b=37 c=4 ?=1 total=43 + +Totals: **a=1, b=37, c=4, ?=1**. + +**The `?` row is genuinely unclassified**, not a guess: +`an_intrabc_block_under_tx_mode_select_decodes_pixel_exact` neither drives aomenc +in its own body nor reads from disk, and is not a probe. It most likely encodes +through a path the helper list does not name. Left as `?` with the reason rather +than assigned a bucket I cannot justify. + +**Per-gate recipe.** Bucket **a** first (1 site): take the count from the pinned +stream's recorded frame count or a length assert on the pinned bytes. Then bucket +**b** (37 sites): bind the encoder's frame count to a named const at the encode +call and pass that, exactly as `stream.rs:3895` does (`const ENCODED_FRAMES: usize += 40;` from its own `encode_aomenc_stream(source, w, h, 40, …)`). Where the encode +is inside a `cq`/`depth` loop, the count is the helper's frame-count argument and +must be read from that call — the sweep's `candidate` column resolves for only one +gate, which is exactly why these were not bulk-edited. Bucket **c**: leave; a +census reports and asserts no verdict, so a wrong count there is not a wrong count. + +**DISPOSITION: deferred(needs a lane that classifies by READING each gate, bucket a +then bucket b).** Not a merge blocker: with `frame_count_diagnosis` in place, a +wrong count is now loud and self-explaining, so the 43 are diagnosable rather than +mysterious. + +## 5. The guard, generalized + +The r7 anchor asserted one literal (`pictures.len()`) at the fixed gate, which +would go quiet as other sites are fixed. It now asserts the **general** rule: + +* no **decode-derived** count (`pictures.len()` / `decoded.len()` / `frames.len()`) + may reappear at the gate r7 fixed, under any binding name; and +* an **unpinned ceiling** of 43 — a NEW site is an immediate red, and the ceiling + is lowered as sites are actually fixed. + +The `>= 40` floor on total sites stays, so the class cannot shrink unnoticed.