forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

refusal_inventory.rs2957 lines, 145.7 KiBHistoryRawDownload
1//! An inventory of what this decoder refuses, and a check on the claims those
2//! refusals make.
3//!
4//! Two rules this repository keeps learning the hard way:
5//!
6//! 1. A refusal string is a **claim**. "This encoder never writes one" asserts
7//! that a real encoder cannot emit the case -- and one such string was
8//! disproved by the very gate that carried it (the wedge-interintra hang,
9//! 2026-08-30): the refusal was written from a mismatching frame's header
10//! state, so it named a correlate rather than the defect. Any refusal
11//! phrased as a capability claim about the ENCODER, rather than about this
12//! decoder, needs evidence, and this module makes the set of such strings
13//! explicit instead of letting it grow quietly.
14//! 2. Refusals accumulate silently. A lane that adds one to unblock itself is
15//! doing the right thing (refuse by name rather than desync), but the total
16//! is the distance to a decoder that handles a default-settings stream, and
17//! nobody sees a total that nothing prints.
18//!
19//! So the test below re-derives every `unsupported(...)` reason reachable on
20//! the decode path -- `decode.rs` and `stream.rs` -- and pins it. Adding or
21//! removing a refusal fails until the list is updated, which is the point: the
22//! diff of this file is the decoder's capability delta, in one place, in
23//! English.
24
25#[cfg(test)]
26const CAPABILITY_CLAIMS: &[&str] = &[
27 // lane-hdrlossless ENUMERATION: this guard is a claim about THIS
28 // decoder's gate, not about the encoder -- `filter_intra_size_class_rect`
29 // admits no arm with a 64 axis (libaom `av1_filter_intra_allowed_bsize`
30 // is "both sides <= 32"), and the strips it protects are exactly
31 // `(64, 32)`/`(32, 64)`, which fall to its `_ => None` arm. So the
32 // `filter_intra.is_some()` guard in `decode_block_rect` is unreachable;
33 // the proof is `a_sb_level_horz_vert_strip_admits_no_filter_intra_symbol`,
34 // which enumerates every arm of the table. Kept as a named pin (not
35 // deleted) per the repo convention for proven-unreachable guards.
36 "filter intra on a superblock-level HORZ/VERT strip (never expected -- av1_filter_intra_allowed_bsize caps at 32x32)",
37];
38
39#[cfg(test)]
40const REFUSALS: &[&str] = &[
41 // lane-av1-444 c4's rect/1:4 chroma port added two shape guards whose
42 // strings never landed here (continuation 8's suite run caught the
43 // drift); both are decoder-side "no table for that shape yet" guards on
44 // 4:4:4 rect strips, same family as the rect luma/chroma entries below.
45 // lane-av1-refusalaudit: the 64-axis one is PROVEN unreachable -- its
46 // chroma-unit table covers every conformant strip unit in both supported
47 // chroma formats (enumeration in PROVEN; the witness2 hunt reached
48 // nothing). The chroma-size one below is still live.
49 "a 64-axis strip whose chroma unit has no coefficient table",
50 "a rectangular chroma transform whose size has no coefficient table",
51 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
52 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)",
53 "an OBMC neighbour whose switchable interp filter was never recorded",
54 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
55 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
56 "a rectangular transform unit whose shape has no coefficient scan table here",
57 "a 32x32 partition type this decoder does not code (value={part32})",
58 "a Golomb tail longer than this decoder reads",
59 "a tx_type symbol outside its CDF's own set: {t}",
60 "an INTER 32x32 partition type this decoder does not code (value={part32})",
61 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
62 "a 128x128 superblock partition value outside the 8-symbol alphabet",
63 "an inter var-tx tree with a leaf transform larger than 64x64",
64 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of their size gates caps at 64x64 or below, so none of these symbols exists there)",
65 // lane-av1unwritten + lane-av1subsizesweep: the BLOCK_INVALID subsize
66 // refusal that mirrors libaom's own (decodeframe.c:1456). The source
67 // string carries escaped quotes around the libaom citation and this
68 // table is matched against the scanner's collected form, so the quotes
69 // stay escaped here the way the scanner keeps them.
70 "a block size 4x8, 8x16 or 16x4 (or 8x4 at 4:4:0) has no chroma plane block at this frame's subsampling mode (libaom: \\\"Block size %dx%d invalid with this subsampling mode\\\", av1/decoder/decodeframe.c:1456, refusing by the same rule)",
71 // lane-t900 r23: palette RECONSTRUCTION now covers the key-frame paths
72 // (earlier lanes), the intra-in-inter square/rect paths (r22) and the
73 // 8x8 LEAF inside an inter frame (this round, gate
74 // `a_screen_stream_with_palette_8x8_leaves_in_inter_frames_decodes_pixel_exact`),
75 // which is why the (UV) string is gone from the decoder entirely -- the
76 // leaf was its only site. The (Y) one survived as the defensive
77 // `palette.is_none()` guard in `read_intra_mode`/`read_intra_mode_rect`
78 // until lane-t900 r33 DELETED both arms: all eight call sites hand the
79 // reader a real ctx/cache pair, so no stream could reach either (audit
80 // `every_read_intra_mode_call_site_hands_the_reader_a_palette_cache`,
81 // which keeps that invariant now the refusal is gone).
82 // lane-av1-ibcrect: `intra block copy on a HORZ/VERT/1:4 rect intra strip
83 // (reconstruction is not ported at this shape)` is GONE -- lane-av1-intrabc
84 // and lane-av1-rect14 reconstructed the 16x16/32x32-level strips, and this
85 // lane ported the last site, `decode_block_128rect`'s 128-root HORZ/VERT
86 // strip (`decode_intrabc_128rect`; a 128 root has no 1:4 arm at all).
87 // Witness:
88 // `an_sb128_rect_strip_with_intrabc_decodes_pixel_exact` (real aomenc
89 // sb128 screen streams coding `use_intrabc` on BLOCK_128X64 strips,
90 // pixel-exact vs ffmpeg).
91 // lane-av1txr: `a sub-8x8 leaf that uses intrabc (…)` is GONE -- the
92 // capability landed in this lane (4x4 / 4x8 / 8x4 intrabc leaves read the
93 // DV and reconstruct a frame copy + the INTER residual; the sub-8x8
94 // intrabc leaf witnesses in `stream.rs` and the `warped.obu` /
95 // `allintra.obu` traces). Its census gate
96 // (`a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal`)
97 // still runs: it now reports `reached = 0` with the same non-vacuous
98 // premise (allow_intrabc frames + decoded sub-8 leaves).
99 // lane-av112bit: the blanket 12-bit refusal is REPLACED by the named
100 // refusals below -- the witnessed paths (intra stack, dequant/
101 // transforms at the 12-bit tables, deblock, CDEF, Wiener+SGR
102 // restoration, translational subpel MC through the parameterised
103 // round_0/round_1) are lifted by the lane's byte-exact ffmpeg gates.
104 // lane-av112bitc: compound joined the witnessed set (six-frame 12-bit
105 // compound stream byte-exact vs ffmpeg; the combines already absorbed
106 // the CONV_BUF gain drop through `INTER_POST_ROUND - delta`).
107 // lane-av112bitg: film grain joined the witnessed set (two-frame
108 // `--film-grain-test=5` stream byte-exact vs ffmpeg; the gate that
109 // replaced the refusal is
110 // `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`).
111 // lane-av112bitw: warp joined too -- the refusal left all three decision
112 // sites (compound, 16x16+, 8x8 leaf): `warp::warp_round_0` implements
113 // convolve.h's 12-bit `round_0` bump (3 -> 5), and both the single-ref
114 // witness (`a_12bit_warped_motion_stream_decodes_pixel_exact`, the exact
115 // recipe that refused pre-lift) and the rotating-mandelbrot
116 // compound-warp witness
117 // (`a_real_compound_global_warp_12bit_stream_decodes_pixel_exact`, 28
118 // compound warp blocks) are byte-exact vs ffmpeg.
119 // lane-av1screen12: screen content tools LEFT the 12-bit refusal set. The
120 // string was "a 12-bit frame with screen content tools
121 // (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit
122 // witness)" -- a guard BROADER than the gap it named, because
123 // `allow_screen_content_tools` only opens the `palette_y_mode` /
124 // `palette_uv_mode` symbols and the leaf `use_intrabc` symbol, and both
125 // reconstructions are already depth-parameterised
126 // (`read_palette_colors_y` / `_uv` read at `bit_depth(fctx)`, the
127 // colour-index map writes u16 samples). Three 12-bit arms decode
128 // BYTE-EXACT against the instrumented `aomdec --rawvideo` and against
129 // ffmpeg, each with a +1 control on the oracle's own bytes:
130 // `a_real_aomenc_12bit_screen_content_palette_stream_decodes_pixel_exact`
131 // (pin `screen12_palette.obu`, 2 frames, 76 palette / 43 palette-UV),
132 // `a_real_aomenc_12bit_intrabc_screen_stream_decodes_pixel_exact` (pin
133 // `screen12_intrabc.obu`, 1 frame, `allow_intrabc = 1`, 36 palette /
134 // 34 palette-UV / 11 intrabc blocks) and
135 // `a_real_aomenc_12bit_lossless_screen_content_stream_decodes_pixel_exact`
136 // (pin `screen12_lossless_palette.obu`, 2 frames, 80 palette /
137 // 59 palette-UV, `CodedLossless` AND screen content in the same frame).
138 // The companion "12-bit intrabc has no producer" note was a RECIPE
139 // artefact: libaom sets that frame-header bit from its content detector
140 // (`encoder.c:2404`), so an untiled `smptebars=size=128x96` source gives
141 // `allow_intrabc = 0` with AND without `--tune-content=screen`, while the
142 // 256x192 `-vf tile=2x2` source gives `= 1` at 8, 10 and 12 bits.
143 // lane-av1txr-r2 added, lane-av1-qmatrix RETIRED: the third member of the
144 // silent-garbage family (`using_qmatrix`/`qm_y`/`qm_u`/`qm_v`, refused by
145 // name at the frame header) now DEQUANTISES through libaom's
146 // `iwt_matrix_ref`/`get_dqv` port (`crate::qm`): the parsed 4-bit levels
147 // select per-plane matrices, 1D/identity transforms and lossless blocks
148 // stay flat. Witness:
149 // `a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact`.
150 // lane-lossless/lane-lossless2: a lossless frame (base_q_idx 0) decodes
151 // sample-exact, KEY and INTER -- TX_4X4 with the Walsh-Hadamard transform
152 // on every plane, no `tx_type` symbol, `is_cfl_allowed` narrowed to a
153 // BLOCK_4X4 chroma plane block, and the chroma plane walked as 4x4 units
154 // plane-major inside each mu chunk (gates
155 // `a_lossless_libaom_key_frame_decodes_sample_exact` /
156 // `a_lossless_libaom_inter_frame_decodes_sample_exact`). The refusal
157 // that stood here for a frame whose SEGMENTS disagree ("the TX_4X4/WHT
158 // rules are per segment there") is LIFTED too: lane-av1mixloss ports the
159 // per-segment table (libaom `decodeframe.c:5205`), and
160 // `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact`
161 // proves a real aq-mode stream sample-exact.
162 "a frame OBU with no tile group",
163 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
164 "a frame with no mode-info grid",
165 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)",
166 // Still live, but NARROWED: lane-rectres r1 added the 32x32-level 1:4
167 // strips (32x8 / 8x32) to `rect_inter_residual_supported` -- THE shape both
168 // 10-bit 3840x1608 film cuts and every measured 1080p offset stopped on
169 // (gate `a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_\
170 // their_rect_residual`). The string stays because the shapes below 8x8 and
171 // the AB-partition footprints still have no rectangular residual path.
172 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
173 "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it",
174 "a reference picture outside the 2x down / 16x up scaling limits",
175 "a show_existing_frame header naming an empty reference slot",
176 "an inter var-tx tree with a leaf transform larger than 32x32",
177 // lane-intrainter r1 lifted the >=16x16 square case (per-TU intra
178 // prediction + coefficients, gate
179 // `a_real_aomenc_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact`);
180 // lane-leaf8tx r4 lifted the 8x8 leaf's TX_4X4 2x2 grid (gate
181 // `a_real_aomenc_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact`).
182 "an inter frame with no key frame before it",
183 // lane-inter16ab r1 lifted the AB half and r2 the 1:4 half (four 16x4 /
184 // 4x16 inter strips, their 8x4/4x8 chroma pair built from BOTH strips'
185 // motion vectors -- gate
186 // `a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact`).
187 // Two narrower refusals are what is left of that shape:
188 "an inter 16x16-level partition value outside NONE/HORZ/VERT/SPLIT/AB/1:4",
189 // r2 residue: `vartx_leaves` is a list of SQUARE units, and
190 // `sub_tx_size_map[TX_16X4]` is the rectangular TX_8X4 -- the split tree
191 // and its per-unit residual reader both need rect leaves.
192 // r2 residue: `decode_intra_rect_in_inter` codes chroma at the strip's own
193 // halved footprint, which for a 16x4 strip is an 8x2 transform libaom
194 // never wrote (its chroma is the PAIR's 8x4, coded by the odd strip).
195 // lane-sub8x4 r3 narrowed this to "a strip with no chroma-pair record";
196 // lane-wit16x4 r1 put it back at FULL width (r3's witness counters were
197 // phantoms of a desync, class `refusal-lifted-without-a-gate`) behind
198 // an opt-in. lane-t900 r6 NARROWED it again -- the opt-in is
199 // gone -- on a real 10-bit 1920x792 128-superblock film witness that
200 // decodes 14/14 decode-order frames exact vs aomdec and 12/12 shown frames
201 // exact vs ffmpeg while the arm fires 78 16x4 + 149 4x16 (108 chroma-
202 // paired): gate
203 // `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_decode_pixel_exact`.
204 // What still refuses is a 16x4/4x16 strip with NO chroma-pair record and
205 // every other sub-8 shape.
206 "an intra 16x4/4x16 strip inside an inter 16x16-level 1:4 partition (its 4:2:0 chroma pair is coded once for two strips; only the inter path implements that pairing)",
207 "an intra mode this decoder does not code (round 2)",
208 // lane-intrarect r1 lifted the whole-shape refusal that stood here (the
209 // inter path's intra arm now routes 2:1 strips through `decode_rect_split`);
210 // what is left is the 1:4 shape, whose `bsize_to_tx_size_cat` breaks the
211 // size-group/category diagonal the 2:1 shapes share.
212 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)",
213 // lane-t900 r21 NARROWED this: the string used to guard EVERY rect intra
214 // strip of a screen-content inter frame, and a real
215 // `--tune-content=screen` stream reached it on an 8x16 (8-bit) / 16x8
216 // (10-bit) strip. The 2:1 reader now codes the palette syntax itself and
217 // the 1:4 arm goes through `read_intra_mode_rect`, which already did --
218 // both arms of gate
219 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`
220 // decode ten frames pixel-exact with the strips counted. What still
221 // lane-t900 r22 NARROWED it again: the 16x4/4x16 arm is LIFTED (that arm
222 // routes through `decode_rect4_16_strip`, which reads the palette syntax
223 // itself -- the premise was stale), gated by
224 // `a_screen_stream_with_16x4_intra_strips_in_inter_frames_decodes_pixel_exact`.
225 // What still refuses is the 128-root half of a screen-content frame, whose
226 // body (`decode_block_128rect`) reads no palette syntax and for which no
227 // `--sb-size=128` screen witness exists yet.
228 // lane-t900 r32: the 128-root arm is LIFTED. r31's enumeration
229 // (`no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax`) is
230 // its proof -- `av1_allow_palette`'s `bw > 64 || bh > 64` bound means a
231 // 128x64/64x128 half codes NO palette syntax at all, so a screen-content
232 // frame's half is byte-identical in syntax to the non-screen twin gate
233 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`
234 // already decodes pixel-exact. Nothing of this string remains.
235 // lane-t900 r32: the residue of the LIFTED "an intrabc block under
236 // TxMode::Select". The inter var-tx tree is read in full, but the intra
237 // luma reconstruct loop it feeds is a UNIFORM grid of one square
238 // transform, so a tree resolving to mixed leaf sizes would be
239 // reconstructed at the wrong stride. Neither arm of
240 // `an_intrabc_block_under_tx_mode_select_decodes_pixel_exact` reaches it
241 // (both resolve uniform), so it is unwitnessed and stays live.
242 // lane-av1-ibcvtx: LIFTED. The t900 census's own maxp32 recipe class,
243 // retargeted at testsrc2 content with `--max-partition-size=64`, reaches
244 // mixed trees on the first encode (12-recipe hunt, 5/12 recipes hit).
245 // The luma reconstruct now walks the tree's own leaf list per leaf, and
246 // the block's chroma inherits the co-located luma unit's coded tx type
247 // (`av1_get_tx_type`, blockd.h:1278 -- that inheritance was missing on
248 // the uniform multi-TU intrabc path too). Gate:
249 // `a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal`.
250 // Its census gate
251 // (`an_intrabc_vartx_census_measures_the_mixed_leaf_refusal`) survives as
252 // the witness that the premise is still exercised -- `reached` is 0 by
253 // construction now.
254 "a motion_mode symbol for a block shape with no CDF row here",
255];
256
257/// The refusals that have a PROVING test, and its name.
258///
259/// A refusal with no such test is an unmeasured claim: nothing in the suite
260/// distinguishes "this case never happens" from "no stream we decode has
261/// reached it yet". A proving test is one of two shapes:
262///
263/// * a WITNESS gate -- a real stream reaches the shape, decodes exact, and the
264/// refusal is gone (the good case), or
265/// * a CENSUS gate -- N real streams decode with the refusal firing 0 times
266/// while the counters for the sibling shapes it names fire, so the claim is
267/// measured against the domain the decoder is actually handed.
268///
269/// The count printed by [`tests::every_proven_refusal_names_a_test_that_exists`]
270/// is the honest numerator over the inventory below.
271///
272/// # lane-av1-hdr: which pins are `spec-conformant` vs a real gap
273///
274/// A negative gate proves our refusal FIRES by name on a hand-built stream; it
275/// does not prove libaom would reject the same stream. This lane read the
276/// libaom counterpart for the header/reference cluster and recorded the
277/// verdict (`lanes/av1hdr.report.md` §3). The spec-conformant pins (libaom
278/// errors identically) are, with their libaom site:
279///
280/// * `primary_ref_frame` empty slot -- `decodeframe.c:5075` `AOM_CODEC_CORRUPT_FRAME`.
281/// * `show_existing_frame` empty slot -- `decodeframe.c:4651` `AOM_CODEC_UNSUP_BITSTREAM`.
282/// * reference selected with no picture -- `decodeframe.c:5027` `AOM_CODEC_CORRUPT_FRAME`.
283/// * inter frame with no key frame before -- same site (`decodeframe.c:5008`).
284/// * no mode-info grid -- no libaom error site; a 0-sized frame cannot be coded.
285///
286/// The two that are NOT spec-conformant, and are kept as named capability gaps
287/// with an assessment (a real gap libaom accepts, no reachable witness here):
288/// a reference picture whose height differs (libaom SCALES,
289/// `decodeframe.c:5089`). A third one -- a frame mixing lossless and lossy
290/// segments (libaom decodes it per segment, `decodeframe.c:5205`) -- was the
291/// same kind of gap until lane-av1mixloss ported the per-segment table; its
292/// refusal is gone and
293/// `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact` is the
294/// witness.
295#[cfg(test)]
296/// Which KIND of proof each [`PROVEN`] row carries.
297///
298/// A 2-tuple made every row look equally proven, which is the whole defect:
299/// a row whose gate drives a hand-built stream into the guard and a row
300/// whose gate sweeps an alphabet and shows nothing reaches it are held to
301/// the same standard and read the same way. `label()` is what the tests
302/// print, so the distinction is visible in the suite's own output.
303///
304/// lane-av1refusalclaim r3 also proposed a third variant, `TablePin`
305/// ("the arms are pinned exactly but the domain the table is REACHED over
306/// is unestablished"). It is deliberately NOT carried: the one row it was
307/// minted for now has a gate that establishes the reach domain
308/// (`every_chroma_unit_decode_block_rect_can_present_has_a_coefficient_table`
309/// reads the eight `decode_block_rect` call sites' own literal `bw`/`bh`,
310/// pins the resulting chroma table exactly, and asserts the `(4,8)`/`(8,4)`
311/// residual is UNPRODUCIBLE), so `Enumeration` is the honest tag and a
312/// variant with no row would be dead weight. Re-add it the day a gate really
313/// pins a table without measuring its caller domain -- and give it a row.
314#[cfg(test)]
315enum Proof {
316 /// A written stream REACHES the guard and is refused by this exact
317 /// string: the gate goes RED if the guard is removed.
318 NegativeGate,
319 /// The gate enumerates every input the guard can be reached over and
320 /// shows that none of them reaches it: it proves UNREACHABILITY, so it
321 /// is GREEN if the guard is removed.
322 Enumeration,
323}
324
325#[cfg(test)]
326impl Proof {
327 fn label(&self) -> &'static str {
328 match self {
329 Proof::NegativeGate => "NEGATIVE (reaches the guard; red on removal)",
330 Proof::Enumeration => "ENUMERATION (proves unreachability; green on removal)",
331 }
332 }
333}
334
335#[cfg(test)]
336const PROVEN: &[(&str, &str, Proof)] = &[
337 // lane-t900 r20, census: three real streams present exactly the 18
338 // `(side, write_w, write_h)` triples `INTER_BLOCK_SHAPES` lists, and
339 // `rect_inter_residual_supported` covers every rectangular one -- the only
340 // footprints `reject_residual` is set for.
341 // lane-av1-witness2 (8 more inter encodes: banded and busy content,
342 // --max-partition-size=32, a single-ref arm, cq 20..45, cpu-used 0..1):
343 // no refusal -- every rect strip the encoder produced sat inside the
344 // supported set. Static half, from the same hunt: the supported list plus
345 // the partition walker's piece set (SB pieces 64x32/32x64/64x16/16x64,
346 // the 32- and 16-level rect/1:4/AB twins, 128 halves tiled as two
347 // TX_64X64) enumerate every rect footprint AV1 partitioning can present;
348 // 1:4 stops at 64 because the 128 root has no 1:4 symbol. No conformant
349 // stream can name an unsupported footprint.
350 (
351 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
352 "a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable",
353 Proof::Enumeration,
354 ),
355 // lane-t900 r20, census: the shapes that can reach `decode_intra_rect_in_inter`'s
356 // size-group/tx-category lookup are the ten rectangular census shapes with
357 // `8 <= min` and `max <= 64` (a sub-8 footprint and a 128-px one take
358 // earlier branches), and every one of them has a row.
359 (
360 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)",
361 "every_intra_in_inter_shape_the_census_lists_has_a_size_group_row",
362 Proof::Enumeration,
363 ),
364 // lane-t900 r20, census: the only sub-8 footprints three real streams
365 // present are the 16x4/4x16 strips of a 16x16-level 1:4 partition, whose
366 // caller records the chroma pair for every strip, while the supported path
367 // fires on both orientations inside streams that decode with no refusal.
368 (
369 "an intra 16x4/4x16 strip inside an inter 16x16-level 1:4 partition (its 4:2:0 chroma pair is coded once for two strips; only the inter path implements that pairing)",
370 "a_sub8_footprint_census_over_real_streams_leaves_the_intra_16x4_pairing_refusal_unreachable",
371 Proof::Enumeration,
372 ),
373 // lane-t900 r20, census: the rect transform tables and scans, enumerated
374 // over the shapes the measured block-shape domain hands each helper (block
375 // footprint, 4:2:0 chroma unit, rect var-tx leaf, clamped coded corner).
376 // lane-av1-witness2 (8 inter encodes, --enable-tx-size-search=1, rect+1:4
377 // on, --min-partition-size=4, 4:2:0 and 4:4:4, sb 64/128, cq 10..45,
378 // cpu-used 0..2): no refusal while the domain was genuinely exercised --
379 // whole-block 32x8 inter TUs and sub-8 rect pieces decoded. The fourteen
380 // rect shapes the enumeration covers are the whole alphabet, so the `_`
381 // arm has no conformant input.
382 (
383 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
384 "every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan",
385 Proof::Enumeration,
386 ),
387 (
388 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
389 "every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan",
390 Proof::Enumeration,
391 ),
392 (
393 "a rectangular transform unit whose shape has no coefficient scan table here",
394 "every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan",
395 Proof::Enumeration,
396 ),
397 // lane-t900 r21, enumeration: a var-tx leaf is never larger than the unit
398 // the tree was entered with, and both callers enter at or below their own
399 // ceiling (the one case that does not, a 64px block at TX_64X64, is the
400 // `single` whole-block case the refusal is guarded by).
401 (
402 "an inter var-tx tree with a leaf transform larger than 32x32",
403 "a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered",
404 Proof::Enumeration,
405 ),
406 (
407 "an inter var-tx tree with a leaf transform larger than 64x64",
408 "a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered",
409 Proof::Enumeration,
410 ),
411 // Pre-existing proofs, registered by lane-t900 r21: a negative gate (a
412 // hand-built 12-bit sequence header is refused BY THIS EXACT STRING rather
413 // than decoded wrong) and a witness gate (a real aomenc screen key frame
414 // reaches intrabc on a rect strip, so the refusal names a shape a real
415 // encoder does write).
416 // lane-t900 r21, enumeration: `partition_w32` is a ten-symbol CDF and
417 // `partition_w128` an eight-symbol one, and every `match` carrying one of
418 // these three fallbacks has an arm for each value of its own alphabet, so
419 // no stream can reach them.
420 (
421 "a 32x32 partition type this decoder does not code (value={part32})",
422 "every_partition_value_of_an_enumerated_alphabet_has_an_arm",
423 Proof::Enumeration,
424 ),
425 (
426 "an INTER 32x32 partition type this decoder does not code (value={part32})",
427 "every_partition_value_of_an_enumerated_alphabet_has_an_arm",
428 Proof::Enumeration,
429 ),
430 (
431 "a 128x128 superblock partition value outside the 8-symbol alphabet",
432 "every_partition_value_of_an_enumerated_alphabet_has_an_arm",
433 Proof::Enumeration,
434 ),
435 // lane-t900 r24, enumeration: the key-frame superblock root's own `match`
436 // has an arm for all ten `partition_w64` values.
437 (
438 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
439 "every_partition_value_of_an_enumerated_alphabet_has_an_arm",
440 Proof::Enumeration,
441 ),
442 // lane-t900 r24, enumeration: the inter 16x16-level if/else chain's
443 // branches name all ten `partition_w16` values between them.
444 (
445 "an inter 16x16-level partition value outside NONE/HORZ/VERT/SPLIT/AB/1:4",
446 "every_partition_value_of_an_if_chain_alphabet_is_named_by_a_branch",
447 Proof::Enumeration,
448 ),
449 // lane-t900 r24, enumeration: every (CDF width, symbol) pair a tx_type row
450 // can present maps to a distinct member of that width's own set.
451 (
452 "a tx_type symbol outside its CDF's own set: {t}",
453 "every_tx_type_symbol_of_every_cdf_width_maps_into_its_own_set",
454 Proof::Enumeration,
455 ),
456 // lane-t900 r24 + lane-av1txr RE-PIN, measured: the reader covers spec
457 // 5.11.40's whole value domain (`0..=(1 << 20) - 2`, both ends of every
458 // prefix length), so no CONFORMANT symbol stream reaches it -- but the
459 // string IS reachable as a SYMPTOM: a frame this decoder desyncs on
460 // (measured: a real libaom monochrome key frame, gate
461 // `a_real_libaom_monochrome_key_frame_is_refused_by_name` at
462 // `stream.rs`) leaves the reader mid-symbol and the next `read_golomb`
463 // reports this tail. The claim below therefore pins the reader's value
464 // coverage, NOT the string's unreachability.
465 (
466 "a Golomb tail longer than this decoder reads",
467 "read_golomb_reads_every_value_a_conformant_stream_can_carry",
468 Proof::Enumeration,
469 ),
470 // lane-t900 r25, enumeration: `parse_tile_group` is the only producer of
471 // the `tiles` vector `decode_stream` tests, and its success path always
472 // pushes at least one `Tile` -- swept over a real frame OBU's tile payload
473 // truncated from empty upwards.
474 (
475 "a frame OBU with no tile group",
476 "a_frame_obu_that_parses_always_carries_at_least_one_tile",
477 Proof::Enumeration,
478 ),
479 // lane-t900 r25, negative gates: hand-built streams that reach each
480 // refusal by name and output no picture (a `show_existing_frame` header
481 // over all 8 empty slots; a stream that opens on an inter frame).
482 (
483 "a show_existing_frame header naming an empty reference slot",
484 "a_show_existing_frame_header_naming_an_empty_slot_is_refused_by_name",
485 Proof::NegativeGate,
486 ),
487 (
488 "an inter frame with no key frame before it",
489 "an_inter_frame_opening_a_stream_is_refused_by_name",
490 Proof::NegativeGate,
491 ),
492 // lane-t900 r25, enumeration: a motion_mode/obmc symbol is read only under
493 // `is_motion_variation_allowed_bsize` (min side >= 8), and each of the 17
494 // `BLOCK_SIZES_ALL` footprints that clause admits maps to a distinct row of
495 // the 17-row table.
496 (
497 "a motion_mode symbol for a block shape with no CDF row here",
498 "every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row",
499 Proof::Enumeration,
500 ),
501 // lane-av112bit: real-aomenc 12-bit streams, each refused by name
502 // (the gates encode with aomenc --bit-depth=12 and assert the exact
503 // string; the pixel witnesses are the same battery's Ok arms).
504 // lane-av112bitc: the compound pair left with its refusal -- the
505 // six-frame compound stream now DECODES byte-exact
506 // (`a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact`).
507 // lane-av112bitg: the grain refusal left with its witness -- the
508 // two-frame 12-bit grain stream now DECODES byte-exact
509 // (`a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`).
510 // lane-av112bitw: the warp pair left too -- its gate now WITNESSES
511 // (`a_12bit_warped_motion_stream_decodes_pixel_exact`, the same recipe
512 // that refused pre-lift) and the compound-warp arm witnesses through
513 // `a_real_compound_global_warp_12bit_stream_decodes_pixel_exact`
514 // (hard `compound_warp_hits > 0`).
515 // lane-av1422lift: the 4:2:2 sequence-header refusal is GONE and so is
516 // this pairing. The tuple named `a_non_420_subsampled_sequence_header_is_
517 // refused_by_name` as the gate that refused (1,0); that gate asserted a
518 // REFUSAL STRING, so it could not fail on a tree where 4:2:2 decode was
519 // completely broken -- it passed unchanged on the broken tree and would
520 // have kept passing if the port had been reverted. Its replacement
521 // `a_real_422_key_frame_and_inter_sequence_decode_pixel_exact` (and the
522 // corpus battery `the_pinned_422_corpus_cells_decode_pixel_exact`) assert
523 // BYTE-EXACT planes against ffmpeg on real 4:2:2 streams, with the
524 // per-plane coefficient-unit census as the non-vacuity arm.
525 // lane-av1txr-r2 paired, lane-av1-qmatrix RETIRED with its gate: the
526 // refusal's witness is now
527 // `a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact`, which
528 // asserts the qm-on stream DECODES pixel-exact vs ffmpeg and the
529 // matrices were really applied (census counters), while the qm-off
530 // control stays exact and flat.
531 // lane-av1-ibcrect: the pairing for "intra block copy on a HORZ/VERT/1:4
532 // rect intra strip (reconstruction is not ported at this shape)" is GONE
533 // with the string -- lane-av1-intrabc/rect14 reconstructed the
534 // 16x16/32x32-level strips and this lane ported the last site,
535 // `decode_block_128rect`'s 128-root strip. Witness:
536 // `an_sb128_rect_strip_with_intrabc_decodes_pixel_exact`.
537 // lane-t900 r26, enumeration: a y_mode symbol comes from a 13-symbol CDF
538 // and all three guards refuse 13 and above.
539 (
540 "an intra mode this decoder does not code (round 2)",
541 "every_intra_mode_symbol_of_the_y_mode_alphabet_is_coded",
542 Proof::Enumeration,
543 ),
544 // lane-t900 r26, enumeration: `compute_image_size` is 0 only for a zero
545 // frame width/height, which no path a header can code produces (swept
546 // through the real reader per axis, superres division enumerated).
547 (
548 "a frame with no mode-info grid",
549 "every_frame_size_a_header_can_code_has_a_mode_info_grid",
550 Proof::Enumeration,
551 ),
552 // lane-t900 r26, negative gates: written streams that reach each refusal
553 // by name (a 64x32 inter frame over a 64x64 reference; a stream opening on
554 // a non-error-resilient inter frame whose primary_ref slot is empty, over
555 // all 8 slots) with the picture/CDF slot invariant enumerated alongside.
556 // lane-t900 r27, negative gate + structural note: every non-`LAST_FRAME`
557 // reference resolves through `ref_planes`, where an empty slot refuses by
558 // name (swept over all six such references). The STREAM-level witness is
559 // out of reach of this crate's writers -- a shown key frame refreshes all
560 // eight slots and nothing ever clears one, and a stream opening on an
561 // inter frame is stopped one guard earlier -- so the reachable premise is
562 // a HIDDEN key frame with a partial `refresh_frame_flags`, which
563 // `write_frame_header` cannot write. That gap is the open half.
564 (
565 "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it",
566 "a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name",
567 Proof::NegativeGate,
568 ),
569 // lane-t900 r27, negative gate + census: a written key frame carrying
570 // each of the three mode-overriding features (over three segment ids) is
571 // refused by name with no picture; and real aomenc recipes never enable
572 // one. lane-av1seglvl re-scoped the census: beyond r27's six 1-pass
573 // no-lag recipes it now parses EVERY frame header's feature table over
574 // alt-ref-lag and genuine two-pass arms (`--aq-mode=1/2`, cq45 and the
575 // branch's own high-q cq63, screen + film sources) -- the shapes that
576 // reach `configure_static_seg_features`, the only setter of ALT_LF/
577 // REF_FRAME/SKIP in the tree, which is gated on `hl_sf.static_segmentation`
578 // ("Always set to 0", speed_features.h) and the second pass
579 // (encoder_utils.c:738). What aomenc codes is `SEG_LVL_ALT_Q` tables and
580 // `segment_id` symbols, and nothing else; the map-inheritance defect that
581 // census surfaced (verbatim copy, decodemv.c:342) is fixed and witnessed
582 // by `a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_ // pixel_exact`.
583 // lane-av1-witness2 re-confirmed the census on the current aomenc build:
584 // it has no --enable-segmentation flag at all (aq-mode is the only
585 // segmentation driver; aq-mode 4 is out of range for the build), and 8
586 // aq-mode recipes (1/2/3, + --delta-lf-mode=1, 4:4:4, banded content)
587 // wrote SEG_LVL_ALT_Q tables and segment_id symbols where segmentation
588 // engaged, decoded clean, and never coded one of the three
589 // mode-overriding features.
590 (
591 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)",
592 "a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name",
593 Proof::NegativeGate,
594 ),
595 // lane-t900 r27, structural audit + witness: `record_inter_rect_mi` is the
596 // single writer of the interp-filter neighbour band, and no call site
597 // stamps the `[3, 3]` sentinel on an INTER cell (the audit tokenises each
598 // site's arguments); two real `--enable-obmc=1 --enable-dual-filter=1
599 // --cpu-used=0` streams then decode with 237 band reads over ~115 OBMC
600 // blocks each and the refusal firing 0 times (gate
601 // `a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour`).
602 // At `--cpu-used=4` aomenc settles on a frame-level fixed filter and the
603 // band is never read -- the speed is load-bearing in that gate.
604 (
605 "an OBMC neighbour whose switchable interp filter was never recorded",
606 "every_inter_record_publishes_an_obmc_readable_filter",
607 Proof::Enumeration,
608 ),
609 // lane-t900 r28: all three scaled-reference (superres) refusals -- the
610 // 8x8 partition leaf, the sub-8x8 inter block and warp -- are LIFTED and
611 // gone from this inventory. The gate
612 // `real_superres_streams_with_sub8_leaf8_and_warp_decode_pixel_exact`
613 // decodes both lifted shapes byte-exact vs ffmpeg, and the census now
614 // asserts none of the three strings comes back.
615 // lane-t900 r33, enumeration: the five callers of `decode_rect_split` pass
616 // the ten rect footprints with `8 <= min` and `max <= 64`, and every one of
617 // them has a chroma table and -- at every tx depth -- a luma arm. The two
618 // shape classes that would miss one (a 128-sided half, a sub-8 strip) have
619 // readers that are not among those callers.
620 (
621 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
622 "every_rect_strip_shape_the_split_path_codes_has_a_luma_and_chroma_table",
623 Proof::Enumeration,
624 ),
625 (
626 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)",
627 "every_rect_strip_shape_the_split_path_codes_has_a_luma_and_chroma_table",
628 Proof::Enumeration,
629 ),
630 // lane-av1-refusalaudit, enumeration + witness2 hunt: decode_block_rect64's
631 // chroma-unit table covers every conformant 64-axis strip unit in both
632 // supported chroma formats -- at 4:4:4 the strips 64x32/32x64/64x16/16x64
633 // tile to (32,32)/(32,16)/(16,32); at 4:2:0 the halved footprints land on
634 // (32,16)/(16,32)/(32,8)/(8,32). A 128-root half is
635 // `decode_block_128rect`'s, and the 128 root has no 1:4 arm. The hunt (8
636 // real aomenc key-frame encodes: screen+intrabc, rect+1:4, sb 64 and 128,
637 // cq 10..63, cpu-used 0..2) never reached the arm; the three streams that
638 // decode to completion never enter decode_block_rect64 at all.
639 (
640 "a 64-axis strip whose chroma unit has no coefficient table",
641 "every_chroma_unit_a_64_axis_strip_can_present_has_a_coefficient_table",
642 Proof::Enumeration,
643 ),
644 // lane-av1rect8x16, enumeration: `decode_block_rect`'s `_` arm. The nine
645 // textual `decode_block_rect(` matches are 1 declaration + 8 call sites
646 // (this test's `assert_eq!(sites, 8)` counts the calls); all eight pass
647 // `bw`/`bh` as integer LITERALS and every one of them is
648 // a 32-level `PARTITION_HORZ`/`VERT`/`HORZ_A`/`_B`/`VERT_A`/`_B` arm of
649 // `read_sb128_root`'s `match part32`, so the caller shape set is exactly
650 // {32x16, 16x32} and their chroma halves under the three subsamplings an
651 // AV1 `color_config` can carry are {(16,8), (8,16), (16,16), (8,32),
652 // (32,16), (16,32)} -- every one of which has a row. The shape the
653 // sibling sweep left open, a 4:2:0 8x16 luma strip's (4,8) chroma, is
654 // NOT reachable here: a 16-level 2:1 luma strip is read by
655 // `decode_leaf_rect`, which carries the (4,8)/(8,4) rows itself
656 // (decode.rs:15409-15420). Measured, not assumed: 840 real aomenc 4:2:0
657 // key-frame encodes, 826 of whose parsed leaf lists carry a coded
658 // 16-level 2:1 luma strip (`horz_vert_intra_hits()`, which fires only
659 // at the three `decode_leaf_rect` strip sites), decoded to completion
660 // with this string firing 0 times.
661 (
662 "a rectangular chroma transform whose size has no coefficient table",
663 "every_chroma_unit_decode_block_rect_can_present_has_a_coefficient_table",
664 Proof::Enumeration,
665 ),
666 // lane-t900 r33, enumeration: each of the four symbols this guard tests is
667 // read under a size gate that no 128-pixel side passes (the call site's
668 // literal `cfl=false`, `filter_intra_size_class_rect`'s table, and
669 // `palette_bsize_ctx_wh`'s bound).
670 (
671 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of their size gates caps at 64x64 or below, so none of these symbols exists there)",
672 "no_128_root_half_reads_a_cfl_filter_intra_or_palette_symbol",
673 Proof::Enumeration,
674 ),
675 // lane-av1txr: the sub-8x8 intrabc refusal this census pinned is GONE (the
676 // capability landed; see the note in `REFUSALS`). The census gate survives
677 // as the witness that its premise is still exercised -- `reached` is 0 by
678 // construction now.
679 // lane-t900 r33, CENSUS: four quantisers of the recipe that reaches the
680 // intrabc var-tx tree at all read it for 5 blocks in total, every one of
681 // which resolved to a UNIFORM leaf size, with the frames pixel-exact.
682 // lane-av1-ibcvtx: the mixed-leaf refusal is LIFTED (see the note in
683 // `REFUSALS`); the pair above moved out with the string. The capability
684 // gate is
685 // `a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal`,
686 // which pins the frame's residual sample mismatch against ffmpeg to the
687 // named second defect (a non-intrabc uniform-tree block elsewhere in the
688 // stream) so the pin tightens automatically when that defect is fixed.
689 (
690 "a reference picture outside the 2x down / 16x up scaling limits",
691 "an_inter_frame_shorter_than_its_reference_is_refused_by_name",
692 Proof::NegativeGate,
693 ),
694 (
695 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
696 "an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name",
697 Proof::NegativeGate,
698 ),
699 // lane-av1bookkeep W1-4, NEGATIVE: the BLOCK_INVALID subsize refusal
700 // (`refuse_invalid_plane_block`, decode.rs). It is libaom's own rule
701 // (`get_plane_block_size` -> `AOM_CODEC_CORRUPT_FRAME`, decodeframe.c:1456)
702 // applied to a stream whose header and tile disagree. The pin is a 4:2:2
703 // sequence header over a 4:2:0 key frame's tile, whose partition symbols
704 // name 8x16 -- a subsize with no chroma plane block at ss (1,0) -- so the
705 // guard FIRES, by name, and the gate also drives a genuine 4:2:2 pin that
706 // must still decode, so it cannot pass by refusing everything. The gate's
707 // body quotes the refusal WHOLE (not just the libaom citation inside it),
708 // which is what makes this row an anchor the checker can hold.
709 (
710 "a block size 4x8, 8x16 or 16x4 (or 8x4 at 4:4:0) has no chroma plane block at this frame's subsampling mode (libaom: \\\"Block size %dx%d invalid with this subsampling mode\\\", av1/decoder/decodeframe.c:1456, refusing by the same rule)",
711 "a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt",
712 Proof::NegativeGate,
713 ),
714 // lane-av1bookkeep W1-4, ENUMERATION: the LONE capability claim. The guard
715 // in `decode_block_rect` fires only when `filter_intra.is_some()`, and that
716 // flag is `Some` only where `filter_intra_size_class_rect` says so. The
717 // strips the guard protects are `(64, 32)` / `(32, 64)`;
718 // `av1_filter_intra_allowed_bsize` caps both sides at 32x32, so no conformant
719 // stream offers the symbol there. The gate walks every EXPLICIT arm of the
720 // table (none admits a 64 axis), drives the square-delegate's callee
721 // `filter_intra_size_class` at 32 and 64 directly, and quotes the claim's
722 // leading clause in its own body.
723 (
724 "filter intra on a superblock-level HORZ/VERT strip (never expected -- av1_filter_intra_allowed_bsize caps at 32x32)",
725 "a_sb_level_horz_vert_strip_admits_no_filter_intra_symbol",
726 Proof::Enumeration,
727 ),
728];
729
730/// Gates whose `Err` arm turns a decode failure into a printed SKIP rather than
731/// a test failure.
732///
733/// A gate named `..._decodes_pixel_exact` that cannot decode has failed, and
734/// swallowing the error keeps the suite green while the gate proves nothing --
735/// the same vacuum as a gate whose feature never fires, arrived at from the
736/// other side. The list is the exact pin of the gates still shaped that way, so
737/// the set cannot grow; a converted gate is DELETED from it.
738///
739/// lane-av1skipfix: emptied. The last four (`filter_intra`, the two
740/// `deblocking` gates, and `gradients_stream_with_cdef`) were converted to the
741/// attempt-loop pattern -- several recipes, at least one required to decode, the
742/// feature counter hard-asserted on a pixel-compared attempt, a decode error on
743/// every attempt a hard failure carrying its refusal text. None of the four had
744/// a genuinely absent capability: every recipe family decoded, the refusals the
745/// old arms swallowed were a named *screen-content* refusal on one recipe and a
746/// stale premise on the CDEF gate (a single-superblock frame cannot make libaom
747/// write `cdef_bits > 0`, so the old recipe never read a `cdef_idx` at all).
748#[cfg(test)]
749const GATES_THAT_SKIP_ON_A_DECODE_ERROR: &[&str] = &[];
750
751/// Source text with Rust's line continuations dropped and every whitespace run
752/// collapsed to one space -- the form rustc gives a multi-line literal -- so a
753/// refusal written across three source lines is still findable in a body, and
754/// a gate's quote of it still matches the guard's spelling.
755#[cfg(test)]
756fn squash_source(s: &str) -> String {
757 let mut out = String::with_capacity(s.len());
758 let mut pending_space = false;
759 for (i, c) in s.char_indices() {
760 if c == '\\' {
761 let rest = &s[i + 1..];
762 if rest.contains('\n')
763 && rest
764 .chars()
765 .take_while(|c| *c != '\n')
766 .all(|c| c == ' ' || c == '\t' || c == '\r')
767 {
768 continue;
769 }
770 }
771 if c.is_whitespace() {
772 pending_space = true;
773 continue;
774 }
775 if pending_space && !out.is_empty() {
776 out.push(' ');
777 }
778 pending_space = false;
779 out.push(c);
780 }
781 out
782}
783
784/// Does `src` carry `refusal`?
785///
786/// Lane-av1refusalspan: a proving gate quotes the refusal it proves, and this
787/// is how it pins that quote to the guard that still carries the string. Both
788/// sides are squashed, so a literal written over two lines with a `\`
789/// continuation still matches.
790#[cfg(test)]
791pub(crate) fn pins_refusal(src: &str, refusal: &str) -> bool {
792 squash_source(src).contains(&squash_source(refusal))
793}
794
795#[cfg(test)]
796mod tests {
797 use super::{
798 CAPABILITY_CLAIMS, GATES_THAT_SKIP_ON_A_DECODE_ERROR, PROVEN, Proof, REFUSALS,
799 squash_source,
800 };
801 use std::collections::BTreeSet;
802
803 /// Every distinct `unsupported(...)` reason on the decode path.
804 ///
805 /// Both sources use the same shape -- `stream.rs` calls
806 /// `Error::unsupported(context, reason)` and `decode.rs` a local
807 /// `unsupported(reason)` helper -- so the reason is always the LAST string
808 /// literal of the call, and Rust's `\` line continuations inside it are
809 /// joined the way rustc joins them.
810 fn decode_path_refusals() -> BTreeSet<String> {
811 let mut found = BTreeSet::new();
812 for src in [crate::test_source::module_source("decode"), crate::test_source::module_source("stream")] {
813 let bytes = src.as_bytes();
814 for (start, _) in src.match_indices("unsupported(") {
815 // `Error::unsupported(` and the bare helper both end here.
816 let mut i = start + "unsupported(".len();
817 // `unsupported(format!("..."))` is the same refusal, one layer in.
818 if src[i..].starts_with("format!(") {
819 i += "format!(".len();
820 }
821 let mut last: Option<String> = None;
822 loop {
823 while i < bytes.len() && (bytes[i] as char).is_whitespace() {
824 i += 1;
825 }
826 if i >= bytes.len() || bytes[i] != b'"' {
827 break;
828 }
829 i += 1;
830 let mut lit = String::new();
831 while i < bytes.len() && bytes[i] != b'"' {
832 if bytes[i] == b'\\' {
833 // A backslash-newline continuation drops the newline
834 // and the indentation that follows it.
835 if bytes.get(i + 1) == Some(&b'\n') {
836 i += 2;
837 while i < bytes.len() && matches!(bytes[i], b' ' | b'\t') {
838 i += 1;
839 }
840 continue;
841 }
842 lit.push(bytes[i] as char);
843 lit.push(bytes[i + 1] as char);
844 i += 2;
845 continue;
846 }
847 lit.push(bytes[i] as char);
848 i += 1;
849 }
850 i += 1;
851 last = Some(lit);
852 while i < bytes.len() && (bytes[i] as char).is_whitespace() {
853 i += 1;
854 }
855 if i < bytes.len() && bytes[i] == b',' {
856 i += 1;
857 continue;
858 }
859 break;
860 }
861 if let Some(reason) = last {
862 // `Error::unsupported`'s first argument is the context
863 // ("AV1 tile"), which is not a reason.
864 if reason != "AV1 tile" {
865 found.insert(reason);
866 }
867 }
868 }
869 }
870 found
871 }
872
873 #[test]
874 fn the_decode_path_refuses_exactly_the_listed_cases() {
875 let found = decode_path_refusals();
876 let listed: BTreeSet<String> = CAPABILITY_CLAIMS
877 .iter()
878 .chain(REFUSALS)
879 .map(|&s| s.to_owned())
880 .collect();
881 assert!(
882 found.len() >= 30,
883 "the refusal scan found only {} reasons -- it is broken, not the decoder",
884 found.len()
885 );
886
887 let added: Vec<&String> = found.difference(&listed).collect();
888 assert!(
889 added.is_empty(),
890 "new decode-path refusals are not in the inventory: {added:#?}\n\
891 Add each to REFUSALS -- or, if it claims something about what an ENCODER can \
892 emit, to CAPABILITY_CLAIMS, which requires evidence that the case is genuinely \
893 unreachable rather than merely unseen."
894 );
895 let removed: Vec<&String> = listed.difference(&found).collect();
896 assert!(
897 removed.is_empty(),
898 "these refusals are listed but no longer in the decode path: {removed:#?}\n\
899 Delete them from the inventory -- the capability landed, which is the good case."
900 );
901 }
902
903 /// A refusal may say what THIS DECODER does not do. Saying what an encoder
904 /// never emits is a claim about the world, and this repository has already
905 /// shipped one that was false.
906 #[test]
907 fn capability_claims_are_declared_not_scattered() {
908 let claimy: Vec<String> = decode_path_refusals()
909 .into_iter()
910 .filter(|r| r.contains("never writes") || r.contains("never expected"))
911 .collect();
912 let declared: BTreeSet<&str> = CAPABILITY_CLAIMS.iter().copied().collect();
913 for reason in &claimy {
914 assert!(
915 declared.contains(reason.as_str()),
916 "{reason:?} claims an encoder never emits this case but is not in \
917 CAPABILITY_CLAIMS. Such a claim needs a gate that proves the case is \
918 unreachable; until it has one, phrase the refusal as what this decoder \
919 does not decode."
920 );
921 }
922 }
923
924 /// No NEW gate may quietly turn a decode error into a skip.
925 #[test]
926 fn gates_that_swallow_a_decode_error_are_declared() {
927 let src = crate::test_source::module_source("stream");
928 let mut found: BTreeSet<String> = BTreeSet::new();
929 for (i, _) in src.match_indices("\"SKIP ") {
930 let rest = &src[i + "\"SKIP ".len()..];
931 let Some(colon) = rest.find(':') else {
932 continue;
933 };
934 let name = &rest[..colon];
935 if !name
936 .chars()
937 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
938 {
939 continue;
940 }
941 // The tail of the message says what was skipped. Only "{e}" -- the
942 // decode error itself -- is the shape this test is about; "no
943 // ffmpeg"/"no aomenc" are tool absence, governed by
944 // EC_AV1_REQUIRE_AOMENC instead.
945 let Some(end) = rest.find("\"") else { continue };
946 if rest[colon..end].contains("{e}") {
947 found.insert(name.to_owned());
948 }
949 }
950 let listed: BTreeSet<&str> = GATES_THAT_SKIP_ON_A_DECODE_ERROR.iter().copied().collect();
951 let added: Vec<&String> = found
952 .iter()
953 .filter(|n| !listed.contains(n.as_str()))
954 .collect();
955 assert!(
956 added.is_empty(),
957 "these gates turn a decode error into a printed SKIP and are not declared: \
958 {added:#?}\nA gate that cannot decode has failed -- assert on the error, or use \
959 the attempt-loop pattern (several fixtures, at least one must decode, firing count \
960 hard-asserted)."
961 );
962 let stale: Vec<&&str> = listed.iter().filter(|n| !found.contains(**n)).collect();
963 assert!(
964 stale.is_empty(),
965 "{stale:#?} no longer swallow a decode error -- delete them from the list."
966 );
967 }
968
969 /// The partition alphabet, in CDF symbol order.
970 const PARTITION_NAMES: [&str; 10] = [
971 "PARTITION_NONE",
972 "PARTITION_HORZ",
973 "PARTITION_VERT",
974 "PARTITION_SPLIT",
975 "PARTITION_HORZ_A",
976 "PARTITION_HORZ_B",
977 "PARTITION_VERT_A",
978 "PARTITION_VERT_B",
979 "PARTITION_HORZ_4",
980 "PARTITION_VERT_4",
981 ];
982
983 /// The partition values a `match` arm pattern -- or an `if` chain's
984 /// condition -- names: its own tokens, plus every value of an inclusive
985 /// range (`(PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p)` is four
986 /// values in one). Tokenised, never `contains()`d: a misspelled constant
987 /// in a match pattern is an irrefutable binding that compiles and swallows
988 /// the alphabet, and a substring check would call that covered.
989 fn partition_values_named(head: &str) -> BTreeSet<usize> {
990 let mut out = BTreeSet::new();
991 let idx: Vec<usize> = head
992 .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
993 .filter_map(|tok| PARTITION_NAMES.iter().position(|n| *n == tok))
994 .collect();
995 if head.contains("..=") && idx.len() == 2 {
996 for v in idx[0]..=idx[1] {
997 out.insert(v);
998 }
999 }
1000 out.extend(idx);
1001 out
1002 }
1003
1004 /// The partition alphabets, enumerated against the arms that code them.
1005 ///
1006 /// A partition value is a CDF symbol, and `SymbolDecoder::symbol_fixed`
1007 /// cannot return one outside `0..nsyms` -- so a `match` whose arms cover
1008 /// its whole alphabet has an unreachable fallback, and the refusal that
1009 /// fallback carries names a value no stream can present. This test finds
1010 /// each such `match` by the refusal in its OWN fallback arm (rather than
1011 /// by line number, which drifts) and enumerates the alphabet against the
1012 /// arm patterns, ranges included.
1013 ///
1014 /// The refusals stay in the code: a partition value is a `usize`, so the
1015 /// match needs a fallback arm, and a named refusal is a better one than a
1016 /// panic (class `branch-dropped-as-unreachable`). What this removes is the
1017 /// UNMEASURED part of the claim.
1018 ///
1019 /// Not every partition fallback belongs here: the ones that name a shape
1020 /// this decoder genuinely does not code yet (the 128-root consumers) are
1021 /// live refusals, and the 16x16-level inter chain is an `if`/`else if`
1022 /// ladder rather than a match, so it needs its own enumerator.
1023 #[test]
1024 fn every_partition_value_of_an_enumerated_alphabet_has_an_arm() {
1025 // (the refusal in the fallback arm, the alphabet its CDF codes)
1026 let blocks: [(&str, usize); 4] = [
1027 (
1028 "a 32x32 partition type this decoder does not code",
1029 crate::cdf::PARTITION_W32[0].len() - 1,
1030 ),
1031 (
1032 "an INTER 32x32 partition type this decoder does not code",
1033 crate::cdf::PARTITION_W32[0].len() - 1,
1034 ),
1035 (
1036 "a 128x128 superblock partition value outside the 8-symbol alphabet",
1037 crate::cdf::PARTITION_W128[0].len() - 1,
1038 ),
1039 // lane-t900 r24: the key-frame superblock root. Its `part` is
1040 // either a `partition_w64` symbol or, at a frame edge, one of the
1041 // three gathered outcomes (PARTITION_HORZ, PARTITION_VERT,
1042 // PARTITION_SPLIT) -- all inside the same ten-value alphabet.
1043 (
1044 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
1045 crate::cdf::PARTITION_W64[0].len() - 1,
1046 ),
1047 ];
1048 let src = crate::test_source::module_source("decode");
1049 let lines: Vec<&str> = src.lines().collect();
1050 let indent = |l: &str| l.len() - l.trim_start().len();
1051 let mut found = 0usize;
1052 for (i, line) in lines.iter().enumerate() {
1053 let t = line.trim();
1054 if !(t.starts_with("match part") && t.ends_with('{')) {
1055 continue;
1056 }
1057 let outer = indent(line);
1058 let close = " ".repeat(outer) + "}";
1059 let (mut arms, mut fallback) = (BTreeSet::new(), String::new());
1060 let mut in_fallback = false;
1061 for l in &lines[i + 1..] {
1062 if *l == close {
1063 break;
1064 }
1065 // Arm patterns sit exactly one level in; anything deeper is an
1066 // arm's body, nested matches and `part == PARTITION_*` reads
1067 // included.
1068 if indent(l) != outer + 4 && !l.trim().is_empty() {
1069 if in_fallback {
1070 fallback.push_str(l.trim());
1071 }
1072 continue;
1073 }
1074 if !l.contains("=>") {
1075 continue;
1076 }
1077 in_fallback = l.trim_start().starts_with("_ =>");
1078 arms.extend(partition_values_named(l.split("=>").next().unwrap_or("")));
1079 }
1080 let Some((reason, alphabet)) =
1081 blocks.iter().find(|(reason, _)| fallback.contains(reason))
1082 else {
1083 continue;
1084 };
1085 found += 1;
1086 let missing: Vec<usize> = (0..*alphabet).filter(|v| !arms.contains(v)).collect();
1087 assert!(
1088 missing.is_empty(),
1089 "the `match` at decode.rs:{} refuses {reason:?} but has no arm for {:?} -- that \
1090 is a real gap in its {alphabet}-value alphabet, not a dead refusal",
1091 i + 1,
1092 missing
1093 .iter()
1094 .map(|v| PARTITION_NAMES[*v])
1095 .collect::<Vec<_>>()
1096 );
1097 }
1098 assert_eq!(
1099 found,
1100 blocks.len(),
1101 "not every enumerated partition refusal was located in decode.rs"
1102 );
1103 }
1104
1105 /// The same enumeration for a partition refusal that sits in an `if`
1106 /// chain rather than a `match` fallback.
1107 ///
1108 /// The inter 16x16-level ladder tests `part16` against constants arm by
1109 /// arm and refuses in its second-to-last branch, with `PARTITION_SPLIT`
1110 /// left to the final `else`. Nothing about that shape is weaker than a
1111 /// `match`: `part16` is a `partition_w16` symbol (or, at a frame edge, a
1112 /// gathered value of the same alphabet), so if the chain's conditions
1113 /// between them name every value of that alphabet, the refusing branch is
1114 /// unreachable.
1115 ///
1116 /// The conditions are read from the source, tokenised (never
1117 /// substring-matched -- lane-t900 r21), and a condition carrying `&&` is
1118 /// rejected outright: a value it names is only conditionally handled, and
1119 /// counting it would overstate the coverage.
1120 #[test]
1121 fn every_partition_value_of_an_if_chain_alphabet_is_named_by_a_branch() {
1122 // (the refusal in the chain's refusing branch, the alphabet its CDF codes)
1123 let chains: [(&str, usize); 1] = [(
1124 "an inter 16x16-level partition value outside NONE/HORZ/VERT/SPLIT/AB/1:4",
1125 crate::cdf::PARTITION_W16[0].len() - 1,
1126 )];
1127
1128 let src = crate::test_source::module_source("decode");
1129 let lines: Vec<&str> = src.lines().collect();
1130 let indent = |l: &str| l.len() - l.trim_start().len();
1131 let mut found = 0usize;
1132 for (reason, alphabet) in chains {
1133 let refusal = lines
1134 .iter()
1135 .position(|l| l.contains(reason))
1136 .unwrap_or_else(|| panic!("{reason:?} is not in decode.rs"));
1137 // The branch that carries the refusal: the nearest `} else if`
1138 // above it. Its indentation is the chain's own.
1139 let head = (0..refusal)
1140 .rev()
1141 .find(|&i| lines[i].trim_start().starts_with("} else if "))
1142 .unwrap_or_else(|| panic!("{reason:?} is not inside an if/else chain"));
1143 let outer = indent(lines[head]);
1144 let var = lines[head].trim_start()["} else if ".len()..]
1145 .split_whitespace()
1146 .next()
1147 .unwrap_or("")
1148 .to_owned();
1149 assert!(
1150 !var.is_empty(),
1151 "the chain at decode.rs:{} tests nothing",
1152 head + 1
1153 );
1154
1155 // Walk up collecting every branch head of this chain, each read to
1156 // the line that opens its body.
1157 let mut named = BTreeSet::new();
1158 let mut i = head + 1;
1159 let mut heads = 0usize;
1160 loop {
1161 i -= 1;
1162 let t = lines[i].trim_start();
1163 if indent(lines[i]) != outer
1164 || !(t.starts_with("} else if ") || t.starts_with("if "))
1165 {
1166 if i == 0 {
1167 break;
1168 }
1169 continue;
1170 }
1171 let mut cond = String::new();
1172 for l in &lines[i..] {
1173 cond.push(' ');
1174 cond.push_str(l.trim());
1175 if l.trim_end().ends_with('{') {
1176 break;
1177 }
1178 }
1179 assert!(
1180 cond.contains(&var),
1181 "the branch at decode.rs:{} sits in the chain that refuses {reason:?} but \
1182 does not test {var}",
1183 i + 1
1184 );
1185 assert!(
1186 !cond.contains("&&"),
1187 "the branch at decode.rs:{} handles its partition values only conditionally \
1188 ({cond:?}) -- the enumeration below would overstate what the chain covers",
1189 i + 1
1190 );
1191 named.extend(partition_values_named(&cond));
1192 heads += 1;
1193 if t.starts_with("if ") {
1194 break;
1195 }
1196 assert!(i > 0, "the chain that refuses {reason:?} has no start");
1197 }
1198 // The value the refusing branch excludes (`part16 != PARTITION_SPLIT`)
1199 // is handled by the chain's final `else`, so require one.
1200 let close = " ".repeat(outer) + "} else {";
1201 assert!(
1202 lines[refusal..].iter().any(|l| *l == close),
1203 "the chain that refuses {reason:?} has no final `else`, so the value its \
1204 refusing branch excludes is handled nowhere"
1205 );
1206 assert!(heads >= 2, "only {heads} branch(es) found for {reason:?}");
1207 found += 1;
1208 let missing: Vec<usize> = (0..alphabet).filter(|v| !named.contains(v)).collect();
1209 assert!(
1210 missing.is_empty(),
1211 "the chain at decode.rs:{} refuses {reason:?} but no branch names {:?} -- that \
1212 is a real gap in its {alphabet}-value alphabet, not a dead refusal",
1213 head + 1,
1214 missing
1215 .iter()
1216 .map(|v| PARTITION_NAMES[*v])
1217 .collect::<Vec<_>>()
1218 );
1219 }
1220 assert_eq!(found, chains.len());
1221 }
1222
1223 /// Every `tx_type` symbol of every CDF width, mapped through the set that
1224 /// width names.
1225 ///
1226 /// The reader decodes `t` from a row of `n` slots, so `t` is in
1227 /// `0..n - 1`, and hands `(n, t)` to [`crate::decode::tx_type_from_symbol`]
1228 /// -- the readers' own mapping, called here rather than transcribed
1229 /// (class `shared-oracle-blindness`: a second copy of a table can be
1230 /// self-consistently wrong). The widths are read from `cdf_state.rs`'s
1231 /// `tx_type` field declarations, so a new table with a width the mapping
1232 /// does not name fails this test rather than reaching the refusal at
1233 /// runtime.
1234 ///
1235 /// Distinctness is part of the claim: a set of `n - 1` symbols must map to
1236 /// `n - 1` DIFFERENT transform types, or the mapping has lost a member of
1237 /// the spec's `Tx_Type_*_Inv_Set*` even while every symbol resolves.
1238 #[test]
1239 fn every_tx_type_symbol_of_every_cdf_width_maps_into_its_own_set() {
1240 let mut widths: BTreeSet<usize> = BTreeSet::new();
1241 for line in include_str!("cdf_state.rs").lines() {
1242 let t = line.trim();
1243 if !(t.starts_with("pub ") && t.contains("tx_type") && t.contains("[u16;")) {
1244 continue;
1245 }
1246 let tail = t.rsplit("[u16;").next().unwrap_or("");
1247 let n: usize = tail
1248 .split(']')
1249 .next()
1250 .unwrap_or("")
1251 .trim()
1252 .parse()
1253 .unwrap_or_else(|_| panic!("cannot read a CDF width out of {t:?}"));
1254 widths.insert(n);
1255 }
1256 assert!(
1257 widths.len() >= 4,
1258 "the cdf_state.rs scan found only {widths:?} -- it is broken, not the decoder"
1259 );
1260 for &n in &widths {
1261 let nsyms = n - 1;
1262 let mut set: Vec<crate::transform::TxType> = Vec::new();
1263 for t in 0..nsyms {
1264 let ty = crate::decode::tx_type_from_symbol(n, t).unwrap_or_else(|| {
1265 panic!(
1266 "a {n}-slot tx_type CDF codes symbol {t}, which maps to no transform \
1267 type -- the refusal \"a tx_type symbol outside its CDF's own set\" is \
1268 reachable, and that is a mapping-table gap to fix"
1269 )
1270 });
1271 assert!(
1272 !set.contains(&ty),
1273 "a {n}-slot tx_type CDF maps symbol {t} to {ty:?}, which another symbol of \
1274 the same set already names -- a member of the spec's inverse table is lost"
1275 );
1276 set.push(ty);
1277 }
1278 assert_eq!(set.len(), nsyms);
1279 }
1280 }
1281
1282 /// The Golomb tail, enumerated over every value a conformant stream can
1283 /// carry.
1284 ///
1285 /// Spec 5.11.40 `read_golomb` counts its unary prefix and BREAKS at
1286 /// `length == 20`, then reads `length - 1` payload bits into an `x` whose
1287 /// top bit is implicit -- so no conformant stream carries a value above
1288 /// `(1 << 20) - 2`, and spec 5.11.39 agrees from the other side by masking
1289 /// the level it feeds with `0xFFFFF`. This walks both ends of every
1290 /// prefix length 1..=20 (plus the small values every real stream uses)
1291 /// through [`crate::tile::write_golomb`] and back through the decoder's own
1292 /// [`crate::decode::read_golomb`], so the refusal "a Golomb tail longer
1293 /// than this decoder reads" is proved to sit strictly OUTSIDE the value
1294 /// domain, not inside it.
1295 ///
1296 /// The residue is a bit pattern, not a value: the spec's break makes the
1297 /// 20th prefix bit a don't-care, so a stream whose 20th prefix bit is 0
1298 /// decodes to the same value there and is refused here. libaom refuses the
1299 /// same bit (`av1/decoder/decodetxb.c:30`, `AOM_CODEC_CORRUPT_FRAME` at
1300 /// `length > 20`), so this refusal is NOT a reader gap to widen: when it
1301 /// fires on a real stream it is an earlier desync's symptom -- see the
1302 /// comment on `read_golomb`.
1303 #[test]
1304 fn read_golomb_reads_every_value_a_conformant_stream_can_carry() {
1305 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so
1306 // it names it and pins its guard site.
1307 const REFUSAL: &str = "a Golomb tail longer than this decoder reads";
1308 assert!(
1309 super::pins_refusal(crate::test_source::module_source("decode"), REFUSAL),
1310 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
1311 );
1312 let roundtrip = |value: u32| -> ec_core::Result<u32> {
1313 let mut enc = crate::msac::SymbolEncoder::new();
1314 crate::tile::write_golomb(&mut enc, value);
1315 let data = enc.finish();
1316 let mut dec = crate::msac::SymbolDecoder::new(&data);
1317 crate::decode::read_golomb(&mut dec)
1318 };
1319 let mut values: BTreeSet<u32> = (0..=64u32).collect();
1320 for length in 1..=20u32 {
1321 // `x` has `length` bits with its top bit set, and the value is
1322 // `x - 1`: the two ends of what this prefix length can express.
1323 values.insert((1u32 << (length - 1)) - 1);
1324 values.insert(((1u64 << length) - 2) as u32);
1325 }
1326 let max = *values.iter().max().unwrap();
1327 assert_eq!(
1328 max,
1329 (1u32 << 20) - 2,
1330 "the enumeration misses the spec's own ceiling"
1331 );
1332 // A coefficient is masked to 20 bits (spec 5.11.39), and the base and
1333 // base-range syntax contribute at most 15 of that before the tail, so
1334 // this is the largest tail a legal coefficient can need.
1335 assert!(
1336 max >= 0xF_FFFF - 15,
1337 "the ceiling is below the largest legal tail"
1338 );
1339 for value in values {
1340 match roundtrip(value) {
1341 Ok(read) => assert_eq!(read, value, "the Golomb tail {value} read back as {read}"),
1342 Err(e) => panic!(
1343 "the Golomb tail {value} is inside the domain spec 5.11.40 can write but \
1344 this decoder refuses it: {e}"
1345 ),
1346 }
1347 }
1348 // And the refusal still names something: 20 zero prefix bits.
1349 let mut enc = crate::msac::SymbolEncoder::new();
1350 for _ in 0..20 {
1351 enc.literal(0, 1);
1352 }
1353 for _ in 0..20 {
1354 enc.literal(1, 1);
1355 }
1356 let data = enc.finish();
1357 let mut dec = crate::msac::SymbolDecoder::new(&data);
1358 assert!(
1359 crate::decode::read_golomb(&mut dec).is_err(),
1360 "the Golomb refusal is dead code -- drop it from the inventory"
1361 );
1362 }
1363
1364 /// The intra-mode alphabet, enumerated against the guard that refuses a
1365 /// symbol outside it.
1366 ///
1367 /// Three readers -- the rect-in-inter arm, the intra-in-inter square arm
1368 /// and the 8x8 leaf -- read a y_mode symbol and refuse `mode >= 13` with
1369 /// "an intra mode this decoder does not code (round 2)". A `y_mode` symbol
1370 /// comes from `Cdfs::y_mode[size_group]`, whose alphabet is
1371 /// `Y_MODE[g].len() - 1` (the last slot is the adaptation counter), and
1372 /// `SymbolDecoder::symbol` cannot return a value outside `0..nsyms` -- so
1373 /// the guard is unreachable exactly when every size group's alphabet is at
1374 /// most the threshold.
1375 ///
1376 /// Found by the refusal in the guard's own body rather than by line
1377 /// number, and the CDF the symbol was read from is checked too: a
1378 /// threshold of 13 over a 14-symbol table would be a live refusal, and a
1379 /// site reading a WIDER alphabet (`uv_mode` with CfL is 14) under the same
1380 /// guard would be one as well.
1381 #[test]
1382 fn every_intra_mode_symbol_of_the_y_mode_alphabet_is_coded() {
1383 const REFUSAL: &str = "an intra mode this decoder does not code (round 2)";
1384 // Both uv_mode alphabets are listed so the CfL-allowed one (14
1385 // symbols, `UV_MODE_CFL_ALLOWED`) cannot silently become the source of
1386 // a symbol tested against 13.
1387 let alphabets: [(&str, usize); 3] = [
1388 ("y_mode", crate::cdf::Y_MODE[0].len() - 1),
1389 ("uv_mode_no_cfl", crate::cdf::UV_MODE_NO_CFL[0].len() - 1),
1390 ("uv_mode_cfl", crate::cdf::UV_MODE_CFL[0].len() - 1),
1391 ];
1392 assert_eq!(alphabets[0].1, 13, "the y_mode alphabet changed size");
1393 for group in &crate::cdf::Y_MODE {
1394 assert_eq!(
1395 group.len() - 1,
1396 alphabets[0].1,
1397 "the y_mode rows disagree on width"
1398 );
1399 }
1400
1401 let src = crate::test_source::module_source("decode");
1402 let lines: Vec<&str> = src.lines().collect();
1403 let mut sites = 0usize;
1404 for (i, line) in lines.iter().enumerate() {
1405 let t = line.trim();
1406 let Some(rest) = t.strip_prefix("if mode >= ") else {
1407 continue;
1408 };
1409 let Some(threshold) = rest.trim_end_matches(" {").parse::<usize>().ok() else {
1410 continue;
1411 };
1412 // Only the guards carrying THIS refusal.
1413 if !lines[i..(i + 4).min(lines.len())]
1414 .join("\n")
1415 .contains(REFUSAL)
1416 {
1417 continue;
1418 }
1419 sites += 1;
1420 // The symbol's own CDF: the nearest `dec.symbol(&mut cdfs.X[..])`
1421 // above the guard.
1422 let read = lines[i.saturating_sub(12)..i]
1423 .iter()
1424 .rev()
1425 .find(|l| l.contains("dec.symbol(&mut cdfs."))
1426 .unwrap_or_else(|| panic!("line {}: no symbol read above the guard", i + 1));
1427 let table = read
1428 .split("dec.symbol(&mut cdfs.")
1429 .nth(1)
1430 .unwrap()
1431 .split('[')
1432 .next()
1433 .unwrap();
1434 let (name, nsyms) = alphabets
1435 .iter()
1436 .find(|(n, _)| *n == table)
1437 .unwrap_or_else(|| panic!("line {}: unknown mode alphabet {table:?}", i + 1));
1438 assert!(
1439 *nsyms <= threshold,
1440 "line {}: the guard refuses mode >= {threshold} on a symbol read from a \
1441 {nsyms}-symbol {name} CDF -- symbol {threshold} is inside that alphabet, so \
1442 the refusal is live and this enumeration does not prove it",
1443 i + 1
1444 );
1445 }
1446 assert_eq!(
1447 sites, 3,
1448 "the intra-mode guard is at three sites, found {sites}"
1449 );
1450 }
1451
1452 /// lane-t900 r31, ENUMERATION for "a HORZ/VERT intra strip in a
1453 /// screen-content frame (palette syntax is consumed for square blocks
1454 /// only)".
1455 ///
1456 /// That refusal guards the 128-root HORZ/VERT arm of the intra-in-inter
1457 /// path (`decode.rs`, the `bw.max(bh) == 128` branch): the body it calls,
1458 /// `decode_block_128rect`, reads no palette syntax, so a screen-content
1459 /// frame was assumed to code some there. It cannot. `av1_allow_palette`
1460 /// (spec 5.11.46 `read_palette_mode_info`: `bsize` between `BLOCK_8X8`
1461 /// and `BLOCK_64X64` by side) is what this decoder mirrors in
1462 /// `palette_bsize_ctx_wh`, whose bound is `bw > 64 || bh > 64 ||
1463 /// bw * bh < 64`. Every footprint with a 128-pixel side fails it, so the
1464 /// screen flag changes NOTHING a 128-root half codes -- the refusal's
1465 /// stated premise is false, and the string is a claim about the SYNTAX
1466 /// (provable, and disproved here) rather than about libaom.
1467 ///
1468 /// It is deliberately NOT registered in [`PROVEN`]: the guarded condition
1469 /// is still reachable (a screen frame CAN code a 128-root half), so this
1470 /// test proves the LIFT is safe, not that the case never happens. Lifting
1471 /// it is a `decode.rs` edit plus a witness stream, and no `--sb-size=128
1472 /// --tune-content=screen` encode found so far codes a 128-root half at all
1473 /// (lane-t900 r23's census).
1474 ///
1475 /// The bound is asserted against `decode.rs`'s own source rather than a
1476 /// copy of it here, so a change to the predicate breaks this test rather
1477 /// than silently invalidating it (class `table-and-reader-move-together`).
1478 #[test]
1479 fn no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax() {
1480 const BOUND: &str = "if bw > 64 || bh > 64 || bw * bh < 64 {";
1481 let src = crate::test_source::module_source("decode");
1482 assert!(
1483 src.contains("fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {"),
1484 "palette_bsize_ctx_wh is gone -- this enumeration no longer names the predicate \
1485 the decoder gates every palette read on"
1486 );
1487 assert_eq!(
1488 src.matches(BOUND).count(),
1489 1,
1490 "av1_allow_palette's size bound is no longer spelled {BOUND:?} exactly once in \
1491 decode.rs -- re-derive this enumeration from the new spelling"
1492 );
1493 // `palette_bsize_ctx_wh`'s own bound, applied to every AV1 block
1494 // footprint (both sides a power of two from 4 to 128).
1495 let allows_palette = |bw: usize, bh: usize| !(bw > 64 || bh > 64 || bw * bh < 64);
1496 let (mut with_128, mut allowed_at_128) = (0u32, 0u32);
1497 for wl in 2..=7u32 {
1498 for hl in 2..=7u32 {
1499 let (bw, bh) = (1usize << wl, 1usize << hl);
1500 if bw.max(bh) != 128 {
1501 continue;
1502 }
1503 with_128 += 1;
1504 if allows_palette(bw, bh) {
1505 allowed_at_128 += 1;
1506 }
1507 }
1508 }
1509 assert!(
1510 with_128 > 0,
1511 "enumeration is vacuous -- no 128-sided footprint was tried"
1512 );
1513 assert_eq!(
1514 allowed_at_128, 0,
1515 "a footprint with a 128-pixel side passed av1_allow_palette's bound -- the \
1516 128-root HORZ/VERT arm really would have to read palette syntax"
1517 );
1518 // And the guarded shapes specifically: the two 128-root HORZ/VERT
1519 // halves the refusal names.
1520 for (bw, bh) in [(128usize, 64usize), (64, 128)] {
1521 assert!(
1522 !allows_palette(bw, bh),
1523 "a {bw}x{bh} half can carry a palette after all"
1524 );
1525 }
1526 }
1527
1528 /// lane-t900 r33, ENUMERATION for the two [`decode_rect_split`] refusals
1529 /// ("a coded HORZ/VERT strip whose chroma transform has no rect
1530 /// coefficient tables here" and "a split intra strip whose transform unit
1531 /// is {tx_w}x{tx_h}").
1532 ///
1533 /// Both guard shape lookups inside one function, so the proof is one
1534 /// enumeration: the footprints that function is CALLED with, walked
1535 /// through `depth_to_tx_wh` at every depth, against the two `match`
1536 /// tables read out of `decode.rs` itself (class
1537 /// `table-and-reader-move-together` -- a table edit invalidates this test
1538 /// rather than sneaking past it).
1539 ///
1540 /// The footprint domain is the five callers' own: `decode_block_rect`
1541 /// (32-level 2:1), `decode_block_rect4` (32-level 1:4), `decode_leaf_rect`
1542 /// (16-level 2:1), `decode_block_rect64` (64-level 2:1 and 1:4) and
1543 /// `decode_intra_rect_in_inter`, whose reachable shapes are the ten
1544 /// rectangular census shapes with `8 <= min` and `max <= 64` (already
1545 /// pinned by `every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`).
1546 /// The two shape classes that would MISS a table -- a 128-sided half
1547 /// (chroma 64x32) and a sub-8 strip (16x4 -> chroma 8x2) -- are excluded
1548 /// structurally: their readers, `decode_block_128rect` and
1549 /// `decode_rect4_16_strip`, are not among the callers, which this test
1550 /// asserts by locating every `decode_rect_split(` call in its enclosing
1551 /// function.
1552 #[test]
1553 fn every_rect_strip_shape_the_split_path_codes_has_a_luma_and_chroma_table() {
1554 let src = crate::test_source::module_source("decode");
1555 // lane-av1refusalspan: this gate is the PROOF for both refusals below,
1556 // so it names both and pins both guard sites.
1557 for refusal in [
1558 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
1559 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)",
1560 ] {
1561 assert!(
1562 super::pins_refusal(src, refusal),
1563 "this gate proves {refusal:?}, but that string is no longer in decode.rs"
1564 );
1565 }
1566
1567 // (1) The caller set. Each call's enclosing function is the last
1568 // top-level `fn` before it.
1569 let fn_starts: Vec<(usize, String)> = src
1570 .match_indices("\nfn ")
1571 .map(|(i, _)| {
1572 let rest = &src[i + 4..];
1573 let name = rest[..rest.find('(').unwrap_or(0)].to_string();
1574 (i, name)
1575 })
1576 .collect();
1577 let mut callers: BTreeSet<String> = BTreeSet::new();
1578 for (at, _) in src.match_indices("decode_rect_split(") {
1579 let enclosing = fn_starts
1580 .iter().rfind(|(i, _)| *i < at)
1581 .expect("a decode_rect_split call outside any function");
1582 if enclosing.1 != "decode_rect_split" {
1583 callers.insert(enclosing.1.clone());
1584 }
1585 }
1586 let expected: BTreeSet<String> = [
1587 "decode_block_rect",
1588 "decode_block_rect4",
1589 "decode_block_rect64",
1590 "decode_intra_rect_in_inter",
1591 "decode_leaf_rect",
1592 ]
1593 .iter()
1594 .map(|s| s.to_string())
1595 .collect();
1596 assert_eq!(
1597 callers, expected,
1598 "the set of functions that call decode_rect_split changed -- re-derive the \
1599 footprint domain below from the new caller (a 128-sided or sub-8 caller makes \
1600 both refusals live)"
1601 );
1602
1603 // (2) The walk, asserted against its own source before it is applied.
1604 const WALK: &str = " let (mut w, mut h) = (bw.min(64), bh.min(64));\n \
1605 for _ in 0..depth {\n match w.cmp(&h) {\n \
1606 std::cmp::Ordering::Greater => w /= 2,\n \
1607 std::cmp::Ordering::Less => h /= 2,\n \
1608 std::cmp::Ordering::Equal => {\n w /= 2;\n \
1609 h /= 2;\n }\n }\n }";
1610 assert_eq!(
1611 src.matches(WALK).count(),
1612 1,
1613 "depth_to_tx_wh's walk is no longer spelled the way this enumeration mirrors it"
1614 );
1615 let depth_to_tx_wh = |bw: usize, bh: usize, depth: usize| {
1616 let (mut w, mut h) = (bw.min(64), bh.min(64));
1617 for _ in 0..depth {
1618 match w.cmp(&h) {
1619 std::cmp::Ordering::Greater => w /= 2,
1620 std::cmp::Ordering::Less => h /= 2,
1621 std::cmp::Ordering::Equal => {
1622 w /= 2;
1623 h /= 2;
1624 }
1625 }
1626 }
1627 (w, h)
1628 };
1629
1630 // (3) The two tables, read out of decode_rect_split's own text: every
1631 // `(w, h) =>` / `(w, h) |` match arm head between the table's `let`
1632 // and the guard that follows it.
1633 let body_at = src
1634 .find("fn decode_rect_split(")
1635 .expect("decode_rect_split is gone");
1636 let body = &src[body_at..];
1637 let slice = |from: &str, to: &str| -> &str {
1638 let a = body
1639 .find(from)
1640 .unwrap_or_else(|| panic!("{from:?} is gone from decode_rect_split"));
1641 let b = body[a..]
1642 .find(to)
1643 .unwrap_or_else(|| panic!("{to:?} is gone from decode_rect_split"));
1644 &body[a..a + b]
1645 };
1646 let arm_shapes = |text: &str| -> BTreeSet<(usize, usize)> {
1647 let mut out = BTreeSet::new();
1648 let bytes = text.as_bytes();
1649 for (i, _) in text.match_indices('(') {
1650 let mut j = i + 1;
1651 let mut w = 0usize;
1652 while j < bytes.len() && bytes[j].is_ascii_digit() {
1653 w = w * 10 + usize::from(bytes[j] - b'0');
1654 j += 1;
1655 }
1656 if j == i + 1 || !text[j..].starts_with(", ") {
1657 continue;
1658 }
1659 j += 2;
1660 let mut h = 0usize;
1661 let start_h = j;
1662 while j < bytes.len() && bytes[j].is_ascii_digit() {
1663 h = h * 10 + usize::from(bytes[j] - b'0');
1664 j += 1;
1665 }
1666 if j == start_h || !text[j..].starts_with(')') {
1667 continue;
1668 }
1669 // Only an arm HEAD counts, never a `(32, 8)` inside prose.
1670 let after = text[j + 1..].trim_start();
1671 if after.starts_with("=>") || after.starts_with('|') {
1672 out.insert((w, h));
1673 }
1674 }
1675 out
1676 };
1677 let chroma = arm_shapes(slice("let chroma: Option<(TxbSet", "if !m.skip {"));
1678 let luma = arm_shapes(slice("let luma_rect: Option<(TxbSet", "no luma \\"));
1679 assert!(
1680 chroma.len() >= 6 && luma.len() >= 6,
1681 "the tables parsed to {} chroma / {} luma shapes -- the parse, not the decoder, \
1682 is what this would be measuring",
1683 chroma.len(),
1684 luma.len()
1685 );
1686
1687 // (4) The enumeration itself.
1688 let mut checked = 0u32;
1689 for wl in 3..=6u32 {
1690 for hl in 3..=6u32 {
1691 let (bw, bh) = (1usize << wl, 1usize << hl);
1692 let ratio = bw.max(bh) / bw.min(bh);
1693 if ratio != 2 && ratio != 4 {
1694 continue;
1695 }
1696 assert!(
1697 chroma.contains(&(bw / 2, bh / 2)),
1698 "a {bw}x{bh} strip's {}x{} chroma transform has no rect table -- the \
1699 chroma refusal is LIVE for a shape a caller codes",
1700 bw / 2,
1701 bh / 2
1702 );
1703 // Every depth: once the walk reaches a square it stays square,
1704 // so this covers any tx_depth a header can code.
1705 for depth in 1..=4 {
1706 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
1707 assert!(
1708 tx_w == tx_h || luma.contains(&(tx_w, tx_h)),
1709 "a {bw}x{bh} strip at depth {depth} resolves to a {tx_w}x{tx_h} \
1710 transform unit, which has no luma arm -- that refusal is LIVE"
1711 );
1712 checked += 1;
1713 }
1714 }
1715 }
1716 assert_eq!(
1717 checked, 40,
1718 "the strip domain is not the ten rect shapes x four depths"
1719 );
1720 }
1721
1722 /// lane-av1rect8x16, ENUMERATION for "a rectangular chroma transform
1723 /// whose size has no coefficient table" --
1724 /// [`crate::decode::decode_block_rect`]'s `_` arm.
1725 ///
1726 /// This refusal had NO `PROVEN` row: the sibling sweep that found the
1727 /// gap (`every_rect_strip_shape_the_split_path_codes_has_a_luma_and_
1728 /// chroma_table`, which audits `decode_rect_split`'s tables, not this
1729 /// function's) asserted only the superblock-level 64x32/32x64
1730 /// footprints, so the 8x16 luma strip's 4x8 chroma was left unasked.
1731 ///
1732 /// The answer is that the shape is UNREACHABLE, and structurally so:
1733 /// every one of the function's call sites passes its `bw`/`bh` as
1734 /// integer LITERALS, and all of them are 32-level `PARTITION_HORZ` /
1735 /// `VERT` / `HORZ_A` / `HORZ_B` / `VERT_A` / `VERT_B` arms of
1736 /// `read_sb128_root`'s `match part32` -- i.e. 32x16 or 16x32, never
1737 /// 8x16. A 16-level 2:1 luma strip (16x8 / 8x16) is read by
1738 /// [`crate::decode::decode_leaf_rect`], which carries the matching
1739 /// `(4, 8)` / `(8, 4)` chroma rows (decode.rs:15409-15420,
1740 /// `TxbSet::ChromaRect8x4` + `SCAN_4X8` / `SCAN_8X4`).
1741 ///
1742 /// So the proof is the CALLER SHAPE SET, read out of the call sites'
1743 /// own argument lists, walked through `bw >> ss_x` / `bh >> ss_y` for
1744 /// every subsampling an AV1 `color_config` can carry, against the
1745 /// `match (chroma_w, chroma_h)` table read out of the function's own
1746 /// text (class `table-and-reader-move-together`: a table edit
1747 /// invalidates this test rather than sneaking past it).
1748 ///
1749 /// The subsampling domain is `{(0,0), (1,0), (1,1)}` and excludes
1750 /// `(0,1)`: `ec-av1-syntax`'s `color_config` only ever READS
1751 /// `subsampling_y` when `subsampling_x == 1` (sequence.rs:481), so
1752 /// `(0,1)` is uncodable. `(1,0)` is 4:2:2. It is walked because that is
1753 /// the codable domain, NOT because a guard stands in the way: as of
1754 /// lane-av1422lift the sequence header no longer refuses 4:2:2 at all, so
1755 /// the sentence this replaces ("refused at the sequence header by
1756 /// `a_non_420_subsampled_sequence_header_is_refused_by_name`") names a
1757 /// gate that no longer exists. The walk was already right; its stated
1758 /// reason was not.
1759 #[test]
1760 fn every_chroma_unit_decode_block_rect_can_present_has_a_coefficient_table() {
1761 let src = crate::test_source::module_source("decode");
1762
1763 // (1) The caller shape set, read out of the call sites' own
1764 // argument lists. `decode_block_rect(dec, cdfs, neighbours, at, bw,
1765 // bh, ...)`, so args 4 and 5 (0-based, after the opening paren) are
1766 // `bw` and `bh`; the first three are the fixed `&mut` borrows.
1767 const LEAD: [&str; 3] = ["&mut dec", "&mut cdfs", "&mut neighbours"];
1768 let mut shapes: BTreeSet<(usize, usize)> = BTreeSet::new();
1769 let mut sites = 0usize;
1770 let at_def = src
1771 .find("fn decode_block_rect(")
1772 .expect("decode_block_rect is gone");
1773 for (i, _) in src.match_indices("decode_block_rect(") {
1774 // The definition's own parameter list carries the same text,
1775 // preceded by "fn " -- that is a declaration, not a call.
1776 if src[..i].ends_with("fn ") {
1777 continue;
1778 }
1779 // Split the argument list at top level (paren/bracket/angle
1780 // balanced), so the `(at32.0 + 1, at32.1)` origin argument --
1781 // which contains its own comma -- does not shift the indices.
1782 let open = i + "decode_block_rect(".len();
1783 let bytes = src.as_bytes();
1784 let mut args: Vec<String> = Vec::new();
1785 let mut depth = 0i32;
1786 let mut start = open;
1787 for j in open..bytes.len() {
1788 match bytes[j] {
1789 b'(' | b'[' => depth += 1,
1790 b')' | b']' => {
1791 if depth == 0 {
1792 args.push(src[start..j].to_string());
1793 break;
1794 }
1795 depth -= 1;
1796 }
1797 b',' if depth == 0 => {
1798 args.push(src[start..j].to_string());
1799 start = j + 1;
1800 }
1801 _ => {}
1802 }
1803 }
1804 assert!(
1805 args.len() >= 6,
1806 "a decode_block_rect call has only {} arguments -- the arg indices this \
1807 enumeration reads are off",
1808 args.len()
1809 );
1810 for k in 0..3 {
1811 assert_eq!(
1812 args[k].trim(),
1813 LEAD[k],
1814 "decode_block_rect's first three arguments changed -- re-derive the bw/bh \
1815 argument indices below"
1816 );
1817 }
1818 let lit = |a: &str| -> usize {
1819 a.trim().parse::<usize>().unwrap_or_else(|_| {
1820 panic!(
1821 "decode_block_rect is called with a non-literal strip size {:?} -- \
1822 this enumeration can no longer read the caller shape set",
1823 a.trim()
1824 )
1825 })
1826 };
1827 shapes.insert((lit(&args[4]), lit(&args[5])));
1828 sites += 1;
1829 }
1830 assert_eq!(
1831 sites, 8,
1832 "the number of decode_block_rect call sites changed"
1833 );
1834 let expected_shapes: BTreeSet<(usize, usize)> =
1835 [(32usize, 16usize), (16, 32)].into_iter().collect();
1836 assert_eq!(
1837 shapes, expected_shapes,
1838 "the set of strip sizes decode_block_rect is called with changed -- re-derive \
1839 the chroma domain below. An 8x16/16x8 caller makes this refusal LIVE (a \
1840 4:2:0 8x16 luma strip's chroma is 4x8, which libaom codes as TX_4X8: \
1841 av1_ss_size_lookup[BLOCK_8X16][1][1] = BLOCK_4X8 in \
1842 av1/common/common_data.c:24, then max_txsize_rect_lookup[BLOCK_4X8] = TX_4X8 \
1843 in av1/common/common_data.h:130, via av1_get_max_uv_txsize, blockd.h:1372)"
1844 );
1845
1846 // (2) The table, read out of the function's own text: every
1847 // `(w, h) =>` / `(w, h) |` arm head between the match and the guard.
1848 let body_at = at_def;
1849 let rest = &src[body_at..];
1850 let body = &rest[..rest.find("\nfn ").expect("unterminated fn")];
1851 let from = body
1852 .find("let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h)")
1853 .expect("decode_block_rect's chroma match is gone");
1854 let to = body[from..]
1855 .find("a rectangular chroma transform whose size has no coefficient table")
1856 .expect("the refusal string is gone from decode_block_rect")
1857 + from;
1858 let table = &body[from..to];
1859 let mut arms: BTreeSet<(usize, usize)> = BTreeSet::new();
1860 let bytes = table.as_bytes();
1861 for (i, _) in table.match_indices('(') {
1862 let mut j = i + 1;
1863 let mut w = 0usize;
1864 while j < bytes.len() && bytes[j].is_ascii_digit() {
1865 w = w * 10 + usize::from(bytes[j] - b'0');
1866 j += 1;
1867 }
1868 if j == i + 1 || !table[j..].starts_with(", ") {
1869 continue;
1870 }
1871 j += 2;
1872 let mut h = 0usize;
1873 let start_h = j;
1874 while j < bytes.len() && bytes[j].is_ascii_digit() {
1875 h = h * 10 + usize::from(bytes[j] - b'0');
1876 j += 1;
1877 }
1878 if j == start_h || !table[j..].starts_with(')') {
1879 continue;
1880 }
1881 // Only an arm HEAD counts, never a `(32, 8)` inside prose.
1882 let after = table[j + 1..].trim_start();
1883 if after.starts_with("=>") || after.starts_with('|') {
1884 arms.insert((w, h));
1885 }
1886 }
1887 // (3) The enumeration itself -- run BEFORE the exact-table pin below
1888 // so a deleted arm fails HERE, naming the footprint, instead of
1889 // behind a vaguer "the table changed".
1890 let mut checked = 0u32;
1891 for &(bw, bh) in &shapes {
1892 for (ss_x, ss_y) in [(0usize, 0usize), (1, 0), (1, 1)] {
1893 let (cw, ch) = (bw >> ss_x, bh >> ss_y);
1894 assert!(
1895 arms.contains(&(cw, ch)),
1896 "a {bw}x{bh} strip at subsampling ({ss_x},{ss_y}) has a {cw}x{ch} chroma \
1897 transform with no coefficient table -- the chroma refusal is LIVE"
1898 );
1899 checked += 1;
1900 }
1901 }
1902 assert_eq!(
1903 checked, 6,
1904 "the chroma domain is not two shapes x three formats"
1905 );
1906
1907 // (4) And the table is EXACTLY those six rows -- no row is a shape no
1908 // caller can present, which is what makes the `_` arm dead.
1909 assert_eq!(
1910 arms,
1911 [
1912 (8usize, 16usize),
1913 (8, 32),
1914 (16, 8),
1915 (16, 16),
1916 (16, 32),
1917 (32, 16)
1918 ]
1919 .into_iter()
1920 .collect::<BTreeSet<(usize, usize)>>(),
1921 "decode_block_rect's chroma table changed -- re-derive the walk above"
1922 );
1923
1924 // (5) The residual, stated as an assertion so it cannot rot: the two
1925 // 4:2:0 rows an 8x16/16x8 luma strip would need are NOT in this
1926 // table, and (4,8)/(8,4) is not a shape any caller can produce. If a
1927 // future caller hands this function an 8x16, step (1) goes red
1928 // first, and the new row has to be added here with it.
1929 for residual in [(4usize, 8usize), (8, 4)] {
1930 assert!(
1931 !arms.contains(&residual),
1932 "decode_block_rect grew a {0}x{1} chroma row -- update the residual note",
1933 residual.0,
1934 residual.1
1935 );
1936 }
1937 let produces: BTreeSet<(usize, usize)> = shapes
1938 .iter()
1939 .flat_map(|&(bw, bh)| {
1940 [(0usize, 0usize), (1, 0), (1, 1)]
1941 .into_iter()
1942 .map(move |(sx, sy)| (bw >> sx, bh >> sy))
1943 })
1944 .collect();
1945 assert!(
1946 !produces.contains(&(4, 8)) && !produces.contains(&(8, 4)),
1947 "the caller set can now produce a 4x8/8x4 chroma shape but the table has no \
1948 such row -- the chroma refusal is LIVE"
1949 );
1950 }
1951
1952 /// lane-av1txsizeaudit r2 -- the one value in `ec-av1` whose correct form
1953 /// is provable against libaom but whose *observable effect* is nil, so a
1954 /// pixel gate is impossible and this source scan is the only instrument
1955 /// that can catch a regression.
1956 ///
1957 /// `decode.rs`'s `suppress_internal_lf_edges` publishes the skipped 128
1958 /// root's own chroma extent into `uv_tx_grid`, so the deblocker's
1959 /// alignment gate (`x0 & (tx - 1)`) sees no internal transform edge. The
1960 /// correct extent is the block's own CHROMA footprint,
1961 /// `w_mi * MI >> ss_x` per axis -- `av1_setup_dst_planes`'s
1962 /// `get_plane_block_size(bsize, ss_x, ss_y)`, which at ss (0,0) is the
1963 /// block itself, so **128 and not 64** for a 128x128 root at 4:4:4. The
1964 /// site carried a hardcoded `w_mi * MI / 2`, which is right at 4:2:0 by
1965 /// the `>> 1 == / 2` identity and half the truth everywhere else; its
1966 /// sibling `fill_lf_grid_rect` had already been repaired to
1967 /// `(w_mi * MI) >> ss_x(fctx)`.
1968 ///
1969 /// **No pixel gate can exist for this, and that is measured, not assumed.**
1970 /// The widening defeats the alignment gate, but every edge it lets
1971 /// through then meets the SAME libaom rule applied at the correct place --
1972 /// `edge_params_body`'s spec-7.14.2 / `set_lpf_parameters` term
1973 /// `!pu_edge && cur_ref != 0 && pv_ref != 0 && skip_at && skip_at`, which
1974 /// holds for every internal edge because both cells are the same skipped
1975 /// block. Over 26 frames / 2 555 904 samples of five 4:4:4
1976 /// `--sb-size=128` streams that fire the arm 30 times, `64` and `128` both
1977 /// decode pixel-exact against `aomdec` and differ from each other in not
1978 /// one sample. The masking is TOTAL: the method is only ever called for a
1979 /// block that is itself skipped, so no input exists on which one side of
1980 /// an internal edge is not skipped. Hence: source scan, not pixels.
1981 ///
1982 /// This also pins the `fctx` threading, because `Neighbours` carries no
1983 /// subsampling of its own -- a sibling lane reached the same site and
1984 /// recorded it as unfixable for exactly that reason.
1985 #[test]
1986 fn the_skipped_128_root_chroma_suppression_publishes_the_blocks_own_per_axis_chroma_extent() {
1987 let src = crate::test_source::module_source("decode");
1988 let start = src
1989 .find("fn suppress_internal_lf_edges(")
1990 .expect("suppress_internal_lf_edges is gone");
1991 let body_start = start + src[start..].find('{').expect("no body");
1992 let body =
1993 &src[body_start..body_start + src[body_start..].find("\n }").expect("no end")];
1994
1995 assert!(
1996 body.contains("((w_mi * MI) >> ss_x(fctx))")
1997 && body.contains("((h_mi * MI) >> ss_y(fctx))"),
1998 "suppress_internal_lf_edges must publish the block's own chroma extent per axis \
1999 -- `w_mi * MI >> ss_x(fctx)`, not a hardcoded `/2`"
2000 );
2001 for stale in ["w_mi * MI / 2", "h_mi * MI / 2"] {
2002 assert!(
2003 !body.contains(stale),
2004 "suppress_internal_lf_edges grew `{stale}` again: correct at 4:2:0 by the \
2005 `>> 1 == / 2` identity, half the truth at 4:4:4"
2006 );
2007 }
2008 // The subsampling is not reachable from `self` -- `Neighbours` has no
2009 // `fctx` field -- so the per-axis shift needs a threaded parameter.
2010 // Without this the body cannot compile, which is how a future edit
2011 // would try to reintroduce a literal.
2012 let sig_end = src[start..body_start].to_string();
2013 assert!(
2014 sig_end.contains("fctx: &FrameCtx"),
2015 "suppress_internal_lf_edges takes no fctx, so the per-axis shift has nothing to read \
2016 -- `Neighbours` carries no subsampling of its own; thread the frame context in"
2017 );
2018 }
2019
2020 /// lane-av1-refusalaudit, ENUMERATION for "a 64-axis strip whose chroma
2021 /// unit has no coefficient table" -- [`decode_block_rect64`]'s `_` arm,
2022 /// reached only for depth-0, non-skip, non-lossless superblock-level
2023 /// HORZ/VERT/1:4 strips.
2024 ///
2025 /// The unit is the strip's chroma shape capped at 32 per axis
2026 /// (`(chroma_w.min(32), chroma_h.min(32))`), so the enumeration walks the
2027 /// strip domain -- the 64-axis 2:1 and 1:4 footprints, the only shapes the
2028 /// two callers (`read_sb128_root`, `decode_intra_rect_in_inter`) hand the
2029 /// function -- through every chroma format an AV1 `color_config` can
2030 /// carry, against the `match` arms read out of decode.rs itself (class
2031 /// `table-and-reader-move-together`).
2032 ///
2033 /// lane-av1422census422 widened the format domain from `{(0,0), (1,1)}`
2034 /// to `{(0,0), (1,0), (1,1)}`. The old walk justified stopping at two
2035 /// formats with "every mixed format is refused at the sequence header" --
2036 /// a proof that DEPENDS on that guard, so the moment the guard is lifted
2037 /// the enumeration keeps passing while covering nothing about 4:2:2, with
2038 /// no failure and no output change. The sibling enumeration
2039 /// `every_chroma_unit_decode_block_rect_can_present_has_a_coefficient_table`
2040 /// (same file, the 32-level strips) already walked `(1,0)` and said why:
2041 /// `ec-av1-syntax`'s `color_config` only ever READS `subsampling_y` when
2042 /// `subsampling_x == 1` (`sequence.rs:481`), so `(0,1)` is uncodable and
2043 /// the reachable set is exactly these three. That sibling was RIGHT and
2044 /// this half was wrong: "the header refuses it" is a statement about
2045 /// today's tree, not about the strip domain, and a domain that shrinks
2046 /// silently when a guard moves is not an enumeration. `(1,0)` is walked
2047 /// here anyway, so this proof does not depend on the guard staying -- and
2048 /// as of lane-av1422lift it does not depend on the guard EXISTING: 4:2:2
2049 /// decodes, and this enumeration is what says the decode has a
2050 /// coefficient table for every chroma unit it can present.
2051 ///
2052 /// The 32-per-axis cap is what keeps 4:2:2 covered without new table
2053 /// arms: a 4:2:0 32x64 strip is a 16x32 chroma unit and its 4:2:2
2054 /// counterpart is a 16x64 one, but the cap resolves BOTH to `(16, 32)`
2055 /// (likewise 16x64 -> `(8, 32)`). So 4:2:2 lands entirely inside the
2056 /// existing five arms and the `hit == handled` non-vacuity assert below is
2057 /// unchanged. That is a measured result, not an assumption: this
2058 /// paragraph describes the widened walk in this test's own body, which
2059 /// asserts both the per-unit table membership and the 12-unit count.
2060 ///
2061 /// lane-av1-witness2 hunted the shape with 8 real aomenc key-frame encodes
2062 /// (screen+intrabc, rect+1:4, sb 64 and 128, cq 10..63, cpu-used 0..2):
2063 /// no recipe reached the arm, and the three streams that decode to
2064 /// completion never enter `decode_block_rect64` at all.
2065 #[test]
2066 fn every_chroma_unit_a_64_axis_strip_can_present_has_a_coefficient_table() {
2067 let src = crate::test_source::module_source("decode");
2068
2069 // (1) The caller set. Each call's enclosing function is the last
2070 // top-level `fn` before it.
2071 let fn_starts: Vec<(usize, String)> = src
2072 .match_indices("\nfn ")
2073 .map(|(i, _)| {
2074 let rest = &src[i + 4..];
2075 let name = rest[..rest.find('(').unwrap_or(0)].to_string();
2076 (i, name)
2077 })
2078 .collect();
2079 let mut callers: BTreeSet<String> = BTreeSet::new();
2080 for (at, _) in src.match_indices("decode_block_rect64(") {
2081 let enclosing = fn_starts
2082 .iter().rfind(|(i, _)| *i < at)
2083 .expect("a decode_block_rect64 call outside any function");
2084 if enclosing.1 != "decode_block_rect64" {
2085 callers.insert(enclosing.1.clone());
2086 }
2087 }
2088 let expected: BTreeSet<String> = ["decode_intra_rect_in_inter", "read_sb128_root"]
2089 .iter()
2090 .map(|s| s.to_string())
2091 .collect();
2092 assert_eq!(
2093 callers, expected,
2094 "the set of functions that call decode_block_rect64 changed -- re-derive the \
2095 strip domain below from the new caller (a 128-sided or sub-8 caller makes the \
2096 refusal live)"
2097 );
2098
2099 // (2) The unit derivation, asserted against its own source before it
2100 // is applied: chroma shape = the strip halved by the plane's
2101 // subsampling; unit = each axis capped at 32.
2102 let body_at = src
2103 .find("fn decode_block_rect64(")
2104 .expect("decode_block_rect64 is gone");
2105 let rest = &src[body_at..];
2106 let body = &rest[..rest.find("\nfn ").expect("unterminated fn")];
2107 assert!(
2108 body.contains("(bw >> ss_x(fctx), bh >> ss_y(fctx))"),
2109 "decode_block_rect64's chroma shape is no longer the strip halved by the \
2110 plane's subsampling -- re-derive this enumeration"
2111 );
2112 const CAP: &str = "let (uw, uh) = (chroma_w.min(32), chroma_h.min(32));";
2113 assert_eq!(
2114 src.matches(CAP).count(),
2115 1,
2116 "the 32-per-axis chroma unit cap is no longer spelled the way this enumeration \
2117 mirrors it"
2118 );
2119
2120 // (3) The table, read out of the match that follows the cap.
2121 let from = body.find(CAP).expect("cap is outside decode_block_rect64");
2122 let to = body
2123 .find("a 64-axis strip whose chroma unit has no coefficient table")
2124 .expect("the refusal string is gone from decode_block_rect64");
2125 let table = &body[from..to];
2126 let mut arms: BTreeSet<(usize, usize)> = BTreeSet::new();
2127 let bytes = table.as_bytes();
2128 for (i, _) in table.match_indices('(') {
2129 let mut j = i + 1;
2130 let mut w = 0usize;
2131 while j < bytes.len() && bytes[j].is_ascii_digit() {
2132 w = w * 10 + usize::from(bytes[j] - b'0');
2133 j += 1;
2134 }
2135 if j == i + 1 || !table[j..].starts_with(", ") {
2136 continue;
2137 }
2138 j += 2;
2139 let mut h = 0usize;
2140 let start_h = j;
2141 while j < bytes.len() && bytes[j].is_ascii_digit() {
2142 h = h * 10 + usize::from(bytes[j] - b'0');
2143 j += 1;
2144 }
2145 if j == start_h || !table[j..].starts_with(") =>") {
2146 continue;
2147 }
2148 // Only an arm HEAD counts, never a `(32, 8)` inside prose.
2149 arms.insert((w, h));
2150 }
2151 let handled: BTreeSet<(usize, usize)> = [(32, 32), (32, 16), (16, 32), (32, 8), (8, 32)]
2152 .into_iter()
2153 .collect();
2154 assert_eq!(
2155 arms, handled,
2156 "decode_block_rect64's chroma-unit table changed -- re-derive the enumeration \
2157 (a unit outside these five arms makes the refusal live for some strip)"
2158 );
2159
2160 // (4) The enumeration: every 64-axis 2:1 and 1:4 strip (the shapes
2161 // superblock partitioning presents at the 64 level) x every supported
2162 // chroma format lands on a handled arm.
2163 let mut checked = 0u32;
2164 let mut hit: BTreeSet<(usize, usize)> = BTreeSet::new();
2165 for wl in 4..=6u32 {
2166 for hl in 4..=6u32 {
2167 let (bw, bh) = (1usize << wl, 1usize << hl);
2168 if bw.max(bh) != 64 {
2169 continue;
2170 }
2171 let ratio = bw.max(bh) / bw.min(bh);
2172 if ratio != 2 && ratio != 4 {
2173 continue;
2174 }
2175 // (ss_x, ss_y): (0, 0) is 4:4:4, (1, 0) is 4:2:2, (1, 1) is
2176 // 4:2:0. `(0, 1)` is uncodable -- `color_config` reads
2177 // `subsampling_y` only when `subsampling_x == 1`
2178 // (sequence.rs:481) -- so these three are the whole
2179 // reachable set, and each is walked independently of any
2180 // sequence-header guard (lifted by lane-av1422lift).
2181 for (ss_x, ss_y) in [(0usize, 0usize), (1, 0), (1, 1)] {
2182 let (chroma_w, chroma_h) = (bw >> ss_x, bh >> ss_y);
2183 let unit = (chroma_w.min(32), chroma_h.min(32));
2184 assert!(
2185 arms.contains(&unit),
2186 "a {bw}x{bh} strip at subsampling ({ss_x},{ss_y}) resolves to the \
2187 chroma unit {unit:?}, which has no coefficient table -- the \
2188 refusal is LIVE for a conformant stream"
2189 );
2190 hit.insert(unit);
2191 checked += 1;
2192 }
2193 }
2194 }
2195 assert_eq!(
2196 checked, 12,
2197 "the strip domain is not the four 64-axis strips x three codable \
2198 chroma formats (4:4:4, 4:2:2, 4:2:0)"
2199 );
2200 assert_eq!(
2201 hit, handled,
2202 "the enumeration stopped exercising every arm -- the proof went vacuous"
2203 );
2204 }
2205
2206 /// lane-t900 r33, ENUMERATION for "CfL, filter intra or a palette on a
2207 /// 128-root HORZ/VERT intra block".
2208 ///
2209 /// The guard fires when any of four symbols came back `Some` from
2210 /// `read_intra_mode_rect` on a 128x64/64x128 half. Each of the four is
2211 /// read under a size gate, and none of those gates admits a 128-pixel
2212 /// side:
2213 ///
2214 /// * `cfl_alpha` -- read only under the `cfl` PARAMETER, and the 128-root
2215 /// call site passes the literal `false`;
2216 /// * `use_filter_intra` -- read only when `filter_intra_size_class_rect`
2217 /// is `Some`, whose table has no arm with a 128 side and whose square
2218 /// fallback (`filter_intra_size_class`) caps at 32
2219 /// (`av1_filter_intra_allowed_bsize`);
2220 /// * `palette_y_mode` / `palette_uv_mode` -- both inside the
2221 /// `palette_bsize_ctx_wh` block already enumerated by
2222 /// [`no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax`].
2223 #[test]
2224 fn no_128_root_half_reads_a_cfl_filter_intra_or_palette_symbol() {
2225 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so
2226 // it names it (the full leading clause, which is the whole clause the
2227 // inventory row's anchor reads) and pins its guard site.
2228 const REFUSAL: &str = "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block";
2229 assert!(
2230 crate::test_source::module_source("decode").contains(REFUSAL),
2231 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
2232 );
2233 let src = crate::test_source::module_source("decode");
2234 // The 128-root call site's own `cfl` argument, with the comment that
2235 // explains it -- the two lines are matched together so that reordering
2236 // the arguments cannot leave this test pointing at another `false`.
2237 //
2238 // Whitespace-normalised (2026-09-28): the anchor used to be matched with
2239 // its exact indentation, so any dedent or reformat of the call site --
2240 // the wave merge dedented it by four spaces -- turned this enumeration
2241 // red without the invariant it guards changing at all. Collapsing runs
2242 // of whitespace keeps the SEMANTIC anchor (both comment lines plus the
2243 // `false,` argument, in order) asserted while removing that fragility.
2244 const CFL_OFF_AT_128: &str = "// `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the \
2245 // 13-symbol no-CFL CDF here, never the 14-symbol one. false,";
2246 fn squash_ws(s: &str) -> String {
2247 s.split_whitespace().collect::<Vec<_>>().join(" ")
2248 }
2249 assert_eq!(
2250 squash_ws(src).matches(&squash_ws(CFL_OFF_AT_128)).count(),
2251 1,
2252 "the 128-root call site no longer passes cfl=false -- a CfL alpha can reach the \
2253 guard, so this enumeration proves nothing"
2254 );
2255 // The filter-intra table: every arm head, plus the square fallback.
2256 let fi_at = src
2257 .find("fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {")
2258 .expect("filter_intra_size_class_rect is gone");
2259 let fi_body = &src[fi_at..fi_at + src[fi_at..].find("\n}\n").expect("unterminated fn")];
2260 assert!(
2261 !fi_body.contains("128"),
2262 "filter_intra_size_class_rect grew an arm naming a 128 side"
2263 );
2264 assert!(
2265 fi_body.contains("_ if bw == bh => filter_intra_size_class(bw),")
2266 && fi_body.contains("_ => None,"),
2267 "filter_intra_size_class_rect's fallbacks changed shape"
2268 );
2269 let sq_at = src
2270 .find("fn filter_intra_size_class(side: usize) -> Option<usize> {")
2271 .expect("filter_intra_size_class is gone");
2272 let sq_body = &src[sq_at..sq_at + src[sq_at..].find("\n}\n").expect("unterminated fn")];
2273 assert!(
2274 !sq_body.contains("128") && !sq_body.contains("64"),
2275 "filter_intra_size_class admits a side above 32 -- av1_filter_intra_allowed_bsize \
2276 does not, so re-derive this proof"
2277 );
2278 // And palette, at the two shapes the refusal names.
2279 assert!(
2280 src.contains("if bw > 64 || bh > 64 || bw * bh < 64 {"),
2281 "palette_bsize_ctx_wh's bound moved -- see \
2282 no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax"
2283 );
2284 for (bw, bh) in [(128usize, 64usize), (64, 128)] {
2285 assert!(bw > 64 || bh > 64, "{bw}x{bh} is not a 128-root half");
2286 }
2287 }
2288
2289 /// lane-hdrlossless, ENUMERATION behind the LONE capability claim
2290 /// ("filter intra on a superblock-level HORZ/VERT strip"). The guard in
2291 /// `decode_block_rect` fires only when `filter_intra.is_some()`, and that
2292 /// flag is `Some` only where `filter_intra_size_class_rect` says so. The
2293 /// strips the guard protects are `(64, 32)` / `(32, 64)`; this test
2294 /// enumerates every EXPLICIT arm of that table (asserting none admits a
2295 /// `64` axis) AND drives the square-delegate guard arm's callee
2296 /// `filter_intra_size_class` directly at 32/64, so a widening on either
2297 /// side turns it red. No conformant stream (libaom
2298 /// `av1_filter_intra_allowed_bsize` caps both sides at 32) can offer the
2299 /// symbol there.
2300 #[test]
2301 fn a_sb_level_horz_vert_strip_admits_no_filter_intra_symbol() {
2302 let src = crate::test_source::module_source("decode");
2303 assert!(
2304 src.contains("\"filter intra on a superblock-level HORZ/VERT strip"),
2305 "the guard this proof is about is gone -- re-derive the capability claim"
2306 );
2307 let at = src
2308 .find("fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {")
2309 .expect("filter_intra_size_class_rect is gone");
2310 let body = &src[at..at + src[at..].find("\n}\n").expect("unterminated fn")];
2311 let (mut arms, mut saw_none_fallback, mut saw_square_delegate) = (0usize, false, false);
2312 let mut seen: Vec<(usize, usize)> = Vec::new();
2313 for line in body.lines() {
2314 let line = line.trim();
2315 if line.starts_with('_') {
2316 if line == "_ => None," {
2317 saw_none_fallback = true;
2318 } else if line.starts_with("_ if ") {
2319 // The square-delegate guard arm hands a square strip to
2320 // `filter_intra_size_class`; the numeric walk below cannot
2321 // see it (it carries no `(bw, bh)` pair), so its callee is
2322 // audited by the direct call after the loop instead.
2323 assert!(
2324 line == "_ if bw == bh => filter_intra_size_class(bw),",
2325 "filter_intra_size_class_rect's guard arm changed shape: {line}"
2326 );
2327 saw_square_delegate = true;
2328 }
2329 continue;
2330 }
2331 let Some(rest) = line.strip_prefix('(') else {
2332 continue;
2333 };
2334 let Some((pair, _)) = rest.split_once(") =>") else {
2335 continue;
2336 };
2337 let Some((a, b)) = pair.split_once(',') else {
2338 continue;
2339 };
2340 let bw: usize = a.trim().parse().expect("arm bw");
2341 let bh: usize = b.trim().parse().expect("arm bh");
2342 assert!(
2343 bw <= 32 && bh <= 32,
2344 "filter_intra_size_class_rect grew an arm with a side above 32 ({bw}x{bh}); \
2345 `av1_filter_intra_allowed_bsize` forbids the symbol there, but if the table \
2346 now admits it the SB-strip guard is reachable"
2347 );
2348 seen.push((bw, bh));
2349 arms += 1;
2350 }
2351 assert!(
2352 arms >= 10,
2353 "only {arms} arms parsed -- the table's shape changed"
2354 );
2355 assert!(
2356 saw_none_fallback,
2357 "filter_intra_size_class_rect lost its `_ => None` fallback"
2358 );
2359 assert!(
2360 saw_square_delegate,
2361 "filter_intra_size_class_rect lost its square-delegate arm"
2362 );
2363 // The guard arm delegates square strips to `filter_intra_size_class`;
2364 // drive the delegate directly, so a widening there turns THIS test red
2365 // (the numeric walk never reaches the guard arm).
2366 assert!(
2367 crate::decode::filter_intra_size_class(32).is_some()
2368 && crate::decode::filter_intra_size_class(64).is_none(),
2369 "filter_intra_size_class now admits a 64-pixel side -- the square-delegate arm of \
2370 filter_intra_size_class_rect can then offer a `use_filter_intra` symbol on a \
2371 superblock-level HORZ/VERT strip and its guard is reachable"
2372 );
2373 for strip in [(64usize, 32usize), (32, 64)] {
2374 assert!(
2375 !seen.contains(&strip),
2376 "{strip:?} has its own filter-intra arm now -- the SB-strip guard is reachable"
2377 );
2378 }
2379 }
2380
2381 /// lane-t900 r33, STRUCTURAL AUDIT behind the DELETION of "a block that
2382 /// actually uses a palette (Y) -- reconstruction is out of scope".
2383 ///
2384 /// That refusal was the `palette.is_none()` arm of `read_intra_mode` and
2385 /// `read_intra_mode_rect`: a stream reached it only if a CALLER read the
2386 /// palette syntax without handing the reader a neighbour ctx/cache pair.
2387 /// Every one of the eight call sites passes `Some((palette_ctx,
2388 /// &palette_cache))`, so no stream could reach either arm and both are
2389 /// gone from `decode.rs`. This test keeps the invariant the deletion rests
2390 /// on: a future caller that passes `None` fails here rather than decoding
2391 /// a palette off an empty colour cache.
2392 #[test]
2393 fn every_read_intra_mode_call_site_hands_the_reader_a_palette_cache() {
2394 let src = crate::test_source::module_source("decode");
2395 let mut sites = 0u32;
2396 for name in ["read_intra_mode(", "read_intra_mode_rect("] {
2397 for (at, _) in src.match_indices(name) {
2398 // The definition itself, not a call.
2399 if src[..at].ends_with("fn ") {
2400 continue;
2401 }
2402 sites += 1;
2403 let window = &src[at..(at + 4096).min(src.len())];
2404 let end = window.find("fctx,\n").unwrap_or(window.len());
2405 assert!(
2406 window[..end].contains("Some((palette_ctx, &palette_cache)),"),
2407 "a {name} call site does not hand the reader a palette ctx/cache pair -- \
2408 the deleted `palette.is_none()` refusal was its guard"
2409 );
2410 }
2411 }
2412 assert_eq!(
2413 sites, 8,
2414 "the call-site audit found {sites} sites, not the 8 it enumerated"
2415 );
2416 }
2417
2418 /// Lane-av1refusalspan: the files a proving gate may live in.
2419 fn gate_sources() -> [(&'static str, &'static str); 3] {
2420 [
2421 ("decode.rs", crate::test_source::module_source("decode")),
2422 ("stream.rs", crate::test_source::module_source("stream")),
2423 ("refusal_inventory.rs", include_str!("refusal_inventory.rs")),
2424 ]
2425 }
2426
2427 /// Lane-av1refusalspan: every offset in `src` of a line that DEFINES
2428 /// `fn <gate>(` -- and nothing that merely names it.
2429 ///
2430 /// "The gate" is a function, so the first thing the anchor needs is the
2431 /// function's own definition. The window rule this replaced took the first
2432 /// `fn <gate>(` the file happened to contain, and a comment or a string
2433 /// produces one. A definition is a line whose text before the keyword is
2434 /// whitespace and qualifiers only (`pub`, `pub(crate)`, `async`, ...).
2435 fn gate_definitions(src: &str, gate: &str) -> Vec<usize> {
2436 src.match_indices(&format!("fn {gate}("))
2437 .map(|(at, _)| at)
2438 .filter(|at| {
2439 let line_start = src[..*at].rfind('\n').map_or(0, |i| i + 1);
2440 // Qualifiers are bare words (`pub`, `pub(crate)`, `async`, ...).
2441 // Anything else on the line before the keyword (a `=`, a quote,
2442 // a `//`, a `#[...]`) means the match is not a definition.
2443 src[line_start..*at].split_whitespace().all(|word| {
2444 let bare = word.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
2445 let visibility = word.starts_with("pub(") && word.ends_with(')');
2446 bare || visibility
2447 })
2448 })
2449 .collect()
2450 }
2451
2452 /// The number of leading-whitespace columns on the line holding `at`.
2453 fn leading_indent(src: &str, at: usize) -> usize {
2454 let line_start = src[..at].rfind('\n').map_or(0, |i| i + 1);
2455 let line = &src[line_start..at];
2456 line.len() - line.trim_start().len()
2457 }
2458
2459 /// The offset of the `"` that closes the string literal opening at `open`.
2460 fn closing_quote(b: &[u8], open: usize) -> Option<usize> {
2461 let mut i = open + 1;
2462 while i < b.len() {
2463 match b[i] {
2464 b'\\' => i += 2,
2465 b'"' => return Some(i),
2466 _ => i += 1,
2467 }
2468 }
2469 None
2470 }
2471
2472 /// The offsets of the `{` that opens the body of the function defined at
2473 /// `gate_at` and of the `}` that closes it; `None` when the body is never
2474 /// closed.
2475 ///
2476 /// This walks Rust, not lines. A brace inside a string literal, a raw
2477 /// string, a byte string, a char literal, a lifetime, a line comment or a
2478 /// (nestable) block comment is not a brace -- counting one is exactly how a
2479 /// "bounded" window becomes the rest of the file.
2480 fn body_braces(src: &str, gate_at: usize) -> Option<(usize, usize)> {
2481 let b = src.as_bytes();
2482 let mut i = gate_at;
2483 let mut depth = 0usize;
2484 let mut open = None;
2485 let mut last: Option<usize> = None;
2486 while i < b.len() {
2487 // Every arm advances `i`, including the ones that `continue`. A spin
2488 // here would hang the suite instead of failing it, which is the one
2489 // outcome a boundary finder must never have.
2490 if let Some(last) = last {
2491 debug_assert!(i > last, "body_braces: an arm must advance the cursor");
2492 }
2493 last = Some(i);
2494 match b[i] {
2495 b'/' if b.get(i + 1) == Some(&b'/') => {
2496 i = src[i..].find('\n').map_or(b.len(), |n| i + n + 1);
2497 continue;
2498 }
2499 b'/' if b.get(i + 1) == Some(&b'*') => {
2500 let mut nesting = 1usize;
2501 i += 2;
2502 while i < b.len() && nesting > 0 {
2503 if b[i] == b'/' && b.get(i + 1) == Some(&b'*') {
2504 nesting += 1;
2505 i += 2;
2506 } else if b[i] == b'*' && b.get(i + 1) == Some(&b'/') {
2507 nesting -= 1;
2508 i += 2;
2509 } else {
2510 i += 1;
2511 }
2512 }
2513 continue;
2514 }
2515 b'r' if b.get(i + 1) == Some(&b'"') || b.get(i + 1) == Some(&b'#') => {
2516 let mut j = i + 1;
2517 while b.get(j) == Some(&b'#') {
2518 j += 1;
2519 }
2520 if b.get(j) != Some(&b'"') {
2521 i += 1;
2522 continue;
2523 }
2524 let hashes = j - i - 1;
2525 let mut end = None;
2526 for k in (j + 1..b.len()).chain(std::iter::once(b.len() - 1)) {
2527 if b[k] == b'"' && b[k + 1..].iter().take(hashes).all(|c| *c == b'#') {
2528 end = Some(k);
2529 break;
2530 }
2531 }
2532 i = end? + 1;
2533 continue;
2534 }
2535 b'"' => {
2536 i = closing_quote(b, i)? + 1;
2537 continue;
2538 }
2539 b'b' if b.get(i + 1) == Some(&b'"') => {
2540 i = closing_quote(b, i + 1)? + 1;
2541 continue;
2542 }
2543 // A lifetime (`'a`, `'static`) is not a char literal: it has no
2544 // closing quote on its line, and reading one as a literal would
2545 // hide real code from the scan.
2546 b'\'' => {
2547 let rest = &b[i + 1..];
2548 let from = if rest.first() == Some(&b'\\') { 2 } else { 0 };
2549 match rest[from..]
2550 .iter()
2551 .take_while(|c| **c != b'\n')
2552 .position(|c| *c == b'\'')
2553 {
2554 Some(k) => i += from + k + 2,
2555 None => i += 1,
2556 }
2557 continue;
2558 }
2559 b'{' => {
2560 open = open.or(Some(i));
2561 depth += 1;
2562 }
2563 b'}'
2564 // A closer seen BEFORE the body opened is not ours (it can
2565 // only come from a signature or a type ascription the scan
2566 // mis-read); ignore it rather than underflowing `depth`.
2567 if depth > 0 => {
2568 depth -= 1;
2569 if depth == 0 {
2570 return open.map(|o| (o, i));
2571 }
2572 }
2573 _ => {}
2574 }
2575 i += 1;
2576 }
2577 None
2578 }
2579
2580 /// The text of the body of the function defined at `gate_at`, or `None`
2581 /// when that body is never closed.
2582 fn function_body(src: &str, gate_at: usize) -> Option<&str> {
2583 let (open, close) = body_braces(src, gate_at)?;
2584 src.get(open..=close)
2585 }
2586
2587 /// The first line of `body` that defines another function at `indent`
2588 /// columns of leading whitespace -- the first sign that a boundary
2589 /// over-reached into a neighbour.
2590 fn sibling_fn(body: &str, indent: usize) -> Option<&str> {
2591 body.lines().skip(1).find(|line| {
2592 let lead = line.len() - line.trim_start().len();
2593 lead == indent && {
2594 let t = line.trim_start();
2595 t.starts_with("fn ") || t.starts_with("pub fn ")
2596 }
2597 })
2598 }
2599
2600 /// Lane-av1refusalspan: the proving gate's OWN body -- the text from the
2601 /// `{` that opens it to the `}` that closes it.
2602 ///
2603 /// Every failure mode here is a FAILURE (`Err`), never a wider window. The
2604 /// rule this replaced -- "the body ends at the next `fn` at the same
2605 /// indentation, or at end of file" -- ended at end of file constantly (a
2606 /// top-level `#[test] fn` in `decode.rs` has its next same-indent `fn`
2607 /// tens of thousands of lines away), and one row's 27,427-line "body" was
2608 /// satisfied by the CHROMA sibling's string seven lines down.
2609 fn gate_body(gate: &str) -> Result<&'static str, String> {
2610 let mut hits: Vec<(&str, usize, &'static str)> = Vec::new();
2611 for (file, src) in gate_sources() {
2612 for at in gate_definitions(src, gate) {
2613 hits.push((file, at, src));
2614 }
2615 }
2616 match hits.as_slice() {
2617 [] => Err(format!(
2618 "{gate} is not defined in decode.rs, stream.rs or refusal_inventory.rs"
2619 )),
2620 [only] => {
2621 let (file, at, src) = *only;
2622 let body = function_body(src, at).ok_or_else(|| {
2623 format!(
2624 "{file}:{at}: the body of {gate}() is never closed -- a missing \
2625 boundary is a FAILURE, not a window that runs on into the next \
2626 function"
2627 )
2628 })?;
2629 if let Some(leak) = sibling_fn(body, leading_indent(src, at)) {
2630 return Err(format!(
2631 "{file}:{at}: the extracted body of {gate}() still contains {} -- the \
2632 boundary over-reached into a neighbour",
2633 leak.trim()
2634 ));
2635 }
2636 Ok(body)
2637 }
2638 many => Err(format!(
2639 "{gate} is defined {} times ({}), so 'its body' is ambiguous",
2640 many.len(),
2641 many.iter()
2642 .map(|(file, at, _)| format!("{file}:{at}"))
2643 .collect::<Vec<_>>()
2644 .join(", ")
2645 )),
2646 }
2647 }
2648
2649 /// The refusal's leading clause: what a gate may quote when it does not
2650 /// quote the whole string -- everything up to the first `(` (the qualifier
2651 /// that varies per call site), else up to the first `:`, else the whole
2652 /// string.
2653 fn leading_clause(reason: &str) -> String {
2654 let cut = reason
2655 .find('(')
2656 .or_else(|| reason.find(':'))
2657 .unwrap_or(reason.len());
2658 reason[..cut].trim_end().to_owned()
2659 }
2660
2661 /// Every entry of [`PROVEN`] must still name a live refusal, and the gate
2662 /// it names must REFERENCE that refusal inside its OWN body.
2663 ///
2664 /// Lane-av1refusalspan: the boundary is the gate's closing brace (see
2665 /// [`gate_body`]); a boundary that cannot be found fails the row.
2666 #[test]
2667 fn every_proven_refusal_names_a_test_that_exists() {
2668 let found = decode_path_refusals();
2669 let mut whole = 0usize;
2670 let mut clause = 0usize;
2671 let mut neither: Vec<&str> = Vec::new();
2672 let mut unanchored: Vec<String> = Vec::new();
2673 let mut unbounded: Vec<String> = Vec::new();
2674 for (reason, gate, _kind) in PROVEN {
2675 assert!(
2676 found.contains(*reason),
2677 "{reason:?} is listed as proven but is no longer a decode-path refusal -- \
2678 drop it from PROVEN (the capability landed) or fix the string"
2679 );
2680 // A missing boundary is a FAILURE for the row, never a wider window.
2681 let body = match gate_body(gate) {
2682 Ok(body) => body,
2683 Err(why) => {
2684 unbounded.push(format!("{reason:?} names {gate}: {why}"));
2685 continue;
2686 }
2687 };
2688 let flat = squash_source(body);
2689 if flat.contains(&squash_source(reason)) {
2690 whole += 1;
2691 } else if flat.contains(&squash_source(&leading_clause(reason))) {
2692 clause += 1;
2693 } else {
2694 neither.push(reason);
2695 unanchored.push(format!("{reason:?} names {gate}"));
2696 }
2697 }
2698 // The anchor-strength line, measured over BODIES. The window rule this
2699 // replaced made these numbers a distribution over "whatever the window
2700 // happened to reach", which is a different question.
2701 eprintln!(
2702 "anchor strength: {whole} rows quote the WHOLE refusal string, {clause} quote its \
2703 LEADING CLAUSE, {} match neither: {neither:?}",
2704 PROVEN.len() - whole - clause
2705 );
2706 eprintln!(
2707 "refusal inventory: {} refusals + {} capability claims, {} proven",
2708 REFUSALS.len(),
2709 CAPABILITY_CLAIMS.len(),
2710 PROVEN.len()
2711 );
2712 assert!(
2713 unbounded.is_empty(),
2714 "these rows name a gate whose body could not be bounded, so nothing was proved \
2715 about them -- a missing boundary is a failure, not a window that runs on:\n\
2716 {unbounded:#?}\n\
2717 The boundary is the gate's own closing brace. If the gate really is there, the \
2718 finder is wrong: fix the finder, never the verdict."
2719 );
2720 assert!(
2721 unanchored.is_empty(),
2722 "these rows name a gate that never references the refusal inside its OWN body -- a \
2723 test that does not use the string it is said to prove is not a proof:\n\
2724 {unanchored:#?}\n\
2725 Name a gate that quotes the refusal (or its leading clause), or write one."
2726 );
2727 }
2728
2729 /// The OTHER half of the inventory's invariant: every string LISTED in
2730 /// [`REFUSALS`] or [`CAPABILITY_CLAIMS`] has a row in [`PROVEN`].
2731 ///
2732 /// `every_proven_refusal_names_a_test_that_exists` checks the direction
2733 /// row -> live refusal, so a string added to the inventory with no proving
2734 /// gate was invisible: the file could list 33 strings, carry 31 rows, and
2735 /// every test in the module stayed green. Two rows were missing on main
2736 /// (the BLOCK_INVALID subsize refusal and the lone filter-intra capability
2737 /// claim) precisely because nothing compared the two sets. This is that
2738 /// comparison, so the next one cannot land unmeasured.
2739 #[test]
2740 fn every_listed_refusal_and_capability_claim_has_a_proven_row() {
2741 let mut listed = 0usize;
2742 let mut unmeasured: Vec<&str> = Vec::new();
2743 for reason in REFUSALS.iter().chain(CAPABILITY_CLAIMS.iter()) {
2744 listed += 1;
2745 if !PROVEN.iter().any(|(row, _, _)| *row == *reason) {
2746 unmeasured.push(reason);
2747 }
2748 }
2749 assert!(
2750 unmeasured.is_empty(),
2751 "these strings are listed as refusals / capability claims but no PROVEN row names a \
2752 gate that proves them -- an unmeasured claim is what this table exists to make \
2753 visible:\n{unmeasured:#?}"
2754 );
2755 assert_eq!(
2756 listed,
2757 PROVEN.len(),
2758 "{listed} strings are listed and {} rows exist -- they must be one to one, so a row \
2759 can never stand in for a string that is not listed",
2760 PROVEN.len()
2761 );
2762 eprintln!(
2763 "refusal inventory: {listed} listed strings, {} PROVEN rows, one to one",
2764 PROVEN.len()
2765 );
2766 }
2767
2768 /// Lane-av1refusalspan, non-vacuity of the BOUNDARY (not of the anchor):
2769 /// a neighbour's function must be unreachable from a gate's body, and a
2770 /// body that is not closed must fail rather than run on.
2771 #[test]
2772 fn a_gate_body_is_bounded_by_its_own_closing_brace() {
2773 let marker = "a rectangular chroma transform whose size has no coefficient table";
2774 let src = format!(
2775 "fn this_gate() {{\n let _ = 1;\n}}\n\nfn next_gate() {{\n let _ = \"{marker}\";\n}}\n\nfn tail() {{}}\n"
2776 );
2777 let this = gate_body_in(&src, "this_gate").expect("the gate has a boundary");
2778 assert!(this.contains("let _ = 1;"), "own text: {this:?}");
2779 assert!(
2780 !this.contains(marker),
2781 "leaked into the neighbour: {this:?}"
2782 );
2783 let next = gate_body_in(&src, "next_gate").expect("the neighbour has a boundary");
2784 assert!(next.contains(marker));
2785 assert!(!next.contains("let _ = 1;"));
2786 // The last function in a file has no following `fn` to stop at: the
2787 // boundary must still close, exactly on its own brace.
2788 assert_eq!(gate_body_in(&src, "tail").as_deref(), Ok("{}"));
2789 // A brace inside a string or a char literal is not a brace. If the scan
2790 // counted one, this body would run past its own `}` into `next_gate`
2791 // -- the over-reach the `sibling_fn` invariant exists to catch, and the
2792 // failure mode that made the old window 27,427 lines long.
2793 let with_braces_in_literals = format!(
2794 "fn this_gate() {{\n let _ = \"{{\";\n let _ = '}}';\n // {{\n /* }} */\n}}\n\nfn next_gate() {{\n let _ = \"{marker}\";\n}}\n"
2795 );
2796 let bounded = gate_body_in(&with_braces_in_literals, "this_gate");
2797 assert!(
2798 bounded.as_deref().is_ok_and(|b| !b.contains(marker)),
2799 "a brace in a literal moved the boundary: {bounded:?}"
2800 );
2801 // A body whose closing brace is missing (a half-finished edit) is a
2802 // FAILURE. The rule it replaced sliced to end of file and carried on.
2803 let truncated =
2804 "fn this_gate() {\n let _ = 1;\n\nfn next_gate() {\n let _ = 2;\n}\n".to_string();
2805 assert!(gate_body_in(&truncated, "this_gate").is_err());
2806 }
2807
2808 /// Lane-av1refusalspan: the boundary is load-bearing on the REAL sources,
2809 /// not only on the synthetic pair above -- every named gate resolves to
2810 /// exactly one function whose body holds no other function, and the last
2811 /// function in each of the three files terminates correctly.
2812 #[test]
2813 fn every_named_gate_body_is_bounded_in_these_files() {
2814 let mut resolved = 0usize;
2815 for (reason, gate, _kind) in PROVEN {
2816 let body =
2817 gate_body(gate).unwrap_or_else(|why| panic!("{reason:?} names {gate}: {why}"));
2818 assert!(
2819 body.ends_with('}'),
2820 "{gate}'s body does not end on its closing brace"
2821 );
2822 resolved += 1;
2823 }
2824 assert_eq!(resolved, PROVEN.len());
2825 for (file, src) in gate_sources() {
2826 let last = last_fn_name(src).unwrap_or_else(|| panic!("{file} has no function"));
2827 let at = gate_definitions(src, &last)
2828 .last()
2829 .copied()
2830 .unwrap_or_else(|| panic!("{file}: no definition of {last}"));
2831 let body = function_body(src, at)
2832 .unwrap_or_else(|| panic!("{file}: the last function {last}() has no boundary"));
2833 assert!(sibling_fn(body, leading_indent(src, at)).is_none());
2834 }
2835 }
2836
2837 /// The taxonomy is a CLAIM about each row, so it carries its own
2838 /// non-vacuity: every variant is used by at least one row (a variant no
2839 /// row can be in is not a category), the two labels do not collapse into
2840 /// one string, and the row lane-av1refusalclaim r3 wanted to RE-TAG is
2841 /// tagged from evidence inside its own gate BODY -- never from the
2842 /// gate's name, which is the only thing the previous 2-tuple carried.
2843 ///
2844 /// r3 minted a `TablePin` variant because "a rectangular chroma transform
2845 /// whose size has no coefficient table" was pinned to a table whose
2846 /// REACHED-OVER domain had never been measured. Main has since replaced
2847 /// that row's gate with one that reads the eight `decode_block_rect` call
2848 /// sites' own literal `bw`/`bh`, pins the resulting chroma table exactly,
2849 /// and asserts the `(4,8)`/`(8,4)` residual is UNPRODUCIBLE. `Enumeration`
2850 /// is therefore the honest tag and `TablePin` is not carried; if a later
2851 /// edit weakens that gate back to a bare table pin, the three evidence
2852 /// pins below go red instead of leaving the row quietly overclaiming.
2853 #[test]
2854 fn every_proven_row_names_which_kind_of_proof_it_carries() {
2855 let mut negative = 0usize;
2856 let mut enumeration = 0usize;
2857 for (reason, gate, kind) in PROVEN {
2858 eprintln!(" {} -- {reason:?} -> {gate}", kind.label());
2859 match kind {
2860 Proof::NegativeGate => negative += 1,
2861 Proof::Enumeration => enumeration += 1,
2862 }
2863 }
2864 assert_eq!(
2865 negative + enumeration,
2866 PROVEN.len(),
2867 "a PROVEN row carries no proof kind, so the table says nothing about it"
2868 );
2869 assert!(
2870 negative > 0,
2871 "no row is tagged NEGATIVE, so the NegativeGate variant is dead weight"
2872 );
2873 assert!(
2874 enumeration > 0,
2875 "no row is tagged ENUMERATION, so the Enumeration variant is dead weight"
2876 );
2877 assert_ne!(
2878 Proof::NegativeGate.label(),
2879 Proof::Enumeration.label(),
2880 "the two kinds print the same string, so the taxonomy is one category in two hats"
2881 );
2882
2883 let (reason, gate, kind) = PROVEN
2884 .iter()
2885 .find(|(reason, _, _)| {
2886 *reason == "a rectangular chroma transform whose size has no coefficient table"
2887 })
2888 .map(|(reason, gate, kind)| (*reason, *gate, kind))
2889 .expect("the (4,8) chroma-table row left PROVEN");
2890 assert!(
2891 matches!(kind, Proof::Enumeration),
2892 "{reason:?} is tagged {:?}, but its gate enumerates the caller domain",
2893 kind.label()
2894 );
2895 let body = gate_body(gate).unwrap_or_else(|why| panic!("{reason:?} names {gate}: {why}"));
2896 for evidence in [
2897 "the number of decode_block_rect call sites changed",
2898 "for residual in [(4usize, 8usize), (8, 4)]",
2899 "the caller set can now produce a 4x8/8x4 chroma shape",
2900 ] {
2901 assert!(
2902 body.contains(evidence),
2903 "{gate} no longer carries {evidence:?}, so the Enumeration tag on {reason:?} \
2904 claims a reach domain the gate has stopped measuring"
2905 );
2906 }
2907 eprintln!(
2908 "refusal inventory: {negative} NEGATIVE, {enumeration} ENUMERATION of {} PROVEN rows",
2909 PROVEN.len()
2910 );
2911 }
2912
2913 /// Lane-av1refusalspan: the invariant that catches a boundary that
2914 /// over-reaches. Tested on its own text, so it cannot be satisfied by the
2915 /// scanner happening to be right on the current sources.
2916 #[test]
2917 fn a_body_carrying_another_function_is_refused() {
2918 assert!(sibling_fn("{\n let _ = 1;\n}\n\nfn neighbour() {\n}\n", 0).is_some());
2919 assert!(sibling_fn("{\n let _ = 1;\n}\n", 0).is_none());
2920 // A nested `fn` is deeper-indented and does belong to the body.
2921 assert!(sibling_fn("{\n fn helper() {}\n}\n", 0).is_none());
2922 }
2923
2924 /// Lane-av1refusalspan: `gate_body` over ONE file, so the boundary tests
2925 /// above can drive it with text that cannot occur in this crate.
2926 fn gate_body_in<'a>(src: &'a str, gate: &str) -> Result<&'a str, String> {
2927 let defs = gate_definitions(src, gate);
2928 match defs.as_slice() {
2929 [] => Err(format!("{gate} is not defined here")),
2930 [at] => {
2931 let body = function_body(src, *at).ok_or_else(|| {
2932 format!("the body of {gate}() is never closed -- boundary missing")
2933 })?;
2934 if let Some(leak) = sibling_fn(body, leading_indent(src, *at)) {
2935 return Err(format!("boundary over-reached into {}", leak.trim()));
2936 }
2937 Ok(body)
2938 }
2939 many => Err(format!("{gate} is defined {} times", many.len())),
2940 }
2941 }
2942
2943 /// The name of the last function defined in `src` -- the boundary rule's
2944 /// hard case, since nothing follows it to stop at.
2945 fn last_fn_name(src: &str) -> Option<String> {
2946 src.lines()
2947 .filter_map(|line| {
2948 let t = line.trim_start();
2949 if !(t.starts_with("fn ") || t.starts_with("pub fn ")) {
2950 return None;
2951 }
2952 Some(t.trim_start_matches("pub fn ").trim_start_matches("fn "))
2953 })
2954 .filter_map(|head| head.split_once('(').map(|(head, _)| head.trim().to_owned()))
2955 .next_back()
2956 }
2957}