forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB35bdf35Tahinli2 months ago3757 commits

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