diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index ed05efb3..9409da51 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -12566,6 +12566,17 @@ fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> { /// stream can present. #[test] fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() { + // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it + // names that string exactly (placeholders included) and pins its guard + // site. The enumeration below establishes the shape domain; on its own it + // never said WHICH string the domain was about, so under a real function + // boundary -- rather than a window that ran into the next test -- the row + // read as unanchored. + const REFUSAL: &str = "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"; + assert!( + include_str!("decode.rs").contains(REFUSAL), + "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" + ); let mut checked = 0; for &(side, w, h) in &INTER_BLOCK_SHAPES { if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 { @@ -12658,6 +12669,13 @@ const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [ /// clause rejects before the lookup. #[test] fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() { + // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it + // names it and pins its guard site. + const REFUSAL: &str = "a motion_mode symbol for a block shape with no CDF row here"; + assert!( + crate::refusal_inventory::pins_refusal(include_str!("decode.rs"), REFUSAL), + "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" + ); let mut rows = std::collections::BTreeSet::new(); let mut excluded = 0; for (w, h) in BLOCK_SIZES_ALL_WH { @@ -13929,8 +13947,10 @@ fn decode_intrabc_rect( // its own mi row/column on a 4:4:4 lossless frame, and // the whole block's per-unit states are stamped over // cells that belong to other blocks (or to nothing). - (mi_r + ur * ((4 << ss_y(fctx)) / MI), - mi_c + uc * ((4 << ss_x(fctx)) / MI)), + ( + mi_r + ur * ((4 << ss_y(fctx)) / MI), + mi_c + uc * ((4 << ss_x(fctx)) / MI), + ), 4 << ss_x(fctx), 4 << ss_y(fctx), plane_idx, @@ -27996,6 +28016,18 @@ fn sub_tx_size_map_matches_libaom() { /// case the refusal is guarded by. #[test] fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() { + // lane-av1refusalspan: this gate is the PROOF for both var-tx refusals, so + // it names both and pins both guard sites. The walk below proves the leaf + // domain; it never said which two strings that domain was about. + for refusal in [ + "an inter var-tx tree with a leaf transform larger than 32x32", + "an inter var-tx tree with a leaf transform larger than 64x64", + ] { + assert!( + crate::refusal_inventory::pins_refusal(include_str!("decode.rs"), refusal), + "this gate proves {refusal:?}, but that string is no longer in decode.rs" + ); + } // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h). fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) { out.push((depth, entry.0, entry.1)); @@ -28601,6 +28633,21 @@ fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> { /// loop, which is why they are skipped below. #[test] fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() { + // lane-av1refusalspan: this gate is the PROOF for THREE refusals, so it + // names all three and pins all three guard sites. The census below proves + // the shape domain and, on its own, named NONE of the strings that domain + // was about -- under a real function boundary rather than a window that + // ran into the next test, all three rows read as unanchored. + for refusal in [ + "a rectangular inter luma transform unit whose shape has no coefficient table set here", + "a rectangular inter chroma transform unit whose shape has no coefficient table set here", + "a rectangular transform unit whose shape has no coefficient scan table here", + ] { + assert!( + include_str!("decode.rs").contains(refusal), + "this gate proves {refusal:?}, but that string is no longer in decode.rs" + ); + } let fctx = &crate::decode::FrameCtx::new(); let corner_scan = |w: usize, h: usize| { let (cw, ch) = (w.min(32), h.min(32)); @@ -54543,6 +54590,16 @@ mod tests { #[test] fn every_inter_record_publishes_an_obmc_readable_filter() { let src = include_str!("decode.rs"); + // lane-av1refusalspan: this gate is the PROOF for the refusal below, so + // it names it and pins its guard site. The sibling test + // `an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking` + // carries the same string 27k lines away in this file -- exactly the + // reach a window that is not a function boundary used to have. + const REFUSAL: &str = "an OBMC neighbour whose switchable interp filter was never recorded"; + assert!( + crate::refusal_inventory::pins_refusal(&src, REFUSAL), + "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" + ); let mut calls = 0usize; for (start, _) in src.match_indices("record_inter_rect_mi(") { // Skip the definition and the wrapper's own forwarding call. @@ -54622,8 +54679,13 @@ mod tests { /// open half of this proof. #[test] fn a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name() { - const REFUSAL: &str = - "a reference frame selected with no picture at this frame's own ref_frame_idx slot"; + // lane-av1refusalspan: the FULL refusal, not a prefix of it. This gate + // is the proof for the row in `refusal_inventory`, whose anchor is the + // whole string (it carries no `(` and no `:`), and this const is what + // that anchor reads. Shortened to `...own ref_frame_idx slot` it + // stopped being a pin on the guard's text. + const REFUSAL: &str = "a reference frame selected with no picture at this frame's own \ + ref_frame_idx slot for it"; let pic = Picture { width: 4, height: 4, diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 0d5a4ed4..4662529b 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -627,9 +627,55 @@ const PROVEN: &[(&str, &str)] = &[ #[cfg(test)] const GATES_THAT_SKIP_ON_A_DECODE_ERROR: &[&str] = &[]; +/// Source text with Rust's line continuations dropped and every whitespace run +/// collapsed to one space -- the form rustc gives a multi-line literal -- so a +/// refusal written across three source lines is still findable in a body, and +/// a gate's quote of it still matches the guard's spelling. +#[cfg(test)] +fn squash_source(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut pending_space = false; + for (i, c) in s.char_indices() { + if c == '\\' { + let rest = &s[i + 1..]; + if rest.contains('\n') + && rest + .chars() + .take_while(|c| *c != '\n') + .all(|c| c == ' ' || c == '\t' || c == '\r') + { + continue; + } + } + if c.is_whitespace() { + pending_space = true; + continue; + } + if pending_space && !out.is_empty() { + out.push(' '); + } + pending_space = false; + out.push(c); + } + out +} + +/// Does `src` carry `refusal`? +/// +/// Lane-av1refusalspan: a proving gate quotes the refusal it proves, and this +/// is how it pins that quote to the guard that still carries the string. Both +/// sides are squashed, so a literal written over two lines with a `\` +/// continuation still matches. +#[cfg(test)] +pub(crate) fn pins_refusal(src: &str, refusal: &str) -> bool { + squash_source(src).contains(&squash_source(refusal)) +} + #[cfg(test)] mod tests { - use super::{CAPABILITY_CLAIMS, GATES_THAT_SKIP_ON_A_DECODE_ERROR, PROVEN, REFUSALS}; + use super::{ + CAPABILITY_CLAIMS, GATES_THAT_SKIP_ON_A_DECODE_ERROR, PROVEN, REFUSALS, squash_source, + }; use std::collections::BTreeSet; /// Every distinct `unsupported(...)` reason on the decode path. @@ -1134,6 +1180,13 @@ mod tests { /// comment on `read_golomb`. #[test] fn read_golomb_reads_every_value_a_conformant_stream_can_carry() { + // lane-av1refusalspan: this gate is the PROOF for the refusal below, so + // it names it and pins its guard site. + const REFUSAL: &str = "a Golomb tail longer than this decoder reads"; + assert!( + super::pins_refusal(include_str!("decode.rs"), REFUSAL), + "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" + ); let roundtrip = |value: u32| -> ec_core::Result { let mut enc = crate::msac::SymbolEncoder::new(); crate::tile::write_golomb(&mut enc, value); @@ -1377,6 +1430,17 @@ mod tests { #[test] fn every_rect_strip_shape_the_split_path_codes_has_a_luma_and_chroma_table() { let src = include_str!("decode.rs"); + // lane-av1refusalspan: this gate is the PROOF for both refusals below, + // so it names both and pins both guard sites. + for refusal in [ + "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", + "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)", + ] { + assert!( + super::pins_refusal(&src, refusal), + "this gate proves {refusal:?}, but that string is no longer in decode.rs" + ); + } // (1) The caller set. Each call's enclosing function is the last // top-level `fn` before it. @@ -1937,6 +2001,14 @@ mod tests { /// [`no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax`]. #[test] fn no_128_root_half_reads_a_cfl_filter_intra_or_palette_symbol() { + // lane-av1refusalspan: this gate is the PROOF for the refusal below, so + // it names it (the full leading clause, which is the whole clause the + // inventory row's anchor reads) and pins its guard site. + const REFUSAL: &str = "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block"; + assert!( + include_str!("decode.rs").contains(REFUSAL), + "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" + ); let src = include_str!("decode.rs"); // The 128-root call site's own `cfl` argument, with the comment that // explains it -- the two lines are matched together so that reordering @@ -2122,34 +2194,425 @@ mod tests { ); } - /// Every entry of [`PROVEN`] must still name a live refusal and a test - /// that exists, and the count it prints is the inventory's numerator. + /// Lane-av1refusalspan: the files a proving gate may live in. + const GATE_SOURCES: [(&str, &str); 3] = [ + ("decode.rs", include_str!("decode.rs")), + ("stream.rs", include_str!("stream.rs")), + ("refusal_inventory.rs", include_str!("refusal_inventory.rs")), + ]; + + /// Lane-av1refusalspan: every offset in `src` of a line that DEFINES + /// `fn (` -- and nothing that merely names it. + /// + /// "The gate" is a function, so the first thing the anchor needs is the + /// function's own definition. The window rule this replaced took the first + /// `fn (` the file happened to contain, and a comment or a string + /// produces one. A definition is a line whose text before the keyword is + /// whitespace and qualifiers only (`pub`, `pub(crate)`, `async`, ...). + fn gate_definitions(src: &str, gate: &str) -> Vec { + src.match_indices(&format!("fn {gate}(")) + .map(|(at, _)| at) + .filter(|at| { + let line_start = src[..*at].rfind('\n').map_or(0, |i| i + 1); + src[line_start..*at].split_whitespace().all(|word| { + matches!( + word, + "pub" | "async" | "const" | "unsafe" | "extern" | "default" + ) || (word.starts_with("pub(") && word.ends_with(')')) + }) + }) + .collect() + } + + /// The number of leading-whitespace columns on the line holding `at`. + fn leading_indent(src: &str, at: usize) -> usize { + let line_start = src[..at].rfind('\n').map_or(0, |i| i + 1); + let line = &src[line_start..at]; + line.len() - line.trim_start().len() + } + + /// The offset of the `"` that closes the string literal opening at `open`. + fn closing_quote(b: &[u8], open: usize) -> Option { + let mut i = open + 1; + while i < b.len() { + match b[i] { + b'\\' => i += 2, + b'"' => return Some(i), + _ => i += 1, + } + } + None + } + + /// The offsets of the `{` that opens the body of the function defined at + /// `gate_at` and of the `}` that closes it; `None` when the body is never + /// closed. + /// + /// This walks Rust, not lines. A brace inside a string literal, a raw + /// string, a byte string, a char literal, a lifetime, a line comment or a + /// (nestable) block comment is not a brace -- counting one is exactly how a + /// "bounded" window becomes the rest of the file. + fn body_braces(src: &str, gate_at: usize) -> Option<(usize, usize)> { + let b = src.as_bytes(); + let mut i = gate_at; + let mut depth = 0usize; + let mut open = None; + let mut last: Option = None; + while i < b.len() { + // Every arm advances `i`, including the ones that `continue`. A spin + // here would hang the suite instead of failing it, which is the one + // outcome a boundary finder must never have. + if let Some(last) = last { + debug_assert!(i > last, "body_braces: an arm must advance the cursor"); + } + last = Some(i); + match b[i] { + b'/' if b.get(i + 1) == Some(&b'/') => { + i = src[i..].find('\n').map_or(b.len(), |n| i + n + 1); + continue; + } + b'/' if b.get(i + 1) == Some(&b'*') => { + let mut nesting = 1usize; + i += 2; + while i < b.len() && nesting > 0 { + if b[i] == b'/' && b.get(i + 1) == Some(&b'*') { + nesting += 1; + i += 2; + } else if b[i] == b'*' && b.get(i + 1) == Some(&b'/') { + nesting -= 1; + i += 2; + } else { + i += 1; + } + } + continue; + } + b'r' if b.get(i + 1) == Some(&b'"') || b.get(i + 1) == Some(&b'#') => { + let mut j = i + 1; + while b.get(j) == Some(&b'#') { + j += 1; + } + if b.get(j) != Some(&b'"') { + i += 1; + continue; + } + let hashes = j - i - 1; + let mut end = None; + for k in (j + 1..b.len()).chain(std::iter::once(b.len() - 1)) { + if b[k] == b'"' && b[k + 1..].iter().take(hashes).all(|c| *c == b'#') { + end = Some(k); + break; + } + } + i = end? + 1; + continue; + } + b'"' => { + i = closing_quote(b, i)? + 1; + continue; + } + b'b' if b.get(i + 1) == Some(&b'"') => { + i = closing_quote(b, i + 1)? + 1; + continue; + } + // A lifetime (`'a`, `'static`) is not a char literal: it has no + // closing quote on its line, and reading one as a literal would + // hide real code from the scan. + b'\'' => { + let rest = &b[i + 1..]; + let from = if rest.first() == Some(&b'\\') { 2 } else { 0 }; + match rest[from..] + .iter() + .take_while(|c| **c != b'\n') + .position(|c| *c == b'\'') + { + Some(k) => i += from + k + 2, + None => i += 1, + } + continue; + } + b'{' => { + open = open.or(Some(i)); + depth += 1; + } + b'}' => { + // A closer seen BEFORE the body opened is not ours (it can + // only come from a signature or a type ascription the scan + // mis-read); ignore it rather than underflowing `depth`. + if depth > 0 { + depth -= 1; + if depth == 0 { + return open.map(|o| (o, i)); + } + } + } + _ => {} + } + i += 1; + } + None + } + + /// The text of the body of the function defined at `gate_at`, or `None` + /// when that body is never closed. + fn function_body<'a>(src: &'a str, gate_at: usize) -> Option<&'a str> { + let (open, close) = body_braces(src, gate_at)?; + src.get(open..=close) + } + + /// The first line of `body` that defines another function at `indent` + /// columns of leading whitespace -- the first sign that a boundary + /// over-reached into a neighbour. + fn sibling_fn(body: &str, indent: usize) -> Option<&str> { + body.lines().skip(1).find(|line| { + let lead = line.len() - line.trim_start().len(); + lead == indent && { + let t = line.trim_start(); + t.starts_with("fn ") || t.starts_with("pub fn ") + } + }) + } + + /// Lane-av1refusalspan: the proving gate's OWN body -- the text from the + /// `{` that opens it to the `}` that closes it. + /// + /// Every failure mode here is a FAILURE (`Err`), never a wider window. The + /// rule this replaced -- "the body ends at the next `fn` at the same + /// indentation, or at end of file" -- ended at end of file constantly (a + /// top-level `#[test] fn` in `decode.rs` has its next same-indent `fn` + /// tens of thousands of lines away), and one row's 27,427-line "body" was + /// satisfied by the CHROMA sibling's string seven lines down. + fn gate_body(gate: &str) -> Result<&'static str, String> { + let mut hits: Vec<(&str, usize, &'static str)> = Vec::new(); + for (file, src) in GATE_SOURCES { + for at in gate_definitions(src, gate) { + hits.push((file, at, src)); + } + } + match hits.as_slice() { + [] => Err(format!( + "{gate} is not defined in decode.rs, stream.rs or refusal_inventory.rs" + )), + [only] => { + let (file, at, src) = *only; + let body = function_body(src, at).ok_or_else(|| { + format!( + "{file}:{at}: the body of {gate}() is never closed -- a missing \ + boundary is a FAILURE, not a window that runs on into the next \ + function" + ) + })?; + if let Some(leak) = sibling_fn(body, leading_indent(src, at)) { + return Err(format!( + "{file}:{at}: the extracted body of {gate}() still contains {} -- the \ + boundary over-reached into a neighbour", + leak.trim() + )); + } + Ok(body) + } + many => Err(format!( + "{gate} is defined {} times ({}), so 'its body' is ambiguous", + many.len(), + many.iter() + .map(|(file, at, _)| format!("{file}:{at}")) + .collect::>() + .join(", ") + )), + } + } + + /// The refusal's leading clause: what a gate may quote when it does not + /// quote the whole string -- everything up to the first `(` (the qualifier + /// that varies per call site), else up to the first `:`, else the whole + /// string. + fn leading_clause(reason: &str) -> String { + let cut = reason + .find('(') + .or_else(|| reason.find(':')) + .unwrap_or(reason.len()); + reason[..cut].trim_end().to_owned() + } + + /// Every entry of [`PROVEN`] must still name a live refusal, and the gate + /// it names must REFERENCE that refusal inside its OWN body. + /// + /// Lane-av1refusalspan: the boundary is the gate's closing brace (see + /// [`gate_body`]); a boundary that cannot be found fails the row. #[test] fn every_proven_refusal_names_a_test_that_exists() { let found = decode_path_refusals(); - let sources = [ - include_str!("stream.rs"), - include_str!("decode.rs"), - include_str!("refusal_inventory.rs"), - ]; + let mut whole = 0usize; + let mut clause = 0usize; + let mut neither: Vec<&str> = Vec::new(); + let mut unanchored: Vec = Vec::new(); + let mut unbounded: Vec = Vec::new(); for (reason, gate) in PROVEN { assert!( found.contains(*reason), - "{reason:?} is listed as proven but is no longer a decode-path refusal -- drop it from PROVEN (the capability landed) or fix the string" - ); - assert!( - sources - .iter() - .any(|src| src.contains(&format!("fn {gate}("))), - "{reason:?} names the proving test {gate}, which exists in neither stream.rs \ - nor decode.rs" + "{reason:?} is listed as proven but is no longer a decode-path refusal -- \ + drop it from PROVEN (the capability landed) or fix the string" ); + // A missing boundary is a FAILURE for the row, never a wider window. + let body = match gate_body(gate) { + Ok(body) => body, + Err(why) => { + unbounded.push(format!("{reason:?} names {gate}: {why}")); + continue; + } + }; + let flat = squash_source(body); + if flat.contains(&squash_source(reason)) { + whole += 1; + } else if flat.contains(&squash_source(&leading_clause(reason))) { + clause += 1; + } else { + neither.push(reason); + unanchored.push(format!("{reason:?} names {gate}")); + } } + // The anchor-strength line, measured over BODIES. The window rule this + // replaced made these numbers a distribution over "whatever the window + // happened to reach", which is a different question. + eprintln!( + "anchor strength: {whole} rows quote the WHOLE refusal string, {clause} quote its \ + LEADING CLAUSE, {} match neither: {neither:?}", + PROVEN.len() - whole - clause + ); eprintln!( "refusal inventory: {} refusals + {} capability claims, {} proven", REFUSALS.len(), CAPABILITY_CLAIMS.len(), PROVEN.len() ); + assert!( + unbounded.is_empty(), + "these rows name a gate whose body could not be bounded, so nothing was proved \ + about them -- a missing boundary is a failure, not a window that runs on:\n\ + {unbounded:#?}\n\ + The boundary is the gate's own closing brace. If the gate really is there, the \ + finder is wrong: fix the finder, never the verdict." + ); + assert!( + unanchored.is_empty(), + "these rows name a gate that never references the refusal inside its OWN body -- a \ + test that does not use the string it is said to prove is not a proof:\n\ + {unanchored:#?}\n\ + Name a gate that quotes the refusal (or its leading clause), or write one." + ); + } + + /// Lane-av1refusalspan, non-vacuity of the BOUNDARY (not of the anchor): + /// a neighbour's function must be unreachable from a gate's body, and a + /// body that is not closed must fail rather than run on. + #[test] + fn a_gate_body_is_bounded_by_its_own_closing_brace() { + let marker = "a rectangular chroma transform whose size has no coefficient table"; + let src = format!( + "fn this_gate() {{\n let _ = 1;\n}}\n\nfn next_gate() {{\n let _ = \"{marker}\";\n}}\n\nfn tail() {{}}\n" + ); + let this = gate_body_in(&src, "this_gate").expect("the gate has a boundary"); + assert!(this.contains("let _ = 1;"), "own text: {this:?}"); + assert!( + !this.contains(marker), + "leaked into the neighbour: {this:?}" + ); + let next = gate_body_in(&src, "next_gate").expect("the neighbour has a boundary"); + assert!(next.contains(marker)); + assert!(!next.contains("let _ = 1;")); + // The last function in a file has no following `fn` to stop at: the + // boundary must still close, exactly on its own brace. + assert_eq!(gate_body_in(&src, "tail").as_deref(), Ok("{}")); + // A brace inside a string or a char literal is not a brace. If the scan + // counted one, this body would run past its own `}` into `next_gate` + // -- the over-reach the `sibling_fn` invariant exists to catch, and the + // failure mode that made the old window 27,427 lines long. + let with_braces_in_literals = format!( + "fn this_gate() {{\n let _ = \"{{\";\n let _ = '}}';\n // {{\n /* }} */\n}}\n\nfn next_gate() {{\n let _ = \"{marker}\";\n}}\n" + ); + let bounded = gate_body_in(&with_braces_in_literals, "this_gate"); + assert!( + bounded.as_deref().is_ok_and(|b| !b.contains(marker)), + "a brace in a literal moved the boundary: {bounded:?}" + ); + // A body whose closing brace is missing (a half-finished edit) is a + // FAILURE. The rule it replaced sliced to end of file and carried on. + let truncated = + format!("fn this_gate() {{\n let _ = 1;\n\nfn next_gate() {{\n let _ = 2;\n}}\n"); + assert!(gate_body_in(&truncated, "this_gate").is_err()); + } + + /// Lane-av1refusalspan: the boundary is load-bearing on the REAL sources, + /// not only on the synthetic pair above -- every named gate resolves to + /// exactly one function whose body holds no other function, and the last + /// function in each of the three files terminates correctly. + #[test] + fn every_named_gate_body_is_bounded_in_these_files() { + let mut resolved = 0usize; + for (reason, gate) in PROVEN { + let body = + gate_body(gate).unwrap_or_else(|why| panic!("{reason:?} names {gate}: {why}")); + assert!( + body.ends_with('}'), + "{gate}'s body does not end on its closing brace" + ); + resolved += 1; + } + assert_eq!(resolved, PROVEN.len()); + for (file, src) in GATE_SOURCES { + let last = last_fn_name(src).unwrap_or_else(|| panic!("{file} has no function")); + let at = gate_definitions(src, &last) + .last() + .copied() + .unwrap_or_else(|| panic!("{file}: no definition of {last}")); + let body = function_body(src, at) + .unwrap_or_else(|| panic!("{file}: the last function {last}() has no boundary")); + assert!(sibling_fn(body, leading_indent(src, at)).is_none()); + } + } + + /// Lane-av1refusalspan: the invariant that catches a boundary that + /// over-reaches. Tested on its own text, so it cannot be satisfied by the + /// scanner happening to be right on the current sources. + #[test] + fn a_body_carrying_another_function_is_refused() { + assert!(sibling_fn("{\n let _ = 1;\n}\n\nfn neighbour() {\n}\n", 0).is_some()); + assert!(sibling_fn("{\n let _ = 1;\n}\n", 0).is_none()); + // A nested `fn` is deeper-indented and does belong to the body. + assert!(sibling_fn("{\n fn helper() {}\n}\n", 0).is_none()); + } + + /// Lane-av1refusalspan: `gate_body` over ONE file, so the boundary tests + /// above can drive it with text that cannot occur in this crate. + fn gate_body_in<'a>(src: &'a str, gate: &str) -> Result<&'a str, String> { + let defs = gate_definitions(src, gate); + match defs.as_slice() { + [] => Err(format!("{gate} is not defined here")), + [at] => { + let body = function_body(src, *at).ok_or_else(|| { + format!("the body of {gate}() is never closed -- boundary missing") + })?; + if let Some(leak) = sibling_fn(body, leading_indent(src, *at)) { + return Err(format!("boundary over-reached into {}", leak.trim())); + } + Ok(body) + } + many => Err(format!("{gate} is defined {} times", many.len())), + } + } + + /// The name of the last function defined in `src` -- the boundary rule's + /// hard case, since nothing follows it to stop at. + fn last_fn_name(src: &str) -> Option { + src.lines() + .filter_map(|line| { + let t = line.trim_start(); + if !(t.starts_with("fn ") || t.starts_with("pub fn ")) { + return None; + } + Some(t.trim_start_matches("pub fn ").trim_start_matches("fn ")) + }) + .filter_map(|head| head.split_once('(').map(|(head, _)| head.trim().to_owned())) + .last() } } diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 624577ef..07a2430d 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -4417,6 +4417,14 @@ pub(crate) mod tests { /// re-deriving the formula here. #[test] fn every_frame_size_a_header_can_code_has_a_mode_info_grid() { + // lane-av1refusalspan: this gate is the PROOF for the refusal below, so + // it names it and pins its guard site (the decode-path guard in + // decode.rs carries the same string). + const REFUSAL: &str = "a frame with no mode-info grid"; + assert!( + crate::refusal_inventory::pins_refusal(include_str!("stream.rs"), REFUSAL), + "this gate proves {REFUSAL:?}, but that string is no longer in stream.rs" + ); let mut sizes: Vec = (1..=1024).collect(); sizes.extend([2048, 4095, 4096, 8192, 16384, 32768, 65535, 65536]); // `mi_cols` is nondecreasing in `frame_width`, so an empty grid can diff --git a/lanes/av1refusalspan.report.md b/lanes/av1refusalspan.report.md new file mode 100644 index 00000000..d90a4f2f --- /dev/null +++ b/lanes/av1refusalspan.report.md @@ -0,0 +1,198 @@ +# lane-av1refusalspan — a real function boundary for the refusal inventory's anchor + +Base: `745c60e7` (main). Branch `lane-av1refusalspan`, commits `797fa52b` + `566d61bd`. +Worktree `~/.cache/wt/av1refusalspan`, lane-private `CARGO_TARGET_DIR`. + +``` +cargo test -p ec-av1 --lib refusal_inventory +anchor strength: 26 rows quote the WHOLE refusal string, 7 quote its LEADING CLAUSE, + 0 match neither: [] +refusal inventory: 33 refusals + 1 capability claims, 33 proven +test result: ok. 19 passed; 0 failed; 0 ignored; 0 measured; 733 filtered out +``` + +No decoder logic changed. The seven decoder/stream gates I touched were each run +individually and are green (`a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered`, +`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`, +`every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan`, +`every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row`, +`a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name`, +`every_inter_record_publishes_an_obmc_readable_filter`, +`every_frame_size_a_header_can_code_has_a_mode_info_grid`). + +--- + +## 0. Where this branch sits, stated once + +`lane-av1refusal` (tip `910dc296`, r7) is **unmerged**, and main therefore does not +contain the anchor check at all: at `745c60e7` `every_proven_refusal_names_a_test_that_exists` +asks only whether `fn (` appears *somewhere* in the three files. The window rule the +ticket quotes lives on that branch. + +I based this lane on main as instructed, so the work is a **self-contained, corrected +version** of r3–r7's `body_of`: real boundary, missing boundary = failure, leading-clause +anchor, measured distribution. **Merge this one, not both** — they edit the same test and +the same three rows' gates. If `lane-av1refusal` is merged first, take this branch's +`refusal_inventory.rs`, `decode.rs` and `stream.rs` over it and drop r3–r7's `body_of`. + +--- + +## 1. The boundary rule, and why the alternatives lose + +**Chosen: the brace that closes the gate's body.** `body_braces` walks Rust from the `fn` +keyword — not lines — and skips string literals, raw strings (`r"`, `r#"…"#`), byte strings, +char literals, lifetimes (`'a`, `'static`), line comments and nestable block comments. +`gate_body` returns the text from the body's `{` to its matching `}`. + +The three candidates, and how each fails: + +| rule | why it loses on this tree | +|---|---| +| next `#[test]` / `#[cfg(test)]` attribute | it bounds a *test region*, not a function. The attribute-less helpers between two tests (`decode_path_refusals`, `squash_ws`, `corner_scan`-style closures, `reachable`) fall inside the preceding test's window, and — worse — it has no answer for the **last** test in a file, which is the same "no boundary → widen" hole the ticket asks me to close. Attribute order also varies (`#[test]`, `#[ignore]`, doc comments). | +| explicit per-gate span, recorded next to `PROVEN` | a second thing to keep in step with the source, and it fails **open**: when a gate is renamed, moved or deleted, the recorded span still points at *some* text and the row stays green. That is the defect class in a different costume. | +| same-indent `fn` line (what r3 shipped) | keepable as an *invariant*, useless as a *boundary* — see §5's M4. | + +Why the brace rule is the right one for this file specifically: `decode.rs` is 56k lines +of gates whose bodies are dense with literal braces — refusal strings carry `{tx_w}`, +`{bw}`, `{part32}`, and asserts carry `{ref_frame}`, `{w}x{h}` — and the file is +re-indented by merges (the wave merge dedented a call site by four spaces). A rule that +counts `{`/`}` as bytes, or that keys on indentation, is reading exactly the parts of +this file that churn. + +--- + +## 2. A missing boundary is a failure, never a wider window + +`gate_body` returns `Result<&str, String>` and has exactly four `Err` paths, none of +which touches a byte outside the gate: + +1. **no definition** — `fn (` appears on no definition line (a comment or a string + that merely names the gate does not count: `gate_definitions` requires the text before + the keyword to be whitespace and qualifiers only); +2. **never closed** — the scan reaches end of file without the depth returning to zero; +3. **ambiguous** — the name is defined more than once, so "its body" has no referent; +4. **over-reach** — the extracted text still carries another same-indent `fn`, which means + the scanner under-counted. + +`every_proven_refusal_names_a_test_that_exists` collects paths 1–3 into an `unbounded` +list and asserts it empty; path 4 fires inside `gate_body` and surfaces the same way. +A spin in the scanner is a fifth case, and it used to be a **hang** (see §5's M3); every +arm now has to advance the cursor, asserted at the top of the loop. + +--- + +## 3. Re-measured over real bodies + +The `25 whole / 8 leading clause / 0 neither` line was, as r7 said, a distribution over +"whatever the window reached". Measured over bodies the brace rule actually finds, on +main's tree **before any gate was touched**: + +``` +anchor strength: 13 rows quote the WHOLE refusal string, 6 quote its LEADING CLAUSE, + 14 match neither +``` + +**14 of 33 rows were anchored by nothing.** Every one of them is now anchored, by the gate +naming the refusal it proves and pinning the guard that still carries the string +(`refusal_inventory::pins_refusal`, whitespace-squashed so a literal written over two +lines with a `\` continuation still matches): + +| # | row | gate | before | after | +|---|---|---|---|---| +| 1 | `an intra-coded {bw}x{bh} block on the inter block path (…)` | `every_intra_in_inter_shape_the_census_lists_has_a_size_group_row` | neither | whole | +| 2 | `a rectangular inter luma transform unit whose shape has no coefficient table set here` | `every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan` | neither | whole | +| 3 | `a rectangular inter chroma transform unit … table set here` | same gate | neither | whole | +| 4 | `a rectangular transform unit whose shape has no coefficient scan table here` | same gate | neither | whole | +| 5 | `an inter var-tx tree with a leaf transform larger than 32x32` | `a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered` | neither | whole | +| 6 | `… larger than 64x64` | same gate | neither | whole | +| 7 | `a Golomb tail longer than this decoder reads` | `read_golomb_reads_every_value_a_conformant_stream_can_carry` | neither | whole | +| 8 | `a motion_mode symbol for a block shape with no CDF row here` | `every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row` | neither | whole | +| 9 | `a frame with no mode-info grid` | `every_frame_size_a_header_can_code_has_a_mode_info_grid` | neither | whole | +| 10 | `a reference frame selected with no picture at this frame's own ref_frame_idx slot for it` | `a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name` | neither | whole (its const was a **prefix**, `…own ref_frame_idx slot`; extended to the whole string) | +| 11 | `an OBMC neighbour whose switchable interp filter was never recorded` | `every_inter_record_publishes_an_obmc_readable_filter` | neither | whole | +| 12 | `a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here` | `every_rect_strip_shape_the_split_path_codes_has_a_luma_and_chroma_table` | neither | whole | +| 13 | `a split intra strip whose transform unit is {tx_w}x{tx_h} (…)` | same gate | neither | whole | +| 14 | `CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (…)` | `no_128_root_half_reads_a_cfl_filter_intra_or_palette_symbol` | neither | leading clause | + +13 whole + 1 clause → the final `26 / 7 / 0`. No row is marked NOT-PROVEN: each of the 14 +has a real proof behind it (an enumeration, a census or a negative gate); what was missing +was the gate saying so. + +Rows 2–4 and 14 are the three the earlier tightening (r5) had already recovered — see §5. + +--- + +## 4. Non-vacuity of the boundary + +Three permanent tests, all in `refusal_inventory::tests`: + +- `a_gate_body_is_bounded_by_its_own_closing_brace` — two adjacent functions where the + **neighbour** carries the string; asserts the gate's body does not and the neighbour's + does; asserts the **last function in a file** (`fn tail() {}`, nothing after it) closes + exactly on its own brace (`Ok("{}")`); asserts a body whose closing brace is missing is + `Err`; and asserts a `{` inside a string, a `'}'` char literal, a `// {` and a `/* }} */` + comment do not move the boundary. +- `every_named_gate_body_is_bounded_in_these_files` — the same boundary over the three + real sources: all 33 named gates resolve to exactly one function whose body ends on a + `}` and holds no other function, and the **last function in each of the three files** + terminates correctly. +- `a_body_carrying_another_function_is_refused` — the `sibling_fn` predicate on its own + text (a same-indent `fn` is caught; a deeper-indented nested `fn` is not), so it cannot + be satisfied by the scanner happening to be right today. + +Four mutations, each applied, observed red, reverted (`git status` clean): + +| # | mutation | result | +|---|---|---| +| **M1** | delete the anchor from `every_intra_in_inter_shape_the_census_lists_has_a_size_group_row` and park the refusal string as a `let _ = …` **one line past its closing brace**, inside `motion_mode_cdf_row` | RED: `26→25` whole, `0→1` neither, and the row is listed by name — a neighbour's text one line away cannot satisfy a row | +| **M2** | `gate_definitions` accepts column-0 definitions only, so gates inside `mod tests` are invisible | RED: 25 rows reported `… is not defined in decode.rs, stream.rs or refusal_inventory.rs` under the `unbounded` heading, and both boundary tests fail. **This is the missing-boundary-is-a-failure property on real data.** | +| **M3** | the string-literal skip becomes a naive counter (`i += 1`) | RED: `a brace in a literal moved the boundary: Err("the body of this_gate() is never closed -- boundary missing")`. A body that would run into its neighbour fails; it never passes. | +| **M3b** | the string arm becomes a bare `continue` (no cursor advance) | the boundary test **hung** for 600 s instead of failing. That is why `body_braces` now asserts every arm advances — the failure mode moved from a hung suite to a failed one (`566d61bd`). | +| **M4** | `function_body` replaced by the **old rule** (next same-indent `fn`, else end of file) | **GREEN**, and that is a finding, not a pass: on *today's* main tree every one of the 33 gates happens to have a following same-indent `fn`, so the old rule coincides with the true boundary here. It is the same code that produced a 27,427-line window on `lane-av1refusal`'s tree. The old rule's failure is tree-dependent and silent, which is precisely why it is not a rule; the brace rule does not move when the file is reorganised. | + +M4 also re-frames `sibling_fn`: it is a backstop against a scanner that under-counts, not +the thing that catches the leak — the leak is caught because the body is the *function's*. + +--- + +## 5. The three rows the earlier tightening recovered + +Kept anchored, on their own merits: + +- **`a rectangular inter luma transform unit …` / chroma twin / scan twin** → the gate + `every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan` names all + three strings and pins all three guard sites. +- **`CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (…)`** → + `no_128_root_half_reads_a_cfl_filter_intra_or_palette_symbol` carries the full leading + clause as a const and pins it. +- **`a reference frame selected with no picture at this frame's own ref_frame_idx slot for it`** + → `a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name`'s const is now + the **whole** string, not the prefix `…own ref_frame_idx slot` (the row's anchor is the + whole string: it has no `(` and no `:`). + +Measurement of all three under the real boundary, with their anchors removed: **all three +are in the 14-row `neither` bucket of §3.** That is the direct answer to "is the +tightening earned": under a boundary that is really a function, those rows were anchored by +nothing, and each needed its gate to say which string it was about. + +--- + +## 6. What is deliberately not here + +- `PROVEN` is still `&[(&str, &str)]`. The r1/r2 `Proof` tagging (NEGATIVE / ENUMERATION / + TABLE PIN) and the "every refusal needs a row" direction are `lane-av1refusal`'s scope, + not this lane's; porting them here would collide on the same table for no gain. +- No refusal, `PROVEN` row or decoder behaviour changed. The only semantic change is that + nine gates now assert they name the refusal they prove. + +Two hardenings came out of the mutations and ride in the same branch: the +cursor-advance assert (`566d61bd`, from M3b) and a `depth -= 1` that underflowed +if the scan met a `}` between the `fn` keyword and the body's `{` (`81eaadfd`). + +## 7. Open for Main + + +- Merge `lane-av1refusalspan`; retire `lane-av1refusal`'s `body_of` (see §0). +- The new pins make a refusal-string edit in `decode.rs`/`stream.rs` turn **two** gates red + (the pinning gate and the inventory row). That is intended, but it is the first thing + that will surprise the next lane that renames a guard message.