forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBbede77eTahinli2 months ago3534 commits

gate_coverage.rs2480 lines, 114.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}
1702
1703/// lane-av1pins5 r5: the PIN INVENTORY.
1704///
1705/// The r3 inventory this replaces matched only two call shapes --
1706/// `crate_pin("X")` and `pin_dir().join("X")` -- both SINGLE-NAME. A gate that
1707/// reads a whole DIRECTORY of pins through a `concat!` literal and then formats
1708/// a name at runtime (`format!("{fixtures}/{n}.obu")`) matched neither, so
1709/// `pinned_warp_stream_decodes_pixel_exact` and its 14 uncommitted pins were
1710/// invisible to it, and r3 reported "the machine-local-pin population is zero".
1711/// It was not. This enumerator resolves all four shapes.
1712///
1713/// Ownership, stated because two lanes touch this: THIS scanner owns the
1714/// ENUMERATION (which gates read which pins, from source). The fixture-preflight
1715/// lane owns the FILE INVENTORY on a runner (does each referenced path exist on
1716/// the box). Different questions; both must agree, and this one is the stricter of
1717/// the two because it fails on an uncommitted pin whether or not some runner
1718/// happens to have a copy.
1719#[cfg(test)]
1720mod pin_inventory {
1721 /// One pin a gate reads, and where it came from.
1722 pub struct PinRead {
1723 pub gate: String,
1724 pub file: String,
1725 pub shape: &'static str,
1726 }
1727
1728 /// Split `src` into `(fn_name, body)` for every `fn name(` at the gate indent.
1729 fn gate_bodies(src: &str) -> Vec<(String, &'static str)> {
1730 let mut out = Vec::new();
1731 let mut cur: Option<(String, usize)> = None;
1732 for (i, line) in src.lines().enumerate() {
1733 let t = line.trim_start();
1734 if let Some(rest) = t.strip_prefix("fn ") {
1735 if let Some(name) = rest.split('(').next() {
1736 if !name.contains(' ') {
1737 cur = Some((name.to_string(), i));
1738 }
1739 }
1740 }
1741 // A `#[test]`/`#[ignore]` line is never a closing brace, so the fn
1742 // ends at the first line that is exactly four-space `}`.
1743 if let Some((name, start)) = &cur {
1744 if i > *start && line == " }" {
1745 let body = src
1746 .lines()
1747 .skip(*start)
1748 .take(i - *start + 1)
1749 .collect::<Vec<_>>()
1750 .join("\n");
1751 out.push((name.clone(), &*Box::leak(body.into_boxed_str())));
1752 cur = None;
1753 }
1754 }
1755 }
1756 out
1757 }
1758
1759 /// Every pin every gate reads, across all four shapes.
1760 pub fn pins_read(src: &str) -> Vec<PinRead> {
1761 let mut out = Vec::new();
1762 for (gate, body) in gate_bodies(src) {
1763 // (a) crate_pin("X") and (b) pin_dir().join("X") -- single name.
1764 for m in body.match_indices("crate_pin(\"") {
1765 let rest = &body[m.0 + 11..];
1766 if let Some(e) = rest.find('"') {
1767 out.push(PinRead {
1768 gate: gate.clone(),
1769 file: rest[..e].to_string(),
1770 shape: "crate_pin",
1771 });
1772 }
1773 }
1774 for m in body.match_indices("pin_dir().join(\"") {
1775 let rest = &body[m.0 + 16..];
1776 if let Some(e) = rest.find('"') {
1777 out.push(PinRead {
1778 gate: gate.clone(),
1779 file: rest[..e].to_string(),
1780 shape: "pin_dir_machine_local",
1781 });
1782 }
1783 }
1784 // (c) a whole-file concat! literal to a named pin:
1785 // concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/X.obu")
1786 for m in body.match_indices("/../../fixtures/") {
1787 let rest = &body[m.0 + 16..];
1788 if let Some(e) = rest.find('"') {
1789 out.push(PinRead {
1790 gate: gate.clone(),
1791 file: rest[..e].to_string(),
1792 shape: "concat_literal_machine_local",
1793 });
1794 }
1795 }
1796 // (d) the shape that hid 14 pins: a DIRECTORY literal bound to a
1797 // local, plus a runtime `format!("{var}/{n}.ext")` over a
1798 // literal name array. Resolve the array's names.
1799 for (vi, line) in body.lines().enumerate() {
1800 let tl = line.trim();
1801 // `let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");`
1802 // -> the bound name is whatever sits between `let ` and the `=`.
1803 let var = match (
1804 tl.find("concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/../../fixtures\")"),
1805 tl.find('='),
1806 ) {
1807 (Some(a), Some(eq)) if eq < a => tl[4..eq].trim().to_string(),
1808 _ => continue,
1809 };
1810 if var.is_empty() {
1811 continue;
1812 }
1813 // `format!("{fixtures}/{n}.obu")` -- built by concatenation, not
1814 // by `format!`: escaping `{{`/`}}` to emit literal braces here is
1815 // exactly the bug that made this shape resolve to 0 pins on the
1816 // first run of the scanner.
1817 let marker = ["format!(\"", "{", &var, "}/{n}"].concat();
1818 let Some(pos) = body.find(&marker) else {
1819 continue;
1820 };
1821 // Walk back from the format! to the `[ ... ].iter()` array and
1822 // take every quoted name in it.
1823 let head = &body[..pos];
1824 let Some(bracket) = head.rfind('[') else {
1825 continue;
1826 };
1827 let names: Vec<String> = head[bracket..]
1828 .split('"')
1829 .skip(1)
1830 .step_by(2)
1831 .filter(|s| !s.is_empty() && !s.contains(' ') && *s != "]")
1832 .map(|s| s.to_string())
1833 .collect();
1834 // `.obu` -- SLICE up to the closing quote. (Stringifying the
1835 // `find` index instead produced names like `warp-mismatch4`.)
1836 let tail = &body[pos + marker.len()..];
1837 let ext = tail
1838 .find('"')
1839 .map(|e| tail[..e].to_string())
1840 .unwrap_or_default();
1841 for n in names {
1842 out.push(PinRead {
1843 gate: gate.clone(),
1844 file: format!("{n}{ext}"),
1845 shape: "concat_dir_runtime_name",
1846 });
1847 }
1848 let _ = vi;
1849 }
1850 // (e) the shape this very fix INTRODUCED:
1851 // `.map(|n| crate_pin(&format!("{n}.obu")))`. Rewriting the
1852 // directory literal as a committed-path lookup made the gate
1853 // correct and simultaneously invisible -- `crate_pin("` no
1854 // longer appears, so shape (a) found nothing and the
1855 // enumerator reported a CLEAN tree while 14 pins were read. A
1856 // false pass is worse than the original gap: the original at
1857 // least showed up in a filesystem audit. Caught here by the
1858 // `reads.len()` floor in the invariant test.
1859 for m in body.match_indices("crate_pin(&format!(") {
1860 let rest = &body[m.0 + 19..];
1861 let Some(close) = rest.find(')') else {
1862 continue;
1863 };
1864 let call = &rest[..close];
1865 if !call.contains('"') {
1866 continue;
1867 }
1868 let head = &body[..m.0];
1869 let Some(bracket) = head.rfind('[') else {
1870 continue;
1871 };
1872 let names: Vec<String> = head[bracket..]
1873 .split('"')
1874 .skip(1)
1875 .step_by(2)
1876 .filter(|x| !x.is_empty() && !x.contains(' ') && *x != "]")
1877 .map(|x| x.to_string())
1878 .collect();
1879 // the literal inside the format!, e.g. `{n}.obu`
1880 let lit = call.split('"').nth(1).unwrap_or("");
1881 let ext = lit
1882 .split_once("}")
1883 .map(|(_, e)| e.to_string())
1884 .unwrap_or_default();
1885 for n in names {
1886 out.push(PinRead {
1887 gate: gate.clone(),
1888 file: format!("{n}{ext}"),
1889 shape: "crate_pin_runtime_name",
1890 });
1891 }
1892 }
1893 }
1894 out
1895 }
1896
1897 /// Does this shape resolve through `crate_pin`, i.e. the COMMITTED
1898 /// crate-local copy? Both the literal form and the runtime-name form do --
1899 /// only the two `pin_dir`/root-`concat!` forms are machine-local.
1900 pub fn resolves_committed(shape: &str) -> bool {
1901 matches!(shape, "crate_pin" | "crate_pin_runtime_name")
1902 }
1903
1904 /// Is `file` present as a committed crate-local fixture?
1905 pub fn is_committed(file: &str) -> bool {
1906 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1907 .join("fixtures")
1908 .join(file)
1909 .is_file()
1910 }
1911}
1912
1913#[cfg(test)]
1914mod pin_inventory_tests {
1915 use super::pin_inventory::{is_committed, pins_read};
1916
1917 /// The scanner must be able to SEE the directory-literal shape. Run over a
1918 /// SYNTHETIC source, not the live tree: r5 removed that shape from
1919 /// `pinned_warp_stream_decodes_pixel_exact`, so a test that asserted it
1920 /// against the live file would rot the moment the fix landed -- which is
1921 /// precisely how a scanner loses its edge and reports a clean tree again.
1922 /// A capability test must have its own input.
1923 #[test]
1924 fn the_pin_scanner_sees_the_directory_literal_shape() {
1925 let synthetic = r#"
1926 #[test]
1927 fn a_gate_using_the_old_shape() {
1928 let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");
1929 let paths: Vec<String> = match std::env::var("EC_AV1_GATE_DUMP_PIN") {
1930 Ok(p) => vec![p],
1931 Err(_) => [
1932 "warp-mismatch",
1933 "ii-flake-1",
1934 "rect-flake-3",
1935 ]
1936 .iter()
1937 .map(|n| format!("{fixtures}/{n}.obu"))
1938 .collect(),
1939 };
1940 for path in paths {
1941 check(&path);
1942 }
1943 }
1944"#;
1945 let reads = pins_read(synthetic);
1946 let names: Vec<&str> = reads.iter().map(|r| r.file.as_str()).collect();
1947 assert_eq!(
1948 names,
1949 vec!["warp-mismatch.obu", "ii-flake-1.obu", "rect-flake-3.obu"],
1950 "the directory-literal + runtime-name shape resolved to {names:?} -- a scanner \
1951 that cannot see this shape is how 14 uncommitted pins survived three rounds"
1952 );
1953 assert!(
1954 reads.iter().all(|r| r.shape == "concat_dir_runtime_name"),
1955 "the synthetic pins were attributed to the wrong shape: {:?}",
1956 reads.iter().map(|r| r.shape).collect::<Vec<_>>()
1957 );
1958 }
1959
1960 /// The other three shapes resolve too -- same reasoning, same synthetic input,
1961 /// so the capability survives the tree being fixed.
1962 #[test]
1963 fn the_pin_scanner_sees_every_shape() {
1964 let synthetic = r#"
1965 #[test]
1966 fn shapes() {
1967 let a = crate_pin("golden3-pin.obu");
1968 let b = pin_dir().join("sbpart-pin.obu");
1969 let c = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/x.obu"));
1970 }
1971"#;
1972 let mut names: Vec<String> = pins_read(synthetic)
1973 .iter()
1974 .map(|r| format!("{}|{}", r.file, r.shape))
1975 .collect();
1976 names.sort();
1977 assert_eq!(
1978 names,
1979 vec![
1980 "golden3-pin.obu|crate_pin",
1981 "sbpart-pin.obu|pin_dir_machine_local",
1982 "x.obu|concat_literal_machine_local",
1983 ],
1984 "shape coverage changed: {names:?}"
1985 );
1986 }
1987
1988 /// THE INVARIANT, on the live tree: every pin a gate reads is a COMMITTED
1989 /// crate-local copy, and NO gate reads through a machine-local shape. This is
1990 /// the check the r3 manifest could not express.
1991 #[test]
1992 fn every_pin_a_gate_reads_is_committed_under_the_crate() {
1993 let src = include_str!("stream.rs");
1994 let reads = pins_read(src);
1995 assert!(
1996 reads.len() >= 20,
1997 "the enumerator found only {} pin reads in stream.rs -- it has lost a shape, \
1998 which is the failure mode that let 14 pins go unseen",
1999 reads.len()
2000 );
2001 let uncommitted: Vec<String> = reads
2002 .iter()
2003 .filter(|r| !is_committed(&r.file))
2004 .map(|r| format!("{}:{} ({})", r.gate, r.file, r.shape))
2005 .collect();
2006 assert!(
2007 uncommitted.is_empty(),
2008 "{} pin(s) a gate reads have no committed copy under \
2009 crates/ec-av1/fixtures/ -- each resolves only on a machine whose \
2010 gitignored root fixtures/ happens to be populated, so a clean checkout \
2011 silently skips or panics:\n {}",
2012 uncommitted.len(),
2013 uncommitted.join("\n ")
2014 );
2015 let machine_local: Vec<String> = reads
2016 .iter()
2017 .filter(|r| !super::pin_inventory::resolves_committed(r.shape))
2018 .map(|r| format!("{} reads {} via {}", r.gate, r.file, r.shape))
2019 .collect();
2020 assert!(
2021 machine_local.is_empty(),
2022 "{} pin read(s) still resolve through a machine-local shape instead of \
2023 `crate_pin` (the committed crate-local copy), so they break on a clean \
2024 checkout:\n {}",
2025 machine_local.len(),
2026 machine_local.join("\n ")
2027 );
2028 }
2029}
2030
2031/// lane-av1pins5 r5: the COUNT-VACUITY enumerator.
2032///
2033/// Passing OUR OWN decode's length as the ORACLE's expected frame count
2034/// (`ffmpeg_decode_sequence(&stream, w, h, ours.len())`) is a real defect, but
2035/// NOT the one r4 claimed. MEASURED, by calling
2036/// `ffmpeg_decode_sequence(&stream, 192, 128, 0)` on a real pinned stream under
2037/// `catch_unwind`: it PANICS at `stream.rs:5110` with
2038/// `expected 0 4:2:0 frames, ffmpeg said: `. The helper asserts
2039/// `out.stdout.len() == frame_bytes * frames` unconditionally, so a wrong count
2040/// cannot pass silently -- it reds, with a message that blames FFMPEG for a
2041/// count OUR decoder chose.
2042///
2043/// TWO DEFECT CLASSES, DO NOT CONFLATE THEM (lane-av1pins5 r6):
2044/// * MISATTRIBUTED RED -- a wrong count reds, and the old message blamed
2045/// ffmpeg for a number OUR decoder chose. This is what these sites are.
2046/// `ffmpeg_decode_sequence`'s `stdout.len() == frame_bytes * frames` assert
2047/// is unconditional, so it cannot pass silently.
2048/// * SILENT PASS -- the compare is skipped or truncated and the gate reports
2049/// green. A DIFFERENT defect with a DIFFERENT fix, and r4 mislabelled these
2050/// sites as belonging to it. If you are reading this to decide what to fix,
2051/// fix the message and the count SOURCE; do not go looking for a silent pass.
2052///
2053/// r4 reported this shape as "a vacuous pass" and told Main so. That was wrong.
2054/// The consequence is a MISATTRIBUTED RED. The fix r4 shipped is still right (the
2055/// count now comes from the fixture, so the red names the real cause), but the
2056/// justification was wrong, and a sweep that repeats it would send the next
2057/// reader after a silent-pass bug that does not exist.
2058///
2059/// This enumerator finds every such site and classifies it, so the class is
2060/// visible and cannot shrink unnoticed.
2061#[cfg(test)]
2062mod count_vacuity {
2063 /// One oracle call whose expected frame count is locally derived.
2064 pub struct Site {
2065 pub line: usize,
2066 pub gate: String,
2067 pub count_expr: String,
2068 /// An independent count assertion on the same binding, within a few
2069 /// lines above: that is what makes the count a SPEC rather than a
2070 /// self-fulfilling number.
2071 pub pinned_by: Option<String>,
2072 /// Does this gate actually COMPARE PIXELS (so a wrong count would
2073 /// corrupt a verdict), or is it a report-only probe?
2074 pub pixel_comparing: bool,
2075 /// The fix bucket, by READING the gate (r7). `Some(b)` where
2076 /// a = pinned stream on disk -> take the count from the PIN
2077 /// b = live aomenc encode -> take it from the ENCODE's frame count;
2078 /// our decode's length is the thing
2079 /// UNDER TEST and must never be the
2080 /// expected value
2081 /// c = census/probe -> report only, never fix
2082 /// `None` = could not classify, and the reason is in `bucket_reason`.
2083 pub bucket: Option<&'static str>,
2084 pub bucket_reason: String,
2085 /// The numeric frame count found in this gate's own encode call, when
2086 /// one is visible -- the value the compare should assert instead.
2087 pub candidate: Option<String>,
2088 /// A frame count already in scope that is a SPEC rather than a
2089 /// self-fulfilling number -- e.g. the `FRAMES` the gate encoded, or a
2090 /// count asserted on the pinned stream. `Some(..)` means the fix is a
2091 /// one-line swap at this site.
2092 pub fixable_from: Option<String>,
2093 }
2094
2095 /// A census/probe/diagnostic gate: it reports, it does not assert a verdict.
2096 fn is_probe(gate: &str) -> bool {
2097 [
2098 "census",
2099 "probe",
2100 "sweep",
2101 "first_diff",
2102 "scratch",
2103 "rectx",
2104 "diagnostic",
2105 ]
2106 .iter()
2107 .any(|m| gate.contains(m))
2108 }
2109
2110 /// Encode helpers a gate can drive INDIRECTLY. The r7 extraction found 21 of
2111 /// the 25 bucket-b gates encode through one of these, not through
2112 /// `aomenc_path()` directly -- which is why a first pass that only looked for
2113 /// `aomenc_path()` classified 6 gates "unclassified" that plainly encode.
2114 fn enc_helpers(body: &str) -> Vec<&'static str> {
2115 const NAMES: &[&str] = &[
2116 "encode_aomenc_stream",
2117 "screen_intrabc_stream_at_depth",
2118 "screen_intrabc_stream_with",
2119 "libaom_encode_with",
2120 "libaom_encode",
2121 "run_multi_tile_gate",
2122 "edge32_gate",
2123 "rect_tx_tool_gate",
2124 "the_chroma_rect_gates",
2125 "restore_gate",
2126 "cdef_gate",
2127 "warp_gate",
2128 "superres_gate",
2129 "grain_gate",
2130 "sgate",
2131 ];
2132 NAMES
2133 .iter()
2134 .copied()
2135 .filter(|n| body.contains(&format!("{n}(")))
2136 .collect()
2137 }
2138
2139 pub fn sites(src: &str) -> Vec<Site> {
2140 let mut out = Vec::new();
2141 let lines: Vec<&str> = src.lines().collect();
2142 // LINE index -> BYTE offset. The body walk indexes `src.as_bytes()`, so
2143 // handing it a line number walks from the wrong place entirely and every
2144 // body-dependent classification reads "unclassified". Same bug I hit in
2145 // the Python classifier one step earlier.
2146 let mut offsets: Vec<usize> = Vec::with_capacity(lines.len());
2147 {
2148 let mut o = 0usize;
2149 for l in &lines {
2150 offsets.push(o);
2151 o += l.len() + 1;
2152 }
2153 }
2154 let mut gate = String::new();
2155 let mut fn_start = 0usize;
2156 for (i, line) in lines.iter().enumerate() {
2157 let t = line.trim_start();
2158 if let Some(rest) = t.strip_prefix("fn ") {
2159 if let Some(n) = rest.split('(').next() {
2160 if !n.contains(' ') {
2161 gate = n.to_string();
2162 fn_start = offsets[i];
2163 }
2164 }
2165 }
2166 for callee in [
2167 "ffmpeg_decode_sequence(",
2168 "ffmpeg_decode_sequence_10bit(",
2169 "ffmpeg_decode_sequence_444(",
2170 ] {
2171 let Some(at) = line.find(callee) else {
2172 continue;
2173 };
2174 let args = &line[at + callee.len()..];
2175 // DEPTH-AWARE close: `args.find(')')` stops at the `)` of
2176 // `pictures.len()` and truncates the arg list mid-expression,
2177 // which silently yielded zero sites on the first run.
2178 let mut depth = 1usize;
2179 let mut close = None;
2180 for (k, ch) in args.char_indices() {
2181 match ch {
2182 '(' => depth += 1,
2183 ')' => {
2184 depth -= 1;
2185 if depth == 0 {
2186 close = Some(k);
2187 break;
2188 }
2189 }
2190 _ => {}
2191 }
2192 }
2193 let Some(close) = close else { continue };
2194 let arglist = &args[..close];
2195 let last = arglist.rsplit(',').next().unwrap_or("").trim();
2196 if !(last.ends_with(".len()") || last.ends_with(".count()")) {
2197 continue;
2198 }
2199 // Is the SAME binding count-asserted against a literal/const
2200 // within the preceding 12 lines? That is the difference between
2201 // a spec and a self-fulfilling number.
2202 let binding = last.trim_end_matches(".len()").trim_end_matches(".count()");
2203 // Match the assertion across a LINE BREAK: rustfmt puts
2204 // assert_eq!(
2205 // frames.len(),
2206 // so requiring `assert_eq!(frames.len()` on one line missed
2207 // every multi-line spelling and inflated the unpinned count.
2208 let want = format!("{binding}.len()");
2209 let mut pinned = None;
2210 for back in 1..=14usize {
2211 if i < back {
2212 break;
2213 }
2214 let prev = lines[i - back].trim_start();
2215 if !prev.starts_with("assert") || !prev.contains('(') {
2216 continue;
2217 }
2218 // rustfmt splits `assert_eq!(` from its first argument, so
2219 // the binding is on THIS line or the NEXT one.
2220 let here = prev.contains(&want);
2221 let next = lines
2222 .get(i - back + 1)
2223 .map(|l| l.trim_start().contains(&want))
2224 .unwrap_or(false);
2225 if here || next {
2226 pinned = Some(prev.chars().take(60).collect());
2227 break;
2228 }
2229 }
2230 // Pixel-comparing? A gate that compares planes is the only
2231 // place a wrong count corrupts a verdict; a report-only probe
2232 // just prints.
2233 // Bound to THIS fn only. Slicing to EOF matched a later gate's
2234 // `const FRAMES` and its `assert_eq!(got.y`, which reported all
2235 // 48 sites as pixel-comparing with a spec in scope -- the same
2236 // over-broad-scope bug the class keeps teaching.
2237 // Brace-depth walk, not `find("\n }")`: a gate with an
2238 // early 4-space `}` (a bare block, a `match` arm tail) truncated
2239 // the slice and made the compare-detection read false.
2240 // STRING-AWARE brace walk. Counting raw bytes counts a `}`
2241 // inside a format string as a closing brace, which truncated the
2242 // body and made every compare-detection read false -- the same
2243 // trap that made stream.rs look 2 braces short in the first
2244 // review of this wave.
2245 let bytes = src.as_bytes();
2246 let mut depth = 0i32;
2247 let mut started = false;
2248 let mut fn_end = src.len();
2249 let mut in_str = false;
2250 let mut in_line_comment = false;
2251 let mut k = fn_start;
2252 while k < bytes.len() {
2253 let c = bytes[k];
2254 if in_line_comment {
2255 if c == b'\n' {
2256 in_line_comment = false;
2257 }
2258 k += 1;
2259 continue;
2260 }
2261 if in_str {
2262 if c == b'\\' {
2263 k += 2;
2264 continue;
2265 }
2266 if c == b'"' {
2267 in_str = false;
2268 }
2269 k += 1;
2270 continue;
2271 }
2272 match c {
2273 b'"' => in_str = true,
2274 b'/' if bytes.get(k + 1) == Some(&b'/') => {
2275 in_line_comment = true;
2276 k += 1;
2277 }
2278 b'{' => {
2279 depth += 1;
2280 started = true;
2281 }
2282 b'}' => {
2283 depth -= 1;
2284 if started && depth == 0 {
2285 fn_end = k + 1;
2286 break;
2287 }
2288 }
2289 _ => {}
2290 }
2291 k += 1;
2292 }
2293 let body = &src[fn_start..fn_end];
2294 // APPROXIMATE, and known to be so: the body slice is a
2295 // hand-rolled brace walk, and this crate's compare idioms vary
2296 // enough that the column under-reports. The LINE, GATE and
2297 // COUNT EXPR columns are exact (line-based scan, no body
2298 // slicing); treat `pixel_comparing` as a hint, not a verdict.
2299 // Idiom-tolerant: this crate spells the compare every which way
2300 // (`assert_eq!(got.y, want.y)`, `assert_eq!(g, w)`,
2301 // `let ok = ours.y == ref_f.y`, `ours.y, want.y`), so match the
2302 // PLANE inside an assertion, not one fixed spelling.
2303 let pixel_comparing = body.contains("assert")
2304 && (body.contains(".y,")
2305 || body.contains(".y ==")
2306 || body.contains(".y)")
2307 || body.contains("vs ffmpeg"));
2308 // A SPEC already in scope for this gate?
2309 let mut fixable = None;
2310 for cand in ["FRAMES", "frame_count", "NFRAMES", "frames_expected"] {
2311 if body.contains(&format!("const {cand}"))
2312 || body.contains(&format!("let {cand}"))
2313 {
2314 fixable = Some(cand.to_string());
2315 break;
2316 }
2317 }
2318 // Bucket by READING the gate. A census/probe reports and never
2319 // asserts, so its count is not a verdict and is left alone. A
2320 // gate that drives aomenc takes the count from the ENCODE -- our
2321 // decode's length is what is under test, so using it as the
2322 // expected value is circular. A gate that reads a stream from
2323 // disk takes it from that stream.
2324 // The candidate fix: the numeric frame count in this gate's own
2325 // encode call. For bucket (b) that number IS the encoder's frame
2326 // count, so it is the spec the compare should assert.
2327 let candidate = enc_helpers(body).first().and_then(|h| {
2328 let at = body.find(&format!("{h}("))?;
2329 let open = at + h.len() + 1;
2330 let seg = &body[open..(open + 400).min(body.len())];
2331 let close = seg.find(';')?;
2332 let nums: Vec<&str> = seg[..close]
2333 .split(',')
2334 .map(|x| x.trim())
2335 .filter(|x| !x.is_empty() && x.chars().all(|c| c.is_ascii_digit()))
2336 .collect();
2337 nums.last().map(|x| x.to_string())
2338 });
2339 let (bucket, bucket_reason) = if is_probe(&gate) {
2340 (
2341 Some("c"),
2342 "census/probe: reports, does not assert a verdict".to_string(),
2343 )
2344 } else if body.contains("aomenc_path()") || !enc_helpers(body).is_empty() {
2345 (
2346 Some("b"),
2347 "live aomenc encode: count belongs to the encoder".to_string(),
2348 )
2349 } else if body.contains("fs::read") || body.contains("crate_pin") {
2350 (
2351 Some("a"),
2352 "stream read from disk: count belongs to the pin".to_string(),
2353 )
2354 } else {
2355 (
2356 None,
2357 "unclassified: no aomenc drive, no disk read, and not a probe -- \
2358 needs a reader"
2359 .to_string(),
2360 )
2361 };
2362 out.push(Site {
2363 line: i + 1,
2364 gate: gate.clone(),
2365 count_expr: last.to_string(),
2366 pinned_by: pinned,
2367 pixel_comparing,
2368 fixable_from: fixable,
2369 bucket,
2370 bucket_reason,
2371 candidate,
2372 });
2373 }
2374 }
2375 out
2376 }
2377}
2378
2379#[cfg(test)]
2380mod count_vacuity_tests {
2381 use super::count_vacuity::sites;
2382
2383 /// The shape is real and widespread; this pins the FLOOR so the sweep cannot
2384 /// silently stop finding sites. Measured count is well above this.
2385 #[test]
2386 fn the_count_vacuity_sweep_finds_the_known_sites() {
2387 let src = include_str!("stream.rs");
2388 let s = sites(src);
2389 assert!(
2390 s.len() >= 40,
2391 "the count-vacuity sweep found only {} site(s); expected 40+ -- it has lost a \
2392 shape",
2393 s.len()
2394 );
2395 // r7: the first reported site (3895, `pictures.len()`) is FIXED -- it now
2396 // asserts `ENCODED_FRAMES`, the encode's own count. The anchor therefore
2397 // moved from "the site is still there" to "the fix is still in place AND
2398 // the dominant remaining shape is still found", so the sweep cannot go
2399 // quiet by either route.
2400 // The GENERAL rule, not the one literal r7 fixed. Every decode-derived
2401 // count expression is banned at the gate r7 fixed, so a future edit that
2402 // reintroduces the shape under a different binding name is caught, and so
2403 // the guard does not go quiet as the OTHER sites are fixed later.
2404 const DECODE_DERIVED: &[&str] = &["pictures.len()", "decoded.len()", "frames.len()"];
2405 assert!(
2406 !s.iter().any(|x| x.gate
2407 == "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact"
2408 && DECODE_DERIVED.contains(&x.count_expr.as_str())),
2409 "the r7 fix regressed: {} is passing a decode-derived count as the oracle's \
2410 expected count again -- our decode's length is the thing UNDER TEST and \
2411 must never be the expected value",
2412 "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact"
2413 );
2414 // A CEILING on the unpinned population, so a NEW site cannot be added
2415 // silently. Lower it as sites are fixed; a fix that does not lower it is
2416 // still a fix, but a NEW site is an immediate red.
2417 let unpinned = s.iter().filter(|x| x.pinned_by.is_none()).count();
2418 const UNPINNED_CEILING: usize = 43;
2419 assert!(
2420 unpinned <= UNPINNED_CEILING,
2421 "{unpinned} unpinned count site(s), ceiling is {UNPINNED_CEILING} -- a new one \
2422 was added (lower the ceiling only when a site is actually fixed)"
2423 );
2424 assert!(
2425 s.iter().any(|x| x.count_expr == "frames.len()"),
2426 "the dominant `frames.len()` shape is no longer found -- the sweep has lost a \
2427 shape, not gained a fix"
2428 );
2429 }
2430
2431 /// Report, per site: does the count come from a SPEC or from our own decode?
2432 /// Prints the table the r5 report carries. The assertion is the FLOOR above,
2433 /// not "zero unpinned" -- the residual unpinned sites are handed to another
2434 /// lane with this table, and forcing them all here would be an unbounded
2435 /// change dressed as a fix.
2436 #[test]
2437 fn every_locally_derived_oracle_count_is_reported() {
2438 let src = include_str!("stream.rs");
2439 let s = sites(src);
2440 let unpinned: Vec<String> = s
2441 .iter()
2442 .filter(|x| x.pinned_by.is_none())
2443 .map(|x| {
2444 format!(
2445 "stream.rs:{} | {} | {} | NOT SPEC-PINNED",
2446 x.line, x.gate, x.count_expr
2447 )
2448 })
2449 .collect();
2450 let pinned = s.len() - unpinned.len();
2451 eprintln!(
2452 "count-vacuity sweep: {} site(s); {} spec-pinned by a prior assert, {} not",
2453 s.len(),
2454 pinned,
2455 unpinned.len()
2456 );
2457 for line in unpinned.iter() {
2458 eprintln!(" {line}");
2459 }
2460 // The table Main asked for, as columns the guard itself computes.
2461 for x in s.iter().filter(|x| x.pinned_by.is_none()) {
2462 eprintln!(
2463 "ROW {} | {} | {} | bucket={} | candidate={} | spec_in_scope={} | {} | \
2464 pixel_comparing={}",
2465 x.line,
2466 x.gate,
2467 x.count_expr,
2468 x.bucket.unwrap_or("?"),
2469 x.candidate.clone().unwrap_or_else(|| "-".into()),
2470 x.fixable_from.clone().unwrap_or_else(|| "-".into()),
2471 x.bucket_reason,
2472 x.pixel_comparing
2473 );
2474 }
2475 assert!(
2476 !s.is_empty() && s.iter().all(|x| !x.gate.is_empty()),
2477 "a site has no owning gate -- the sweep's gate attribution is broken"
2478 );
2479 }
2480}