forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

stack_budget.rs748 lines, 34.5 KiBHistoryRawDownload
1#![cfg(test)]
2//! A measured bound on the crate's BY-VALUE types, and a gate that bites.
3//!
4//! # The class
5//!
6//! A large struct returned BY VALUE from a public constructor is a stack
7//! cost, not a heap cost, and the cost is paid by the CALLER. The
8//! constructors nest, and in an unoptimized build each level materialises
9//! its whole `Result<T>` return slot before the inner call returns. So one
10//! value's `size_of` is the MULTIPLIER, and the chain length is the other
11//! factor.
12//!
13//! That is not hypothetical. `Decoder` was **10,944** bytes by value --
14//! five INLINE `FrameContext` slots (2,039 bytes each: the `frame_ctxs`
15//! array of four, plus the `ctx` in force) -- and 10,944 is **1.34x** this
16//! crate's 8 KiB by-value budget. Boxing both fields
17//! (`frame_ctxs: Box<[FrameContext; 4]>` and `ctx: Box<FrameContext>`) took
18//! it to **768**, and [`the_frame_contexts_stay_behind_a_box`] is the pin
19//! that keeps it there.
20//!
21//! # Why this module exists
22//!
23//! One boxed field is one measurement. This module is the sweep:
24//!
25//! 1. [`BY_VALUE_TYPES`] is the inventory -- every type in this crate a
26//! public `fn` can return by value, with a measured `size_of` recorded
27//! as of this commit. [`the_measured_inventory_is_accurate`] fails if a
28//! type's size moves, so the table cannot rot into stale small numbers.
29//! 2. [`STACK_BUDGET`] is the bound, and
30//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for
31//! every public row, so a regression reds naming the type.
32//! 3. [`the_frame_contexts_stay_behind_a_box`] pins the boxed field, with
33//! a negative control so the pin cannot be matching a comment.
34//! 4. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the
35//! capability arm: it really constructs `Decoder` on a deliberately
36//! tight thread and asserts real post-construction state, pinning the
37//! measured live stack of the by-value return path. At 256 KiB it does
38//! NOT red the unboxing mutation -- a 10,944-byte struct is not that
39//! expensive; the budget assert and the box pin are what red, BY NAME.
40//! The arm's own docs carry the measured threshold table.
41//! 5. [`every_by_value_public_return_is_in_the_inventory`] re-derives the
42//! set of by-value public returns from the crate source.
43//! [`the_inventory_scan_is_not_vacuous`] is its control.
44//!
45//! # The bound, and why this number
46//!
47//! [`STACK_BUDGET`] = 8192 bytes (8 KiB) -- the SAME number as ec-av1's,
48//! deliberately, so one bound covers the by-value class across the codec
49//! crates rather than each crate calibrating its own.
50//!
51//! **The quantity being bounded.** Not `size_of` in the abstract, but
52//! *what a caller can be made to owe*: the size of one by-value return,
53//! multiplied by how many public levels hold a copy at once. Three inputs:
54//! 1. **The smallest stack a caller can hand this crate is 2 MiB.** That
55//! is libtest's default test thread and what `std::thread::Builder`
56//! hands a caller who does not ask for a size. A library consumer gets
57//! no `.cargo/config.toml` -- and this repo's sets
58//! `RUST_MIN_STACK = 67108864`, which HIDES the problem from this
59//! workspace's own runs. The bound is therefore derived against the
60//! 2 MiB an unconfigured caller really has.
61//! 2. **The deepest PUBLIC by-value chain is 3**
62//! ([`DEEPEST_PUBLIC_CHAIN`]): `stream::decode_stream` (stream.rs:74)
63//! -> `stream::decode_stream_with` (stream.rs:88) ->
64//! `Decoder::decode` (decode.rs:238), after which the remaining frames
65//! (`decode_one`, `decode_keyframe`, `decode_inter`) are private. The
66//! test asserts `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB` -- the
67//! by-value return slots may claim at most an EIGHTH of a caller's
68//! stack, leaving the rest for the decode walk, which is the thing that
69//! actually needs it.
70//! 3. **The budget applies only to types a `pub fn` returns.** The
71//! crate-private 2,039-byte `FrameContext` is measured and listed but
72//! NOT bounded, because no caller can reach it by value -- every field
73//! holding one is a `Box`, pinned by
74//! [`the_frame_contexts_stay_behind_a_box`]. Bounding it would
75//! calibrate the number to something unreachable.
76//!
77//! **Where the number sits.** At 8 KiB with the worst public return at
78//! 768 bytes ([`Decoder`]), the worst a caller owes on return slots
79//! alone is `3 x 768 = 2,304` bytes -- 0.11% of a 2 MiB thread, and the
80//! budget itself is 10.7x the largest live by-value type. Both directions
81//! have room, which is the point: a bound the largest type sits just
82//! under is a bound the next lane will quietly raise.
83//!
84//! **What it catches.** The pre-fix `Decoder` (10,944 B) is **1.34x over**
85//! -- the SMALLEST over-budget case of the three crates this sweep has
86//! measured (ec-av1's pre-fix `Av1Encoder` was 17.1x over, ec-ac3's
87//! pre-fix `Ac3Decoder` 2.43x). It still reds, and by a factor rather than
88//! a hair, which is all a bound has to do.
89//!
90//! # This crate's inventory is SMALL, and that is a measurement
91//!
92//! ec-av1's floor for bound-checked public rows is 10. **ec-vp9 genuinely
93//! has 3** ([`Decoder`], [`Picture`], [`BoolDecoder`]) and the floor is
94//! lowered to 3 rather than padded with types this crate does not have.
95//! The reason is structural, not accidental: every other module here
96//! (`inter`, `mc`, `modes`, `tokens`, `transform`, `loopfilter`, `intra`,
97//! `header`, `tables`) exposes ZERO `pub fn` -- its API is
98//! `pub(crate)`, reached through `Decoder`. There are 13 `pub fn` lines
99//! in the whole crate, 11 of which return a primitive, a `Self`, or
100//! `()`.
101//!
102//! The sweep is still worth having at that size, and the reason is
103//! direction of travel: the scan found exactly ONE by-value public return
104//! name (`Picture`, from `Decoder::decode`), because `Decoder::new`
105//! returns `Self` and `BoolDecoder::new` returns `Result<Self>`, both of
106//! which the matcher exempts. A tiny inventory is a floor to grow into,
107//! and [`every_by_value_public_return_is_in_the_inventory`] is what makes
108//! a new 40 KB by-value return impossible to add unnoticed -- which is the
109//! only direction that can actually bite here.
110//!
111//! # What it does not claim
112//!
113//! `size_of` is layout, not stack depth. The residual is why
114//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs
115//! for real instead of trusting the arithmetic. And note
116//! [`the_frame_contexts_stay_behind_a_box`] pins ONE field: `Decoder::ctx`
117//! (decode.rs:129) is still an INLINE `FrameContext`, and at 2,039 bytes
118//! it is 72.8% of the 2,800 a caller pays today. Boxing that too is the
119//! obvious next move in this class; this module only records the
120//! measurement.
121
122use crate::bool::BoolDecoder;
123use crate::decode::{Decoder, Picture};
124
125/// The per-type ceiling for a type a CALLER can be made to hold by value, in
126/// bytes. See the module docs for the derivation; it is two-sided, and both
127/// sides are measured.
128pub(crate) const STACK_BUDGET: usize = 8192;
129
130/// The deepest PUBLIC by-value chain in this crate, counted from the source:
131/// `stream::decode_stream` (stream.rs:74) -> `stream::decode_stream_with`
132/// (stream.rs:88) -> `Decoder::decode` (decode.rs:238) is three public
133/// levels, after which `decode_one` / `decode_keyframe` / `decode_inter`
134/// are private. The budget is checked against three.
135///
136/// The by-value return slots IN that chain are all small
137/// (`Result<Vec<Picture>>`, `Result<()>`, `Result<Option<Picture>>`); the
138/// 2,800-byte `Decoder` is a by-value LOCAL in `decode_stream_with` that
139/// stays live across the inner `decode` calls. Multiplying the chain by the
140/// crate's worst public return is the conservative direction, and is what
141/// [`every_by_value_type_fits_the_stack_budget`] asserts.
142#[cfg(test)]
143const DEEPEST_PUBLIC_CHAIN: usize = 3;
144
145/// Every type in this crate a public `fn` can return BY VALUE, with the
146/// `size_of` measured at the commit that wrote this table. `None` means "not
147/// yet measured", which [`the_measured_inventory_is_accurate`] rejects.
148///
149/// The third column names the return path, so a reader can see why a type is
150/// here rather than a coincidence of the type system.
151pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
152 // -- knobs.rs ---------------------------------------------------------
153 (
154 "Override",
155 Some(16),
156 true,
157 "knobs::set_skip_lf / set_force_tail -> test-only guard that puts an \
158 EC_VP9 debug switch back on drop. A boxed restore closure, so one \
159 type covers every knob.",
160 ),
161 // -- decode.rs --------------------------------------------------------
162 (
163 "Decoder",
164 Some(800),
165 true,
166 "Decoder::new -> Self (and `Default::default`), the crate's whole \
167 public surface. Was 10944 with five inline FrameContext slots \
168 (10,195 of it), 1.34x over budget; frame_ctxs and ctx are both \
169 Boxes now. Boxing frame_ctxs ALONE left 2800 -- under budget, but \
170 with ctx still inline that was 72.8% of it",
171 ),
172 (
173 "Picture",
174 Some(96),
175 true,
176 "Decoder::decode -> Result<Option<Picture>>. Its fields ARE pub \
177 (y/u/v are Vec<Sample>), but it is thin -- three Vecs are three \
178 heap pointers, so the 96 bytes are a stack cost of three words, \
179 not of frame data",
180 ),
181 // -- bool.rs ----------------------------------------------------------
182 (
183 "BoolDecoder",
184 Some(40),
185 true,
186 "bool::BoolDecoder::new(data) -> Result<Self>; the sole public \
187 by-value return in the crate besides Picture, and the only type a \
188 caller can hold by value outside the decode surface",
189 ),
190 // -- crate-private: never a public return, and the one that was
191 // -- inline is behind a Box now. The budget does not apply; the pin
192 // -- that does is `the_frame_contexts_stay_behind_a_box`.
193 (
194 "FrameContext",
195 Some(2039),
196 false,
197 "header::FrameContext is pub(crate) and the payload of BOTH \
198 `frame_ctxs: Box<[FrameContext; 4]>` and `ctx: Box<FrameContext>`; \
199 five inline were 10195 of the pre-fix 10944. No FrameContext is \
200 stored inline in Decoder any more",
201 ),
202];
203
204/// The live `size_of` for every inventoried type, keyed BY NAME.
205///
206/// Keyed rather than positional on purpose: a row inserted into
207/// [`BY_VALUE_TYPES`] without a matching insert here would zip cleanly and
208/// assert the wrong type's size against the wrong recorded one. A name key
209/// makes that mistake loud instead.
210#[cfg(test)]
211fn measured_by_name() -> Vec<(&'static str, usize)> {
212 vec![
213 ("Decoder", std::mem::size_of::<Decoder>()),
214 ("Picture", std::mem::size_of::<Picture>()),
215 ("Override", std::mem::size_of::<crate::knobs::Override>()),
216 ("BoolDecoder", std::mem::size_of::<BoolDecoder<'static>>()),
217 (
218 "FrameContext",
219 std::mem::size_of::<crate::header::FrameContext>(),
220 ),
221 ]
222}
223
224/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`]
225/// constructs on.
226///
227/// 256 KiB: an eighth of what an unconfigured caller hands this crate, and
228/// far above what a 2,800-byte by-value `Decoder` needs in a debug build
229/// (the threshold is swept with `EC_VP9_TIGHT_STACK_BYTES`).
230const TIGHT_STACK: usize = 256 * 1024;
231
232#[cfg(test)]
233mod tests {
234 use super::{
235 BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name,
236 };
237 use crate::bool::BoolDecoder;
238 use crate::decode::Decoder;
239
240 /// Return types that are not a by-value copy of anything the caller has
241 /// to own: a pointer, a slice, a `Vec` (three words, and the heap is
242 /// not the stack), or a primitive. `Self` is a by-value copy of the
243 /// impl's type, which the inventory rows already cover, so it is exempt
244 /// from the scan and not from the table.
245 const THIN: &[&str] = &[
246 "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap",
247 "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16",
248 "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self",
249 ];
250
251 /// The type name a `pub fn` line returns BY VALUE, or `None` when the
252 /// line returns a pointer, a `Vec`, a primitive, or nothing.
253 ///
254 /// One function, shared by the sweep and its control, so the control
255 /// cannot pass while the sweep's copy of the logic rotted.
256 fn by_value_return_name(line: &str) -> Option<String> {
257 let trimmed = line.trim_start();
258 if !trimmed.starts_with("pub fn ") {
259 return None;
260 }
261 let arrow = line.find("->")?;
262 let rest = &line[arrow + 2..];
263 let end = rest.find('{').unwrap_or(rest.len());
264 let ret = rest[..end].trim();
265 if ret.is_empty() {
266 return None;
267 }
268 // Unwrap the `Result<..>` / `Option<..>` layers. ec-av1 unwraps one;
269 // this crate needs the loop, because its ONE by-value public return
270 // is spelled `Result<Option<Picture>>` (decode.rs:238) and a
271 // single unwrap reads that as the name "Option" -- an uninventoried
272 // non-type that would have made the sweep permanently red for a
273 // reason that has nothing to do with the class.
274 let mut inner = ret;
275 loop {
276 let stripped = inner
277 .strip_prefix("Result<")
278 .or_else(|| inner.strip_prefix("Option<"));
279 match stripped {
280 Some(t) => {
281 let head = t.split('>').next().unwrap_or(t);
282 if head.is_empty() {
283 return None;
284 }
285 inner = head;
286 }
287 None => break,
288 }
289 }
290 // Drop the error type and any lifetime or generic argument:
291 // `Result<Decoder, Error>`, `BoolDecoder<'a>` and `Picture` are all
292 // the bare name for this purpose. Splitting on the comma is
293 // load-bearing: the first version of this matcher cut only at `>`
294 // and so read `Result<Decoder, Error>` as the name
295 // "Decoder, Error".
296 let name = inner.split(['<', ',']).next().unwrap_or(inner).trim();
297 if name.is_empty() || THIN.contains(&name) {
298 return None;
299 }
300 // A generic parameter, not a concrete type.
301 if !name.chars().next().is_some_and(char::is_uppercase) {
302 return None;
303 }
304 Some(name.to_string())
305 }
306
307 /// The source files the by-value scan reads. Every module `lib.rs`
308 /// declares, plus this one; a new module added to `lib.rs` needs
309 /// adding here, and [`every_by_value_module_is_scanned`] is what keeps
310 /// that honest.
311 ///
312 /// The label is the path relative to `src/`, so a directory module is
313 /// `tables/mod.rs` rather than `tables.rs`.
314 const FILES: &[(&str, &str)] = &[
315 ("adapt.rs", include_str!("adapt.rs")),
316 ("bool.rs", include_str!("bool.rs")),
317 ("decode.rs", include_str!("decode.rs")),
318 ("header.rs", include_str!("header.rs")),
319 ("inter.rs", include_str!("inter.rs")),
320 ("intra.rs", include_str!("intra.rs")),
321 ("loopfilter.rs", include_str!("loopfilter.rs")),
322 ("knobs.rs", include_str!("knobs.rs")),
323 ("mc.rs", include_str!("mc.rs")),
324 ("modes.rs", include_str!("modes.rs")),
325 ("prof.rs", include_str!("prof.rs")),
326 ("stream.rs", include_str!("stream.rs")),
327 ("tables/mod.rs", include_str!("tables/mod.rs")),
328 ("tokens.rs", include_str!("tokens.rs")),
329 ("transform.rs", include_str!("transform.rs")),
330 ("stack_budget.rs", include_str!("stack_budget.rs")),
331 ];
332
333 /// Every module `lib.rs` declares, so the scan's file list cannot
334 /// silently fall behind a new module. A new `mod foo;` with a
335 /// by-value `pub fn` that the scan never reads is exactly the hole
336 /// this class would come back through, so the list is derived, not
337 /// curated.
338 #[test]
339 fn every_by_value_module_is_scanned() {
340 let lib = include_str!("lib.rs");
341 let mut declared: Vec<&str> = Vec::new();
342 for line in lib.lines() {
343 let t = line.trim();
344 let rest = t
345 .strip_prefix("pub mod ")
346 // This crate's `inter` and `mc` are `pub(crate) mod`, a
347 // spelling ec-av1 has no instance of. They are declared
348 // modules and are scanned, so they must be derived here
349 // too -- otherwise the check below is blind to exactly
350 // the two files a future by-value return would most
351 // likely land in.
352 .or_else(|| t.strip_prefix("pub(crate) mod "))
353 .or_else(|| t.strip_prefix("mod "))
354 .unwrap_or("");
355 if rest.is_empty() {
356 continue;
357 }
358 let name = rest.split([';', ' ']).next().unwrap_or("");
359 if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
360 declared.push(name);
361 }
362 }
363 // 12 modules (incl. the `pub(crate)` ones -- `inter`, `mc`) plus
364 // this one. The floor is a REACH floor: below it the parse is
365 // broken, not the crate small.
366 assert!(
367 declared.len() >= 13,
368 "only {} module declarations parsed out of lib.rs, so the derived \
369 file list is broken rather than small",
370 declared.len()
371 );
372 let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect();
373 let mut missing: Vec<String> = declared
374 .iter()
375 .filter(|d| {
376 let flat = format!("{d}.rs");
377 let dir = format!("{d}/mod.rs");
378 !scanned.iter().any(|s| *s == flat || *s == dir)
379 })
380 .map(|d| (*d).to_string())
381 .collect();
382 missing.sort();
383 assert!(
384 missing.is_empty(),
385 "lib.rs declares modules the by-value scan never reads: {:?}. Add \
386 them to FILES, or the sweep cannot see a new by-value return that \
387 lands in one of them.",
388 missing
389 );
390 }
391
392 /// The inventory, printed as a sorted table, and checked against the
393 /// types' real sizes.
394 ///
395 /// The print is the instrument: one command
396 /// (`cargo test -p ec-vp9 --lib -- stack_budget -- --nocapture`)
397 /// reproduces the whole table, biggest first, so "what is the largest
398 /// by-value type in this crate" has an answer that is a measurement
399 /// rather than a grep.
400 ///
401 /// The check reds on ANY change with both numbers. That is deliberate: a
402 /// by-value type that grew raises the question of whether it should
403 /// have been boxed instead, and auto-accepting the new number would
404 /// answer that question by default.
405 #[test]
406 fn the_measured_inventory_is_accurate() {
407 let live = measured_by_name();
408 assert_eq!(
409 BY_VALUE_TYPES.len(),
410 live.len(),
411 "the inventory names {} types but {} are measured; every row needs \
412 a measured size or the sweep is a list of hopes",
413 BY_VALUE_TYPES.len(),
414 live.len()
415 );
416 let mut rows: Vec<(&str, usize)> = live.clone();
417 rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size));
418 eprintln!(
419 "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)",
420 rows.len(),
421 STACK_BUDGET / 1024
422 );
423 eprintln!("{:>8} {:>7} TYPE", "BYTES", "%BUDGET");
424 for (name, size) in &rows {
425 eprintln!(
426 "{size:>8} {:>6.1}% {name}",
427 *size as f64 * 100.0 / STACK_BUDGET as f64
428 );
429 }
430 for (name, recorded, _public, _path) in BY_VALUE_TYPES {
431 let recorded = recorded.expect("every inventory row carries a measured size");
432 let actual = live
433 .iter()
434 .find(|(n, _)| n == name)
435 .map(|(_, size)| *size)
436 .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
437 assert_eq!(
438 recorded, actual,
439 "{name} is {actual} bytes, the inventory records {recorded}; \
440 update the table deliberately -- a by-value type that changed \
441 is a stack cost every caller of its constructor now pays"
442 );
443 }
444 }
445
446 /// The bound, asserted BY NAME. A regression in any inventoried type
447 /// reds here naming the type, not "some type is too big".
448 #[test]
449 fn every_by_value_type_fits_the_stack_budget() {
450 let live = measured_by_name();
451 let mut checked = 0usize;
452 for (name, _, public, path) in BY_VALUE_TYPES {
453 if !public {
454 continue;
455 }
456 checked += 1;
457 let size = live
458 .iter()
459 .find(|(n, _)| n == name)
460 .map(|(_, size)| *size)
461 .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
462 assert!(
463 size <= STACK_BUDGET,
464 "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \
465 stack budget ({:.2}x). It is returned by value from {path}, so \
466 every caller pays it on its own stack. Box the large field \
467 (frame_ctxs: Box<[FrameContext; 4]> did exactly this for \
468 Decoder, 10944 -> 2800) or hand back a reference.",
469 size as f64 / STACK_BUDGET as f64
470 );
471 }
472 // ec-av1's floor is 10. THIS CRATE HAS 4, and that is a measurement,
473 // not a gap to pad: every module but `bool`, `decode`, `knobs` and
474 // `stream` exposes zero `pub fn` (its API is `pub(crate)`, reached
475 // through `Decoder`). Inventing rows to reach ec-av1's number would
476 // make the gate theatre -- it would count types no caller can reach.
477 // `knobs::Override` is the fourth: the test-only guard the knob
478 // setters return.
479 assert!(
480 checked == 4,
481 "{checked} public rows were bound-checked, and this crate has \
482 exactly 4 types a caller can hold by value (Decoder, Picture, \
483 BoolDecoder, knobs::Override). If a fifth appeared, measure it, \
484 add it to BY_VALUE_TYPES, and raise this floor with it; if a row was \
485 removed, the count is wrong here and in the inventory."
486 );
487 // The other half of the derivation, asserted so it cannot rot: the
488 // worst a caller can owe is DEEPEST_CHAIN x the worst public return.
489 let worst = live
490 .iter()
491 .filter(|(n, _)| {
492 BY_VALUE_TYPES
493 .iter()
494 .any(|(row, _, public, _)| row == n && *public)
495 })
496 .map(|(_, size)| *size)
497 .max()
498 .expect("at least one public row");
499 assert!(
500 DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024,
501 "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \
502 public by-value return ({worst} B) is {} B, over an eighth of the \
503 2 MiB stack an unconfigured caller hands this crate; \
504 re-derive STACK_BUDGET",
505 DEEPEST_PUBLIC_CHAIN * worst
506 );
507 }
508
509 /// The four stored frame contexts stay BEHIND A BOX.
510 ///
511 /// The budget does not apply to `header::FrameContext` (2,039 B) because
512 /// no `pub fn` returns it, so bounding it would calibrate the number to
513 /// something no caller can reach. What keeps four of them off a
514 /// caller's stack is that the array is a `Box`, and THIS is the pin.
515 ///
516 /// It earned its place twice. `Decoder` was 10,944 B, of which 8,156 was
517 /// `frame_ctxs: [FrameContext; 4]` sitting inline -- 1.34x over budget.
518 /// Boxing the array alone left 2,800, of which `ctx` was 2,039 (72.8%):
519 /// under the budget, but with a single field carrying nearly all of it.
520 #[test]
521 fn the_frame_contexts_stay_behind_a_box() {
522 const PINS: &[(&str, &str)] = &[
523 // The field declarations (decode.rs:134, decode.rs:139).
524 ("frame_ctxs: Box<[FrameContext; 4]>", "the frame_ctxs field"),
525 ("ctx: Box<FrameContext>", "the ctx field"),
526 // Their construction in `Decoder::new` (decode.rs:216, 221).
527 (
528 "Box::new([d.clone(), d.clone(), d.clone(), d])",
529 "Decoder::new",
530 ),
531 ("ctx: Box::new(FrameContext::new(true))", "Decoder::new"),
532 ];
533 const SRC: &str = include_str!("decode.rs");
534 for (spelling, where_) in PINS {
535 assert!(
536 SRC.contains(spelling),
537 "decode.rs::{where_} is no longer declared `{spelling}`. An \
538 inline `FrameContext` there puts 2039 bytes back into every \
539 caller's stack -- five of them were 10195 bytes, which is how \
540 `Decoder` was 10944 bytes and 1.34x over the by-value budget \
541 before the boxes.",
542 );
543 }
544 // And the negative control: the unboxed spelling must NOT still be
545 // present, or the scan above would be matching a comment.
546 assert!(
547 !SRC.contains("frame_ctxs: [FrameContext; 4],") && !SRC.contains("ctx: FrameContext,"),
548 "decode.rs still spells a FrameContext field inline, so the box \
549 pin above is matching a spelling that is not the live declaration"
550 );
551 }
552
553 /// CAPABILITY: really construct the heavy type on a tight stack, so a
554 /// regression ABORTS THE PROCESS instead of costing invisible margin.
555 ///
556 /// `Decoder::new` is the crate's one large by-value return path, and it
557 /// is also the one whose boxing moved the threshold.
558 ///
559 /// **What this arm does and does not catch, measured.** Swept in an
560 /// unoptimized build, one process per point:
561 ///
562 /// | stack | pre-fix (unboxed, 10,944 B) | boxed (2,800 B) |
563 /// |---|---|---|
564 /// | 16384 | overflow | overflow |
565 /// | 24576 | overflow | overflow |
566 /// | 32768 | overflow | **ok** |
567 /// | 40960 | **ok** | ok |
568 /// | 262144 (the gate) | **ok** | ok |
569 ///
570 /// So the boxing moved the threshold from 40,960 to 32,768 -- real, and
571 /// HONESTLY SMALL: a 10,944-byte struct does not need a small stack to
572 /// overflow. **The unboxing mutation does NOT red this arm at 256 KiB.**
573 /// It reds [`every_by_value_type_fits_the_stack_budget`] (named, with
574 /// the 1.34x factor) and [`the_frame_contexts_stay_behind_a_box`]
575 /// instead. This arm is the capability floor -- it pins the real live
576 /// stack of the crate's by-value return path, which the arithmetic in
577 /// the other two tests does not model -- and it is deliberately set
578 /// well clear of the measured 32,768 B so an unoptimised-build
579 /// regression in stack need shows up here as a margin loss rather than
580 /// as a mysterious abort. Reproduce either column with
581 /// `EC_VP9_TIGHT_STACK_BYTES`.
582 ///
583 /// The env read is a raw `std::env::var`, not the crate's `cached_gate!`
584 /// macro: `cached_gate!` answers PRESENCE and caches a bool, and this
585 /// override needs a VALUE, read once per test run and never on a decode
586 /// path. Using the hot-path convention for a cold, value-shaped read
587 /// would be the wrong tool.
588 #[test]
589 fn the_deepest_by_value_constructors_fit_on_a_tight_stack() {
590 let stack: usize = std::env::var("EC_VP9_TIGHT_STACK_BYTES")
591 .ok()
592 .and_then(|v| v.parse().ok())
593 .unwrap_or(TIGHT_STACK);
594 let handle = std::thread::Builder::new()
595 .stack_size(stack)
596 .spawn(|| {
597 // The by-value return path: a whole `Decoder` built and
598 // returned from `new` on a 256 KiB stack.
599 let decoder = Decoder::new();
600 // Real post-construction state, not just "did not crash": a
601 // fresh decoder has parsed no inter frame and produced no
602 // blocks, and the four boxed frame contexts are addressable
603 // and distinct from the live `ctx`.
604 let blocks = decoder.last_frame_blocks();
605 let bools = BoolDecoder::new(&[]).expect("BoolDecoder::new on an empty partition");
606 let overreads = bools.overreads();
607 (blocks, overreads, std::mem::size_of::<Decoder>())
608 })
609 .expect("spawn tight-stack thread");
610 let (blocks, overreads, size) = handle.join().unwrap_or_else(|_| {
611 panic!(
612 "Decoder::new overflowed a {stack}-byte stack; that is what the \
613 pre-fix 10944-byte by-value layout costs a caller"
614 )
615 });
616 assert_eq!(
617 blocks, 0,
618 "a freshly constructed Decoder reports {blocks} last-frame blocks"
619 );
620 assert_eq!(
621 overreads, 0,
622 "an empty BoolDecoder partition reports {overreads} overreads"
623 );
624 eprintln!("TIGHTSTACK {stack} bytes: Decoder={size} B, constructed and returned");
625 }
626
627 /// The sweep's teeth against a NEW by-value return: re-derive the set
628 /// from the crate source and require every name to be inventoried.
629 ///
630 /// Without this the inventory is a list of what someone remembered to
631 /// measure, and a lane that adds `pub fn make() -> HugeThing` where
632 /// `HugeThing` is 200 KB of inline tables passes every other test here.
633 #[test]
634 fn every_by_value_public_return_is_in_the_inventory() {
635 let mut found: Vec<(String, String)> = Vec::new();
636 let mut pub_fn_lines = 0usize;
637 for (file, src) in FILES {
638 for (n, line) in src.lines().enumerate() {
639 if line.trim_start().starts_with("pub fn ") {
640 pub_fn_lines += 1;
641 }
642 if let Some(name) = by_value_return_name(line) {
643 found.push((name, format!("{file}:{}", n + 1)));
644 }
645 }
646 }
647 found.sort();
648 found.dedup();
649 // A REACH floor, not a size floor: ec-av1 asserts > 5 names because
650 // it has 20 KB of encoders. This crate has 13 `pub fn` lines in
651 // total, 11 of which return a primitive / `Self` / `()`, so the
652 // one by-value public return it really has is `Picture`. Asserting
653 // a bigger number would be asserting a fact about ec-av1.
654 assert!(
655 pub_fn_lines >= 10,
656 "the scan saw only {pub_fn_lines} `pub fn` lines across {} files, \
657 too few to be a real sweep -- the matcher, not the crate, is \
658 broken",
659 FILES.len()
660 );
661 assert!(
662 !found.is_empty(),
663 "the by-value return scan found NO name across {} files and {} \
664 `pub fn` lines; `Decoder::decode -> Result<Option<Picture>>` \
665 (decode.rs:238) must be in there, so the matcher is broken",
666 FILES.len(),
667 pub_fn_lines
668 );
669
670 let mut missing = Vec::new();
671 for (name, site) in &found {
672 if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) {
673 missing.push(format!("{name} ({site})"));
674 }
675 }
676 assert!(
677 missing.is_empty(),
678 "these types are returned BY VALUE from a public fn and are not in \
679 the inventory: {}. Either they are thin enough not to be a stack \
680 cost -- say so by adding a row with its measured size -- or they \
681 are the next instance of the class this module exists for.",
682 missing.join(", ")
683 );
684 eprintln!(
685 "BYVALUE-SCAN {} `pub fn` lines, {} by-value public return name(s): {:?}",
686 pub_fn_lines,
687 found.len(),
688 found
689 );
690 }
691
692 /// The control for the scan above, on synthetic text rather than by
693 /// trusting the live tree to happen to contain a case.
694 ///
695 /// If the matcher silently stopped recognising a shape, the sweep would
696 /// pass everything and this would still be asserting nothing. So: every
697 /// by-value spelling this crate uses must yield its type name, and every
698 /// pointer/Vec/primitive/`Self` spelling must yield nothing.
699 #[test]
700 fn the_inventory_scan_is_not_vacuous() {
701 for synthetic in [
702 "pub fn zz_a() -> ZzNotInventoried { todo!() }",
703 "pub fn zz_b() -> Result<ZzNotInventoried, Error> { todo!() }",
704 "pub fn zz_c() -> Result<ZzNotInventoried> { todo!() }",
705 "pub fn zz_d() -> Option<ZzNotInventoried> { todo!() }",
706 "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }",
707 // The DOUBLE-wrapped shape this crate actually uses, at
708 // decode.rs:238. A single-layer unwrap reads it as "Option",
709 // which is not a type and would red the sweep forever.
710 "pub fn zz_f() -> Result<Option<ZzNotInventoried>> { todo!() }",
711 ] {
712 let name = by_value_return_name(synthetic)
713 .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`"));
714 assert_eq!(
715 name, "ZzNotInventoried",
716 "the matcher mangled `{synthetic}` into `{name}`, so the sweep \
717 cannot see a new by-value return and its green is vacuous"
718 );
719 assert!(
720 !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name),
721 "the synthetic control name is in the inventory, so the control \
722 proves nothing"
723 );
724 }
725 for thin in [
726 "pub fn zz_t() -> Box<Decoder> { todo!() }",
727 "pub fn zz_u() -> Result<Vec<u8>, Error> { todo!() }",
728 "pub fn zz_v() -> Option<&Path> { todo!() }",
729 "pub fn zz_w() -> usize { todo!() }",
730 "pub fn zz_x() -> Self { todo!() }",
731 "pub fn zz_y() -> Result<Arc<Decoder>, Error> { todo!() }",
732 "pub fn zz_z() { todo!() }",
733 "fn zz_private() -> ZzNotInventoried { todo!() }",
734 // The two live spellings this crate exempts on purpose:
735 // `Vec` is three words and its heap is not the caller's stack.
736 "pub fn zz_g() -> Result<Vec<Picture>> { todo!() }",
737 "pub fn zz_h() -> Result<Self> { todo!() }",
738 ] {
739 assert_eq!(
740 by_value_return_name(thin),
741 None,
742 "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \
743 above already cover, or not a `pub fn` -- the matcher must not \
744 read it as an uninventoried by-value return"
745 );
746 }
747 }
748}