forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB1f91eddTahinli2 months ago3507 commits

gate_coverage.rs1701 lines, 80.3 KiBHistoryRawDownload
1//! A guard over the real-aomenc gates' own encoder recipes.
2//!
3//! Every gate in [`crate::stream`] that runs a real `aomenc` picks its coding
4//! tools with `--enable-*=0/1` flags, and a flag left off the command line
5//! takes aomenc's default. That default is `1` for essentially every tool in
6//! [`TOOL_UNIVERSE`] on a non-realtime build -- `default_extra_cfg` in
7//! `av1/av1_cx_iface.c` is all-ones across the seq-level tool fields, and this
8//! oracle is built with `CONFIG_REALTIME_ONLY 0`. But a `1` default is NOT
9//! the same as the tool reaching the stream, and the rest of this file's
10//! "defaulted means unknown" rule rests on that gap: palette and intrabc are
11//! gated on CONTENT (`encoder.c:2079` derives `allow_screen_content_tools`
12//! from block counts, and `seq_force_screen_content_tools` is left at the
13//! adaptive `SELECT_SCREEN_CONTENT_TOOLS`), and `speed_features.c` masks
14//! several tools OFF again per `--cpu-used`. A `1` default proves the encoder
15//! was ALLOWED the tool, never that any block used it.
16//!
17//! With that default in place it is possible -- and it happened -- for a
18//! coding tool to be switched *off in every single gate*, so that no real
19//! stream in this repository ever exercised it and a corner-cut in the
20//! decoder survived twenty gates unnoticed: `reconstruct`'s
21//! `smooth_neighbor` was hardcoded `false`, wrong whenever a directional
22//! block neighbours a smooth-mode one, and invisible because all twenty
23//! gates passed `--enable-smooth-intra=0` (lane-chroma r1, 2026-08-30).
24//!
25//! The test below re-derives that set from the gate source and pins it. A tool
26//! that is switched off in every gate and on in none is *provably never
27//! exercised* by a real stream, and belongs on [`NEVER_EXERCISED`] with a
28//! reason. Landing the decode support for one means enabling it in that
29//! feature's gate, which shrinks the derived set and fails this test until the
30//! list is updated -- the point being that the shrink is noticed.
31
32// TILING is deliberately NOT in this derivation (lane-tiles r11): the check
33// keys on `--enable-<tool>=0/1`, and `--tile-columns=<log2>` has no such
34// shape -- a `--tile-columns=` presence check would also read `=0` (one tile)
35// as coverage, which is the opposite of what it would claim. It needs no
36// entry either: measured 2026-09-29 (lane-av1distwtd r2), 19 of the 146
37// census-selected gate bodies spell `--tile-columns`/`--tile-rows` with a
38// nonzero log2 -- 9 assert the parsed `tile_info` in the same body and 10
39// more delegate to a shared helper that asserts it -- and
40// `run_multi_tile_gate` covers a 2D grid with the coding tools ON at both
41// bit depths.
42
43/// aomenc coding tools that no real-`aomenc` gate is proven to exercise:
44/// switched off in every gate that names them, and on in none.
45///
46/// A gate that simply leaves the flag off its command line does NOT close the
47/// hole. aomenc's default for these is content-dependent -- palette and
48/// intrabc only come on for screen content -- so "defaulted" means "unknown",
49/// not "exercised", and treating it as coverage would retire the entry
50/// without a single stream proving the decoder ever saw the tool. Only an
51/// explicit `--enable-<tool>=1` in a gate that then asserts the feature fired
52/// closes one.
53///
54/// Each entry is `(flag, why)`. Removing an entry is how a lane records that
55/// its tool is now covered by a real stream.
56#[cfg(test)]
57const NEVER_EXERCISED: &[(&str, &str)] = &[
58 // `enable-intrabc` LEFT this list on 2026-09-02 (lane-kf900 r6). The
59 // premise it carried -- "every real stream's intrabc block sits under
60 // TX_MODE_SELECT" -- was false: with `--enable-tx-size-search=0` aomenc
61 // codes intrabc blocks under TX_MODE_LARGEST, and
62 // `a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips`
63 // spells `--enable-intrabc=1` and decodes three such 8-bit streams whole-
64 // frame pixel-exact against ffmpeg, with the block counter asserted > 0.
65 // Re-verified 2026-09-17 (lane-av1-intrabc) at main f715d70c: 185 rect
66 // `use_intrabc` symbols read, and 5 blocks took the DV path -- 4 of them
67 // DECODED whole-frame pixel-exact across 4 arms (7 frames compared, 0
68 // mismatches). The fifth is the testsrc2 rectangle-strip arm, which reads
69 // the symbol and then refuses by name (the `intrabc_hits` bump happens on
70 // the READ), so "5 blocks decoded" would overcount: 4 decoded + 1 refused,
71 // exactly the single `refused == 1` the gate asserts.
72];
73
74/// The `--enable-*` tools this decoder cares about, whether or not any gate
75/// names one. A flag no gate mentions is *defaulted*, i.e. unknown, and by the
76/// rule above unknown is not coverage -- so the universe is fixed here rather
77/// than derived from the gate source, which would silently shrink to whatever
78/// the gates happen to spell.
79#[cfg(test)]
80const TOOL_UNIVERSE: &[&str] = &[
81 "enable-1to4-partitions",
82 "enable-ab-partitions",
83 "enable-angle-delta",
84 "enable-cdef",
85 "enable-cfl-intra",
86 "enable-dist-wtd-comp",
87 "enable-dual-filter",
88 "enable-filter-intra",
89 "enable-flip-idtx",
90 "enable-global-motion",
91 "enable-interintra-comp",
92 "enable-intra-edge-filter",
93 "enable-intrabc",
94 "enable-masked-comp",
95 "enable-obmc",
96 "enable-order-hint",
97 "enable-paeth-intra",
98 "enable-palette",
99 "enable-rect-partitions",
100 "enable-rect-tx",
101 "enable-ref-frame-mvs",
102 "enable-restoration",
103 "enable-smooth-intra",
104 "enable-superres",
105 "enable-tx64",
106 "enable-warped-motion",
107];
108
109/// How a non-boolean aomenc knob reads as "the tool is on".
110#[cfg(test)]
111#[derive(Clone, Copy, PartialEq)]
112enum On {
113 /// Any non-zero value enables the tool (`--tile-columns=1`, `--loopfilter-control=1`).
114 NonZero,
115 /// The tool's search only runs at or below this speed (`--cpu-used`).
116 AtMost(u32),
117}
118
119/// Coding tools aomenc drives through a spelling [`TOOL_UNIVERSE`] does not
120/// cover, listed with their aomenc default.
121///
122/// lane-covbd's derivation read `--enable-*` flags only, so a tool a gate pins
123/// off through another spelling was invisible: every gate that named
124/// `--enable-tx-size-search` passed `--enable-tx-size-search=0` when this was
125/// written, and the real-stream PANIC hiding behind that pin was found by
126/// lane-ab16, not by this guard. `--loopfilter-control=0`,
127/// `--tile-columns=0` and a `--cpu-used` high enough to switch a search off are
128/// the same shape. `enable-tx-size-search` has since been SETTLED, in both
129/// directions -- see the entry below and `print_tx_size_search_census`.
130///
131/// The "all 49" count is GONE as of 2026-09-29 (lane-av1distwtd r2) and is
132/// deliberately not replaced by a number here: it is a snapshot that rots
133/// every time a recipe changes. The live count is a TEST
134/// ([`print_tx_size_search_census`], below), not prose, so it cannot go stale
135/// silently -- re-run it and read the numbers rather than trusting a comment.
136///
137/// Each entry is `(tool, spellings, aomenc default, what counts as on)`. The
138/// "defaulted means unknown" rule of [`NEVER_EXERCISED`] applies unchanged: a
139/// default of `1` does not prove the encoder picked the tool for any stream, so
140/// only a gate that spells an on-value at that bit depth retires an entry.
141// `enable-tx-size-search` SETTLED 2026-09-29 (lane-av1txsearch), by
142// measurement rather than by a name-shaped guess. The r3 note here said the
143// count was a FLOOR: 9 gate bodies built the flag into a `format!`
144// variable that neither `flags_in` nor `settings_in` could see, because
145// both scan for a literal `"--flag=value"` inside one segment. The method
146// r3 asked for is now [`spelling_values`] -> [`bound_values`], and it
147// resolves all of them; `print_tx_size_search_census` asserts the
148// unresolvable count is ZERO, so the floor cannot come back unnoticed.
149//
150// THE ENTRY IS RETIRED, on an ARRIVAL ASSERT rather than on the spelling.
151// `a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact`
152// spells `--enable-tx-size-search=1` as a literal and hard-asserts
153// `compared_tx_depths > 0` -- "never produced a nonzero tx depth on a
154// compared attempt -- the flag did not arrive". `tx_depth` is read ONLY
155// under the frame header's `tx_mode_select` bit (spec 5.11.16,
156// `decode.rs`: the read is guarded by `tx_select_inter`), so a nonzero
157// counter IS the parsed tx-size-search behaviour, not a proxy for it.
158// Measured run of that gate on this tree (aom 3.13.3): 12 pixel-exact
159// decodes, 0 named refusals, 6 of the 12 at 10 BIT, 219 rect coefficient
160// TUs on compared attempts, and `flag arrival: ... tx depths 53` -- so the
161// tool is exercised at BOTH depths, and the assertion is not vacuous.
162//
163// The `tx_select_inter_gate` twins
164// (`a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact{,_10bit}`)
165// are the stronger witness still: they DELIBERATELY omit the flag
166// ("DELIBERATELY ABSENT: --enable-tx-size-search=0") and assert
167// `decode::txfm_split_hits()` moved, proving the var-tx `txfm_split` tree
168// of spec 5.11.17 is read -- an inter transform is then a recursive split
169// tree, which is the whole content of the tool.
170#[cfg(test)]
171const DEFAULT_ON_TOOLS: &[(&str, &[&str], &str, On)] = &[
172 (
173 "enable-tx-size-search",
174 &["enable-tx-size-search"],
175 "1",
176 On::NonZero,
177 ),
178 (
179 "enable-directional-intra",
180 &["enable-directional-intra"],
181 "1",
182 On::NonZero,
183 ),
184 (
185 "enable-smooth-interintra",
186 &["enable-smooth-interintra"],
187 "1",
188 On::NonZero,
189 ),
190 (
191 "enable-interintra-wedge",
192 &["enable-interintra-wedge"],
193 "1",
194 On::NonZero,
195 ),
196 (
197 "enable-diff-wtd-comp",
198 &["enable-diff-wtd-comp"],
199 "1",
200 On::NonZero,
201 ),
202 (
203 "enable-onesided-comp",
204 &["enable-onesided-comp"],
205 "1",
206 On::NonZero,
207 ),
208 ("enable-fwd-kf", &["enable-fwd-kf"], "0", On::NonZero),
209 ("deblocking", &["loopfilter-control"], "1", On::NonZero),
210 (
211 "multi-tile",
212 &["tile-columns", "tile-rows"],
213 "0",
214 On::NonZero,
215 ),
216 ("intrabc-search", &["cpu-used"], "0", On::AtMost(2)),
217];
218
219/// Non-`--enable-*` spellings that drive a [`TOOL_UNIVERSE`] tool.
220///
221/// `--superres-mode=1` is how every superres gate switches superres on;
222/// without this map they read as an `enable-superres` hole while a real stream
223/// exercises the tool (lane-covbd deferred exactly this). The count was "all
224/// three" until 2026-09-29 (lane-av1distwtd r2), which measured SIX gates
225/// spelling a nonzero `--superres-mode` (5 among the 146 census-selected
226/// bodies, plus `a_superres_census_over_six_real_streams_...`). No count is
227/// given here for the same reason as `enable-tx-size-search` above: it rots.
228/// Worth noting the alias is the ONLY positive evidence for superres, and
229/// those gates do assert arrival -- `superres_hits` / `predict_scaled_hits`
230/// are read in five of them -- so this one is a healthy alias, not a
231/// spelling-only one.
232#[cfg(test)]
233const ALIASES: &[(&str, &str)] = &[("superres-mode", "enable-superres")];
234
235/// Coverage is per (tool x bit depth), not per tool.
236///
237/// lane-hbdinter found two 10-bit-only defects (SGR box sums unscaled, Wiener
238/// clamp pinned at the 8-bit bound) that survived the "10-bit bit-exact"
239/// milestone because every 10-bit gate passed `--enable-restoration=0`:
240/// `enable-restoration` is positively exercised -- at 8 bits only. A tool the
241/// 8-bit gates cover says nothing about the high-bit-depth path through the
242/// same code, so the two lists below are pinned separately.
243///
244/// Each entry is `(flag, why)`. A gate that passes `--enable-<tool>=1` at that
245/// depth retires the entry, and this test fails until it is deleted.
246#[cfg(test)]
247const NEVER_EXERCISED_8BIT: &[(&str, &str)] = &[
248 // `enable-cfl-intra` LEFT both lists on 2026-09-02 (lane-reelckf r1): the
249 // sb128 skipped-CfL / 1:4-chroma gate passes `--enable-cfl-intra=1` at 8
250 // AND 10 bits and pixel-compares both arms.
251 // `enable-dist-wtd-comp` LEFT this list on 2026-09-29 (lane-av1distwtd).
252 // The entry's stated reason was WRONG: the distance-weighted compound
253 // combine is not unimplemented -- `compound::dist_wtd_comp_weight_assign`
254 // (lane-av1comp) and `mc::combine_compound`'s weighted path have been in
255 // the tree for a long time. What was missing was a stream CARRYING the
256 // tool, and `a_distance_weighted_compound_stream_decodes_pixel_exact`
257 // (stream.rs) now supplies one: it spells `--enable-dist-wtd-comp=1` and
258 // asserts the PARSED sequence header carries `enable_jnt_comp == true`
259 // (and `false` from the same recipe with `=0`, so the bit is proven to
260 // move with the flag), that `dist_wtd_comp_hits() > 0` -- the
261 // `compound_idx == 0` arm, the only branch whose blend weights are not the
262 // constant (8, 8) -- and pixel-compares every frame against the oracle.
263 // The existing lane-cwarp compound-warp gates already SPELLED `=1` and
264 // the census still read this entry as open, so the hole was a missing
265 // witness, not a missing flag.
266 // `enable-dual-filter` LEFT this list on 2026-09-29 (lane-av1distwtd r3),
267 // paid by a DETECTOR fix rather than by a new gate. The r2 audit found
268 // this entry's reason false on both halves. It is spelled -- as `=0`, by
269 // `real_aomenc_1to4_streams_...` and
270 // `a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_...` -- so
271 // "never spelled" was wrong; and a stream IS proven to carry the tool,
272 // because `a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact`
273 // spells `--enable-dual-filter=1` and hard-asserts
274 // `decode::dual_filter_diff_hits()` moved, the differing-direction arrival
275 // assert (`resolve_interp_filter` in decode.rs). That gate builds its
276 // stream through `inter_sb_none_gate`, so it spells none of the three
277 // tokens `gate_bodies()` used to filter on and was INVISIBLE to the
278 // census; r3 made `gate_bodies()` resolve calls as well as spellings, and
279 // `the_detector_sees_the_gates_the_spelling_filter_missed` pins that.
280 // Supporting measurement: with the flag left off the command line the
281 // parsed sequence header already carries `enable_dual_filter = true`
282 // (6855 B), while `--enable-dual-filter=0` parses false and encodes
283 // different bytes (6874 B) -- so the gates pinning it `=0` were removing
284 // the tool and the ones leaving it defaulted carry it.
285 //
286 // `enable-flip-idtx` LEFT this list the same day, also by detector fix.
287 // `a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact`
288 // spells `=1` and hard-asserts `compared_class1 > 0` ("--enable-flip-idtx=1
289 // never produced a V_DCT/H_DCT transform on a compared attempt"). Its
290 // recipe is parameterised on `ten_bit` and names BOTH fixture formats, so
291 // `is_ten_bit` filed the whole body 10-bit-ONLY and the 8-bit bucket
292 // never saw it -- the lane-defon/reelckf blind spot through a THIRD
293 // spelling, which r3 taught `covers_both_depths` to recognise as the
294 // pair-of-formats marker. Measured run of that gate: 12 pixel-exact
295 // decodes, 6 of them 8-bit, 219 rect coefficient TUs of which 10 carry a
296 // 1D tx class.
297 // `enable-global-motion` LEFT this list on 2026-09-25 (lane-av1gwarp12 r2):
298 // `a_real_affine_global_motion_stream_decodes_pixel_exact` loops
299 // `for depth in [8u32, 10u32]` passing `--enable-global-motion=1` and
300 // pixel-compares both depths, so the 8-bit hole has been closed since
301 // lane-gmaffine r1 -- the entry survived because no suite ran a tree
302 // containing both the gate and this test until the ROTZOOM suite.
303 // The 12-bit ROTZOOM gate rides the high-depth bucket via `encode_12bit(`
304 // in `is_ten_bit`, so it plays no part in this retirement.
305 // `enable-rect-tx` -- reason RE-VERIFIED 2026-09-29 (lane-av1distwtd
306 // r2), both halves still TRUE, and the second half is now PROVEN rather
307 // than asserted. (1) "never spelled": measured across all 146
308 // census-selected gate bodies, zero spell `--enable-rect-tx` at either
309 // depth -- the only `--enable-*` tool in [`TOOL_UNIVERSE`] with no
310 // spelling anywhere. (2) "reach the decoder only through partition
311 // shape": aom 3.13.3 has no sequence-header bit for it. `enable_rect_tx`
312 // is an `AV1E_SET_ENABLE_RECT_TX` encoder-search control
313 // (`av1_cx_iface.c:2125`, copied to `txfm_cfg->enable_rect_tx` at
314 // `av1_cx_iface.c:1483`) and is read ONLY inside `tx_search.c`
315 // (lines 2568/2662/2686/2710/2956); `bitstream.c` writes no such bit, and
316 // this crate's `SequenceHeader` (`ec-av1-syntax/src/sequence.rs`) has no
317 // such field. The decoder's own gate is `is_rect_tx_allowed`, derived
318 // from partition shape -- exactly what this reason says. A gate can
319 // therefore never prove this tool by naming the flag, only by proving a
320 // rect transform unit fired (`rect_partition_hits` /
321 // `rect_coeff_tu_hits`, which lane-rect1d's gate does assert).
322 // `enable-rect-tx` LEFT this list on 2026-09-29 (merge wave 2,
323 // lane-av1toolgates). Both halves of the reason recorded above still hold
324 // as statements about the FLAG, and the second is exactly why the closing
325 // evidence is a parsed shape and not a spelling: `enable_rect_tx` has no
326 // sequence-header bit, so a decoder path can never be proven by naming the
327 // flag -- only by proving a rect transform unit fired.
328 // `a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact`
329 // (and its 10-bit twin) now spell `--enable-rect-tx=1` in their OWN test
330 // bodies -- inline on purpose, because a helper-owned recipe collapses
331 // both gates into one helper segment that `is_ten_bit` files 10-bit, and
332 // the 8-bit hole would stay open -- and prove the tool on the PARSED
333 // shape: `rect_partition_hits()` and `rect_coeff_tu_hits()` are both
334 // asserted > 0 over arms that decoded AND pixel-compared, and each
335 // counter is mutation-proven red on its own message.
336 // Census on the merged tree (`print_never_exercised_per_bit_depth`):
337 // 255 real-aomenc gate bodies, NEVER_EXERCISED derived EMPTY at 8 bits
338 // and at 10 bits -- 0 of 26 tools -- so this list is empty on the same
339 // evidence, not by deletion of a claim.
340];
341
342#[cfg(test)]
343const NEVER_EXERCISED_10BIT: &[(&str, &str)] = &[
344 // lane-cwarp's 10-bit compound-global-warp gate closed `enable-global-motion`
345 // and `enable-dist-wtd-comp` at 10 bits without deleting their entries here,
346 // so this list was already stale (and this test already red) at main 9c35ecc;
347 // lane-tiles r11's multi-tile 10-bit gates then closed `enable-ab-partitions`,
348 // `enable-rect-partitions` and `enable-restoration` at 10 bits. All five
349 // deleted together.
350
351 // The "Only 4 of the 45 real-aomenc gates encode at 10 bits" sentence that
352 // stood here is STALE (lane-av1distwtd r2, 2026-09-29), and understated
353 // the high-depth bucket by more than an order of magnitude. Measured
354 // against this tree with `gate_bodies()`' own filter: 146 selected gate
355 // bodies, of which 83 are classified 10-bit-or-higher by `is_ten_bit`.
356 // The historical point stands -- those gates pin the pixel filters and
357 // the intra tool set off far more often than not -- but the counts a
358 // reader would check them against no longer exist.
359 // Every entry the 8-bit list carries is a hole here too. lane-hbdgates r1
360 // closed six of the seven 8-bit-only entries with real 10-bit gates
361 // paeth-intra, intra-edge-filter, rect-partitions, ab-partitions); its
362 // seventh, the 10-bit LR gate, was `#[ignore]`d on that branch and passes
363 // un-ignored on main, which carries the fix.
364 // `enable-restoration` LEFT this list on 2026-09-01: lane-hbdinter's
365 // 10-bit inter gate passes `--enable-restoration=1` and asserts a real
366 // Wiener/SGR unit fired, which is what caught the two defects (SGR box
367 // sums never brought back to the 8-bit scale, Wiener clamp at the wrong
368 // bound). `enable-dist-wtd-comp` and `enable-global-motion` left it the
369 // same day for the same reason: lane-cwarp's 10-bit compound global-warp
370 // gate passes `=1` for both. `enable-1to4-partitions` left it on 2026-09-02:
371 // lane-tx64x16 r4's 32-level 1:4 gate has a 10-bit arm that asserts both
372 // orientations and coded strips inside pixel-exact attempts.
373 // `enable-dual-filter` -- reason CORRECTED 2026-09-29 (lane-av1distwtd
374 // r3), and this entry STAYS while its 8-bit twin was retired. That is the
375 // honest outcome, not an oversight: after the r3 detector fix the 8-bit
376 // bucket sees the tool exercised and the 10-bit bucket still does not.
377 // The only `=1` witness is
378 // `a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact`,
379 // and it calls `inter_sb_none_gate(NAME, false, ...)` -- `false` is the
380 // `ten_bit` parameter, so that gate builds an 8-bit stream only. Its
381 // sibling `a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact`
382 // passes `true`, and the 8x8-leaf pair likewise, but none of those spells
383 // `--enable-dual-filter=1`. So: exercised at 8 bits (arrival assert
384 // `dual_filter_diff_hits()` moved, `resolve_interp_filter` in decode.rs),
385 // NOT exercised at 10 bits. Retiring this entry needs a 10-bit arm of that
386 // gate -- pass `true` to `inter_sb_none_gate` and assert the differing-
387 // direction counter still moves there.
388 //
389 // The two numbers in the `enable-flip-idtx` retirement below were
390 // RE-MEASURED 2026-09-29 (lane-av1distwtd r2) by running the gate, and
391 // both still hold exactly: "pixel-compares six 10-bit decodes" (the run
392 // reports 12 pixel-exact decodes, 6 of them 10-bit) and "10 of its rect
393 // coefficient TUs carry a 1D tx class" (219 rect coefficient TUs on
394 // compared attempts, 10 of them 1D). The gate also hard-asserts
395 // `compared_class1 > 0`, so its "passes =1 at both depths" is backed by an
396 // arrival assert, not just a spelling.
397 // `enable-dual-filter` LEFT this list on 2026-09-29 (merge wave 2,
398 // lane-av1dualfilter10), by exactly the 10-bit arm the note above names.
399 // `a_real_aomenc_10bit_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact`
400 // spells `--enable-dual-filter=1` in its own body and hard-asserts the
401 // arrival counter `decode::dual_filter_diff_hits()` moved at 10 BITS, so
402 // the entry is closed at the depth it was held open at, not by a spelling
403 // alone.
404 // `enable-flip-idtx` LEFT this list on 2026-09-02 (lane-rect1d r1):
405 // `a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact`
406 // passes `=1` at both depths and pixel-compares six 10-bit decodes, so the
407 // flip/identity/1D transform types are proven to reach a real 10-bit stream
408 // this decoder reconstructs exactly (10 of its rect coefficient TUs carry a
409 // 1D tx class).
410 // `enable-intrabc` LEFT this 10-bit list on 2026-09-02 (lane-kf900 r6).
411 // The entry it first rested on was a flag spelling -- the palette gate's
412 // `smptebars-screen-txs-cq40/cq55` arms pass `--enable-intrabc=1` -- and
413 // lane-av1-intrabc MEASURED that those arms decode ZERO intrabc blocks at
414 // both depths, so they retired the entry without a stream carrying the
415 // tool (class `tool-disabled-in-every-gate`, the same defect this list
416 // exists for). The closing evidence is now
417 // `an_sb128_screen_stream_with_intrabc_decodes_pixel_exact`: its sb128
418 // screen recipes run at 10 bits and hard-assert a decoded intrabc block
419 // per depth (4-6 per arm), every frame pixel-compared against ffmpeg's own
420 // 10-bit decode.
421 // `enable-rect-tx` LEFT this list on 2026-09-29 (merge wave 2,
422 // lane-av1toolgates), together with its 8-bit twin, by
423 // `a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact`:
424 // the depth is spelled in the test's OWN body, which is what files it in
425 // the 10-bit bucket, and the witness is the parsed shape
426 // (`rect_partition_hits()` / `rect_coeff_tu_hits()` > 0 over arms that
427 // decoded AND pixel-compared). See the 8-bit list for why the flag alone
428 // could never have been the evidence.
429];
430
431/// [`DEFAULT_ON_TOOLS`] entries no 8-bit gate spells on, with the reason.
432///
433/// Each entry is `(tool, why)`; the reason states whether the tool is pinned
434/// OFF in every gate that names it (a hard hole -- no stream can carry it) or
435/// merely defaulted (unknown, and unknown is not coverage).
436#[cfg(test)]
437const NEVER_ON_8BIT: &[(&str, &str)] = &[];
438
439/// [`DEFAULT_ON_TOOLS`] entries no 10-bit gate spells on, with the reason.
440#[cfg(test)]
441const NEVER_ON_10BIT: &[(&str, &str)] = &[];
442
443#[cfg(test)]
444mod tests {
445 use super::{
446 ALIASES, DEFAULT_ON_TOOLS, NEVER_EXERCISED, NEVER_EXERCISED_8BIT, NEVER_EXERCISED_10BIT,
447 NEVER_ON_8BIT, NEVER_ON_10BIT, On, TOOL_UNIVERSE,
448 };
449 use std::collections::{BTreeMap, BTreeSet};
450
451 /// Whether `body` contains a call to the `fn` named `name`.
452 ///
453 /// The name must not be the tail of a longer identifier, or
454 /// `inter_sb_none_gate` would "call" `sb_none_gate`.
455 fn calls_fn(body: &str, name: &str) -> bool {
456 let ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
457 let mut at = 0usize;
458 while let Some(rel) = body[at..].find(name) {
459 let start = at + rel;
460 let end = start + name.len();
461 let starts_clean = start == 0 || !ident(body.as_bytes()[start - 1]);
462 if starts_clean && body[end..].starts_with('(') {
463 return true;
464 }
465 at = end;
466 }
467 false
468 }
469
470 /// Every `fn` defined in `stream.rs`'s test module, as `(name, body)`.
471 ///
472 /// The census reasons about whole `#[`-segments (see [`gate_bodies`]) but
473 /// has to know which segment DEFINES or CALLS an encoder-driving `fn`, and
474 /// the only way to answer that is to name the units.
475 fn fn_units(src: &'static str) -> Vec<(&'static str, &'static str)> {
476 const OPEN: &str = "\n fn ";
477 let mut units = Vec::new();
478 let mut at = 0usize;
479 while let Some(rel) = src[at..].find(OPEN) {
480 let head = at + rel + OPEN.len();
481 let Some(paren) = src[head..].find('(') else {
482 break;
483 };
484 let close = src[head..]
485 .find("\n }\n")
486 .map_or(src.len(), |e| head + e);
487 units.push((&src[head..head + paren], &src[head..close]));
488 at = close.max(head + paren + 1);
489 }
490 units
491 }
492
493 /// Names of every `fn` in `stream.rs` that drives the real `aomenc`,
494 /// DIRECTLY (it mentions `aomenc_path()`) or by DELEGATING to one.
495 ///
496 /// lane-av1distwtd r3: the transitive closure is the whole point. A gate
497 /// that hands its recipe to a shared helper (`inter_sb_none_gate` and
498 /// friends) never spells `--passes=1` itself, so the old token filter
499 /// dropped it -- 165 of 311 segments, 6 of which spell `--enable-X=1`.
500 /// That is not a coverage fact, it is a segmentation fact, and it is what
501 /// kept `enable-dual-filter` on the never-exercised lists while a named
502 /// gate exercised the tool and hard-asserted the arrival.
503 fn encoder_fns(src: &'static str) -> BTreeSet<&'static str> {
504 let units = fn_units(src);
505 let mut enc: BTreeSet<&'static str> = units
506 .iter()
507 .filter(|(_, body)| body.contains("aomenc_path()"))
508 .map(|(name, _)| *name)
509 .collect();
510 // Fixpoint: `inter_sb_none_gate` is an encoder fn because it names
511 // `aomenc_path()`; the `#[test]` that only CALLS it is a gate too.
512 loop {
513 let mut grew = false;
514 for (name, body) in &units {
515 if enc.contains(name) {
516 continue;
517 }
518 if enc.iter().any(|e| calls_fn(body, e)) {
519 enc.insert(name);
520 grew = true;
521 }
522 }
523 if !grew {
524 return enc;
525 }
526 }
527 }
528
529 /// The token spellings the filter used before it resolved calls. Kept as a
530 /// floor: a gate is still recognised by these even if the call graph
531 /// misses it, so the fix can only ever ADD gates, never lose one.
532 fn legacy_gate_tokens(body: &str) -> bool {
533 body.contains("\"--passes=1\"")
534 || body.contains("ten_bit_tool_gate(")
535 || body.contains("encode_10bit_gradients")
536 }
537
538 /// Bodies of the real-aomenc gates: a `fn` body that drives the real
539 /// `aomenc`, however it gets there. Split on the attribute that opens a
540 /// test.
541 ///
542 /// lane-av1distwtd r3: a segment qualifies if it spells one of the
543 /// [`legacy_gate_tokens`] OR names an encoder `fn` -- either by defining
544 /// one (it mentions `aomenc_path()`) or by calling one. Recognition by
545 /// CALL is what a helper-delegating gate needs: its flags live in the
546 /// helper it calls, and it is invisible to a spelling-only filter.
547 fn gate_bodies() -> Vec<&'static str> {
548 let src = include_str!("stream.rs");
549 let enc = encoder_fns(src);
550 let gates: Vec<&str> = src
551 .split("\n #[")
552 // lane-hbdgates r1: an `#[ignore]`d gate exercises nothing, so it
553 // must not close a hole. Its body is the segment that opens with
554 // the ignore attribute.
555 .filter(|body| !body.starts_with("ignore"))
556 // lane-av1distwtd r3: a segment qualifies by what it SPELLS
557 // (`legacy_gate_tokens`) or by what it CALLS. `calls_fn` is
558 // deliberately the weak half of an OR, so the fix can only add
559 // gates -- it can never stop recognising one the old filter did.
560 .filter(|body| {
561 legacy_gate_tokens(body)
562 || body.contains("aomenc_path()")
563 || enc.iter().any(|e| calls_fn(body, e))
564 })
565 .collect();
566 assert!(
567 gates.len() >= 20,
568 "expected the real-aomenc gates, found {}",
569 gates.len()
570 );
571 gates
572 }
573
574 /// `--enable-<flag>=<value>` settings spelled inside one gate body.
575 fn flags_in(gate: &str) -> BTreeMap<String, char> {
576 let mut here = BTreeMap::new();
577 for (i, _) in gate.match_indices("\"--enable-") {
578 let rest = &gate[i + 3..];
579 let Some(end) = rest.find('"') else { continue };
580 let Some((flag, value)) = rest[..end].split_once('=') else {
581 continue;
582 };
583 let Some(value) = value.chars().next() else {
584 continue;
585 };
586 here.insert(flag.to_owned(), value);
587 }
588 here
589 }
590
591 /// Every `--flag=value` spelled inside one gate body, values kept whole
592 /// (`--cpu-used=4`, `--tile-columns=2`), not just their first character.
593 fn settings_in(gate: &str) -> BTreeMap<String, String> {
594 let mut here = BTreeMap::new();
595 for (i, _) in gate.match_indices("\"--") {
596 let rest = &gate[i + 3..];
597 let Some(end) = rest.find('"') else { continue };
598 let Some((flag, value)) = rest[..end].split_once('=') else {
599 continue;
600 };
601 here.insert(flag.to_owned(), value.to_owned());
602 }
603 here
604 }
605
606 /// The values a `--<flag>={var}` TEMPLATE can take in one gate body, from
607 /// the local binding of `var`.
608 ///
609 /// lane-av1txsearch: `settings_in` reads a `--flag=value` string LITERAL,
610 /// so a flag a gate builds with `format!` was invisible to it -- 10 gate
611 /// bodies spell `--enable-tx-size-search` only this way, and the census
612 /// filed them as "defaulted", i.e. unknown in BOTH directions. The
613 /// bindings that actually exist in `stream.rs` are four shapes, and each
614 /// is resolved from the gate's own text rather than from the variable's
615 /// name:
616 ///
617 /// 1. `let <var> = if <attempt> == 0 { "0" } else { "1" };` -- an
618 /// attempt-indexed arm; the QUOTED values in the initializer are
619 /// collected. Bare integers in the initializer (`attempt % 2`) are
620 /// deliberately NOT read as flag values.
621 /// 2. `for <var> in [0usize, 1]` / `["0", "1"]` -- a loop over both
622 /// values; every element of the array is collected.
623 /// 3. `for (<var>, <other>) in [("1", 8u8), ("0", 8u8), ...]` -- a
624 /// tuple-destructured loop; only the element at `<var>`'s POSITION is
625 /// collected from each tuple, so the arm table's bit-depth column is
626 /// not read as a flag value.
627 /// 4. `u8::from(<a>.<field>)` over a struct-literal arm table whose
628 /// `field: true` / `field: false` rows are the flag values.
629 ///
630 /// `None` means the binding is NOT in this body -- the variable is a
631 /// parameter of a shared helper and its value is bound at the CALL SITE,
632 /// which lives in a different `#[`-segment. That is a real limit of a
633 /// per-segment census and is reported as unknown rather than guessed:
634 /// inferring the value from the variable's name is the exact failure this
635 /// function exists to remove.
636 fn bound_values(body: &str, var: &str) -> Option<BTreeSet<char>> {
637 // Quoted single digits: `"0"`, `"1"`.
638 let quoted_digits = |t: &str| -> BTreeSet<char> {
639 let mut out = BTreeSet::new();
640 let mut at = 0usize;
641 while let Some(rel) = t[at..].find('"') {
642 let start = at + rel + 1;
643 let Some(end) = t[start..].find('"') else {
644 break;
645 };
646 let literal = &t[start..start + end];
647 if literal.len() == 1 {
648 if let Some(c) = literal.chars().next() {
649 if c.is_ascii_digit() {
650 out.insert(c);
651 }
652 }
653 }
654 at = start + end + 1;
655 }
656 out
657 };
658 // Bare integer literals: `0usize`, `1`, `8u8`. Whole tokens only, so
659 // `10u8` contributes nothing rather than a bogus `1`.
660 let bare_digits = |t: &str| -> BTreeSet<char> {
661 let mut out = BTreeSet::new();
662 let bytes = t.as_bytes();
663 let mut i = 0usize;
664 while i < bytes.len() {
665 if !bytes[i].is_ascii_digit() {
666 i += 1;
667 continue;
668 }
669 let start = i;
670 while i < bytes.len() && bytes[i].is_ascii_digit() {
671 i += 1;
672 }
673 let clean_before = start == 0 || !is_ident_byte(bytes[start - 1]);
674 // A typed literal's suffix (`0usize`, `8u8`, `1u32`) belongs to
675 // the same token, so a run of LOWERCASE letters right after
676 // the digit is a type, not a different identifier. Anything
677 // else -- a multi-digit `10u8`, a camelCase `1x` -- is not a
678 // flag value and is rejected.
679 let rest = &t[i..];
680 let suffix = rest
681 .bytes()
682 .take_while(|b| b.is_ascii_lowercase() || *b == b'_')
683 .count();
684 let clean_after = i >= bytes.len()
685 || !is_ident_byte(bytes[i])
686 || (suffix > 0
687 && i + suffix < bytes.len()
688 && !is_ident_byte(bytes[i + suffix]));
689 if clean_before && clean_after && i - start == 1 {
690 out.insert(bytes[start] as char);
691 }
692 }
693 out
694 };
695 // Split a comma-separated list at TOP level only, so `("1", 8u8)`
696 // stays one element.
697 fn split_top<'a>(t: &'a str) -> Vec<&'a str> {
698 let mut out = Vec::new();
699 let (mut depth, mut start) = (0i32, 0usize);
700 for (i, c) in t.char_indices() {
701 match c {
702 '(' | '[' | '{' => depth += 1,
703 ')' | ']' | '}' => depth -= 1,
704 ',' if depth == 0 => {
705 out.push(t[start..i].trim());
706 start = i + 1;
707 }
708 _ => {}
709 }
710 }
711 if start < t.len() {
712 out.push(t[start..].trim());
713 }
714 out
715 }
716 // The body of the `[...]` that FOLLOWS `head` in `text`. Scoped to
717 // the header rather than searching from the start of the body: a
718 // gate's first `[` may be an unrelated array, and brackets that do
719 // not balance across a whole gate body would leave the depth count
720 // never returning to zero.
721 fn loop_array_after<'a>(text: &'a str, head: &str) -> Option<&'a str> {
722 let at = text.find(head)? + head.len();
723 let open = at + text[at..].find('[')?;
724 let mut depth = 0i32;
725 for (i, c) in text[open..].char_indices() {
726 match c {
727 '[' => depth += 1,
728 ']' => {
729 depth -= 1;
730 if depth == 0 {
731 return Some(&text[open + 1..open + i]);
732 }
733 }
734 _ => {}
735 }
736 }
737 None
738 }
739 let mut found: Option<BTreeSet<char>> = None;
740 let mut merge = |set: BTreeSet<char>| match &mut found {
741 Some(all) => all.extend(set),
742 None => found = Some(set),
743 };
744 // (1) `let <var> = if ... { "0" } else { "1" };` -- quoted values only.
745 if let Some(at) = body.find(&format!("let {var} =")) {
746 let init = &body[at..];
747 let end = init.find(';').unwrap_or(init.len());
748 merge(quoted_digits(&init[..end]));
749 }
750 // (2) `for <var> in [...]` -- every element of the array.
751 if let Some(array) = loop_array_after(body, &format!("for {var} in ")) {
752 merge(bare_digits(array));
753 merge(quoted_digits(array));
754 }
755 // (3) `for (<var>, ...) in [(...), ...]` -- only `<var>`'s column.
756 if let Some(at) = body.find("for (") {
757 let head = &body[at..];
758 if let Some(close) = head.find(')') {
759 let pattern = &head["for (".len()..close];
760 if let Some(pos) = pattern.split(',').position(|p| p.trim() == var) {
761 let header = format!("for ({pattern}) in ");
762 if let Some(array) = loop_array_after(body, &header) {
763 let mut set: BTreeSet<char> = BTreeSet::new();
764 for tuple in split_top(array) {
765 let Some(inner) =
766 tuple.strip_prefix('(').and_then(|t| t.strip_suffix(')'))
767 else {
768 continue;
769 };
770 let fields = split_top(inner);
771 let Some(field) = fields.get(pos) else {
772 continue;
773 };
774 set.extend(bare_digits(field));
775 set.extend(quoted_digits(field));
776 }
777 merge(set);
778 }
779 }
780 }
781 }
782 // (3b) `for (<var>, ...) in <ident>` where `<ident>` is a `let`
783 // binding in this same body -- the arm table hoisted OUT of the
784 // loop header, so the `for` line NAMES the array instead of
785 // spelling it. Strategy (3) alone silently reads past the `for`
786 // line to the next `[` in the body (an unrelated `&[..]` flag
787 // list), finds no digits, and returns an empty set: the gate is
788 // then filed as UNRESOLVED even though both of its arms sit
789 // verbatim in the source. Measured: the 128x96 4:4:4 lossy
790 // tx-size-search gate, whose `for (label, search, ...) in arms`
791 // drove `print_tx_size_search_census`'s `unresolvable == 0`
792 // assertion red on merge. The `=` hop matters: the binding's
793 // TYPE annotation is itself bracketed
794 // (`[(&str, &str, TxMode, usize, u64); 2]`), so scanning for the
795 // first `[` after the name would return the type.
796 // `<var>`'s column, read off the arm table a hoisted `for` line
797 // NAMES rather than spells. Returns `None` unless the body really
798 // has that shape, so an unrecognised loop is left to the other
799 // strategies instead of being read as "no values".
800 let named_column = |pos: usize| -> Option<BTreeSet<char>> {
801 let at = body.find("for (")?;
802 let head = &body[at..];
803 let close = head.find(')')?;
804 let after = head[close + 1..].trim_start().strip_prefix("in ")?;
805 let name: &str = after
806 .split(|c: char| !is_ident_byte(c as u8))
807 .next()
808 .filter(|n| !n.is_empty() && !n.starts_with(|c: char| c.is_ascii_digit()))?;
809 let decl = body.find(&format!("let {name}"))?;
810 let after_name = decl + "let ".len() + name.len();
811 // `let arms_foo` must not answer for `let arms`.
812 if body[after_name..]
813 .chars()
814 .next()
815 .is_some_and(|c| is_ident_byte(c as u8))
816 {
817 return None;
818 }
819 // Hop the `=`: the binding's TYPE annotation is itself
820 // bracketed, so the first `[` after the name is the type.
821 let eq = after_name + body[after_name..].find('=')?;
822 let open = eq + 1 + body[eq + 1..].find('[')?;
823 let mut depth = 0i32;
824 for (i, c) in body[open..].char_indices() {
825 match c {
826 '[' => depth += 1,
827 ']' => {
828 depth -= 1;
829 if depth == 0 {
830 let mut set: BTreeSet<char> = Default::default();
831 for tuple in split_top(&body[open + 1..open + i]) {
832 let Some(inner) =
833 tuple.strip_prefix('(').and_then(|t| t.strip_suffix(')'))
834 else {
835 continue;
836 };
837 let fields = split_top(inner);
838 let Some(field) = fields.get(pos) else {
839 continue;
840 };
841 set.extend(bare_digits(field));
842 set.extend(quoted_digits(field));
843 }
844 return Some(set);
845 }
846 }
847 _ => {}
848 }
849 }
850 None
851 };
852 if let Some(at) = body.find("for (") {
853 let head = &body[at..];
854 if let Some(close) = head.find(')') {
855 let pattern = &head["for (".len()..close];
856 if let Some(pos) = pattern.split(',').position(|p| p.trim() == var) {
857 if let Some(set) = named_column(pos) {
858 merge(set);
859 }
860 }
861 }
862 }
863 // (4) `u8::from(<a>.<field>)` over a struct-literal arm table.
864 for (i, _) in body.match_indices("u8::from(") {
865 let arg = &body[i + "u8::from(".len()..];
866 let Some(close) = arg.find(')') else { continue };
867 let field = arg[..close].rsplit('.').next().unwrap_or_default().trim();
868 if field.is_empty() || !field.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
869 continue;
870 }
871 let mut set = BTreeSet::new();
872 for (row, value) in [("true", '1'), ("false", '0')] {
873 if body.contains(&format!("{field}: {row}")) {
874 set.insert(value);
875 }
876 }
877 merge(set);
878 }
879 found
880 }
881
882 fn is_ident_byte(b: u8) -> bool {
883 b.is_ascii_alphanumeric() || b == b'_'
884 }
885
886 /// Values of one [`DEFAULT_ON_TOOLS`] spelling in one gate body: the
887 /// literal `--<spelling>=<digit>` spellings plus every value a `format!`
888 /// template built from a local binding resolves to.
889 ///
890 /// A gate that reaches BOTH values counts ON, not off: it builds a `=1`
891 /// stream on some attempt, which is what the census asks for. This is the
892 /// file's standing "any spelling that says on wins" rule
893 /// (`--tile-columns=0 --tile-rows=1` is a multi-tile stream), now applied
894 /// across a loop's arms as well as across spellings.
895 fn spelling_values(gate: &str, spelling: &str) -> BTreeSet<char> {
896 let mut out = BTreeSet::new();
897 // A literal `"--<spelling>=<digit>"`: the needle ends at the `=`, so
898 // the value starts AT the needle's length, not three characters in.
899 let literal = format!("\"--{spelling}=");
900 for (i, _) in gate.match_indices(&literal) {
901 let rest = &gate[i + literal.len()..];
902 let Some(end) = rest.find('"') else { continue };
903 if let Some(c) = rest[..end].chars().next() {
904 if c.is_ascii_digit() {
905 out.insert(c);
906 }
907 }
908 }
909 // A template `format!("--<spelling>={<var>}")`: the placeholder name
910 // is the part between the braces, and its VALUE is whatever the
911 // binding of `<var>` in this same body reaches.
912 let template = format!("format!(\"--{spelling}=");
913 for (i, _) in gate.match_indices(&template) {
914 let rest = &gate[i + template.len()..];
915 let Some(end) = rest.find('"') else { continue };
916 let Some(var) = rest[..end]
917 .strip_prefix('{')
918 .and_then(|v| v.strip_suffix('}'))
919 else {
920 continue;
921 };
922 if var.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
923 out.extend(bound_values(gate, var).unwrap_or_default());
924 }
925 }
926 out
927 }
928
929 /// Whether a gate body spells one [`DEFAULT_ON_TOOLS`] entry on / off,
930 /// over [`spelling_values`] -- so a `format!`-built flag is classified
931 /// instead of being filed as "defaulted".
932 fn resolved_on_state(gate: &str, spellings: &[&str], on: On) -> Option<bool> {
933 let mut state = None;
934 for spelling in spellings {
935 for c in spelling_values(gate, spelling) {
936 let value = c.to_digit(10).unwrap_or(0);
937 let is_on = match on {
938 On::NonZero => value != 0,
939 On::AtMost(limit) => value <= limit,
940 };
941 state = Some(state.unwrap_or(false) || is_on);
942 }
943 }
944 state
945 }
946
947 /// `--enable-*` settings per real-aomenc gate, derived from the gate
948 /// source: `flag -> (turned off in N gates, turned on in N, defaulted in N)`.
949 fn tool_settings() -> (usize, BTreeMap<String, (usize, usize, usize)>) {
950 let gates = gate_bodies();
951
952 let mut per_tool: BTreeMap<String, (usize, usize, usize)> = BTreeMap::new();
953 let mut names: BTreeSet<String> = BTreeSet::new();
954 let mut seen: Vec<BTreeMap<String, char>> = Vec::new();
955 for gate in &gates {
956 let here = flags_in(gate);
957 names.extend(here.keys().cloned());
958 seen.push(here);
959 }
960 for name in names {
961 let off = seen.iter().filter(|g| g.get(&name) == Some(&'0')).count();
962 let on = seen.iter().filter(|g| g.get(&name) == Some(&'1')).count();
963 per_tool.insert(name, (off, on, gates.len() - off - on));
964 }
965 (gates.len(), per_tool)
966 }
967
968 #[test]
969 fn every_gate_disabling_a_tool_is_a_listed_coverage_hole() {
970 let (gate_count, per_tool) = tool_settings();
971 // A hole OPENS when every gate names the flag and every one of them
972 // says 0 -- then no real stream can exercise the tool.
973 let derived: BTreeSet<&str> = per_tool
974 .iter()
975 .filter(|&(_, &(off, on, defaulted))| off == gate_count && on == 0 && defaulted == 0)
976 .map(|(name, _)| name.as_str())
977 .collect();
978 // A hole CLOSES only on positive evidence: some gate passes `=1`.
979 // A gate that merely leaves the flag off its command line proves
980 // nothing -- aomenc's default for palette and intrabc is content-
981 // dependent -- so "defaulted" must not retire an entry, or a listing
982 // would disappear the moment an unrelated gate is added.
983 let exercised: BTreeSet<&str> = per_tool
984 .iter()
985 .filter(|&(_, &(_, on, _))| on > 0)
986 .map(|(name, _)| name.as_str())
987 .collect();
988 let listed: BTreeSet<&str> = NEVER_EXERCISED.iter().map(|&(flag, _)| flag).collect();
989
990 let unlisted: Vec<&&str> = derived.difference(&listed).collect();
991 assert!(
992 unlisted.is_empty(),
993 "these aomenc tools are switched off in all {gate_count} real-aomenc gates and on in \
994 none, so no real stream exercises them, and they are not listed in NEVER_EXERCISED: \
995 {unlisted:?} -- either enable the tool with `=1` in its own gate or add it to the \
996 list with a reason"
997 );
998 let stale: Vec<&&str> = listed.intersection(&exercised).collect();
999 assert!(
1000 stale.is_empty(),
1001 "NEVER_EXERCISED lists {stale:?}, but a gate now passes `=1` for them -- delete \
1002 those entries, the coverage hole is closed"
1003 );
1004 }
1005
1006 /// The derivation is only meaningful if a flag left off a gate's command
1007 /// line really does mean "aomenc's default", i.e. the parser above is
1008 /// reading whole flags and not fragments.
1009 #[test]
1010 fn tool_settings_reads_whole_flags() {
1011 let (gate_count, per_tool) = tool_settings();
1012 assert!(
1013 per_tool.contains_key("enable-cdef"),
1014 "expected --enable-cdef among the gate flags"
1015 );
1016 for (name, &(off, on, defaulted)) in &per_tool {
1017 assert!(
1018 !name.is_empty() && !name.contains(['"', '=']),
1019 "malformed flag {name:?}"
1020 );
1021 assert_eq!(
1022 off + on + defaulted,
1023 gate_count,
1024 "{name} counts do not cover every gate"
1025 );
1026 }
1027 }
1028
1029 /// A gate encodes at 10 bits when its recipe says so: the shared 10-bit
1030 /// helper, an explicit `--bit-depth=10`/`--input-bit-depth=10`, or a
1031 /// `yuv420p10le` fixture handed to aomenc. Everything else is aomenc's
1032 /// 8-bit default.
1033 /// lane-defon r1: a gate helper parameterised on `bit_depth` builds BOTH
1034 /// an 8-bit and a 10-bit stream from one recipe, so its flags cover both
1035 /// depths -- classifying it by the 10-bit strings inside its conditional
1036 /// alone hid `--enable-tx-size-search=1` from the 8-bit list.
1037 /// lane-reelckf r1: the same blind spot with the other spelling -- a gate
1038 /// that loops `for depth in [8usize, 10]` builds BOTH streams from one
1039 /// recipe, but its `yuv420p10le` arm made `is_ten_bit` classify it as
1040 /// 10-bit only, hiding `--enable-cfl-intra=1` from the 8-bit list.
1041 /// lane-av1-intrabc r1: the shared recipe helper
1042 /// `screen_intrabc_stream_at_depth` is parameterised on `depth` and sits in
1043 /// the segment that opens at the PRECEDING gate's `#[test]`, so without
1044 /// this marker that gate's own 8-bit-only flags read as 10-bit-only -- the
1045 /// lane-defon/reelckf blind spot with `depth` spelled instead of
1046 /// `bit_depth`. Three gates share the helper, at both depths.
1047 /// lane-av1distwtd r3: the THIRD spelling of the same blind spot, still
1048 /// live after lane-defon and lane-reelckf. A recipe parameterised on
1049 /// `ten_bit` names BOTH fixture formats in one body -- `let pix_fmt = if
1050 /// ten_bit { "yuv420p10le" } else { "yuv420p" };` -- so `is_ten_bit` saw
1051 /// the 10-bit arm and filed the whole body 10-bit-ONLY, hiding its 8-bit
1052 /// arm from the 8-bit bucket. The marker is the PAIR OF FORMATS, not the
1053 /// parameter name: a body spelling both pixel formats builds streams at
1054 /// both depths, whatever it calls the flag. The quotes matter -- a bare
1055 /// `yuv420p` substring test also matches `yuv420p10le` and would fire on
1056 /// every 10-bit gate, retiring entries on no evidence.
1057 ///
1058 /// This is what mis-filed `a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact`
1059 /// and kept `enable-flip-idtx` on the 8-bit list while that gate ran 6
1060 /// pixel-exact 8-bit decodes through it.
1061 fn covers_both_depths(body: &str) -> bool {
1062 body.contains("if bit_depth == 10")
1063 || body.contains("if depth == 10")
1064 || body.contains("for depth in [8usize, 10]")
1065 || (body.contains("\"yuv420p\"") && body.contains("\"yuv420p10le\""))
1066 }
1067
1068 /// lane-av1distwtd r3: the detector fix, pinned. A detector change with
1069 /// no test can only be shown to find MORE, never to stop missing, so this
1070 /// asserts the three gates the two blind spots actually hid are now seen
1071 /// -- the two `enable-dual-filter` witnesses and the `enable-flip-idtx`
1072 /// both-depths gate -- and that the fix is strictly ADDITIVE against the
1073 /// old spelling-only filter.
1074 #[test]
1075 fn the_detector_sees_the_gates_the_spelling_filter_missed() {
1076 let src = include_str!("stream.rs");
1077 let gates = gate_bodies();
1078 // The helper-delegation half: each of these builds its stream through
1079 // `inter_sb_none_gate` and spells none of `legacy_gate_tokens`, so the
1080 // old filter dropped both while each hard-asserts its tool arrived.
1081 for name in [
1082 "a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact",
1083 "a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour",
1084 ] {
1085 let body = gates
1086 .iter()
1087 .find(|b| b.contains(name))
1088 .unwrap_or_else(|| panic!("{name}: not seen by gate_bodies()"));
1089 assert_eq!(
1090 flags_in(body).get("enable-dual-filter"),
1091 Some(&'1'),
1092 "{name}: seen, but its --enable-dual-filter=1 spelling is not visible to \
1093 flags_in, so recognising the gate would not retire the entry"
1094 );
1095 }
1096 // The both-depths half: this gate's recipe is parameterised on `ten_bit`
1097 // and names both fixture formats, so `covers_both_depths` must credit
1098 // it to the 8-bit bucket, not just the 10-bit one.
1099 let flip = gates
1100 .iter()
1101 .find(|b| b.contains("a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform"))
1102 .expect("the flip-idtx gate must be seen");
1103 assert!(
1104 covers_both_depths(flip),
1105 "the flip-idtx gate spells both fixture formats, so covers_both_depths must \
1106 credit it to the 8-bit bucket as well"
1107 );
1108 assert!(
1109 covers_depth(flip, false) && covers_depth(flip, true),
1110 "the flip-idtx gate must cover BOTH depths"
1111 );
1112 // Strictly additive: every segment the old spelling-only filter kept
1113 // is still kept, so the fix cannot have cost the census a gate.
1114 let legacy_only: Vec<&str> = src
1115 .split("\n #[")
1116 .filter(|b| !b.starts_with("ignore") && legacy_gate_tokens(b))
1117 .collect();
1118 assert!(
1119 legacy_only.len() < gates.len(),
1120 "the call-resolving filter found {} gates, the old spelling-only filter found \
1121 {} -- the fix is expected to ADD gates, never to drop one",
1122 gates.len(),
1123 legacy_only.len()
1124 );
1125 for body in &legacy_only {
1126 assert!(
1127 gates.contains(body),
1128 "a gate the spelling-only filter recognised is no longer recognised: \
1129 {:?}",
1130 &body[..body.len().min(60)]
1131 );
1132 }
1133 }
1134
1135 /// Whether a gate body drives a stream at this depth.
1136 fn covers_depth(body: &str, ten_bit: bool) -> bool {
1137 covers_both_depths(body) || is_ten_bit(body) == ten_bit
1138 }
1139
1140 fn is_ten_bit(body: &str) -> bool {
1141 // The lists pin two buckets, 8-bit and high-bit-depth; 12-bit gates
1142 // count in the high-depth bucket (lane-av1gwarp12's ROTZOOM gate was
1143 // the first 12-bit gate to positively enable a listed tool, and the
1144 // 10-bit-only spellings mis-filed it as 8-bit).
1145 body.contains("encode_10bit_gradients")
1146 || body.contains("ten_bit_tool_gate(")
1147 || body.contains("--bit-depth=10")
1148 || body.contains("--input-bit-depth=10")
1149 || body.contains("yuv420p10le")
1150 || body.contains("encode_12bit(")
1151 || body.contains("--bit-depth=12")
1152 || body.contains("--input-bit-depth=12")
1153 || body.contains("yuv420p12le")
1154 }
1155
1156 /// Flags a gate positively enables (`=1`), at gates of the given depth.
1157 fn enabled_at(ten_bit: bool) -> BTreeSet<String> {
1158 let mut on = BTreeSet::new();
1159 for gate in gate_bodies() {
1160 if !covers_depth(gate, ten_bit) {
1161 continue;
1162 }
1163 for (flag, value) in flags_in(gate) {
1164 if value == '1' {
1165 on.insert(flag);
1166 }
1167 }
1168 // A tool driven by its own spelling counts as exercised.
1169 let here = settings_in(gate);
1170 for (alias, tool) in ALIASES {
1171 if here.get(*alias).is_some_and(|v| v != "0") {
1172 on.insert((*tool).to_owned());
1173 }
1174 }
1175 }
1176 on
1177 }
1178
1179 /// The tools of [`TOOL_UNIVERSE`] that no gate of this depth enables.
1180 fn never_exercised_at(ten_bit: bool) -> BTreeSet<&'static str> {
1181 let on = enabled_at(ten_bit);
1182 TOOL_UNIVERSE
1183 .iter()
1184 .copied()
1185 .filter(|t| !on.contains(*t))
1186 .collect()
1187 }
1188
1189 fn check_depth(ten_bit: bool, listed: &[(&str, &str)]) {
1190 let derived = never_exercised_at(ten_bit);
1191 let listed: BTreeSet<&str> = listed.iter().map(|&(flag, _)| flag).collect();
1192 let depth = if ten_bit { "10-bit" } else { "8-bit" };
1193 let unlisted: Vec<&&str> = derived.difference(&listed).collect();
1194 assert!(
1195 unlisted.is_empty(),
1196 "no {depth} gate passes `=1` for {unlisted:?}, so no real {depth} stream exercises \
1197 them -- enable the tool in a {depth} gate that asserts it fired, or list it"
1198 );
1199 let stale: Vec<&&str> = listed.difference(&derived).collect();
1200 assert!(
1201 stale.is_empty(),
1202 "the {depth} list still names {stale:?}, but a {depth} gate now passes `=1` for them \
1203 -- delete those entries, the coverage hole is closed"
1204 );
1205 }
1206
1207 #[test]
1208 fn never_exercised_8bit_matches_the_gate_recipes() {
1209 check_depth(false, NEVER_EXERCISED_8BIT);
1210 }
1211
1212 #[test]
1213 fn never_exercised_10bit_matches_the_gate_recipes() {
1214 check_depth(true, NEVER_EXERCISED_10BIT);
1215 }
1216
1217 /// `cargo test -p ec-av1 --lib gate_coverage -- --nocapture` prints both
1218 /// lists, so the per-depth holes can be read without opening this file.
1219 #[test]
1220 fn print_never_exercised_per_bit_depth() {
1221 let ten: Vec<&str> = gate_bodies()
1222 .into_iter()
1223 .filter(|b| is_ten_bit(b))
1224 .collect();
1225 let total = gate_bodies().len();
1226 println!(
1227 "gate_coverage: {} real-aomenc gates, {} of them 10-bit",
1228 total,
1229 ten.len()
1230 );
1231 for (label, ten_bit) in [("8BIT", false), ("10BIT", true)] {
1232 let holes = never_exercised_at(ten_bit);
1233 println!(
1234 "NEVER_EXERCISED_{label} ({} of {}):",
1235 holes.len(),
1236 TOOL_UNIVERSE.len()
1237 );
1238 for flag in &holes {
1239 println!(" --{flag}");
1240 }
1241 }
1242 }
1243
1244 /// [`DEFAULT_ON_TOOLS`] per depth: `tool -> (off in N gates, on in N, defaulted in N)`.
1245 fn default_on_settings(
1246 ten_bit: bool,
1247 ) -> (usize, BTreeMap<&'static str, (usize, usize, usize)>) {
1248 let gates: Vec<&str> = gate_bodies()
1249 .into_iter()
1250 .filter(|b| covers_depth(b, ten_bit))
1251 .collect();
1252 let mut per_tool = BTreeMap::new();
1253 for &(tool, spellings, _, on) in DEFAULT_ON_TOOLS {
1254 // lane-av1txsearch: `resolved_on_state`, not `default_on_state` --
1255 // the literal-only reader filed every `format!`-built flag as
1256 // "defaulted", which is unknown rather than measured.
1257 let states: Vec<Option<bool>> = gates
1258 .iter()
1259 .map(|g| resolved_on_state(g, spellings, on))
1260 .collect();
1261 let turned_on = states.iter().filter(|s| **s == Some(true)).count();
1262 let turned_off = states.iter().filter(|s| **s == Some(false)).count();
1263 per_tool.insert(
1264 tool,
1265 (turned_off, turned_on, gates.len() - turned_off - turned_on),
1266 );
1267 }
1268 (gates.len(), per_tool)
1269 }
1270
1271 /// The [`DEFAULT_ON_TOOLS`] no gate of this depth positively enables.
1272 fn never_on_at(ten_bit: bool) -> BTreeSet<&'static str> {
1273 default_on_settings(ten_bit)
1274 .1
1275 .into_iter()
1276 .filter(|&(_, (_, on, _))| on == 0)
1277 .map(|(tool, _)| tool)
1278 .collect()
1279 }
1280
1281 fn check_default_on(ten_bit: bool, listed: &[(&str, &str)]) {
1282 let derived = never_on_at(ten_bit);
1283 let listed: BTreeSet<&str> = listed.iter().map(|&(tool, _)| tool).collect();
1284 let depth = if ten_bit { "10-bit" } else { "8-bit" };
1285 let unlisted: Vec<&&str> = derived.difference(&listed).collect();
1286 assert!(
1287 unlisted.is_empty(),
1288 "no {depth} gate spells an on-value for {unlisted:?}, so no real {depth} stream is \
1289 proven to carry them -- switch the tool on in a {depth} gate that asserts it fired, \
1290 or list it with a reason"
1291 );
1292 let stale: Vec<&&str> = listed.difference(&derived).collect();
1293 assert!(
1294 stale.is_empty(),
1295 "the {depth} default-on list still names {stale:?}, but a {depth} gate now switches \
1296 them on -- delete those entries, the coverage hole is closed"
1297 );
1298 }
1299
1300 #[test]
1301 fn never_on_8bit_matches_the_gate_recipes() {
1302 check_default_on(false, NEVER_ON_8BIT);
1303 }
1304
1305 #[test]
1306 fn never_on_10bit_matches_the_gate_recipes() {
1307 check_default_on(true, NEVER_ON_10BIT);
1308 }
1309
1310 /// A tool must not be pinned twice: [`TOOL_UNIVERSE`] already derives the
1311 /// `--enable-*` spellings under the `=1` rule.
1312 #[test]
1313 fn default_on_tools_do_not_duplicate_the_universe() {
1314 for &(tool, spellings, _, _) in DEFAULT_ON_TOOLS {
1315 assert!(
1316 !TOOL_UNIVERSE.contains(&tool),
1317 "{tool} is already covered by TOOL_UNIVERSE"
1318 );
1319 assert!(!spellings.is_empty(), "{tool} has no aomenc spelling");
1320 }
1321 for (alias, tool) in ALIASES {
1322 assert!(
1323 TOOL_UNIVERSE.contains(tool),
1324 "alias --{alias} names {tool}, which is not a TOOL_UNIVERSE tool"
1325 );
1326 }
1327 }
1328
1329 /// `cargo test -p ec-av1 --lib gate_coverage -- --nocapture` prints the
1330 /// default-on holes with their off/defaulted split.
1331 #[test]
1332 fn print_never_on_per_bit_depth() {
1333 for (label, ten_bit) in [("8BIT", false), ("10BIT", true)] {
1334 let (gate_count, per_tool) = default_on_settings(ten_bit);
1335 let holes = never_on_at(ten_bit);
1336 println!(
1337 "NEVER_ON_{label} ({} of {}, over {gate_count} {label} gates):",
1338 holes.len(),
1339 DEFAULT_ON_TOOLS.len()
1340 );
1341 for tool in &holes {
1342 let (off, _, defaulted) = per_tool[tool];
1343 let spellings = DEFAULT_ON_TOOLS
1344 .iter()
1345 .find(|e| e.0 == *tool)
1346 .map(|e| e.1.join(","))
1347 .unwrap_or_default();
1348 println!(
1349 " {tool} (--{spellings}): off in {off}, defaulted in {defaulted}, on in 0"
1350 );
1351 }
1352 }
1353 }
1354
1355 /// lane-av1txsearch: the `enable-tx-size-search` census, MEASURED rather
1356 /// than floored. Prints, per gate body, the values the resolver reads for
1357 /// the flag -- literal spellings and `format!` templates alike -- and the
1358 /// three-way split at the end. Re-run it after any gate recipe change:
1359 ///
1360 /// `cargo test -p ec-av1 --lib gate_coverage::tests::print_tx_size_search_census -- --nocapture`
1361 #[test]
1362 fn print_tx_size_search_census() {
1363 const TOOL: &str = "enable-tx-size-search";
1364 let (zero, one, both, unresolvable, unnamed) = {
1365 let (mut zero, mut one, mut both, mut unresolvable, mut unnamed) =
1366 (0usize, 0usize, 0usize, 0usize, 0usize);
1367 for gate in gate_bodies() {
1368 let values = spelling_values(gate, TOOL);
1369 let name = gate
1370 .split("fn ")
1371 .nth(1)
1372 .and_then(|s| s.split('(').next())
1373 .unwrap_or("<segment>")
1374 .to_owned();
1375 let state = match (values.contains(&'0'), values.contains(&'1')) {
1376 (false, false) => {
1377 unnamed += 1;
1378 "not named (defaulted)"
1379 }
1380 (true, false) => {
1381 zero += 1;
1382 "=0"
1383 }
1384 (false, true) => {
1385 one += 1;
1386 "=1"
1387 }
1388 (true, true) => {
1389 both += 1;
1390 "=0 and =1 (one arm each)"
1391 }
1392 };
1393 let via = if gate.contains(&format!("format!(\"--{TOOL}=")) {
1394 " [format! template resolved]"
1395 } else {
1396 ""
1397 };
1398 let helper = if gate.contains(&format!("format!(\"--{TOOL}=")) && values.is_empty()
1399 {
1400 " [UNRESOLVED: variable is a shared helper's parameter]"
1401 } else {
1402 ""
1403 };
1404 if !helper.is_empty() {
1405 unresolvable += 1;
1406 unnamed -= 1;
1407 }
1408 println!("{name}: {state}{via}{helper}");
1409 }
1410 (zero, one, both, unresolvable, unnamed)
1411 };
1412 let total = gate_bodies().len();
1413 println!(
1414 "enable-tx-size-search over {total} census-selected gate bodies: \
1415 =0 only {zero}, =1 only {one}, both {both}, unresolvable {unresolvable}, \
1416 not named {unnamed}"
1417 );
1418 assert_eq!(
1419 unresolvable, 0,
1420 "{unresolvable} gate bodies build --{TOOL} into a variable this census cannot bind -- \
1421 the count is a floor again, and an unknown direction is the failure mode this file \
1422 exists to prevent"
1423 );
1424 }
1425
1426 /// lane-av1txsearch: the RED-BEFORE proof for the template resolver, in
1427 /// both directions, on the gate bodies that actually exist.
1428 ///
1429 /// Direction 1 -- a `format!`-built value MOVES the classification. Each
1430 /// case below takes a real gate body, mutates only the bound value, and
1431 /// asserts the resolved state changed. A resolver that found nothing
1432 /// would read every one of these as "not named" and fail all four.
1433 ///
1434 /// Direction 2 -- a spelling the LITERAL reader already saw still
1435 /// classifies. Without this half, a resolver that overwrote the literal
1436 /// path would pass direction 1 while losing the 15 `=1` gates the census
1437 /// already counted.
1438 #[test]
1439 fn the_resolver_binds_a_format_built_flag_in_both_directions() {
1440 let gates = gate_bodies();
1441 let find = |needle: &str| -> &'static str {
1442 gates
1443 .iter()
1444 .copied()
1445 .find(|b| b.contains(needle))
1446 .unwrap_or_else(|| panic!("no gate body contains {needle:?}"))
1447 };
1448 // Direction 1, one per template shape.
1449 let cases = [
1450 (
1451 "format!(\"--enable-tx-size-search={txs}\")",
1452 "for txs in [0usize, 1]",
1453 "for txs in [0usize, 0]",
1454 "a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact",
1455 ),
1456 (
1457 "format!(\"--enable-tx-size-search={tx_search}\")",
1458 "if attempt % 2 == 0 { \"0\" } else { \"1\" }",
1459 "if attempt % 2 == 0 { \"0\" } else { \"0\" }",
1460 "a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact",
1461 ),
1462 (
1463 "format!(\"--enable-tx-size-search={tx_search}\")",
1464 "for (tx_search, bit_depth) in [(\"1\", 8u8), (\"0\", 8u8), (\"1\", 10u8)]",
1465 "for (tx_search, bit_depth) in [(\"0\", 8u8), (\"0\", 8u8), (\"0\", 10u8)]",
1466 "a_real_aomenc_stream_with_filter_intra_on_a_sub8_rect_leaf_decodes_pixel_exact",
1467 ),
1468 // The arm table hoisted OUT of the `for` line into a named
1469 // `let` -- the shape lane-av1lossy128x96 writes, and the one
1470 // that reads as UNRESOLVED unless the `for` line's collection
1471 // name is followed back to its binding. Without this case a
1472 // resolver that only understood inline arrays passes the
1473 // three above and still cannot bind this gate.
1474 (
1475 "format!(\"--enable-tx-size-search={search}\")",
1476 "\"tx size search on\",\n \"1\",",
1477 "\"tx size search on\",\n \"0\",",
1478 "a_real_aomenc_444_whole_64_root_tx_size_search_stream_decodes_pixel_exact_at_128x96",
1479 ),
1480 ];
1481 for (template, from, to, name) in cases {
1482 let body = find(name);
1483 assert!(
1484 body.contains(template),
1485 "{name} does not spell {template}, so this case proves nothing"
1486 );
1487 assert!(
1488 body.contains(from),
1489 "{name} does not contain the source binding {from:?}"
1490 );
1491 let before = spelling_values(body, "enable-tx-size-search");
1492 let mutated = body.replace(from, to);
1493 assert_ne!(
1494 mutated, body,
1495 "the mutation {from:?} -> {to:?} changed nothing"
1496 );
1497 let after = spelling_values(&mutated, "enable-tx-size-search");
1498 assert_eq!(
1499 before,
1500 BTreeSet::from(['0', '1']),
1501 "{name}: the unmutated body should resolve to both values, got {before:?}"
1502 );
1503 assert_eq!(
1504 after,
1505 BTreeSet::from(['0']),
1506 "{name}: mutating the bound value {from:?} -> {to:?} did not move the \
1507 classification (still {after:?}) -- the resolver is not reading the binding"
1508 );
1509 }
1510 // Direction 2: every gate the LITERAL reader already classified as
1511 // `=1` still is. Asserted as CONTAINMENT, not equality: a segment may
1512 // spell the flag twice (`=0` in the base recipe, `=1` as the per-arm
1513 // override), and the old reader took the last one while the resolver
1514 // takes the set. The claim being pinned is "still on", which is the
1515 // direction a regression would lose.
1516 let mut pinned = 0usize;
1517 for gate in &gates {
1518 if !gate.contains("\"--enable-tx-size-search=1\"") {
1519 continue;
1520 }
1521 pinned += 1;
1522 assert!(
1523 spelling_values(gate, "enable-tx-size-search").contains(&'1'),
1524 "a gate that literally spells --enable-tx-size-search=1 is no longer \
1525 classified on: {:?}",
1526 &gate[..gate.len().min(80)]
1527 );
1528 }
1529 assert!(
1530 pinned >= 10,
1531 "expected the literal `=1` gates to still be there, found {pinned}"
1532 );
1533 }
1534
1535 /// lane-av1oracleskip: the ORACLE-PRESENCE SCAN — the mechanical
1536 /// anti-regression for the skip class this lane closed.
1537 ///
1538 /// Why a scan and not a review rule: the r2 sweep found FIVE gates that
1539 /// had been added with the bare `if aomdec_path().is_file() { …compare… }`
1540 /// shape AFTER the first fix had already routed thirteen sites — every one
1541 /// of them compiled, passed review and reported green with the oracle
1542 /// compare silently skipped, under `EC_AV1_REQUIRE_AOMENC=1`. A guard
1543 /// written the old way re-opens the class the moment it merges, so the
1544 /// only thing that holds is a check that reads the source itself.
1545 ///
1546 /// The rule: a TOOL PRESENCE CHECK (`aomenc_path().is_file()`,
1547 /// `aomdec_path().is_file()`, `affine_aomenc_path().is_file()`, plain or
1548 /// `!…` inverted) may appear ONLY
1549 /// 1. inside the body of the probe that owns that path
1550 /// (`have_aomenc`, `aomdec_available`, `have_affine_aomenc`) — that
1551 /// is where the assert-last and the env escape live, and
1552 /// 2. inside an `assert!` (the deliberate hard-failure form), or
1553 /// 3. in a comment, which cannot execute.
1554 /// Anything else is a skip with no env escape, and the test fails naming
1555 /// the exact `file:line`.
1556 ///
1557 /// THE FLOOR. A source scan that matches nothing is the false-pass shape
1558 /// this crate has been bitten by twice (a `format!` brace escape, and
1559 /// `args.find(')')` stopping at the wrong paren), so the scan refuses to
1560 /// pass unless it actually inspected a plausible number of sites: the
1561 /// count is printed and asserted against `MIN_SITES`. A probe that moved
1562 /// out of the scan's reach, or a matcher broken by a rename, reds here
1563 /// instead of reporting a clean bill of health.
1564 #[test]
1565 fn no_tool_presence_check_outside_its_probe() {
1566 /// Below this, the scan is not looking at the tree it thinks it is.
1567 /// Five is the STRUCTURAL floor: three probes (whose existence the span
1568 /// assert below already pins) plus the two hard `assert!` sites. Doc
1569 /// comments mentioning the old shape come and go with the prose, so
1570 /// they are counted but never load-bearing here.
1571 const MIN_SITES: usize = 5;
1572 /// (file, the line that opens the probe owning that path)
1573 const PROBES: &[(&str, &str)] = &[
1574 ("stream.rs", "fn have_aomenc()"),
1575 ("stream.rs", "fn aomdec_available("),
1576 ("stream.rs", "fn have_affine_aomenc()"),
1577 ];
1578 const PATHS: &[&str] = &[
1579 "aomenc_path().is_file()",
1580 "aomdec_path().is_file()",
1581 "affine_aomenc_path().is_file()",
1582 ];
1583 let files: [(&str, &str); 3] = [
1584 ("stream.rs", include_str!("stream.rs")),
1585 ("decode.rs", include_str!("decode.rs")),
1586 ("encode.rs", include_str!("encode.rs")),
1587 ];
1588
1589 // The line range each probe body owns: from its opener to the first
1590 // following line that closes it at column 0.
1591 let mut probe_spans: Vec<(usize, usize)> = Vec::new();
1592 for (name, src) in files {
1593 let lines: Vec<&str> = src.lines().collect();
1594 for (probe_file, opener) in PROBES {
1595 if *probe_file != name {
1596 continue;
1597 }
1598 let Some(start) = lines.iter().position(|l| l.contains(opener)).map(|i| i + 1)
1599 else {
1600 continue;
1601 };
1602 let end = lines
1603 .iter()
1604 .skip(start)
1605 .position(|l| l.trim_end() == "}")
1606 .map(|off| start + off)
1607 .unwrap_or(lines.len());
1608 probe_spans.push((start, end));
1609 }
1610 }
1611 assert!(
1612 probe_spans.len() == PROBES.len(),
1613 "the oracle-presence scan recognised {} of the {} probe bodies it is meant to \
1614 exempt ({probe_spans:?}); a renamed or moved probe would silently exempt every \
1615 site in the crate, so it reds here",
1616 probe_spans.len(),
1617 PROBES.len()
1618 );
1619
1620 let mut sites = 0usize;
1621 let mut allowed = 0usize;
1622 let mut per_pattern: BTreeMap<&str, usize> = PATHS.iter().map(|p| (*p, 0)).collect();
1623 let mut offenders: Vec<String> = Vec::new();
1624 for (name, src) in files {
1625 for (i, line) in src.lines().enumerate() {
1626 // LONGEST match wins: `affine_aomenc_path().is_file()` CONTAINS
1627 // `aomenc_path().is_file()`, so a first-match scan credits the
1628 // affine probe's line to the aomenc pattern and the per-pattern
1629 // floor below reds on a pattern that is very much present. (It
1630 // did, on the first run of this test — which is the floor
1631 // earning its place.)
1632 let Some(path) = PATHS
1633 .iter()
1634 .filter(|p| line.contains(**p))
1635 .max_by_key(|p| p.len())
1636 else {
1637 continue;
1638 };
1639 sites += 1;
1640 *per_pattern.get_mut(path).expect("pattern came from PATHS") += 1;
1641 let lineno = i + 1;
1642 let trimmed = line.trim_start();
1643 let in_probe = probe_spans
1644 .iter()
1645 .any(|(start, end)| lineno >= *start && lineno <= *end);
1646 let in_assert = trimmed.starts_with("assert!")
1647 || trimmed.starts_with("aomdec_path().is_file(),")
1648 || trimmed.starts_with("aomenc_path().is_file(),")
1649 || trimmed.starts_with("affine_aomenc_path().is_file(),");
1650 let in_comment = trimmed.starts_with("//");
1651 if in_probe || in_assert || in_comment {
1652 allowed += 1;
1653 } else {
1654 offenders.push(format!(
1655 "{name}:{lineno}: {}\n a tool presence check outside its probe — \
1656 route it through the probe that owns this path (`have_aomenc`, \
1657 `aomdec_available`, `have_affine_aomenc`): a bare `{path}` skips the \
1658 gate with NO env escape, so under EC_AV1_REQUIRE_AOMENC=1 the gate still \
1659 reports green with the oracle compare never run.",
1660 line.trim()
1661 ));
1662 }
1663 }
1664 }
1665 println!(
1666 "oracle-presence scan: {sites} site(s) inspected, {allowed} in a probe / assert / \
1667 comment, {} offender(s); per pattern {per_pattern:?}",
1668 offenders.len()
1669 );
1670 // PER-PATTERN floor: a total count can hide one broken matcher (mutate
1671 // ONE pattern and the other two still add up), so each of the three
1672 // path patterns must be found at least once -- which the probe bodies
1673 // guarantee, since each probe contains its own path's presence check.
1674 let never_matched: Vec<&str> = per_pattern
1675 .iter()
1676 .filter(|(_, n)| **n == 0)
1677 .map(|(p, _)| *p)
1678 .collect();
1679 assert!(
1680 never_matched.is_empty(),
1681 "the oracle-presence scan matched NOTHING for {never_matched:?}: that pattern is \
1682 stale (renamed helper, `exists()` instead of `is_file()`, a `format!` escape) and \
1683 the gates it was meant to police would pass unreviewed. Matched per pattern: \
1684 {per_pattern:?}"
1685 );
1686 assert!(
1687 sites >= MIN_SITES,
1688 "the oracle-presence scan inspected only {sites} site(s), below its floor of \
1689 {MIN_SITES}: the matcher has stopped matching this tree (renamed path helper, a \
1690 `format!` escape, a moved probe), and with no floor this would pass while scanning \
1691 nothing — the false-pass shape this crate has been bitten by twice"
1692 );
1693 assert!(
1694 offenders.is_empty(),
1695 "{} bare tool presence check(s) outside a probe — each one is a gate that can report \
1696 green without running the oracle compare:\n {}",
1697 offenders.len(),
1698 offenders.join("\n ")
1699 );
1700 }
1701}