forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

gate_coverage.rs2775 lines, 129.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 = crate::test_source::module_source("stream");
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 && let Some(c) = literal.chars().next()
649 && c.is_ascii_digit() {
650 out.insert(c);
651 }
652 at = start + end + 1;
653 }
654 out
655 };
656 // Bare integer literals: `0usize`, `1`, `8u8`. Whole tokens only, so
657 // `10u8` contributes nothing rather than a bogus `1`.
658 let bare_digits = |t: &str| -> BTreeSet<char> {
659 let mut out = BTreeSet::new();
660 let bytes = t.as_bytes();
661 let mut i = 0usize;
662 while i < bytes.len() {
663 if !bytes[i].is_ascii_digit() {
664 i += 1;
665 continue;
666 }
667 let start = i;
668 while i < bytes.len() && bytes[i].is_ascii_digit() {
669 i += 1;
670 }
671 let clean_before = start == 0 || !is_ident_byte(bytes[start - 1]);
672 // A typed literal's suffix (`0usize`, `8u8`, `1u32`) belongs to
673 // the same token, so a run of LOWERCASE letters right after
674 // the digit is a type, not a different identifier. Anything
675 // else -- a multi-digit `10u8`, a camelCase `1x` -- is not a
676 // flag value and is rejected.
677 let rest = &t[i..];
678 let suffix = rest
679 .bytes()
680 .take_while(|b| b.is_ascii_lowercase() || *b == b'_')
681 .count();
682 let clean_after = i >= bytes.len()
683 || !is_ident_byte(bytes[i])
684 || (suffix > 0
685 && i + suffix < bytes.len()
686 && !is_ident_byte(bytes[i + suffix]));
687 if clean_before && clean_after && i - start == 1 {
688 out.insert(bytes[start] as char);
689 }
690 }
691 out
692 };
693 // Split a comma-separated list at TOP level only, so `("1", 8u8)`
694 // stays one element.
695 fn split_top(t: &str) -> Vec<&str> {
696 let mut out = Vec::new();
697 let (mut depth, mut start) = (0i32, 0usize);
698 for (i, c) in t.char_indices() {
699 match c {
700 '(' | '[' | '{' => depth += 1,
701 ')' | ']' | '}' => depth -= 1,
702 ',' if depth == 0 => {
703 out.push(t[start..i].trim());
704 start = i + 1;
705 }
706 _ => {}
707 }
708 }
709 if start < t.len() {
710 out.push(t[start..].trim());
711 }
712 out
713 }
714 // The body of the `[...]` that FOLLOWS `head` in `text`. Scoped to
715 // the header rather than searching from the start of the body: a
716 // gate's first `[` may be an unrelated array, and brackets that do
717 // not balance across a whole gate body would leave the depth count
718 // never returning to zero.
719 fn loop_array_after<'a>(text: &'a str, head: &str) -> Option<&'a str> {
720 let at = text.find(head)? + head.len();
721 let open = at + text[at..].find('[')?;
722 let mut depth = 0i32;
723 for (i, c) in text[open..].char_indices() {
724 match c {
725 '[' => depth += 1,
726 ']' => {
727 depth -= 1;
728 if depth == 0 {
729 return Some(&text[open + 1..open + i]);
730 }
731 }
732 _ => {}
733 }
734 }
735 None
736 }
737 let mut found: Option<BTreeSet<char>> = None;
738 let mut merge = |set: BTreeSet<char>| match &mut found {
739 Some(all) => all.extend(set),
740 None => found = Some(set),
741 };
742 // (1) `let <var> = if ... { "0" } else { "1" };` -- quoted values only.
743 if let Some(at) = body.find(&format!("let {var} =")) {
744 let init = &body[at..];
745 let end = init.find(';').unwrap_or(init.len());
746 merge(quoted_digits(&init[..end]));
747 }
748 // (2) `for <var> in [...]` -- every element of the array.
749 if let Some(array) = loop_array_after(body, &format!("for {var} in ")) {
750 merge(bare_digits(array));
751 merge(quoted_digits(array));
752 }
753 // (3) `for (<var>, ...) in [(...), ...]` -- only `<var>`'s column.
754 if let Some(at) = body.find("for (") {
755 let head = &body[at..];
756 if let Some(close) = head.find(')') {
757 let pattern = &head["for (".len()..close];
758 if let Some(pos) = pattern.split(',').position(|p| p.trim() == var) {
759 let header = format!("for ({pattern}) in ");
760 if let Some(array) = loop_array_after(body, &header) {
761 let mut set: BTreeSet<char> = BTreeSet::new();
762 for tuple in split_top(array) {
763 let Some(inner) =
764 tuple.strip_prefix('(').and_then(|t| t.strip_suffix(')'))
765 else {
766 continue;
767 };
768 let fields = split_top(inner);
769 let Some(field) = fields.get(pos) else {
770 continue;
771 };
772 set.extend(bare_digits(field));
773 set.extend(quoted_digits(field));
774 }
775 merge(set);
776 }
777 }
778 }
779 }
780 // (3b) `for (<var>, ...) in <ident>` where `<ident>` is a `let`
781 // binding in this same body -- the arm table hoisted OUT of the
782 // loop header, so the `for` line NAMES the array instead of
783 // spelling it. Strategy (3) alone silently reads past the `for`
784 // line to the next `[` in the body (an unrelated `&[..]` flag
785 // list), finds no digits, and returns an empty set: the gate is
786 // then filed as UNRESOLVED even though both of its arms sit
787 // verbatim in the source. Measured: the 128x96 4:4:4 lossy
788 // tx-size-search gate, whose `for (label, search, ...) in arms`
789 // drove `print_tx_size_search_census`'s `unresolvable == 0`
790 // assertion red on merge. The `=` hop matters: the binding's
791 // TYPE annotation is itself bracketed
792 // (`[(&str, &str, TxMode, usize, u64); 2]`), so scanning for the
793 // first `[` after the name would return the type.
794 // `<var>`'s column, read off the arm table a hoisted `for` line
795 // NAMES rather than spells. Returns `None` unless the body really
796 // has that shape, so an unrecognised loop is left to the other
797 // strategies instead of being read as "no values".
798 let named_column = |pos: usize| -> Option<BTreeSet<char>> {
799 let at = body.find("for (")?;
800 let head = &body[at..];
801 let close = head.find(')')?;
802 let after = head[close + 1..].trim_start().strip_prefix("in ")?;
803 let name: &str = after
804 .split(|c: char| !is_ident_byte(c as u8))
805 .next()
806 .filter(|n| !n.is_empty() && !n.starts_with(|c: char| c.is_ascii_digit()))?;
807 let decl = body.find(&format!("let {name}"))?;
808 let after_name = decl + "let ".len() + name.len();
809 // `let arms_foo` must not answer for `let arms`.
810 if body[after_name..]
811 .chars()
812 .next()
813 .is_some_and(|c| is_ident_byte(c as u8))
814 {
815 return None;
816 }
817 // Hop the `=`: the binding's TYPE annotation is itself
818 // bracketed, so the first `[` after the name is the type.
819 let eq = after_name + body[after_name..].find('=')?;
820 let open = eq + 1 + body[eq + 1..].find('[')?;
821 let mut depth = 0i32;
822 for (i, c) in body[open..].char_indices() {
823 match c {
824 '[' => depth += 1,
825 ']' => {
826 depth -= 1;
827 if depth == 0 {
828 let mut set: BTreeSet<char> = Default::default();
829 for tuple in split_top(&body[open + 1..open + i]) {
830 let Some(inner) =
831 tuple.strip_prefix('(').and_then(|t| t.strip_suffix(')'))
832 else {
833 continue;
834 };
835 let fields = split_top(inner);
836 let Some(field) = fields.get(pos) else {
837 continue;
838 };
839 set.extend(bare_digits(field));
840 set.extend(quoted_digits(field));
841 }
842 return Some(set);
843 }
844 }
845 _ => {}
846 }
847 }
848 None
849 };
850 if let Some(at) = body.find("for (") {
851 let head = &body[at..];
852 if let Some(close) = head.find(')') {
853 let pattern = &head["for (".len()..close];
854 if let Some(pos) = pattern.split(',').position(|p| p.trim() == var)
855 && let Some(set) = named_column(pos) {
856 merge(set);
857 }
858 }
859 }
860 // (4) `u8::from(<a>.<field>)` over a struct-literal arm table.
861 for (i, _) in body.match_indices("u8::from(") {
862 let arg = &body[i + "u8::from(".len()..];
863 let Some(close) = arg.find(')') else { continue };
864 let field = arg[..close].rsplit('.').next().unwrap_or_default().trim();
865 if field.is_empty() || !field.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
866 continue;
867 }
868 let mut set = BTreeSet::new();
869 for (row, value) in [("true", '1'), ("false", '0')] {
870 if body.contains(&format!("{field}: {row}")) {
871 set.insert(value);
872 }
873 }
874 merge(set);
875 }
876 found
877 }
878
879 fn is_ident_byte(b: u8) -> bool {
880 b.is_ascii_alphanumeric() || b == b'_'
881 }
882
883 /// Values of one [`DEFAULT_ON_TOOLS`] spelling in one gate body: the
884 /// literal `--<spelling>=<digit>` spellings plus every value a `format!`
885 /// template built from a local binding resolves to.
886 ///
887 /// A gate that reaches BOTH values counts ON, not off: it builds a `=1`
888 /// stream on some attempt, which is what the census asks for. This is the
889 /// file's standing "any spelling that says on wins" rule
890 /// (`--tile-columns=0 --tile-rows=1` is a multi-tile stream), now applied
891 /// across a loop's arms as well as across spellings.
892 fn spelling_values(gate: &str, spelling: &str) -> BTreeSet<char> {
893 let mut out = BTreeSet::new();
894 // A literal `"--<spelling>=<digit>"`: the needle ends at the `=`, so
895 // the value starts AT the needle's length, not three characters in.
896 let literal = format!("\"--{spelling}=");
897 for (i, _) in gate.match_indices(&literal) {
898 let rest = &gate[i + literal.len()..];
899 let Some(end) = rest.find('"') else { continue };
900 if let Some(c) = rest[..end].chars().next()
901 && c.is_ascii_digit() {
902 out.insert(c);
903 }
904 }
905 // A template `format!("--<spelling>={<var>}")`: the placeholder name
906 // is the part between the braces, and its VALUE is whatever the
907 // binding of `<var>` in this same body reaches.
908 let template = format!("format!(\"--{spelling}=");
909 for (i, _) in gate.match_indices(&template) {
910 let rest = &gate[i + template.len()..];
911 let Some(end) = rest.find('"') else { continue };
912 let Some(var) = rest[..end]
913 .strip_prefix('{')
914 .and_then(|v| v.strip_suffix('}'))
915 else {
916 continue;
917 };
918 if var.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
919 out.extend(bound_values(gate, var).unwrap_or_default());
920 }
921 }
922 out
923 }
924
925 /// Whether a gate body spells one [`DEFAULT_ON_TOOLS`] entry on / off,
926 /// over [`spelling_values`] -- so a `format!`-built flag is classified
927 /// instead of being filed as "defaulted".
928 fn resolved_on_state(gate: &str, spellings: &[&str], on: On) -> Option<bool> {
929 let mut state = None;
930 for spelling in spellings {
931 for c in spelling_values(gate, spelling) {
932 let value = c.to_digit(10).unwrap_or(0);
933 let is_on = match on {
934 On::NonZero => value != 0,
935 On::AtMost(limit) => value <= limit,
936 };
937 state = Some(state.unwrap_or(false) || is_on);
938 }
939 }
940 state
941 }
942
943 /// `--enable-*` settings per real-aomenc gate, derived from the gate
944 /// source: `flag -> (turned off in N gates, turned on in N, defaulted in N)`.
945 fn tool_settings() -> (usize, BTreeMap<String, (usize, usize, usize)>) {
946 let gates = gate_bodies();
947
948 let mut per_tool: BTreeMap<String, (usize, usize, usize)> = BTreeMap::new();
949 let mut names: BTreeSet<String> = BTreeSet::new();
950 let mut seen: Vec<BTreeMap<String, char>> = Vec::new();
951 for gate in &gates {
952 let here = flags_in(gate);
953 names.extend(here.keys().cloned());
954 seen.push(here);
955 }
956 for name in names {
957 let off = seen.iter().filter(|g| g.get(&name) == Some(&'0')).count();
958 let on = seen.iter().filter(|g| g.get(&name) == Some(&'1')).count();
959 per_tool.insert(name, (off, on, gates.len() - off - on));
960 }
961 (gates.len(), per_tool)
962 }
963
964 #[test]
965 fn every_gate_disabling_a_tool_is_a_listed_coverage_hole() {
966 let (gate_count, per_tool) = tool_settings();
967 // A hole OPENS when every gate names the flag and every one of them
968 // says 0 -- then no real stream can exercise the tool.
969 let derived: BTreeSet<&str> = per_tool
970 .iter()
971 .filter(|&(_, &(off, on, defaulted))| off == gate_count && on == 0 && defaulted == 0)
972 .map(|(name, _)| name.as_str())
973 .collect();
974 // A hole CLOSES only on positive evidence: some gate passes `=1`.
975 // A gate that merely leaves the flag off its command line proves
976 // nothing -- aomenc's default for palette and intrabc is content-
977 // dependent -- so "defaulted" must not retire an entry, or a listing
978 // would disappear the moment an unrelated gate is added.
979 let exercised: BTreeSet<&str> = per_tool
980 .iter()
981 .filter(|&(_, &(_, on, _))| on > 0)
982 .map(|(name, _)| name.as_str())
983 .collect();
984 let listed: BTreeSet<&str> = NEVER_EXERCISED.iter().map(|&(flag, _)| flag).collect();
985
986 let unlisted: Vec<&&str> = derived.difference(&listed).collect();
987 assert!(
988 unlisted.is_empty(),
989 "these aomenc tools are switched off in all {gate_count} real-aomenc gates and on in \
990 none, so no real stream exercises them, and they are not listed in NEVER_EXERCISED: \
991 {unlisted:?} -- either enable the tool with `=1` in its own gate or add it to the \
992 list with a reason"
993 );
994 let stale: Vec<&&str> = listed.intersection(&exercised).collect();
995 assert!(
996 stale.is_empty(),
997 "NEVER_EXERCISED lists {stale:?}, but a gate now passes `=1` for them -- delete \
998 those entries, the coverage hole is closed"
999 );
1000 }
1001
1002 /// The derivation is only meaningful if a flag left off a gate's command
1003 /// line really does mean "aomenc's default", i.e. the parser above is
1004 /// reading whole flags and not fragments.
1005 #[test]
1006 fn tool_settings_reads_whole_flags() {
1007 let (gate_count, per_tool) = tool_settings();
1008 assert!(
1009 per_tool.contains_key("enable-cdef"),
1010 "expected --enable-cdef among the gate flags"
1011 );
1012 for (name, &(off, on, defaulted)) in &per_tool {
1013 assert!(
1014 !name.is_empty() && !name.contains(['"', '=']),
1015 "malformed flag {name:?}"
1016 );
1017 assert_eq!(
1018 off + on + defaulted,
1019 gate_count,
1020 "{name} counts do not cover every gate"
1021 );
1022 }
1023 }
1024
1025 /// A gate encodes at 10 bits when its recipe says so: the shared 10-bit
1026 /// helper, an explicit `--bit-depth=10`/`--input-bit-depth=10`, or a
1027 /// `yuv420p10le` fixture handed to aomenc. Everything else is aomenc's
1028 /// 8-bit default.
1029 /// lane-defon r1: a gate helper parameterised on `bit_depth` builds BOTH
1030 /// an 8-bit and a 10-bit stream from one recipe, so its flags cover both
1031 /// depths -- classifying it by the 10-bit strings inside its conditional
1032 /// alone hid `--enable-tx-size-search=1` from the 8-bit list.
1033 /// lane-reelckf r1: the same blind spot with the other spelling -- a gate
1034 /// that loops `for depth in [8usize, 10]` builds BOTH streams from one
1035 /// recipe, but its `yuv420p10le` arm made `is_ten_bit` classify it as
1036 /// 10-bit only, hiding `--enable-cfl-intra=1` from the 8-bit list.
1037 /// lane-av1-intrabc r1: the shared recipe helper
1038 /// `screen_intrabc_stream_at_depth` is parameterised on `depth` and sits in
1039 /// the segment that opens at the PRECEDING gate's `#[test]`, so without
1040 /// this marker that gate's own 8-bit-only flags read as 10-bit-only -- the
1041 /// lane-defon/reelckf blind spot with `depth` spelled instead of
1042 /// `bit_depth`. Three gates share the helper, at both depths.
1043 /// lane-av1distwtd r3: the THIRD spelling of the same blind spot, still
1044 /// live after lane-defon and lane-reelckf. A recipe parameterised on
1045 /// `ten_bit` names BOTH fixture formats in one body -- `let pix_fmt = if
1046 /// ten_bit { "yuv420p10le" } else { "yuv420p" };` -- so `is_ten_bit` saw
1047 /// the 10-bit arm and filed the whole body 10-bit-ONLY, hiding its 8-bit
1048 /// arm from the 8-bit bucket. The marker is the PAIR OF FORMATS, not the
1049 /// parameter name: a body spelling both pixel formats builds streams at
1050 /// both depths, whatever it calls the flag. The quotes matter -- a bare
1051 /// `yuv420p` substring test also matches `yuv420p10le` and would fire on
1052 /// every 10-bit gate, retiring entries on no evidence.
1053 ///
1054 /// This is what mis-filed `a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact`
1055 /// and kept `enable-flip-idtx` on the 8-bit list while that gate ran 6
1056 /// pixel-exact 8-bit decodes through it.
1057 fn covers_both_depths(body: &str) -> bool {
1058 body.contains("if bit_depth == 10")
1059 || body.contains("if depth == 10")
1060 || body.contains("for depth in [8usize, 10]")
1061 || (body.contains("\"yuv420p\"") && body.contains("\"yuv420p10le\""))
1062 }
1063
1064 /// lane-av1distwtd r3: the detector fix, pinned. A detector change with
1065 /// no test can only be shown to find MORE, never to stop missing, so this
1066 /// asserts the three gates the two blind spots actually hid are now seen
1067 /// -- the two `enable-dual-filter` witnesses and the `enable-flip-idtx`
1068 /// both-depths gate -- and that the fix is strictly ADDITIVE against the
1069 /// old spelling-only filter.
1070 #[test]
1071 fn the_detector_sees_the_gates_the_spelling_filter_missed() {
1072 let src = crate::test_source::module_source("stream");
1073 let gates = gate_bodies();
1074 // The helper-delegation half: each of these builds its stream through
1075 // `inter_sb_none_gate` and spells none of `legacy_gate_tokens`, so the
1076 // old filter dropped both while each hard-asserts its tool arrived.
1077 for name in [
1078 "a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact",
1079 "a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour",
1080 ] {
1081 let body = gates
1082 .iter()
1083 .find(|b| b.contains(name))
1084 .unwrap_or_else(|| panic!("{name}: not seen by gate_bodies()"));
1085 assert_eq!(
1086 flags_in(body).get("enable-dual-filter"),
1087 Some(&'1'),
1088 "{name}: seen, but its --enable-dual-filter=1 spelling is not visible to \
1089 flags_in, so recognising the gate would not retire the entry"
1090 );
1091 }
1092 // The both-depths half: this gate's recipe is parameterised on `ten_bit`
1093 // and names both fixture formats, so `covers_both_depths` must credit
1094 // it to the 8-bit bucket, not just the 10-bit one.
1095 let flip = gates
1096 .iter()
1097 .find(|b| b.contains("a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform"))
1098 .expect("the flip-idtx gate must be seen");
1099 assert!(
1100 covers_both_depths(flip),
1101 "the flip-idtx gate spells both fixture formats, so covers_both_depths must \
1102 credit it to the 8-bit bucket as well"
1103 );
1104 assert!(
1105 covers_depth(flip, false) && covers_depth(flip, true),
1106 "the flip-idtx gate must cover BOTH depths"
1107 );
1108 // Strictly additive: every segment the old spelling-only filter kept
1109 // is still kept, so the fix cannot have cost the census a gate.
1110 let legacy_only: Vec<&str> = src
1111 .split("\n #[")
1112 .filter(|b| !b.starts_with("ignore") && legacy_gate_tokens(b))
1113 .collect();
1114 assert!(
1115 legacy_only.len() < gates.len(),
1116 "the call-resolving filter found {} gates, the old spelling-only filter found \
1117 {} -- the fix is expected to ADD gates, never to drop one",
1118 gates.len(),
1119 legacy_only.len()
1120 );
1121 for body in &legacy_only {
1122 assert!(
1123 gates.contains(body),
1124 "a gate the spelling-only filter recognised is no longer recognised: \
1125 {:?}",
1126 &body[..body.len().min(60)]
1127 );
1128 }
1129 }
1130
1131 /// Whether a gate body drives a stream at this depth.
1132 fn covers_depth(body: &str, ten_bit: bool) -> bool {
1133 covers_both_depths(body) || is_ten_bit(body) == ten_bit
1134 }
1135
1136 fn is_ten_bit(body: &str) -> bool {
1137 // The lists pin two buckets, 8-bit and high-bit-depth; 12-bit gates
1138 // count in the high-depth bucket (lane-av1gwarp12's ROTZOOM gate was
1139 // the first 12-bit gate to positively enable a listed tool, and the
1140 // 10-bit-only spellings mis-filed it as 8-bit).
1141 body.contains("encode_10bit_gradients")
1142 || body.contains("ten_bit_tool_gate(")
1143 || body.contains("--bit-depth=10")
1144 || body.contains("--input-bit-depth=10")
1145 || body.contains("yuv420p10le")
1146 || body.contains("encode_12bit(")
1147 || body.contains("--bit-depth=12")
1148 || body.contains("--input-bit-depth=12")
1149 || body.contains("yuv420p12le")
1150 }
1151
1152 /// Flags a gate positively enables (`=1`), at gates of the given depth.
1153 fn enabled_at(ten_bit: bool) -> BTreeSet<String> {
1154 let mut on = BTreeSet::new();
1155 for gate in gate_bodies() {
1156 if !covers_depth(gate, ten_bit) {
1157 continue;
1158 }
1159 for (flag, value) in flags_in(gate) {
1160 if value == '1' {
1161 on.insert(flag);
1162 }
1163 }
1164 // A tool driven by its own spelling counts as exercised.
1165 let here = settings_in(gate);
1166 for (alias, tool) in ALIASES {
1167 if here.get(*alias).is_some_and(|v| v != "0") {
1168 on.insert((*tool).to_owned());
1169 }
1170 }
1171 }
1172 on
1173 }
1174
1175 /// The tools of [`TOOL_UNIVERSE`] that no gate of this depth enables.
1176 fn never_exercised_at(ten_bit: bool) -> BTreeSet<&'static str> {
1177 let on = enabled_at(ten_bit);
1178 TOOL_UNIVERSE
1179 .iter()
1180 .copied()
1181 .filter(|t| !on.contains(*t))
1182 .collect()
1183 }
1184
1185 fn check_depth(ten_bit: bool, listed: &[(&str, &str)]) {
1186 let derived = never_exercised_at(ten_bit);
1187 let listed: BTreeSet<&str> = listed.iter().map(|&(flag, _)| flag).collect();
1188 let depth = if ten_bit { "10-bit" } else { "8-bit" };
1189 let unlisted: Vec<&&str> = derived.difference(&listed).collect();
1190 assert!(
1191 unlisted.is_empty(),
1192 "no {depth} gate passes `=1` for {unlisted:?}, so no real {depth} stream exercises \
1193 them -- enable the tool in a {depth} gate that asserts it fired, or list it"
1194 );
1195 let stale: Vec<&&str> = listed.difference(&derived).collect();
1196 assert!(
1197 stale.is_empty(),
1198 "the {depth} list still names {stale:?}, but a {depth} gate now passes `=1` for them \
1199 -- delete those entries, the coverage hole is closed"
1200 );
1201 }
1202
1203 #[test]
1204 fn never_exercised_8bit_matches_the_gate_recipes() {
1205 check_depth(false, NEVER_EXERCISED_8BIT);
1206 }
1207
1208 #[test]
1209 fn never_exercised_10bit_matches_the_gate_recipes() {
1210 check_depth(true, NEVER_EXERCISED_10BIT);
1211 }
1212
1213 /// `cargo test -p ec-av1 --lib gate_coverage -- --nocapture` prints both
1214 /// lists, so the per-depth holes can be read without opening this file.
1215 #[test]
1216 fn print_never_exercised_per_bit_depth() {
1217 let ten: Vec<&str> = gate_bodies()
1218 .into_iter()
1219 .filter(|b| is_ten_bit(b))
1220 .collect();
1221 let total = gate_bodies().len();
1222 println!(
1223 "gate_coverage: {} real-aomenc gates, {} of them 10-bit",
1224 total,
1225 ten.len()
1226 );
1227 for (label, ten_bit) in [("8BIT", false), ("10BIT", true)] {
1228 let holes = never_exercised_at(ten_bit);
1229 println!(
1230 "NEVER_EXERCISED_{label} ({} of {}):",
1231 holes.len(),
1232 TOOL_UNIVERSE.len()
1233 );
1234 for flag in &holes {
1235 println!(" --{flag}");
1236 }
1237 }
1238 }
1239
1240 /// [`DEFAULT_ON_TOOLS`] per depth: `tool -> (off in N gates, on in N, defaulted in N)`.
1241 fn default_on_settings(
1242 ten_bit: bool,
1243 ) -> (usize, BTreeMap<&'static str, (usize, usize, usize)>) {
1244 let gates: Vec<&str> = gate_bodies()
1245 .into_iter()
1246 .filter(|b| covers_depth(b, ten_bit))
1247 .collect();
1248 let mut per_tool = BTreeMap::new();
1249 for &(tool, spellings, _, on) in DEFAULT_ON_TOOLS {
1250 // lane-av1txsearch: `resolved_on_state`, not `default_on_state` --
1251 // the literal-only reader filed every `format!`-built flag as
1252 // "defaulted", which is unknown rather than measured.
1253 let states: Vec<Option<bool>> = gates
1254 .iter()
1255 .map(|g| resolved_on_state(g, spellings, on))
1256 .collect();
1257 let turned_on = states.iter().filter(|s| **s == Some(true)).count();
1258 let turned_off = states.iter().filter(|s| **s == Some(false)).count();
1259 per_tool.insert(
1260 tool,
1261 (turned_off, turned_on, gates.len() - turned_off - turned_on),
1262 );
1263 }
1264 (gates.len(), per_tool)
1265 }
1266
1267 /// The [`DEFAULT_ON_TOOLS`] no gate of this depth positively enables.
1268 fn never_on_at(ten_bit: bool) -> BTreeSet<&'static str> {
1269 default_on_settings(ten_bit)
1270 .1
1271 .into_iter()
1272 .filter(|&(_, (_, on, _))| on == 0)
1273 .map(|(tool, _)| tool)
1274 .collect()
1275 }
1276
1277 fn check_default_on(ten_bit: bool, listed: &[(&str, &str)]) {
1278 let derived = never_on_at(ten_bit);
1279 let listed: BTreeSet<&str> = listed.iter().map(|&(tool, _)| tool).collect();
1280 let depth = if ten_bit { "10-bit" } else { "8-bit" };
1281 let unlisted: Vec<&&str> = derived.difference(&listed).collect();
1282 assert!(
1283 unlisted.is_empty(),
1284 "no {depth} gate spells an on-value for {unlisted:?}, so no real {depth} stream is \
1285 proven to carry them -- switch the tool on in a {depth} gate that asserts it fired, \
1286 or list it with a reason"
1287 );
1288 let stale: Vec<&&str> = listed.difference(&derived).collect();
1289 assert!(
1290 stale.is_empty(),
1291 "the {depth} default-on list still names {stale:?}, but a {depth} gate now switches \
1292 them on -- delete those entries, the coverage hole is closed"
1293 );
1294 }
1295
1296 #[test]
1297 fn never_on_8bit_matches_the_gate_recipes() {
1298 check_default_on(false, NEVER_ON_8BIT);
1299 }
1300
1301 #[test]
1302 fn never_on_10bit_matches_the_gate_recipes() {
1303 check_default_on(true, NEVER_ON_10BIT);
1304 }
1305
1306 /// A tool must not be pinned twice: [`TOOL_UNIVERSE`] already derives the
1307 /// `--enable-*` spellings under the `=1` rule.
1308 #[test]
1309 fn default_on_tools_do_not_duplicate_the_universe() {
1310 for &(tool, spellings, _, _) in DEFAULT_ON_TOOLS {
1311 assert!(
1312 !TOOL_UNIVERSE.contains(&tool),
1313 "{tool} is already covered by TOOL_UNIVERSE"
1314 );
1315 assert!(!spellings.is_empty(), "{tool} has no aomenc spelling");
1316 }
1317 for (alias, tool) in ALIASES {
1318 assert!(
1319 TOOL_UNIVERSE.contains(tool),
1320 "alias --{alias} names {tool}, which is not a TOOL_UNIVERSE tool"
1321 );
1322 }
1323 }
1324
1325 /// `cargo test -p ec-av1 --lib gate_coverage -- --nocapture` prints the
1326 /// default-on holes with their off/defaulted split.
1327 #[test]
1328 fn print_never_on_per_bit_depth() {
1329 for (label, ten_bit) in [("8BIT", false), ("10BIT", true)] {
1330 let (gate_count, per_tool) = default_on_settings(ten_bit);
1331 let holes = never_on_at(ten_bit);
1332 println!(
1333 "NEVER_ON_{label} ({} of {}, over {gate_count} {label} gates):",
1334 holes.len(),
1335 DEFAULT_ON_TOOLS.len()
1336 );
1337 for tool in &holes {
1338 let (off, _, defaulted) = per_tool[tool];
1339 let spellings = DEFAULT_ON_TOOLS
1340 .iter()
1341 .find(|e| e.0 == *tool)
1342 .map(|e| e.1.join(","))
1343 .unwrap_or_default();
1344 println!(
1345 " {tool} (--{spellings}): off in {off}, defaulted in {defaulted}, on in 0"
1346 );
1347 }
1348 }
1349 }
1350
1351 /// lane-av1txsearch: the `enable-tx-size-search` census, MEASURED rather
1352 /// than floored. Prints, per gate body, the values the resolver reads for
1353 /// the flag -- literal spellings and `format!` templates alike -- and the
1354 /// three-way split at the end. Re-run it after any gate recipe change:
1355 ///
1356 /// `cargo test -p ec-av1 --lib gate_coverage::tests::print_tx_size_search_census -- --nocapture`
1357 #[test]
1358 fn print_tx_size_search_census() {
1359 const TOOL: &str = "enable-tx-size-search";
1360 let (zero, one, both, unresolvable, unnamed) = {
1361 let (mut zero, mut one, mut both, mut unresolvable, mut unnamed) =
1362 (0usize, 0usize, 0usize, 0usize, 0usize);
1363 for gate in gate_bodies() {
1364 let values = spelling_values(gate, TOOL);
1365 let name = gate
1366 .split("fn ")
1367 .nth(1)
1368 .and_then(|s| s.split('(').next())
1369 .unwrap_or("<segment>")
1370 .to_owned();
1371 let state = match (values.contains(&'0'), values.contains(&'1')) {
1372 (false, false) => {
1373 unnamed += 1;
1374 "not named (defaulted)"
1375 }
1376 (true, false) => {
1377 zero += 1;
1378 "=0"
1379 }
1380 (false, true) => {
1381 one += 1;
1382 "=1"
1383 }
1384 (true, true) => {
1385 both += 1;
1386 "=0 and =1 (one arm each)"
1387 }
1388 };
1389 let via = if gate.contains(&format!("format!(\"--{TOOL}=")) {
1390 " [format! template resolved]"
1391 } else {
1392 ""
1393 };
1394 // A segment that does not open at a `#[test]` is glued non-test helper
1395 // text from a split module (the support helpers have no attribute between
1396 // them), so its `format!` parameter is not a gate's own value.
1397 let helper = if gate.starts_with("test]")
1398 && gate.contains(&format!("format!(\"--{TOOL}="))
1399 && values.is_empty()
1400 {
1401 " [UNRESOLVED: variable is a shared helper's parameter]"
1402 } else {
1403 ""
1404 };
1405 if !helper.is_empty() {
1406 unresolvable += 1;
1407 unnamed -= 1;
1408 }
1409 println!("{name}: {state}{via}{helper}");
1410 }
1411 (zero, one, both, unresolvable, unnamed)
1412 };
1413 let total = gate_bodies().len();
1414 println!(
1415 "enable-tx-size-search over {total} census-selected gate bodies: \
1416 =0 only {zero}, =1 only {one}, both {both}, unresolvable {unresolvable}, \
1417 not named {unnamed}"
1418 );
1419 assert_eq!(
1420 unresolvable, 0,
1421 "{unresolvable} gate bodies build --{TOOL} into a variable this census cannot bind -- \
1422 the count is a floor again, and an unknown direction is the failure mode this file \
1423 exists to prevent"
1424 );
1425 }
1426
1427 /// lane-av1txsearch: the RED-BEFORE proof for the template resolver, in
1428 /// both directions, on the gate bodies that actually exist.
1429 ///
1430 /// Direction 1 -- a `format!`-built value MOVES the classification. Each
1431 /// case below takes a real gate body, mutates only the bound value, and
1432 /// asserts the resolved state changed. A resolver that found nothing
1433 /// would read every one of these as "not named" and fail all four.
1434 ///
1435 /// Direction 2 -- a spelling the LITERAL reader already saw still
1436 /// classifies. Without this half, a resolver that overwrote the literal
1437 /// path would pass direction 1 while losing the 15 `=1` gates the census
1438 /// already counted.
1439 #[test]
1440 fn the_resolver_binds_a_format_built_flag_in_both_directions() {
1441 let gates = gate_bodies();
1442 let find = |needle: &str| -> &'static str {
1443 gates
1444 .iter()
1445 .copied()
1446 .find(|b| b.contains(needle))
1447 .unwrap_or_else(|| panic!("no gate body contains {needle:?}"))
1448 };
1449 // Direction 1, one per template shape.
1450 let cases = [
1451 (
1452 "format!(\"--enable-tx-size-search={txs}\")",
1453 "for txs in [0usize, 1]",
1454 "for txs in [0usize, 0]",
1455 "a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact",
1456 ),
1457 (
1458 "format!(\"--enable-tx-size-search={tx_search}\")",
1459 "if attempt % 2 == 0 { \"0\" } else { \"1\" }",
1460 "if attempt % 2 == 0 { \"0\" } else { \"0\" }",
1461 "a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact",
1462 ),
1463 (
1464 "format!(\"--enable-tx-size-search={tx_search}\")",
1465 "for (tx_search, bit_depth) in [(\"1\", 8u8), (\"0\", 8u8), (\"1\", 10u8)]",
1466 "for (tx_search, bit_depth) in [(\"0\", 8u8), (\"0\", 8u8), (\"0\", 10u8)]",
1467 "a_real_aomenc_stream_with_filter_intra_on_a_sub8_rect_leaf_decodes_pixel_exact",
1468 ),
1469 // The arm table hoisted OUT of the `for` line into a named
1470 // `let` -- the shape lane-av1lossy128x96 writes, and the one
1471 // that reads as UNRESOLVED unless the `for` line's collection
1472 // name is followed back to its binding. Without this case a
1473 // resolver that only understood inline arrays passes the
1474 // three above and still cannot bind this gate.
1475 (
1476 "format!(\"--enable-tx-size-search={search}\")",
1477 "\"tx size search on\",\n \"1\",",
1478 "\"tx size search on\",\n \"0\",",
1479 "a_real_aomenc_444_whole_64_root_tx_size_search_stream_decodes_pixel_exact_at_128x96",
1480 ),
1481 ];
1482 for (template, from, to, name) in cases {
1483 let body = find(name);
1484 assert!(
1485 body.contains(template),
1486 "{name} does not spell {template}, so this case proves nothing"
1487 );
1488 assert!(
1489 body.contains(from),
1490 "{name} does not contain the source binding {from:?}"
1491 );
1492 let before = spelling_values(body, "enable-tx-size-search");
1493 let mutated = body.replace(from, to);
1494 assert_ne!(
1495 mutated, body,
1496 "the mutation {from:?} -> {to:?} changed nothing"
1497 );
1498 let after = spelling_values(&mutated, "enable-tx-size-search");
1499 assert_eq!(
1500 before,
1501 BTreeSet::from(['0', '1']),
1502 "{name}: the unmutated body should resolve to both values, got {before:?}"
1503 );
1504 assert_eq!(
1505 after,
1506 BTreeSet::from(['0']),
1507 "{name}: mutating the bound value {from:?} -> {to:?} did not move the \
1508 classification (still {after:?}) -- the resolver is not reading the binding"
1509 );
1510 }
1511 // Direction 2: every gate the LITERAL reader already classified as
1512 // `=1` still is. Asserted as CONTAINMENT, not equality: a segment may
1513 // spell the flag twice (`=0` in the base recipe, `=1` as the per-arm
1514 // override), and the old reader took the last one while the resolver
1515 // takes the set. The claim being pinned is "still on", which is the
1516 // direction a regression would lose.
1517 let mut pinned = 0usize;
1518 for gate in &gates {
1519 if !gate.contains("\"--enable-tx-size-search=1\"") {
1520 continue;
1521 }
1522 pinned += 1;
1523 assert!(
1524 spelling_values(gate, "enable-tx-size-search").contains(&'1'),
1525 "a gate that literally spells --enable-tx-size-search=1 is no longer \
1526 classified on: {:?}",
1527 &gate[..gate.len().min(80)]
1528 );
1529 }
1530 assert!(
1531 pinned >= 10,
1532 "expected the literal `=1` gates to still be there, found {pinned}"
1533 );
1534 }
1535
1536 /// lane-av1oracleskip: the ORACLE-PRESENCE SCAN — the mechanical
1537 /// anti-regression for the skip class this lane closed.
1538 ///
1539 /// Why a scan and not a review rule: the r2 sweep found FIVE gates that
1540 /// had been added with the bare `if aomdec_path().is_file() { …compare… }`
1541 /// shape AFTER the first fix had already routed thirteen sites — every one
1542 /// of them compiled, passed review and reported green with the oracle
1543 /// compare silently skipped, under `EC_AV1_REQUIRE_AOMENC=1`. A guard
1544 /// written the old way re-opens the class the moment it merges, so the
1545 /// only thing that holds is a check that reads the source itself.
1546 ///
1547 /// The rule: a TOOL PRESENCE CHECK (`aomenc_path().is_file()`,
1548 /// `aomdec_path().is_file()`, `affine_aomenc_path().is_file()`, plain or
1549 /// `!…` inverted) may appear ONLY
1550 /// 1. inside the body of the probe that owns that path
1551 /// (`have_aomenc`, `aomdec_available`, `have_affine_aomenc`) — that
1552 /// is where the assert-last and the env escape live, and
1553 /// 2. inside an `assert!` (the deliberate hard-failure form), or
1554 /// 3. in a comment, which cannot execute.
1555 /// Anything else is a skip with no env escape, and the test fails naming
1556 /// the exact `file:line`.
1557 ///
1558 /// THE FLOOR. A source scan that matches nothing is the false-pass shape
1559 /// this crate has been bitten by twice (a `format!` brace escape, and
1560 /// `args.find(')')` stopping at the wrong paren), so the scan refuses to
1561 /// pass unless it actually inspected a plausible number of sites: the
1562 /// count is printed and asserted against `MIN_SITES`. A probe that moved
1563 /// out of the scan's reach, or a matcher broken by a rename, reds here
1564 /// instead of reporting a clean bill of health.
1565 #[test]
1566 fn no_tool_presence_check_outside_its_probe() {
1567 /// Below this, the scan is not looking at the tree it thinks it is.
1568 /// Five is the STRUCTURAL floor: three probes (whose existence the span
1569 /// assert below already pins) plus the two hard `assert!` sites. Doc
1570 /// comments mentioning the old shape come and go with the prose, so
1571 /// they are counted but never load-bearing here.
1572 const MIN_SITES: usize = 5;
1573 /// (file, the line that opens the probe owning that path)
1574 const PROBES: &[(&str, &str)] = &[
1575 ("stream.rs", "fn have_aomenc()"),
1576 ("stream.rs", "fn aomdec_available("),
1577 ("stream.rs", "fn have_affine_aomenc()"),
1578 ];
1579 const PATHS: &[&str] = &[
1580 "aomenc_path().is_file()",
1581 "aomdec_path().is_file()",
1582 "affine_aomenc_path().is_file()",
1583 ];
1584 let files: [(&str, &str); 3] = [
1585 ("stream.rs", crate::test_source::module_source("stream")),
1586 ("decode.rs", crate::test_source::module_source("decode")),
1587 ("encode.rs", crate::test_source::module_source("encode")),
1588 ];
1589
1590 // The line range each probe body owns: from its opener to the first
1591 // following line that closes it at column 0.
1592 let mut probe_spans: Vec<(usize, usize)> = Vec::new();
1593 for (name, src) in files {
1594 let lines: Vec<&str> = src.lines().collect();
1595 for (probe_file, opener) in PROBES {
1596 if *probe_file != name {
1597 continue;
1598 }
1599 let Some(start) = lines.iter().position(|l| l.contains(opener)).map(|i| i + 1)
1600 else {
1601 continue;
1602 };
1603 let end = lines
1604 .iter()
1605 .skip(start)
1606 .position(|l| l.trim_end() == "}")
1607 .map(|off| start + off)
1608 .unwrap_or(lines.len());
1609 probe_spans.push((start, end));
1610 }
1611 }
1612 assert!(
1613 probe_spans.len() == PROBES.len(),
1614 "the oracle-presence scan recognised {} of the {} probe bodies it is meant to \
1615 exempt ({probe_spans:?}); a renamed or moved probe would silently exempt every \
1616 site in the crate, so it reds here",
1617 probe_spans.len(),
1618 PROBES.len()
1619 );
1620
1621 let mut sites = 0usize;
1622 let mut allowed = 0usize;
1623 let mut per_pattern: BTreeMap<&str, usize> = PATHS.iter().map(|p| (*p, 0)).collect();
1624 let mut offenders: Vec<String> = Vec::new();
1625 for (name, src) in files {
1626 for (i, line) in src.lines().enumerate() {
1627 // LONGEST match wins: `affine_aomenc_path().is_file()` CONTAINS
1628 // `aomenc_path().is_file()`, so a first-match scan credits the
1629 // affine probe's line to the aomenc pattern and the per-pattern
1630 // floor below reds on a pattern that is very much present. (It
1631 // did, on the first run of this test — which is the floor
1632 // earning its place.)
1633 let Some(path) = PATHS
1634 .iter()
1635 .filter(|p| line.contains(**p))
1636 .max_by_key(|p| p.len())
1637 else {
1638 continue;
1639 };
1640 sites += 1;
1641 *per_pattern.get_mut(path).expect("pattern came from PATHS") += 1;
1642 let lineno = i + 1;
1643 let trimmed = line.trim_start();
1644 let in_probe = probe_spans
1645 .iter()
1646 .any(|(start, end)| lineno >= *start && lineno <= *end);
1647 let in_assert = trimmed.starts_with("assert!")
1648 || trimmed.starts_with("aomdec_path().is_file(),")
1649 || trimmed.starts_with("aomenc_path().is_file(),")
1650 || trimmed.starts_with("affine_aomenc_path().is_file(),");
1651 let in_comment = trimmed.starts_with("//");
1652 if in_probe || in_assert || in_comment {
1653 allowed += 1;
1654 } else {
1655 offenders.push(format!(
1656 "{name}:{lineno}: {}\n a tool presence check outside its probe — \
1657 route it through the probe that owns this path (`have_aomenc`, \
1658 `aomdec_available`, `have_affine_aomenc`): a bare `{path}` skips the \
1659 gate with NO env escape, so under EC_AV1_REQUIRE_AOMENC=1 the gate still \
1660 reports green with the oracle compare never run.",
1661 line.trim()
1662 ));
1663 }
1664 }
1665 }
1666 println!(
1667 "oracle-presence scan: {sites} site(s) inspected, {allowed} in a probe / assert / \
1668 comment, {} offender(s); per pattern {per_pattern:?}",
1669 offenders.len()
1670 );
1671 // PER-PATTERN floor: a total count can hide one broken matcher (mutate
1672 // ONE pattern and the other two still add up), so each of the three
1673 // path patterns must be found at least once -- which the probe bodies
1674 // guarantee, since each probe contains its own path's presence check.
1675 let never_matched: Vec<&str> = per_pattern
1676 .iter()
1677 .filter(|(_, n)| **n == 0)
1678 .map(|(p, _)| *p)
1679 .collect();
1680 assert!(
1681 never_matched.is_empty(),
1682 "the oracle-presence scan matched NOTHING for {never_matched:?}: that pattern is \
1683 stale (renamed helper, `exists()` instead of `is_file()`, a `format!` escape) and \
1684 the gates it was meant to police would pass unreviewed. Matched per pattern: \
1685 {per_pattern:?}"
1686 );
1687 assert!(
1688 sites >= MIN_SITES,
1689 "the oracle-presence scan inspected only {sites} site(s), below its floor of \
1690 {MIN_SITES}: the matcher has stopped matching this tree (renamed path helper, a \
1691 `format!` escape, a moved probe), and with no floor this would pass while scanning \
1692 nothing — the false-pass shape this crate has been bitten by twice"
1693 );
1694 assert!(
1695 offenders.is_empty(),
1696 "{} bare tool presence check(s) outside a probe — each one is a gate that can report \
1697 green without running the oracle compare:\n {}",
1698 offenders.len(),
1699 offenders.join("\n ")
1700 );
1701 }
1702}
1703
1704/// lane-av1pins5 r5: the PIN INVENTORY.
1705///
1706/// The r3 inventory this replaces matched only two call shapes --
1707/// `crate_pin("X")` and `pin_dir().join("X")` -- both SINGLE-NAME. A gate that
1708/// reads a whole DIRECTORY of pins through a `concat!` literal and then formats
1709/// a name at runtime (`format!("{fixtures}/{n}.obu")`) matched neither, so
1710/// `pinned_warp_stream_decodes_pixel_exact` and its 14 uncommitted pins were
1711/// invisible to it, and r3 reported "the machine-local-pin population is zero".
1712/// It was not. This enumerator resolves all four shapes.
1713///
1714/// Ownership, stated because two lanes touch this: THIS scanner owns the
1715/// ENUMERATION (which gates read which pins, from source). The fixture-preflight
1716/// lane owns the FILE INVENTORY on a runner (does each referenced path exist on
1717/// the box). Different questions; both must agree, and this one is the stricter of
1718/// the two because it fails on an uncommitted pin whether or not some runner
1719/// happens to have a copy.
1720#[cfg(test)]
1721mod pin_inventory {
1722 /// One pin a gate reads, and where it came from.
1723 pub struct PinRead {
1724 pub gate: String,
1725 pub file: String,
1726 pub shape: &'static str,
1727 }
1728
1729 /// Split `src` into `(fn_name, body)` for every `fn name(` at the gate indent.
1730 fn gate_bodies(src: &str) -> Vec<(String, &'static str)> {
1731 let mut out = Vec::new();
1732 let mut cur: Option<(String, usize)> = None;
1733 for (i, line) in src.lines().enumerate() {
1734 let t = line.trim_start();
1735 if let Some(rest) = t.strip_prefix("fn ")
1736 && let Some(name) = rest.split('(').next()
1737 && !name.contains(' ') {
1738 cur = Some((name.to_string(), i));
1739 }
1740 // A `#[test]`/`#[ignore]` line is never a closing brace, so the fn
1741 // ends at the first line that is exactly four-space `}`.
1742 if let Some((name, start)) = &cur
1743 && i > *start && line == " }" {
1744 let body = src
1745 .lines()
1746 .skip(*start)
1747 .take(i - *start + 1)
1748 .collect::<Vec<_>>()
1749 .join("\n");
1750 out.push((name.clone(), &*Box::leak(body.into_boxed_str())));
1751 cur = None;
1752 }
1753 }
1754 out
1755 }
1756
1757 /// Every pin every gate reads, across all four shapes.
1758 pub fn pins_read(src: &str) -> Vec<PinRead> {
1759 let mut out = Vec::new();
1760 for (gate, body) in gate_bodies(src) {
1761 // (a) crate_pin("X") and (b) pin_dir().join("X") -- single name.
1762 for m in body.match_indices("crate_pin(\"") {
1763 let rest = &body[m.0 + 11..];
1764 if let Some(e) = rest.find('"') {
1765 out.push(PinRead {
1766 gate: gate.clone(),
1767 file: rest[..e].to_string(),
1768 shape: "crate_pin",
1769 });
1770 }
1771 }
1772 for m in body.match_indices("pin_dir().join(\"") {
1773 let rest = &body[m.0 + 16..];
1774 if let Some(e) = rest.find('"') {
1775 out.push(PinRead {
1776 gate: gate.clone(),
1777 file: rest[..e].to_string(),
1778 shape: "pin_dir_machine_local",
1779 });
1780 }
1781 }
1782 // (c) a whole-file concat! literal to a named pin:
1783 // concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/X.obu")
1784 for m in body.match_indices("/../../fixtures/") {
1785 let rest = &body[m.0 + 16..];
1786 if let Some(e) = rest.find('"') {
1787 out.push(PinRead {
1788 gate: gate.clone(),
1789 file: rest[..e].to_string(),
1790 shape: "concat_literal_machine_local",
1791 });
1792 }
1793 }
1794 // (d) the shape that hid 14 pins: a DIRECTORY literal bound to a
1795 // local, plus a runtime `format!("{var}/{n}.ext")` over a
1796 // literal name array. Resolve the array's names.
1797 for (vi, line) in body.lines().enumerate() {
1798 let tl = line.trim();
1799 // `let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");`
1800 // -> the bound name is whatever sits between `let ` and the `=`.
1801 let var = match (
1802 tl.find("concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/../../fixtures\")"),
1803 tl.find('='),
1804 ) {
1805 (Some(a), Some(eq)) if eq < a => tl[4..eq].trim().to_string(),
1806 _ => continue,
1807 };
1808 if var.is_empty() {
1809 continue;
1810 }
1811 // `format!("{fixtures}/{n}.obu")` -- built by concatenation, not
1812 // by `format!`: escaping `{{`/`}}` to emit literal braces here is
1813 // exactly the bug that made this shape resolve to 0 pins on the
1814 // first run of the scanner.
1815 let marker = ["format!(\"", "{", &var, "}/{n}"].concat();
1816 let Some(pos) = body.find(&marker) else {
1817 continue;
1818 };
1819 // Walk back from the format! to the `[ ... ].iter()` array and
1820 // take every quoted name in it.
1821 let head = &body[..pos];
1822 let Some(bracket) = head.rfind('[') else {
1823 continue;
1824 };
1825 let names: Vec<String> = head[bracket..]
1826 .split('"')
1827 .skip(1)
1828 .step_by(2)
1829 .filter(|s| !s.is_empty() && !s.contains(' ') && *s != "]")
1830 .map(|s| s.to_string())
1831 .collect();
1832 // `.obu` -- SLICE up to the closing quote. (Stringifying the
1833 // `find` index instead produced names like `warp-mismatch4`.)
1834 let tail = &body[pos + marker.len()..];
1835 let ext = tail
1836 .find('"')
1837 .map(|e| tail[..e].to_string())
1838 .unwrap_or_default();
1839 for n in names {
1840 out.push(PinRead {
1841 gate: gate.clone(),
1842 file: format!("{n}{ext}"),
1843 shape: "concat_dir_runtime_name",
1844 });
1845 }
1846 let _ = vi;
1847 }
1848 // (e) the shape this very fix INTRODUCED:
1849 // `.map(|n| crate_pin(&format!("{n}.obu")))`. Rewriting the
1850 // directory literal as a committed-path lookup made the gate
1851 // correct and simultaneously invisible -- `crate_pin("` no
1852 // longer appears, so shape (a) found nothing and the
1853 // enumerator reported a CLEAN tree while 14 pins were read. A
1854 // false pass is worse than the original gap: the original at
1855 // least showed up in a filesystem audit. Caught here by the
1856 // `reads.len()` floor in the invariant test.
1857 for m in body.match_indices("crate_pin(&format!(") {
1858 let rest = &body[m.0 + 19..];
1859 let Some(close) = rest.find(')') else {
1860 continue;
1861 };
1862 let call = &rest[..close];
1863 if !call.contains('"') {
1864 continue;
1865 }
1866 let head = &body[..m.0];
1867 let Some(bracket) = head.rfind('[') else {
1868 continue;
1869 };
1870 let names: Vec<String> = head[bracket..]
1871 .split('"')
1872 .skip(1)
1873 .step_by(2)
1874 .filter(|x| !x.is_empty() && !x.contains(' ') && *x != "]")
1875 .map(|x| x.to_string())
1876 .collect();
1877 // the literal inside the format!, e.g. `{n}.obu`
1878 let lit = call.split('"').nth(1).unwrap_or("");
1879 let ext = lit
1880 .split_once("}")
1881 .map(|(_, e)| e.to_string())
1882 .unwrap_or_default();
1883 for n in names {
1884 out.push(PinRead {
1885 gate: gate.clone(),
1886 file: format!("{n}{ext}"),
1887 shape: "crate_pin_runtime_name",
1888 });
1889 }
1890 }
1891 }
1892 out
1893 }
1894
1895 /// Does this shape resolve through `crate_pin`, i.e. the COMMITTED
1896 /// crate-local copy? Both the literal form and the runtime-name form do --
1897 /// only the two `pin_dir`/root-`concat!` forms are machine-local.
1898 pub fn resolves_committed(shape: &str) -> bool {
1899 matches!(shape, "crate_pin" | "crate_pin_runtime_name")
1900 }
1901
1902 /// Is `file` present as a committed crate-local fixture?
1903 pub fn is_committed(file: &str) -> bool {
1904 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1905 .join("fixtures")
1906 .join(file)
1907 .is_file()
1908 }
1909}
1910
1911#[cfg(test)]
1912mod pin_inventory_tests {
1913 use super::pin_inventory::{is_committed, pins_read};
1914
1915 /// The scanner must be able to SEE the directory-literal shape. Run over a
1916 /// SYNTHETIC source, not the live tree: r5 removed that shape from
1917 /// `pinned_warp_stream_decodes_pixel_exact`, so a test that asserted it
1918 /// against the live file would rot the moment the fix landed -- which is
1919 /// precisely how a scanner loses its edge and reports a clean tree again.
1920 /// A capability test must have its own input.
1921 #[test]
1922 fn the_pin_scanner_sees_the_directory_literal_shape() {
1923 let synthetic = r#"
1924 #[test]
1925 fn a_gate_using_the_old_shape() {
1926 let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");
1927 let paths: Vec<String> = match std::env::var("EC_AV1_GATE_DUMP_PIN") {
1928 Ok(p) => vec![p],
1929 Err(_) => [
1930 "warp-mismatch",
1931 "ii-flake-1",
1932 "rect-flake-3",
1933 ]
1934 .iter()
1935 .map(|n| format!("{fixtures}/{n}.obu"))
1936 .collect(),
1937 };
1938 for path in paths {
1939 check(&path);
1940 }
1941 }
1942"#;
1943 let reads = pins_read(synthetic);
1944 let names: Vec<&str> = reads.iter().map(|r| r.file.as_str()).collect();
1945 assert_eq!(
1946 names,
1947 vec!["warp-mismatch.obu", "ii-flake-1.obu", "rect-flake-3.obu"],
1948 "the directory-literal + runtime-name shape resolved to {names:?} -- a scanner \
1949 that cannot see this shape is how 14 uncommitted pins survived three rounds"
1950 );
1951 assert!(
1952 reads.iter().all(|r| r.shape == "concat_dir_runtime_name"),
1953 "the synthetic pins were attributed to the wrong shape: {:?}",
1954 reads.iter().map(|r| r.shape).collect::<Vec<_>>()
1955 );
1956 }
1957
1958 /// The other three shapes resolve too -- same reasoning, same synthetic input,
1959 /// so the capability survives the tree being fixed.
1960 #[test]
1961 fn the_pin_scanner_sees_every_shape() {
1962 let synthetic = r#"
1963 #[test]
1964 fn shapes() {
1965 let a = crate_pin("golden3-pin.obu");
1966 let b = pin_dir().join("sbpart-pin.obu");
1967 let c = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/x.obu"));
1968 }
1969"#;
1970 let mut names: Vec<String> = pins_read(synthetic)
1971 .iter()
1972 .map(|r| format!("{}|{}", r.file, r.shape))
1973 .collect();
1974 names.sort();
1975 assert_eq!(
1976 names,
1977 vec![
1978 "golden3-pin.obu|crate_pin",
1979 "sbpart-pin.obu|pin_dir_machine_local",
1980 "x.obu|concat_literal_machine_local",
1981 ],
1982 "shape coverage changed: {names:?}"
1983 );
1984 }
1985
1986 /// THE INVARIANT, on the live tree: every pin a gate reads is a COMMITTED
1987 /// crate-local copy, and NO gate reads through a machine-local shape. This is
1988 /// the check the r3 manifest could not express.
1989 #[test]
1990 fn every_pin_a_gate_reads_is_committed_under_the_crate() {
1991 let src = crate::test_source::module_source("stream");
1992 let reads = pins_read(src);
1993 assert!(
1994 reads.len() >= 20,
1995 "the enumerator found only {} pin reads in stream.rs -- it has lost a shape, \
1996 which is the failure mode that let 14 pins go unseen",
1997 reads.len()
1998 );
1999 let uncommitted: Vec<String> = reads
2000 .iter()
2001 .filter(|r| !is_committed(&r.file))
2002 .map(|r| format!("{}:{} ({})", r.gate, r.file, r.shape))
2003 .collect();
2004 assert!(
2005 uncommitted.is_empty(),
2006 "{} pin(s) a gate reads have no committed copy under \
2007 crates/ec-av1/fixtures/ -- each resolves only on a machine whose \
2008 gitignored root fixtures/ happens to be populated, so a clean checkout \
2009 silently skips or panics:\n {}",
2010 uncommitted.len(),
2011 uncommitted.join("\n ")
2012 );
2013 let machine_local: Vec<String> = reads
2014 .iter()
2015 .filter(|r| !super::pin_inventory::resolves_committed(r.shape))
2016 .map(|r| format!("{} reads {} via {}", r.gate, r.file, r.shape))
2017 .collect();
2018 assert!(
2019 machine_local.is_empty(),
2020 "{} pin read(s) still resolve through a machine-local shape instead of \
2021 `crate_pin` (the committed crate-local copy), so they break on a clean \
2022 checkout:\n {}",
2023 machine_local.len(),
2024 machine_local.join("\n ")
2025 );
2026 }
2027}
2028
2029/// lane-av1pins5 r5: the COUNT-VACUITY enumerator.
2030///
2031/// Passing OUR OWN decode's length as the ORACLE's expected frame count
2032/// (`ffmpeg_decode_sequence(&stream, w, h, ours.len())`) is a real defect, but
2033/// NOT the one r4 claimed. MEASURED, by calling
2034/// `ffmpeg_decode_sequence(&stream, 192, 128, 0)` on a real pinned stream under
2035/// `catch_unwind`: it PANICS at `stream.rs:5110` with
2036/// `expected 0 4:2:0 frames, ffmpeg said: `. The helper asserts
2037/// `out.stdout.len() == frame_bytes * frames` unconditionally, so a wrong count
2038/// cannot pass silently -- it reds, with a message that blames FFMPEG for a
2039/// count OUR decoder chose.
2040///
2041/// TWO DEFECT CLASSES, DO NOT CONFLATE THEM (lane-av1pins5 r6):
2042/// * MISATTRIBUTED RED -- a wrong count reds, and the old message blamed
2043/// ffmpeg for a number OUR decoder chose. This is what these sites are.
2044/// `ffmpeg_decode_sequence`'s `stdout.len() == frame_bytes * frames` assert
2045/// is unconditional, so it cannot pass silently.
2046/// * SILENT PASS -- the compare is skipped or truncated and the gate reports
2047/// green. A DIFFERENT defect with a DIFFERENT fix, and r4 mislabelled these
2048/// sites as belonging to it. If you are reading this to decide what to fix,
2049/// fix the message and the count SOURCE; do not go looking for a silent pass.
2050///
2051/// r4 reported this shape as "a vacuous pass" and told Main so. That was wrong.
2052/// The consequence is a MISATTRIBUTED RED. The fix r4 shipped is still right (the
2053/// count now comes from the fixture, so the red names the real cause), but the
2054/// justification was wrong, and a sweep that repeats it would send the next
2055/// reader after a silent-pass bug that does not exist.
2056///
2057/// This enumerator finds every such site and classifies it, so the class is
2058/// visible and cannot shrink unnoticed.
2059#[cfg(test)]
2060mod count_vacuity {
2061 /// One oracle call whose expected frame count is locally derived.
2062 pub struct Site {
2063 pub line: usize,
2064 pub gate: String,
2065 pub count_expr: String,
2066 /// An independent count assertion on the same binding, within a few
2067 /// lines above: that is what makes the count a SPEC rather than a
2068 /// self-fulfilling number.
2069 pub pinned_by: Option<String>,
2070 /// Does this gate actually COMPARE PIXELS (so a wrong count would
2071 /// corrupt a verdict), or is it a report-only probe?
2072 pub pixel_comparing: bool,
2073 /// The fix bucket, by READING the gate (r7). `Some(b)` where
2074 /// a = pinned stream on disk -> take the count from the PIN
2075 /// b = live aomenc encode -> take it from the ENCODE's frame count;
2076 /// our decode's length is the thing
2077 /// UNDER TEST and must never be the
2078 /// expected value
2079 /// c = census/probe -> report only, never fix
2080 /// `None` = could not classify, and the reason is in `bucket_reason`.
2081 pub bucket: Option<&'static str>,
2082 pub bucket_reason: String,
2083 /// The numeric frame count found in this gate's own encode call, when
2084 /// one is visible -- the value the compare should assert instead.
2085 pub candidate: Option<String>,
2086 /// A frame count already in scope that is a SPEC rather than a
2087 /// self-fulfilling number -- e.g. the `FRAMES` the gate encoded, or a
2088 /// count asserted on the pinned stream. `Some(..)` means the fix is a
2089 /// one-line swap at this site.
2090 pub fixable_from: Option<String>,
2091 }
2092
2093 /// The scanner's matchers, as SINGLE-SOURCE tables.
2094 ///
2095 /// They are `pub const` rather than inline literals because the sweep's
2096 /// floor only catches a LOST shape; nothing caught a matcher that has
2097 /// never fired, so a dead spelling sat in this list advertising coverage
2098 /// the scan does not have (class: unexercised matcher in a source
2099 /// scanner). [`count_vacuity_tests::every_scanner_matcher_fires_on_a_known_site`]
2100 /// iterates THESE arrays, so a matcher cannot be added here without a
2101 /// positive control that has to pass. ///
2102 /// Oracle call spellings whose LAST argument is a locally derived count.
2103 /// `ffmpeg_decode_sequence_444(` fires on five real `stream.rs` gates
2104 /// (stream.rs:7030/7545/7735/8439/11643) but yields no count-vacuity SITE,
2105 /// because every one of those five passes the spec const `FRAMES` rather
2106 /// than a decode-derived `.len()`. It is live coverage, not a dead
2107 /// spelling, and the control below measures the spelling, not the site.
2108 pub const CALLEES: &[&str] = &[
2109 "ffmpeg_decode_sequence(",
2110 "ffmpeg_decode_sequence_10bit(",
2111 "ffmpeg_decode_sequence_444(",
2112 ];
2113
2114 /// Gate-name substrings that mark a census/probe/diagnostic gate: it
2115 /// reports, it does not assert a verdict. `"diagnostic"` was here and has
2116 /// no gate in the tree carrying it (and no other occurrence in the crate
2117 /// outside this list), so it was DELETED rather than kept: there is no
2118 /// hypothetical caller to name, and a probe that later wants that name
2119 /// re-adds one line here, where the control then holds it to firing.
2120 pub const PROBE_SUBSTRINGS: &[&str] =
2121 &["census", "probe", "sweep", "first_diff", "scratch", "rectx"];
2122
2123 /// Encode helpers a gate can drive INDIRECTLY. The r7 extraction found 21 of
2124 /// the 25 bucket-b gates encode through one of these, not through
2125 /// `aomenc_path()` directly -- which is why a first pass that only looked for
2126 /// `aomenc_path()` classified 6 gates "unclassified" that plainly encode.
2127 /// Six further names (`the_chroma_rect_gates`, `restore_gate`,
2128 /// `cdef_gate`, `superres_gate`, `grain_gate`, `sgate`) were here and
2129 /// matched no `fn` body in the tree; `grep -rn '\bNAME\b' crates/ec-av1/src`
2130 /// returns these six and NOTHING ELSE -- no helper, no caller, no comment
2131 /// naming them -- so they were rot and are DELETED, not kept with a
2132 /// hypothetical-caller note.
2133 pub const ENC_HELPERS: &[&str] = &[
2134 "encode_aomenc_stream",
2135 "screen_intrabc_stream_at_depth",
2136 "screen_intrabc_stream_with",
2137 "libaom_encode_with",
2138 "libaom_encode",
2139 "run_multi_tile_gate",
2140 "edge32_gate",
2141 "rect_tx_tool_gate",
2142 "warp_gate",
2143 ];
2144
2145 /// Frame-count bindings that are a SPEC rather than a self-fulfilling
2146 /// number. `NFRAMES` and `frames_expected` were here, matched no `fn`
2147 /// body, and appear nowhere else in the crate -- DELETED as rot.
2148 pub const FIXABLE_CANDS: &[&str] = &["FRAMES", "frame_count"];
2149
2150 /// How many lines above a count site an `assert(..)` on the same binding
2151 /// may sit and still call the count spec-pinned. A single-sourced const so
2152 /// the control below can hold the WINDOW itself to being the window the
2153 /// sweep walks (a window widened to EOF would pin sites it never pinned).
2154 pub const PIN_WINDOW: usize = 14;
2155
2156 /// The bucket-(b) leaf: a gate that drives aomenc directly rather than
2157 /// through [`ENC_HELPERS`].
2158 pub const AOMENC_LEAF: &str = "aomenc_path()";
2159
2160 /// The bucket-(a) leaves: a gate that reads its stream from disk.
2161 pub const DISK_READ_LEAVES: &[&str] = &["fs::read", "crate_pin"];
2162
2163 /// A census/probe/diagnostic gate: it reports, it does not assert a verdict.
2164 fn is_probe(gate: &str) -> bool {
2165 PROBE_SUBSTRINGS.iter().any(|m| gate.contains(m))
2166 }
2167
2168 /// Encode helpers a gate can drive INDIRECTLY -- see [`ENC_HELPERS`].
2169 fn enc_helpers(body: &str) -> Vec<&'static str> {
2170 ENC_HELPERS
2171 .iter()
2172 .copied()
2173 .filter(|n| body.contains(&format!("{n}(")))
2174 .collect()
2175 }
2176
2177 /// End byte of the `fn` body starting at `fn_start`: a STRING- and
2178 /// line-comment-aware brace walk (the trap it dodges is recorded at the
2179 /// call site). Extracted so the matchers' positive-control test walks the
2180 /// EXACT slice the scanner classifies -- a control that re-implemented the
2181 /// walk would be measuring a different thing than the guard (class
2182 /// control-and-measurement-drift).
2183 pub fn fn_body_end(src: &str, fn_start: usize) -> usize {
2184 let bytes = src.as_bytes();
2185 let mut depth = 0i32;
2186 let mut started = false;
2187 let mut fn_end = src.len();
2188 let mut in_str = false;
2189 let mut in_line_comment = false;
2190 let mut k = fn_start;
2191 while k < bytes.len() {
2192 let c = bytes[k];
2193 if in_line_comment {
2194 if c == b'\n' {
2195 in_line_comment = false;
2196 }
2197 k += 1;
2198 continue;
2199 }
2200 if in_str {
2201 if c == b'\\' {
2202 k += 2;
2203 continue;
2204 }
2205 if c == b'"' {
2206 in_str = false;
2207 }
2208 k += 1;
2209 continue;
2210 }
2211 match c {
2212 b'"' => in_str = true,
2213 b'/' if bytes.get(k + 1) == Some(&b'/') => {
2214 in_line_comment = true;
2215 k += 1;
2216 }
2217 b'{' => {
2218 depth += 1;
2219 started = true;
2220 }
2221 b'}' => {
2222 depth -= 1;
2223 if started && depth == 0 {
2224 fn_end = k + 1;
2225 break;
2226 }
2227 }
2228 _ => {}
2229 }
2230 k += 1;
2231 }
2232 fn_end
2233 }
2234
2235 /// `(fn name, body slice)` for every top-level `fn` in `src`, attributed
2236 /// the way [`sites`] attributes a site to its gate.
2237 pub fn fn_slices(src: &str) -> Vec<(String, &str)> {
2238 let lines: Vec<&str> = src.lines().collect();
2239 let mut offsets: Vec<usize> = Vec::with_capacity(lines.len());
2240 {
2241 let mut o = 0usize;
2242 for l in &lines {
2243 offsets.push(o);
2244 o += l.len() + 1;
2245 }
2246 }
2247 let mut out: Vec<(String, &str)> = Vec::new();
2248 for (i, line) in lines.iter().enumerate() {
2249 let t = line.trim_start();
2250 let Some(rest) = t.strip_prefix("fn ") else {
2251 continue;
2252 };
2253 let Some(nm) = rest.split('(').next() else {
2254 continue;
2255 };
2256 if nm.contains(' ') {
2257 continue;
2258 }
2259 let at = offsets[i];
2260 let end = fn_body_end(src, at);
2261 out.push((nm.to_string(), &src[at..end]));
2262 }
2263 out
2264 }
2265
2266 pub fn sites(src: &str) -> Vec<Site> {
2267 let mut out = Vec::new();
2268 let lines: Vec<&str> = src.lines().collect();
2269 // LINE index -> BYTE offset. The body walk indexes `src.as_bytes()`, so
2270 // handing it a line number walks from the wrong place entirely and every
2271 // body-dependent classification reads "unclassified". Same bug I hit in
2272 // the Python classifier one step earlier.
2273 let mut offsets: Vec<usize> = Vec::with_capacity(lines.len());
2274 {
2275 let mut o = 0usize;
2276 for l in &lines {
2277 offsets.push(o);
2278 o += l.len() + 1;
2279 }
2280 }
2281 let mut gate = String::new();
2282 let mut fn_start = 0usize;
2283 for (i, line) in lines.iter().enumerate() {
2284 let t = line.trim_start();
2285 if let Some(rest) = t.strip_prefix("fn ")
2286 && let Some(n) = rest.split('(').next()
2287 && !n.contains(' ') {
2288 gate = n.to_string();
2289 fn_start = offsets[i];
2290 }
2291 // A DOC COMMENT is prose about code, not code. One row in the ledger
2292 // was a `///` line quoting a gate's pre-fix body (`stream.rs:30924`,
2293 // inside `pinned_lr_sgr_stream_call_unique_dump`) and the sweep
2294 // counted it as an unpinned count site for a whole round: the gate
2295 // it describes already spends `FRAMES` and asserts
2296 // `pics.len() == FRAMES`. Skipping comment lines is not cosmetic --
2297 // without it the ledger carries a row no reader can act on, and the
2298 // ceiling can never reach 0.
2299 //
2300 // Only the SITE scan skips comments. The pin-window walk further
2301 // down still sees every line, because a `//`-led line there is a
2302 // comment BETWEEN the assert and the call, not a site.
2303 if t.starts_with("//") {
2304 continue;
2305 }
2306 for callee in CALLEES {
2307 let Some(at) = line.find(callee) else {
2308 continue;
2309 };
2310 let args = &line[at + callee.len()..];
2311 // DEPTH-AWARE close: `args.find(')')` stops at the `)` of
2312 // `pictures.len()` and truncates the arg list mid-expression,
2313 // which silently yielded zero sites on the first run.
2314 let mut depth = 1usize;
2315 let mut close = None;
2316 for (k, ch) in args.char_indices() {
2317 match ch {
2318 '(' => depth += 1,
2319 ')' => {
2320 depth -= 1;
2321 if depth == 0 {
2322 close = Some(k);
2323 break;
2324 }
2325 }
2326 _ => {}
2327 }
2328 }
2329 let Some(close) = close else { continue };
2330 let arglist = &args[..close];
2331 let last = arglist.rsplit(',').next().unwrap_or("").trim();
2332 if !(last.ends_with(".len()") || last.ends_with(".count()")) {
2333 continue;
2334 }
2335 // Is the SAME binding count-asserted against a literal/const
2336 // within the preceding 12 lines? That is the difference between
2337 // a spec and a self-fulfilling number.
2338 let binding = last.trim_end_matches(".len()").trim_end_matches(".count()");
2339 // Match the assertion across a LINE BREAK: rustfmt puts
2340 // assert_eq!(
2341 // frames.len(),
2342 // so requiring `assert_eq!(frames.len()` on one line missed
2343 // every multi-line spelling and inflated the unpinned count.
2344 let want = format!("{binding}.len()");
2345 let mut pinned = None;
2346 for back in 1..=PIN_WINDOW {
2347 if i < back {
2348 break;
2349 }
2350 let prev = lines[i - back].trim_start();
2351 if !prev.starts_with("assert") || !prev.contains('(') {
2352 continue;
2353 }
2354 // rustfmt splits `assert_eq!(` from its first argument, so
2355 // the binding is on THIS line or the NEXT one.
2356 let here = prev.contains(&want);
2357 let next = lines
2358 .get(i - back + 1)
2359 .map(|l| l.trim_start().contains(&want))
2360 .unwrap_or(false);
2361 if here || next {
2362 pinned = Some(prev.chars().take(60).collect());
2363 break;
2364 }
2365 }
2366 // Pixel-comparing? A gate that compares planes is the only
2367 // place a wrong count corrupts a verdict; a report-only probe
2368 // just prints.
2369 // Bound to THIS fn only. Slicing to EOF matched a later gate's
2370 // `const FRAMES` and its `assert_eq!(got.y`, which reported all
2371 // 48 sites as pixel-comparing with a spec in scope -- the same
2372 // over-broad-scope bug the class keeps teaching.
2373 // Brace-depth walk, not `find("\n }")`: a gate with an
2374 // early 4-space `}` (a bare block, a `match` arm tail) truncated
2375 // the slice and made the compare-detection read false.
2376 // STRING-AWARE brace walk. Counting raw bytes counts a `}`
2377 // inside a format string as a closing brace, which truncated the
2378 // body and made every compare-detection read false -- the same
2379 // trap that made stream.rs look 2 braces short in the first
2380 // review of this wave.
2381 let fn_end = fn_body_end(src, fn_start);
2382 let body = &src[fn_start..fn_end];
2383 // APPROXIMATE, and known to be so: the body slice is a
2384 // hand-rolled brace walk, and this crate's compare idioms vary
2385 // enough that the column under-reports. The LINE, GATE and
2386 // COUNT EXPR columns are exact (line-based scan, no body
2387 // slicing); treat `pixel_comparing` as a hint, not a verdict.
2388 // Idiom-tolerant: this crate spells the compare every which way
2389 // (`assert_eq!(got.y, want.y)`, `assert_eq!(g, w)`,
2390 // `let ok = ours.y == ref_f.y`, `ours.y, want.y`), so match the
2391 // PLANE inside an assertion, not one fixed spelling.
2392 let pixel_comparing = body.contains("assert")
2393 && (body.contains(".y,")
2394 || body.contains(".y ==")
2395 || body.contains(".y)")
2396 || body.contains("vs ffmpeg"));
2397 // A SPEC already in scope for this gate?
2398 let mut fixable = None;
2399 for cand in FIXABLE_CANDS {
2400 if body.contains(&format!("const {cand}"))
2401 || body.contains(&format!("let {cand}"))
2402 {
2403 fixable = Some(cand.to_string());
2404 break;
2405 }
2406 }
2407 // Bucket by READING the gate. A census/probe reports and never
2408 // asserts, so its count is not a verdict and is left alone. A
2409 // gate that drives aomenc takes the count from the ENCODE -- our
2410 // decode's length is what is under test, so using it as the
2411 // expected value is circular. A gate that reads a stream from
2412 // disk takes it from that stream.
2413 // The candidate fix: the numeric frame count in this gate's own
2414 // encode call. For bucket (b) that number IS the encoder's frame
2415 // count, so it is the spec the compare should assert.
2416 let candidate = enc_helpers(body).first().and_then(|h| {
2417 let at = body.find(&format!("{h}("))?;
2418 let open = at + h.len() + 1;
2419 let seg = &body[open..(open + 400).min(body.len())];
2420 let close = seg.find(';')?;
2421 let nums: Vec<&str> = seg[..close]
2422 .split(',')
2423 .map(|x| x.trim())
2424 .filter(|x| !x.is_empty() && x.chars().all(|c| c.is_ascii_digit()))
2425 .collect();
2426 nums.last().map(|x| x.to_string())
2427 });
2428 let (bucket, bucket_reason) = if is_probe(&gate) {
2429 (
2430 Some("c"),
2431 "census/probe: reports, does not assert a verdict".to_string(),
2432 )
2433 } else if body.contains(AOMENC_LEAF) || !enc_helpers(body).is_empty() {
2434 (
2435 Some("b"),
2436 "live aomenc encode: count belongs to the encoder".to_string(),
2437 )
2438 } else if DISK_READ_LEAVES.iter().any(|leaf| body.contains(leaf)) {
2439 (
2440 Some("a"),
2441 "stream read from disk: count belongs to the pin".to_string(),
2442 )
2443 } else {
2444 (
2445 None,
2446 "unclassified: no aomenc drive, no disk read, and not a probe -- \
2447 needs a reader"
2448 .to_string(),
2449 )
2450 };
2451 out.push(Site {
2452 line: i + 1,
2453 gate: gate.clone(),
2454 count_expr: last.to_string(),
2455 pinned_by: pinned,
2456 pixel_comparing,
2457 fixable_from: fixable,
2458 bucket,
2459 bucket_reason,
2460 candidate,
2461 });
2462 }
2463 }
2464 out
2465 }
2466
2467 /// Every matcher's POSITIVE CONTROL: each spelling in this module's tables
2468 /// must fire on at least one real thing in the scanned source, or the
2469 /// spelling is advertising coverage the scan does not have.
2470 ///
2471 /// This is the missing half of the sweep's own floor. `s.len() >= 40` and
2472 /// the unpinned ceiling both catch a LOST shape; nothing caught a matcher
2473 /// that never fired -- which is how six encode-helper names, two spec
2474 /// binding names and one probe substring sat in these tables matching
2475 /// nothing anywhere in the crate (class: unexercised matcher in a source
2476 /// scanner). Those nine are deleted. The control reads the SAME `const`
2477 /// tables the scanner reads, so a matcher added later cannot skip it.
2478 ///
2479 /// `fn_slices` walks the same `fn_body_end` the scanner classifies with, so
2480 /// "fires" means fires on the slice the guard actually reads.
2481 #[test]
2482 fn every_scanner_matcher_fires_on_a_known_site() {
2483 let src = crate::test_source::module_source("stream");
2484 let lines: Vec<&str> = src.lines().collect();
2485 let fns = fn_slices(src);
2486
2487 // The callee list, as a SPELLING. Not as a produced site: the
2488 // `_444` spelling fires on five real gates that all pass the spec
2489 // const `FRAMES`, so it correctly yields no count-vacuity site. A
2490 // spelling that no `stream.rs` line uses is a spelling that has
2491 // stopped being written and is now dead weight in the table.
2492 for callee in CALLEES {
2493 let hits = lines.iter().filter(|l| l.contains(callee)).count();
2494 assert!(
2495 hits > 0,
2496 "the callee matcher `{callee}` fires on NO line of stream.rs -- it is dead \
2497 coverage: either a gate stopped using that spelling (drop the entry) or a \
2498 new one is expected to (add the call site first, not the matcher)"
2499 );
2500 }
2501
2502 // The gate-name probe substrings, against real fn names.
2503 for sub in PROBE_SUBSTRINGS {
2504 let hits = fns.iter().filter(|(g, _)| g.contains(sub)).count();
2505 assert!(
2506 hits > 0,
2507 "the probe substring `{sub}` matches NO fn name in stream.rs -- bucket (c) is \
2508 unpopulated and the substring is dead weight"
2509 );
2510 }
2511
2512 // The indirect-encode helpers, against real fn BODIES.
2513 for helper in ENC_HELPERS {
2514 let hits = fns
2515 .iter()
2516 .filter(|(_, b)| b.contains(&format!("{helper}(")))
2517 .count();
2518 assert!(
2519 hits > 0,
2520 "the encode-helper matcher `{helper}(` matches NO fn body in stream.rs -- it is \
2521 dead coverage (grep the crate: if the helper has no caller, delete the entry; if \
2522 it has a caller outside stream.rs, say so here and name the file)"
2523 );
2524 }
2525
2526 // The spec-binding candidates, against real fn BODIES.
2527 for cand in FIXABLE_CANDS {
2528 let hits = fns
2529 .iter()
2530 .filter(|(_, b)| {
2531 b.contains(&format!("const {cand}")) || b.contains(&format!("let {cand}"))
2532 })
2533 .count();
2534 assert!(
2535 hits > 0,
2536 "the spec-binding matcher `{cand}` matches NO fn body in stream.rs -- `fixable_from` \
2537 can never name it, so it is dead coverage"
2538 );
2539 }
2540
2541 // The two bucket leaves the classifier short-circuits on.
2542 assert!(
2543 fns.iter().any(|(_, b)| b.contains(AOMENC_LEAF)),
2544 "no fn body in stream.rs calls `{AOMENC_LEAF}`, so the bucket-(b) direct-encode leaf \
2545 never fires"
2546 );
2547 for leaf in DISK_READ_LEAVES {
2548 let hits = fns.iter().filter(|(_, b)| b.contains(leaf)).count();
2549 assert!(
2550 hits > 0,
2551 "the disk-read leaf `{leaf}` matches NO fn body in stream.rs -- bucket (a) is \
2552 unpopulated by that spelling"
2553 );
2554 }
2555
2556 // The pin window is a matcher too: a window so wide it pinned
2557 // everything, or so narrow it pinned nothing, would leave the
2558 // ceiling reading a population it no longer describes.
2559 let s = sites(src);
2560 let pinned = s.iter().filter(|x| x.pinned_by.is_some()).count();
2561 assert!(
2562 PIN_WINDOW > 0 && pinned > 0,
2563 "PIN_WINDOW={PIN_WINDOW} pins {pinned} of {} site(s) -- the window must be the one \
2564 the sweep walks and must still pin at least one site",
2565 s.len()
2566 );
2567 }
2568}
2569
2570#[cfg(test)]
2571mod count_vacuity_tests {
2572 use super::count_vacuity::sites;
2573
2574 /// The shape is real and widespread; this pins the FLOOR so the sweep cannot
2575 /// silently stop finding sites. Measured count is well above this.
2576 #[test]
2577 fn the_count_vacuity_sweep_finds_the_known_sites() {
2578 let src = crate::test_source::module_source("stream");
2579 let s = sites(src);
2580 assert!(
2581 s.len() >= 40,
2582 "the count-vacuity sweep found only {} site(s); expected 40+ -- it has lost a \
2583 shape",
2584 s.len()
2585 );
2586 // r7: the first reported site (3895, `pictures.len()`) is FIXED -- it now
2587 // asserts `ENCODED_FRAMES`, the encode's own count. The anchor therefore
2588 // moved from "the site is still there" to "the fix is still in place AND
2589 // the dominant remaining shape is still found", so the sweep cannot go
2590 // quiet by either route.
2591 // The GENERAL rule, not the one literal r7 fixed. Every decode-derived
2592 // count expression is banned at the gate r7 fixed, so a future edit that
2593 // reintroduces the shape under a different binding name is caught, and so
2594 // the guard does not go quiet as the OTHER sites are fixed later.
2595 const DECODE_DERIVED: &[&str] = &["pictures.len()", "decoded.len()", "frames.len()"];
2596 assert!(
2597 !s.iter().any(|x| x.gate
2598 == "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact"
2599 && DECODE_DERIVED.contains(&x.count_expr.as_str())),
2600 "the r7 fix regressed: {} is passing a decode-derived count as the oracle's \
2601 expected count again -- our decode's length is the thing UNDER TEST and \
2602 must never be the expected value",
2603 "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact"
2604 );
2605 // A CEILING on the unpinned population, so a NEW site cannot be added
2606 // silently. Lower it as sites are fixed; a fix that does not lower it is
2607 // still a fix, but a NEW site is an immediate red.
2608 //
2609 // lane-av1pinspec: 43 -> 2. Each of the 41 fixes adds the ENCODE's own
2610 // frame count as an `assert_eq!` ABOVE the `ffmpeg_decode_sequence*`
2611 // call (`-frames:v 1` / `-vframes 1` / `--limit=N` / a helper's `frames`
2612 // parameter / the arm tuple's `frame_count` / the wire's own OBU frame
2613 // headers), so the count handed to the oracle is a value already proven
2614 // against the encode instead of read off our decode. Two rows survived
2615 // that round; lane-av1pinspec2 closed both, so the ceiling is now 0.
2616 //
2617 // lane-av1pinspec2: 2 -> 0, in two steps.
2618 // * `an_svt_screen_palette_block_with_a_split_transform_decodes_exactly`
2619 // was handed forward because the count was underivable: the stream
2620 // came from `EC_AV1_SVT1_STREAM`, was never committed, and the gate
2621 // SKIPped on a stock box -- so a wire-derived assert would have been
2622 // an unexercised assert wearing a pin's clothes. The crop is now
2623 // COMMITTED (`fixtures/svt1-split-tx-pin.obu`, a byte-reproducible
2624 // replay of a `-frames:v 1` libsvtav1 encode), the gate reads it, and
2625 // its count comes from the stream's own OBU frame headers with
2626 // `show_existing_frame` asserted false so a header count cannot
2627 // over-count. The gate runs on a stock box, so the assert executes.
2628 // * the other row was a `///` DOC COMMENT quoting the pre-r4 body of
2629 // `pinned_lr_sgr_stream_call_unique_dump`, which this line-based
2630 // scan could not tell from code. `sites()` now skips comment lines,
2631 // so the row is no longer a site at all.
2632 //
2633 // RED-BEFORE for the comment skip, which is a coverage change and not a
2634 // cosmetic one: with the `t.starts_with("//")` guard removed and this
2635 // ceiling at 0, the doc-comment row comes BACK as an unpinned site and
2636 // reds with "1 unpinned count site(s), ceiling is 0".
2637 const UNPINNED_CEILING: usize = 0;
2638 let unpinned = s.iter().filter(|x| x.pinned_by.is_none()).count();
2639 // The ceiling is deliberately 0 today; it stays a ceiling so a site can be grandfathered by raising it.
2640 #[allow(clippy::absurd_extreme_comparisons)]
2641 let within_ceiling = unpinned <= UNPINNED_CEILING;
2642 assert!(
2643 within_ceiling,
2644 "{unpinned} unpinned count site(s), ceiling is {UNPINNED_CEILING} -- a new one \
2645 was added (lower the ceiling only when a site is actually fixed)"
2646 );
2647 assert!(
2648 s.iter().any(|x| x.count_expr == "frames.len()"),
2649 "the dominant `frames.len()` shape is no longer found -- the sweep has lost a \
2650 shape, not gained a fix"
2651 );
2652 }
2653
2654 /// Report, per site: does the count come from a SPEC or from our own decode?
2655 /// Prints the table the r5 report carries. The assertion is the FLOOR above,
2656 /// not "zero unpinned" -- the residual unpinned sites are handed to another
2657 /// lane with this table, and forcing them all here would be an unbounded
2658 /// change dressed as a fix.
2659 #[test]
2660 fn every_locally_derived_oracle_count_is_reported() {
2661 let src = crate::test_source::module_source("stream");
2662 let s = sites(src);
2663 let unpinned: Vec<String> = s
2664 .iter()
2665 .filter(|x| x.pinned_by.is_none())
2666 .map(|x| {
2667 format!(
2668 "stream.rs:{} | {} | {} | NOT SPEC-PINNED",
2669 x.line, x.gate, x.count_expr
2670 )
2671 })
2672 .collect();
2673 let pinned = s.len() - unpinned.len();
2674 eprintln!(
2675 "count-vacuity sweep: {} site(s); {} spec-pinned by a prior assert, {} not",
2676 s.len(),
2677 pinned,
2678 unpinned.len()
2679 );
2680 for line in unpinned.iter() {
2681 eprintln!(" {line}");
2682 }
2683 // The table Main asked for, as columns the guard itself computes.
2684 for x in s.iter().filter(|x| x.pinned_by.is_none()) {
2685 eprintln!(
2686 "ROW {} | {} | {} | bucket={} | candidate={} | spec_in_scope={} | {} | \
2687 pixel_comparing={}",
2688 x.line,
2689 x.gate,
2690 x.count_expr,
2691 x.bucket.unwrap_or("?"),
2692 x.candidate.clone().unwrap_or_else(|| "-".into()),
2693 x.fixable_from.clone().unwrap_or_else(|| "-".into()),
2694 x.bucket_reason,
2695 x.pixel_comparing
2696 );
2697 }
2698 assert!(
2699 !s.is_empty() && s.iter().all(|x| !x.gate.is_empty()),
2700 "a site has no owning gate -- the sweep's gate attribution is broken"
2701 );
2702 }
2703
2704 /// The comment skip is a COVERAGE change, so it is held to the same shape
2705 /// the `pin_inventory` capability tests use: a SYNTHETIC source, not the
2706 /// live tree, with BOTH halves. Run against the live tree instead, a fix
2707 /// to the very gate that motivated it would delete the row that proves the
2708 /// scanner still works -- the failure mode `pin_inventory` already records
2709 /// as "a scanner that cannot see this shape is how 14 pins survived three
2710 /// rounds".
2711 ///
2712 /// Half one: a count call that lives INSIDE a doc comment must not be a
2713 /// site. That is the real `stream.rs:30924` row, which spent a whole round
2714 /// in the ledger as an unpinned count no reader could act on -- the gate it
2715 /// quotes already spends `FRAMES` and asserts `pics.len() == FRAMES`.
2716 ///
2717 /// Half two, the control: the SAME call as real code must still be a site,
2718 /// and must still be pinned by an assert above it. A scanner that skips
2719 /// comments by skipping the wrong thing looks identical on half one, and a
2720 /// ceiling of 0 is exactly the state where an over-broad skip would go
2721 /// unnoticed.
2722 #[test]
2723 fn a_doc_commented_count_call_is_not_a_site_but_real_code_still_is() {
2724 let commented = r#"
2725 /// The old body passed the wrong count to the oracle:
2726 /// let reference = ffmpeg_decode_sequence(&stream, 192, 128, pics.len());
2727 /// so a decoder that emitted zero frames asked ffmpeg for zero frames.
2728 fn a_gate_whose_doc_comment_quotes_the_old_body() {
2729 let pics = decode_stream(&data).unwrap();
2730 }
2731"#;
2732 let commented_sites = sites(commented);
2733 assert!(
2734 commented_sites.is_empty(),
2735 "a count call inside a `///` doc comment was counted as a site: {:?} -- a line-based \
2736 scan cannot tell prose from code, and this row is why it now skips comment lines",
2737 commented_sites
2738 .iter()
2739 .map(|x| (x.line, x.count_expr.clone()))
2740 .collect::<Vec<_>>()
2741 );
2742
2743 let real = r#"
2744 fn a_gate_that_really_spends_its_own_decode_length() {
2745 let pics = decode_stream(&data).unwrap();
2746 assert_eq!(pics.len(), 7, "{NAME}: expected seven key frames");
2747 let reference = ffmpeg_decode_sequence(&stream, 192, 128, pics.len());
2748 }
2749"#;
2750 let found = sites(real);
2751 assert_eq!(
2752 found.len(),
2753 1,
2754 "the control did not find its one real site: {:?} -- the comment skip is over-broad \
2755 if the same call is skipped as code",
2756 found
2757 .iter()
2758 .map(|x| (x.line, x.count_expr.clone(), x.gate.clone()))
2759 .collect::<Vec<_>>()
2760 );
2761 assert_eq!(
2762 found[0].count_expr, "pics.len()",
2763 "control: wrong count expr"
2764 );
2765 assert_eq!(
2766 found[0].gate, "a_gate_that_really_spends_its_own_decode_length",
2767 "control: wrong gate attribution"
2768 );
2769 assert!(
2770 found[0].pinned_by.is_some(),
2771 "the control's site is UNPINNED: the comment skip changed the pin window too, \
2772 because a `//` line between an assert and its call is still walked"
2773 );
2774 }
2775}