forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

stack_budget.rs993 lines, 43.6 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 cost,
7//! not a heap cost, and the cost is paid by the CALLER. The constructors here
8//! nest -- `with_pyramid_and_rate_target` -> `with_pyramid` -> `new` for the
9//! encoder, and `encode_key_frame` -> `encode_key_frame_with_ctx` ->
10//! `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner` for a
11//! frame -- and in an unoptimized build each level materialises its whole
12//! `Result<T>` return slot before the inner call returns. So one value's
13//! `size_of` is the MULTIPLIER, and the chain length is the other factor.
14//!
15//! That is not hypothetical. `Av1Encoder` was 139960 bytes by value (eight
16//! inline `CdfSnapshot` DPB slots) and aborted with `fatal runtime error:
17//! stack overflow, aborting` on libtest's 2 MiB thread, twice, on an unmodified
18//! `main`. `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864` to hide it
19//! from this workspace's own runs -- a band-aid a library consumer does not
20//! get. lane-av1enchang boxed the per-slot snapshot (139960 -> 18168) and
21//! gated the constructors on a 1 MiB thread.
22//!
23//! # Why this module exists when that gate already exists
24//!
25//! lane-av1enchang gated ONE type. The class was not swept: nothing stopped the
26//! next 15 KB inline table from landing, and nothing said which types had been
27//! checked. This module is the sweep:
28//!
29//! 1. [`BY_VALUE_TYPES`] is the inventory -- every public type in this crate
30//! that a public `fn` can return by value, with a measured `size_of` floor
31//! recorded as of this commit.
32//! [`the_measured_inventory_is_accurate`] fails if a type's size moves, so
33//! the table cannot rot into a list of stale small numbers.
34//! 2. [`STACK_BUDGET`] is the bound, and
35//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for
36//! every row, so a regression reds naming the type that caused it.
37//! 3. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the
38//! capability arm: it really constructs the heavy types on a deliberately
39//! tight thread, so the old layout ABORTS THE PROCESS rather than quietly
40//! costing margin. Red/green in milliseconds.
41//! 4. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's
42//! teeth against NEW types: a source scan re-derives the set of by-value
43//! public returns from the crate source, so a lane that adds a 40 KB struct
44//! to a `pub fn` return reds here until it is measured and listed.
45//! [`the_inventory_scan_is_not_vacuous`] is its control.
46//!
47//! # The bound, and why this number
48//!
49//! [`STACK_BUDGET`] = 8192 bytes (8 KiB). It is bounded from BOTH sides by
50//! measurement, and both sides are asserted in
51//! [`every_by_value_type_fits_the_stack_budget`] so neither can rot silently.
52//!
53//! **The quantity being bounded.** Not `size_of` in the abstract, but *what a
54//! caller can be made to owe*: the size of one by-value return, multiplied by
55//! how many constructor levels hold a copy of it at once. Three inputs:
56//!
57//! 1. **The smallest stack a caller can hand this crate is 2,101,248 bytes.**
58//! Measured, not assumed, by
59//! [`test_threads_get_the_stack_they_are_given`] reading
60//! `/proc/self/task/<tid>/maps`. That is libtest's default test thread and
61//! also what `std::thread::Builder::new()` gives a caller who does not ask
62//! for a size. A library consumer gets no `.cargo/config.toml`.
63//! 2. **The deepest PUBLIC by-value chain is 4** ([`DEEPEST_PUBLIC_CHAIN`]):
64//! `encode_key_frame` -> `encode_key_frame_with_ctx` ->
65//! `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner`. The
66//! encoder's own nest is 3. The test asserts
67//! `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB` -- i.e. the by-value return
68//! slots may claim at most an EIGHTH of a caller's stack, leaving the rest
69//! for the encode search, which is the thing that actually needs it.
70//! 3. **The budget applies only to types a `pub fn` returns.** The
71//! crate-private 15,232-byte `Cdfs` / `CdfSnapshot` are measured and listed
72//! but are NOT bounded, because no caller can reach them by value -- every
73//! field that holds one is a `Box`, which
74//! [`the_crate_private_cdf_tables_stay_behind_a_box`] pins by source.
75//! Bounding them would calibrate the number to something unreachable.
76//!
77//! **Where the number sits.** At 8 KiB with the worst public return at 2,944
78//! bytes ([`Av1Encoder`]), the worst a caller owes is
79//! `4 x 2944 = 11,776` bytes -- **0.56%** of a 2 MiB thread -- and the budget
80//! itself is 2.78x above the incumbent. Both directions have room, which is
81//! the point: a bound the largest type sits just under is a bound the next
82//! lane will quietly raise.
83//!
84//! **What it catches.** A pre-fix `Av1Encoder` (139,960 B) is **17.1x over**.
85//! `Encoded` as it stood before this lane boxed its two inline snapshots
86//! (30,728 B) is **3.75x over**. `ec_opus::Encoder`, measured in a sibling
87//! crate by the same sweep, is **10.6x over**. The historical defect, the
88//! near-miss, and the largest live instance of the class in the workspace all
89//! red by a factor, not by a hair.
90//!
91//! **What it does not claim.** `size_of` is layout, not stack depth. The
92//! measured stack/size ratio on a by-value constructor is ~4.4x
93//! (`ec_opus::Encoder`: 87,024 B of struct, ~384 KiB of live stack), which is
94//! the nesting multiplier made visible. That residual is why
95//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs for
96//! real instead of trusting the arithmetic.
97
98#![cfg(test)]
99//! A measured bound on the crate's BY-VALUE types, and a gate that bites.
100//!
101//! # The class
102//!
103//! A large struct returned BY VALUE from a public constructor is a stack cost,
104//! not a heap cost, and the cost is paid by the CALLER. The constructors here
105//! nest -- `with_pyramid_and_rate_target` -> `with_pyramid` -> `new` for the
106//! encoder, and `encode_key_frame` -> `encode_key_frame_with_ctx` ->
107//! `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner` for a
108//! frame -- and in an unoptimized build each level materialises its whole
109//! `Result<T>` return slot before the inner call returns. So one value's
110//! `size_of` is the MULTIPLIER, and the chain length is the other factor.
111//!
112//! That is not hypothetical. `Av1Encoder` was 139960 bytes by value (eight
113//! inline `CdfSnapshot` DPB slots) and aborted with `fatal runtime error:
114//! stack overflow, aborting` on libtest's 2 MiB thread, twice, on an unmodified
115//! `main`. `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864` to hide it
116//! from this workspace's own runs -- a band-aid a library consumer does not
117//! get. lane-av1enchang boxed the per-slot snapshot (139960 -> 18168) and
118//! gated the constructors on a 1 MiB thread.
119//!
120//! # Why this module exists when that gate already exists
121//!
122//! lane-av1enchang gated ONE type. The class was not swept: nothing stopped the
123//! next 15 KB inline table from landing, and nothing said which types had been
124//! checked. This module is the sweep:
125//!
126//! 1. [`BY_VALUE_TYPES`] is the inventory -- every public type in this crate
127//! that a public `fn` can return by value, with a measured `size_of` floor
128//! recorded as of this commit.
129//! [`the_measured_inventory_is_accurate`] fails if a type's size moves, so
130//! the table cannot rot into a list of stale small numbers.
131//! 2. [`STACK_BUDGET`] is the bound, and
132//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for
133//! every row, so a regression reds naming the type that caused it.
134//! 3. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the
135//! capability arm: it really constructs the heavy types on a deliberately
136//! tight thread, so the old layout ABORTS THE PROCESS rather than quietly
137//! costing margin. Red/green in milliseconds.
138//! 4. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's
139//! teeth against NEW types: a source scan re-derives the set of by-value
140//! public returns from the crate source, so a lane that adds a 40 KB struct
141//! to a `pub fn` return reds here until it is measured and listed.
142//! [`the_inventory_scan_is_not_vacuous`] is its control.
143//!
144//! # The bound, and why this number
145//!
146//! [`STACK_BUDGET`] = 32768 bytes (32 KiB). The reasoning, from measured
147//! numbers rather than taste:
148//!
149//! * The smallest stack a caller can hand this crate is **2101248 bytes**,
150//! measured by [`test_threads_get_the_stack_they_are_given`] reading
151//! `/proc/self/task/<tid>/maps` for the region containing a running frame.
152//! That is libtest's default test thread and also what
153//! `std::thread::Builder::new()` hands a caller who does not ask for a size.
154//! A library consumer gets no `.cargo/config.toml`.
155//! * The deepest public by-value chain in this crate is FOUR frames, so the
156//! worst live stack from return slots alone is `4 * size_of::<T>()`.
157//! * At 32 KiB that is 128 KiB: **6.1%** of a 2 MiB thread. A type at the
158//! budget still leaves 94% of the caller's stack for its own work.
159//! * 32 KiB is above every type here with headroom, and it is 2.14x below the
160//! pre-fix `Av1Encoder`, so the historical defect reds by a factor rather
161//! than by a hair.
162//!
163//! `Encoded` is at 30728, i.e. **93.8% of budget** and the one row with no
164//! margin left. It is 99.2% two inline `CdfSnapshot`s, and boxing those two
165//! fields is the next move in this class; the report says so. A budget the
166//! current tree already violates is not a budget, it is a to-do list, and the
167//! fix belongs in the lane that does the boxing.
168
169use crate::encode::Encoded;
170use crate::encoder::Av1Encoder;
171
172/// The per-type ceiling for a type a CALLER can be made to hold by value, in
173/// bytes. See the module docs for the derivation; it is two-sided, and both
174/// sides are measured.
175pub(crate) const STACK_BUDGET: usize = 8192;
176
177/// The deepest PUBLIC by-value constructor chain in this crate, counted from
178/// the source: `encode_key_frame` -> `encode_key_frame_with_ctx` ->
179/// `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner` is four,
180/// and `with_pyramid_and_rate_target` -> `with_pyramid` -> `new` is three. The
181/// budget is checked against four, the worse of the two.
182#[cfg(test)]
183const DEEPEST_PUBLIC_CHAIN: usize = 4;
184
185/// Every public type in this crate a public `fn` can return BY VALUE, with the
186/// `size_of` measured at the commit that wrote this table. `None` means "not
187/// yet measured", which [`the_measured_inventory_is_accurate`] rejects.
188///
189/// The third column names the return path, so a reader can see why a type is
190/// here rather than a coincidence of the type system.
191pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
192 // -- encoder.rs -------------------------------------------------------
193 (
194 "Av1Encoder",
195 Some(2704),
196 true,
197 "Av1Encoder::new / with_speed / with_pyramid / with_rate_target / \
198 with_pyramid_and_rate_target, all `Result<Self>`, nesting three deep",
199 ),
200 ("EncoderConfig", Some(40), true, "EncoderConfig::new"),
201 (
202 "Pyramid",
203 Some(24),
204 true,
205 "Pyramid's own ctor + Av1Encoder::pyramid",
206 ),
207 (
208 "RateTarget",
209 Some(16),
210 true,
211 "constructor by value; carried in every Av1Encoder",
212 ),
213 (
214 "Packet",
215 Some(48),
216 true,
217 "Av1Encoder::encode -> Result<Packet>",
218 ),
219 // -- encode.rs --------------------------------------------------------
220 (
221 "Encoded",
222 Some(280),
223 true,
224 "encode_key_frame / encode_key_frame_with_modes / \
225 encode_key_frame_at_size -> Result<Encoded>, nesting four deep",
226 ),
227 (
228 "EncodedSequence",
229 Some(72),
230 true,
231 "encode_sequence -> Result<EncodedSequence>",
232 ),
233 ("Picture", Some(88), true, "Picture::grey -> Self"),
234 // -- crate-private: never a public return, and every one of them is
235 // -- behind a Box now. The budget does not apply to these; the pin that
236 // -- does is `the_crate_private_cdf_tables_stay_behind_a_box`.
237 (
238 "Cdfs",
239 Some(15232),
240 false,
241 "Cdfs::new(q_ctx) -> Cdfs; the payload of every CdfSnapshot. Not \
242 reachable from a pub fn, and boxed everywhere it is stored",
243 ),
244 (
245 "CdfSnapshot",
246 Some(15232),
247 false,
248 "crate-private newtype over Cdfs. Boxed in DpbSlot (lane-av1enchang), \
249 in Av1Encoder::carried_cdfs and in both of Encoded's fields \
250 (lane-av1stacksweep)",
251 ),
252 (
253 "TxbTables",
254 Some(112),
255 false,
256 "Cdfs::txb -> TxbTables<'_>; nine BORROWED table slices, so the move \
257 copies pointers, not tables",
258 ),
259 // -- decode.rs --------------------------------------------------------
260 (
261 "FrameCtx",
262 Some(1056),
263 false,
264 "FrameCtx::for_encoder() -> Self, pub(crate); one inline per Av1Encoder",
265 ),
266 // -- the small public surface ----------------------------------------
267 (
268 "SymbolEncoder",
269 Some(56),
270 true,
271 "msac::SymbolEncoder::new / pricer",
272 ),
273 ("SymbolDecoder", Some(64), true, "msac::SymbolDecoder::new"),
274 (
275 "MiInfo",
276 Some(16),
277 true,
278 "mvstack::MvStack::get -> Option<MiInfo>",
279 ),
280 (
281 "WarpParams",
282 Some(32),
283 true,
284 "warp::global_warp_params -> Option<WarpParams>",
285 ),
286 ("Iqm", Some(24), true, "qm::iwt_matrix -> Option<Iqm>"),
287 ("MvStack", Some(240), true, "mvstack::MvStack::new -> Self"),
288 (
289 "Frame",
290 Some(352),
291 true,
292 "census::Frame rows, moved by value",
293 ),
294 (
295 "InterpFilterKind",
296 Some(1),
297 true,
298 "mc::InterpFilterKind::from_switchable_symbol / from_header",
299 ),
300 (
301 "TplProbe",
302 Some(48),
303 false,
304 "a borrowed-view handle the tile search passes around by value",
305 ),
306];
307
308/// The live `size_of` for every inventoried type, keyed BY NAME.
309///
310/// Keyed rather than positional on purpose: `Packet` and `TplProbe` are both
311/// 48 bytes, so a row inserted into [`BY_VALUE_TYPES`] without a matching
312/// insert here would zip cleanly and assert the wrong type's size against the
313/// wrong recorded one. A name key makes that mistake loud instead.
314#[cfg(test)]
315fn measured_by_name() -> Vec<(&'static str, usize)> {
316 vec![
317 ("Av1Encoder", std::mem::size_of::<Av1Encoder>()),
318 (
319 "EncoderConfig",
320 std::mem::size_of::<crate::encoder::EncoderConfig>(),
321 ),
322 ("Pyramid", std::mem::size_of::<crate::encoder::Pyramid>()),
323 (
324 "RateTarget",
325 std::mem::size_of::<crate::encoder::RateTarget>(),
326 ),
327 ("Packet", std::mem::size_of::<crate::encoder::Packet>()),
328 ("Encoded", std::mem::size_of::<Encoded>()),
329 (
330 "EncodedSequence",
331 std::mem::size_of::<crate::encode::EncodedSequence>(),
332 ),
333 ("Picture", std::mem::size_of::<crate::encode::Picture>()),
334 ("Cdfs", std::mem::size_of::<crate::cdf_state::Cdfs>()),
335 (
336 "CdfSnapshot",
337 std::mem::size_of::<crate::encode::CdfSnapshot>(),
338 ),
339 (
340 "TxbTables",
341 std::mem::size_of::<crate::cdf_state::TxbTables<'static>>(),
342 ),
343 ("FrameCtx", std::mem::size_of::<crate::decode::FrameCtx>()),
344 (
345 "SymbolEncoder",
346 std::mem::size_of::<crate::msac::SymbolEncoder>(),
347 ),
348 (
349 "SymbolDecoder",
350 std::mem::size_of::<crate::msac::SymbolDecoder<'static>>(),
351 ),
352 ("MiInfo", std::mem::size_of::<crate::mvstack::MiInfo>()),
353 ("WarpParams", std::mem::size_of::<crate::warp::WarpParams>()),
354 ("Iqm", std::mem::size_of::<crate::qm::Iqm>()),
355 ("MvStack", std::mem::size_of::<crate::mvstack::MvStack>()),
356 ("Frame", std::mem::size_of::<crate::census::Frame>()),
357 (
358 "InterpFilterKind",
359 std::mem::size_of::<crate::mc::InterpFilterKind>(),
360 ),
361 (
362 "TplProbe",
363 std::mem::size_of::<crate::motion_field::TplProbe<'static>>(),
364 ),
365 ]
366}
367
368/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`]
369/// constructs on.
370///
371/// 1 MiB: half of what an unconfigured caller gives this crate, and 2.7x what
372/// the deepest measured chain needs in a debug build. Both thresholds were
373/// swept in an unoptimized build and are reproducible with
374/// `EC_AV1_TIGHT_STACK_BYTES`.
375const TIGHT_STACK: usize = 1024 * 1024;
376
377#[cfg(test)]
378mod tests {
379 use super::{
380 BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name,
381 };
382 use crate::encode::Encoded;
383
384 /// Return types that are not a by-value copy of anything the caller has to
385 /// own: a pointer, a slice, a `Vec` (three words, and the heap is not the
386 /// stack), or a primitive. `Self` is a by-value copy of the impl's type,
387 /// which the inventory rows already cover, so it is exempt from the scan
388 /// and not from the table.
389 const THIN: &[&str] = &[
390 "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap",
391 "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16",
392 "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self",
393 ];
394
395 /// The type name a `pub fn` line returns BY VALUE, or `None` when the line
396 /// returns a pointer, a `Vec`, a primitive, or nothing.
397 ///
398 /// One function, shared by the sweep and its control, so the control
399 /// cannot pass while the sweep's copy of the logic rotted.
400 fn by_value_return_name(line: &str) -> Option<String> {
401 let trimmed = line.trim_start();
402 if !trimmed.starts_with("pub fn ") {
403 return None;
404 }
405 let arrow = line.find("->")?;
406 let rest = &line[arrow + 2..];
407 let end = rest.find('{').unwrap_or(rest.len());
408 let ret = rest[..end].trim();
409 if ret.is_empty() {
410 return None;
411 }
412 // Unwrap one `Result<..>` / `Option<..>` layer. A deeper nesting is
413 // not a shape this crate uses, and flagging one as uninventoried is
414 // the safe direction to be wrong in.
415 let inner = {
416 let t = ret
417 .strip_prefix("Result<")
418 .or_else(|| ret.strip_prefix("Option<"))
419 .unwrap_or(ret);
420 t.split('>').next().unwrap_or(t)
421 };
422 // Drop the error type and any lifetime or generic argument:
423 // `Result<Decoder, Error>`, `SymbolDecoder<'a>` and `TxbTables<'_>`
424 // are all the bare name for this purpose. Splitting on the comma is
425 // load-bearing: the first version of this matcher cut only at `>` and
426 // so read `Result<Decoder, Error>` as the name "Decoder, Error".
427 // `the_inventory_scan_is_not_vacuous` caught exactly that, which is
428 // why the control is not optional.
429 let name = inner.split(['<', ',']).next().unwrap_or(inner).trim();
430 if name.is_empty() || THIN.contains(&name) {
431 return None;
432 }
433 // A generic parameter, not a concrete type.
434 if !name.chars().next().is_some_and(char::is_uppercase) {
435 return None;
436 }
437 Some(name.to_string())
438 }
439
440 /// The source files the by-value scan reads. Every module that can expose
441 /// a `pub fn` returning a named type; a new module added to `lib.rs` needs
442 /// adding here, and
443 /// [`every_by_value_module_is_scanned`] is what keeps that honest.
444 fn files() -> Vec<(&'static str, &'static str)> {
445 vec![
446 ("bits.rs", include_str!("bits.rs")),
447 ("cdf.rs", crate::test_source::module_source("cdf")),
448 ("cdf_state.rs", include_str!("cdf_state.rs")),
449 ("census.rs", include_str!("census.rs")),
450 ("compound.rs", include_str!("compound.rs")),
451 ("decode.rs", crate::test_source::module_source("decode")),
452 ("dumpio.rs", include_str!("dumpio.rs")),
453 ("encode.rs", crate::test_source::module_source("encode")),
454 ("encoder.rs", crate::test_source::module_source("encoder")),
455 ("envflags.rs", include_str!("envflags.rs")),
456 ("film_grain.rs", include_str!("film_grain.rs")),
457 ("filter_search.rs", include_str!("filter_search.rs")),
458 ("frame.rs", include_str!("frame.rs")),
459 ("gate_coverage.rs", include_str!("gate_coverage.rs")),
460 ("hits.rs", include_str!("hits.rs")),
461 ("intra.rs", include_str!("intra.rs")),
462 ("library_fixture.rs", include_str!("library_fixture.rs")),
463 ("mc.rs", include_str!("mc.rs")),
464 ("motion.rs", include_str!("motion.rs")),
465 ("motion_field.rs", include_str!("motion_field.rs")),
466 ("msac.rs", include_str!("msac.rs")),
467 ("mvstack.rs", include_str!("mvstack.rs")),
468 ("obu.rs", include_str!("obu.rs")),
469 ("par.rs", include_str!("par.rs")),
470 ("autothreads.rs", include_str!("autothreads.rs")),
471 ("probe.rs", include_str!("probe.rs")),
472 ("qm.rs", crate::test_source::module_source("qm")),
473 ("quant.rs", include_str!("quant.rs")),
474 ("refusal_inventory.rs", include_str!("refusal_inventory.rs")),
475 ("restoration.rs", include_str!("restoration.rs")),
476 ("sequence.rs", include_str!("sequence.rs")),
477 ("speed.rs", include_str!("speed.rs")),
478 ("stream.rs", crate::test_source::module_source("stream")),
479 ("superres.rs", include_str!("superres.rs")),
480 ("test_source.rs", include_str!("test_source.rs")),
481 ("tile.rs", crate::test_source::module_source("tile")),
482 ("timeline.rs", include_str!("timeline.rs")),
483 ("transform.rs", include_str!("transform.rs")),
484 ("warp.rs", include_str!("warp.rs")),
485 ("wedge.rs", include_str!("wedge.rs")),
486 ("stack_budget.rs", include_str!("stack_budget.rs")),
487 ("fault.rs", include_str!("fault.rs")),
488 ]
489 }
490
491 /// Every module `lib.rs` declares, so the scan's file list cannot silently
492 /// fall behind a new module. A new `mod foo;` with a by-value `pub fn`
493 /// that the scan never reads is exactly the hole this class would come
494 /// back through, so the list is derived, not curated.
495 #[test]
496 fn every_by_value_module_is_scanned() {
497 let lib = include_str!("lib.rs");
498 let mut declared: Vec<&str> = Vec::new();
499 for line in lib.lines() {
500 let t = line.trim();
501 let rest = t
502 .strip_prefix("pub mod ")
503 .or_else(|| t.strip_prefix("mod "))
504 .unwrap_or("");
505 if rest.is_empty() {
506 continue;
507 }
508 let name = rest.split([';', ' ']).next().unwrap_or("");
509 if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
510 declared.push(name);
511 }
512 }
513 assert!(
514 declared.len() > 10,
515 "only {} module declarations parsed out of lib.rs, so the \
516 derived file list is broken rather than small",
517 declared.len()
518 );
519 let scanned: Vec<&str> = files().iter().map(|(n, _)| *n).collect();
520 let mut missing: Vec<String> = declared
521 .iter()
522 .filter(|d| !scanned.iter().any(|s| *s == format!("{d}.rs")))
523 .map(|d| (*d).to_string())
524 .collect();
525 missing.sort();
526 assert!(
527 missing.is_empty(),
528 "lib.rs declares modules the by-value scan never reads: {:?}. Add \
529 them to files(), or the sweep cannot see a new by-value return that \
530 lands in one of them.",
531 missing
532 );
533 }
534
535 /// The inventory, printed as a sorted table, and checked against the
536 /// types' real sizes.
537 ///
538 /// The print is the instrument: one command
539 /// (`cargo test -p ec-av1 --lib -- stack_budget -- --nocapture`)
540 /// reproduces the whole table, biggest first, so "what is the largest
541 /// by-value type in this crate" has an answer that is a measurement
542 /// rather than a grep.
543 ///
544 /// The check reds on ANY change with both numbers. That is deliberate: a
545 /// by-value type that grew raises the question of whether it should have
546 /// been boxed instead, and auto-accepting the new number would answer
547 /// that question by default.
548 #[test]
549 fn the_measured_inventory_is_accurate() {
550 let live = measured_by_name();
551 assert_eq!(
552 BY_VALUE_TYPES.len(),
553 live.len(),
554 "the inventory names {} types but {} are measured; every row needs \
555 a measured size or the sweep is a list of hopes",
556 BY_VALUE_TYPES.len(),
557 live.len()
558 );
559 let mut rows: Vec<(&str, usize)> = live.clone();
560 rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size));
561 eprintln!(
562 "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)",
563 rows.len(),
564 STACK_BUDGET / 1024
565 );
566 eprintln!("{:>8} {:>7} TYPE", "BYTES", "%BUDGET");
567 for (name, size) in &rows {
568 eprintln!(
569 "{size:>8} {:>6.1}% {name}",
570 *size as f64 * 100.0 / STACK_BUDGET as f64
571 );
572 }
573 for (name, recorded, _public, _path) in BY_VALUE_TYPES {
574 let recorded = recorded.expect("every inventory row carries a measured size");
575 let actual = live
576 .iter()
577 .find(|(n, _)| n == name)
578 .map(|(_, size)| *size)
579 .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
580 assert_eq!(
581 recorded, actual,
582 "{name} is {actual} bytes, the inventory records {recorded}; \
583 update the table deliberately -- a by-value type that changed \
584 is a stack cost every caller of its constructor now pays"
585 );
586 }
587 }
588
589 /// The bound, asserted BY NAME. A regression in any inventoried type reds
590 /// here naming the type, not "some type is too big".
591 #[test]
592 fn every_by_value_type_fits_the_stack_budget() {
593 let live = measured_by_name();
594 let mut checked = 0usize;
595 for (name, _, public, path) in BY_VALUE_TYPES {
596 if !public {
597 continue;
598 }
599 checked += 1;
600 let size = live
601 .iter()
602 .find(|(n, _)| n == name)
603 .map(|(_, size)| *size)
604 .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
605 assert!(
606 size <= STACK_BUDGET,
607 "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \
608 stack budget ({:.2}x). It is returned by value from {path}, so \
609 every caller pays it on its own stack, and the constructors \
610 nest -- one value's size is the multiplier, not the cost. \
611 Box the large field (lane-av1enchang did exactly this for \
612 Av1Encoder::dpb, and lane-av1stacksweep for Encoded's two \
613 inline CdfSnapshots) or hand back a reference.",
614 size as f64 / STACK_BUDGET as f64
615 );
616 }
617 assert!(
618 checked >= 10,
619 "only {checked} rows were bound-checked; the budget must apply to \
620 every type a caller can be made to hold by value"
621 );
622 // The other half of the derivation, asserted so it cannot rot: the
623 // worst a caller can owe is DEEPEST_CHAIN x the worst public return.
624 let worst = live
625 .iter()
626 .filter(|(n, _)| {
627 BY_VALUE_TYPES
628 .iter()
629 .any(|(row, _, public, _)| row == n && *public)
630 })
631 .map(|(_, size)| *size)
632 .max()
633 .expect("at least one public row");
634 assert!(
635 DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024,
636 "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \
637 public by-value return ({worst} B) is {} B, over an eighth of the \
638 2101248-byte stack an unconfigured caller hands this crate; \
639 re-derive STACK_BUDGET",
640 DEEPEST_PUBLIC_CHAIN * worst
641 );
642 }
643
644 /// The crate-private CDF tables stay BEHIND A BOX.
645 ///
646 /// The budget does not apply to `Cdfs` / `CdfSnapshot` (15,232 B each)
647 /// because no `pub fn` returns them, so bounding them would calibrate the
648 /// number to something no caller can reach. What keeps them off the stack
649 /// is that every field holding one is a `Box`, and THIS is the pin for
650 /// that -- a source scan over the four declarations.
651 ///
652 /// It earned its place during this lane: `Av1Encoder` was 18,168 B after
653 /// lane-av1enchang boxed the DPB slot, and 15,232 of that was
654 /// `carried_cdfs: Option<CdfSnapshot>` sitting inline on the very same
655 /// struct. Nothing had measured it. Unboxing any of the four puts the
656 /// stack cost straight back.
657 #[test]
658 fn the_crate_private_cdf_tables_stay_behind_a_box() {
659 const PINS: &[(&str, &str, &str)] = &[
660 (
661 "encoder.rs",
662 "DpbSlot::cdfs",
663 "cdfs: Box<crate::encode::CdfSnapshot>",
664 ),
665 (
666 "encoder.rs",
667 "Av1Encoder::carried_cdfs",
668 "carried_cdfs: Option<Box<crate::encode::CdfSnapshot>>",
669 ),
670 (
671 "encode.rs",
672 "Encoded::start_cdfs",
673 "start_cdfs: Box<CdfSnapshot>",
674 ),
675 (
676 "encode.rs",
677 "Encoded::next_cdfs",
678 "next_cdfs: Box<CdfSnapshot>",
679 ),
680 ];
681 let files: [(&str, &str); 2] = [
682 ("encoder.rs", crate::test_source::module_source("encoder")),
683 ("encode.rs", crate::test_source::module_source("encode")),
684 ];
685 for (file, field, spelling) in PINS {
686 let src = files
687 .iter()
688 .find(|(name, _)| name == file)
689 .map(|(_, src)| *src)
690 .unwrap_or_else(|| panic!("no source pinned for {file}"));
691 let where_ = format!("{file}::{field}");
692 assert!(
693 src.contains(spelling),
694 "{where_} is no longer declared `{spelling}`. An inline \
695 CdfSnapshot there puts {field}'s 15232 bytes back on every \
696 caller's stack -- that is how Av1Encoder was 139960 bytes \
697 before lane-av1enchang, and how it was still 18168 after it, \
698 because carried_cdfs was missed.",
699 );
700 }
701 // And the negative control: the unboxed spellings must NOT all still
702 // be present, or the scan above would be matching a comment.
703 let encoder = files[0].1;
704 assert!(
705 !encoder.contains("cdfs: crate::encode::CdfSnapshot,"),
706 "the box pin is matching a spelling that is not the live \
707 declaration"
708 );
709 }
710
711 /// CAPABILITY: really construct the heavy types on a tight stack, so a
712 /// regression ABORTS THE PROCESS instead of costing invisible margin.
713 ///
714 /// Both arms are the deepest public chains in the crate: the encoder's
715 /// three-deep `Result<Self>` constructor nest, and the four-deep
716 /// `Result<Encoded>` chain, the longest by-value return path here.
717 ///
718 /// Measured stack need, **debug** build, 64x64, one process per point so a
719 /// SIGABRT cannot truncate the sweep:
720 ///
721 /// | stack | before this lane boxed `Encoded` | after |
722 /// |---|---|---|
723 /// | 131072 | overflow | overflow |
724 /// | 262144 | overflow | overflow |
725 /// | 327680 | overflow | overflow |
726 /// | 466944 | overflow | **overflow** |
727 /// | 475136 | overflow | **ok** |
728 /// | 524288 | overflow | **ok** |
729 /// | 786432 | **overflow** | ok |
730 /// | 1048576 | **ok** | **ok** |
731 ///
732 /// The gate sits at 1 MiB, now **2.2x** the deepest measured need rather
733 /// than 1.33x. Boxing `Encoded`'s two inline `CdfSnapshot`s (99.2% of its
734 /// 30,728 bytes) and `Av1Encoder::carried_cdfs` (15,232 of its 18,168) is
735 /// what moved the threshold. The ~470 KB that remains is the encode
736 /// search's own frames, which this module does not claim to shrink.
737 ///
738 /// Pre-fix (`CdfSnapshot` by value in the DPB) the encoder arm overflowed
739 /// at 1 MiB and at 2 MiB. `EC_AV1_TIGHT_STACK_BYTES` overrides the size,
740 /// which is how the table above is reproduced.
741 #[test]
742 fn the_deepest_by_value_constructors_fit_on_a_tight_stack() {
743 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Pyramid, RateTarget};
744 let stack: usize = std::env::var("EC_AV1_TIGHT_STACK_BYTES")
745 .ok()
746 .and_then(|v| v.parse().ok())
747 .unwrap_or(TIGHT_STACK);
748 let config = EncoderConfig {
749 width: 64,
750 height: 64,
751 base_q_idx: 100,
752 gop: 48,
753 colour: Colour::Bt709Limited,
754 tile_cols_log2: 0,
755 tile_rows_log2: 0,
756 };
757 let rate = RateTarget::Bitrate {
758 bits_per_second: 1_536_000,
759 frames_per_second: 24.0,
760 };
761 let handle = std::thread::Builder::new()
762 .stack_size(stack)
763 .spawn(move || {
764 // Arm 1: the three-deep Result<Self> constructor nest.
765 let encoder =
766 Av1Encoder::with_pyramid_and_rate_target(config, Pyramid::default(), rate)
767 .expect("with_pyramid_and_rate_target");
768 let pyramid = encoder.pyramid().is_some();
769 drop(encoder);
770 // Arm 2: the four-deep Result<Encoded> chain, the crate's
771 // largest by-value return.
772 let grey = crate::encode::Picture::grey(64, 64);
773 let encoded =
774 crate::encode::encode_key_frame(&grey, 100, 0.0).expect("encode_key_frame");
775 (pyramid, encoded.stream.len())
776 })
777 .expect("spawn tight-stack thread");
778 let (pyramid, bytes) = handle.join().unwrap_or_else(|_| {
779 panic!(
780 "a by-value constructor overflowed a {stack}-byte stack; the \
781 threshold table on this test says what that costs"
782 )
783 });
784 assert!(pyramid, "with_pyramid_and_rate_target lost its pyramid");
785 assert!(bytes > 0, "encode_key_frame produced no stream");
786 eprintln!(
787 "TIGHTSTACK {stack} bytes: Av1Encoder={} Encoded={} bytes, both chains returned",
788 std::mem::size_of::<Av1Encoder>(),
789 std::mem::size_of::<Encoded>(),
790 );
791 }
792
793 /// The sweep's teeth against a NEW by-value return: re-derive the set from
794 /// the crate source and require every name to be inventoried.
795 ///
796 /// Without this the inventory is a list of what someone remembered to
797 /// measure, and a lane that adds `pub fn make() -> HugeThing` where
798 /// `HugeThing` is 200 KB of inline tables passes every other test here.
799 #[test]
800 fn every_by_value_public_return_is_in_the_inventory() {
801 let mut found: Vec<(String, String)> = Vec::new();
802 for (file, src) in files() {
803 for (n, line) in src.lines().enumerate() {
804 if let Some(name) = by_value_return_name(line) {
805 found.push((name, format!("{file}:{}", n + 1)));
806 }
807 }
808 }
809 found.sort();
810 found.dedup();
811 assert!(
812 found.len() > 5,
813 "the by-value return scan found {} names across {} files, which is \
814 too few to be a real sweep -- the matcher, not the crate, is broken",
815 found.len(),
816 files().len()
817 );
818
819 let mut missing = Vec::new();
820 for (name, site) in &found {
821 if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) {
822 missing.push(format!("{name} ({site})"));
823 }
824 }
825 assert!(
826 missing.is_empty(),
827 "these types are returned BY VALUE from a public fn and are not in \
828 the inventory: {}. Either they are thin enough not to be a stack \
829 cost -- say so by adding a row with its measured size -- or they \
830 are the next instance of the class this module exists for.",
831 missing.join(", ")
832 );
833 }
834
835 /// The control for the scan above, on synthetic text rather than by
836 /// trusting the live tree to happen to contain a case.
837 ///
838 /// If the matcher silently stopped recognising a shape, the sweep would
839 /// pass everything and this would still be asserting nothing. So: every
840 /// by-value spelling the crate uses must yield its type name, and every
841 /// pointer/Vec/primitive/`Self` spelling must yield nothing.
842 #[test]
843 fn the_inventory_scan_is_not_vacuous() {
844 for synthetic in [
845 "pub fn zz_a() -> ZzNotInventoried { todo!() }",
846 "pub fn zz_b() -> Result<ZzNotInventoried, Error> { todo!() }",
847 "pub fn zz_c() -> Result<ZzNotInventoried> { todo!() }",
848 "pub fn zz_d() -> Option<ZzNotInventoried> { todo!() }",
849 "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }",
850 ] {
851 let name = by_value_return_name(synthetic)
852 .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`"));
853 assert_eq!(
854 name, "ZzNotInventoried",
855 "the matcher mangled `{synthetic}` into `{name}`, so the sweep \
856 cannot see a new by-value return and its green is vacuous"
857 );
858 assert!(
859 !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name),
860 "the synthetic control name is in the inventory, so the control \
861 proves nothing"
862 );
863 }
864 for thin in [
865 "pub fn zz_t() -> Box<Decoder> { todo!() }",
866 "pub fn zz_u() -> Result<Vec<u8>, Error> { todo!() }",
867 "pub fn zz_v() -> Option<&Path> { todo!() }",
868 "pub fn zz_w() -> usize { todo!() }",
869 "pub fn zz_x() -> Self { todo!() }",
870 "pub fn zz_y() -> Result<Arc<Decoder>, Error> { todo!() }",
871 "pub fn zz_z() { todo!() }",
872 "fn zz_private() -> ZzNotInventoried { todo!() }",
873 ] {
874 assert_eq!(
875 by_value_return_name(thin),
876 None,
877 "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \
878 above already cover, or not a `pub fn` -- the matcher must not \
879 read it as an uninventoried by-value return"
880 );
881 }
882 }
883
884 /// The stack mapping containing `addr` in `/proc/self/task/<tid>/maps`.
885 ///
886 /// The returned size is a LOWER BOUND, never an exact count. Linux MERGES
887 /// adjacent VMAs that share protections, and a merged region is
888 /// indistinguishable from a single one in the maps file -- a thread whose
889 /// 1 MiB stack abutted a neighbour's read back here as 69218304 bytes with
890 /// nothing to indicate the join. Two earlier versions of this test tried to
891 /// be exact anyway (asserting a byte count, then detecting the merge by
892 /// looking for an abutting same-protection neighbour) and both were wrong
893 /// for that reason.
894 ///
895 /// A lower bound is what the budget's reasoning needs: the claim is "no
896 /// caller gets less than 2 MiB", and `size >= 2 MiB` is exactly that,
897 /// whether the region is one mapping or three.
898 ///
899 /// The third field is whether the mapping is writable. Merging only joins
900 /// VMAs whose protections match, so a merged thread stack is still
901 /// writable. Its size can grow without bound, which is why the tests check
902 /// this flag and never an upper bound on the size.
903 fn stack_region(tid: u32, addr: usize) -> Option<(usize, usize, bool)> {
904 let maps = std::fs::read_to_string(format!("/proc/self/task/{tid}/maps")).ok()?;
905 for line in maps.lines() {
906 let (range, perms) = line.split_once(' ')?;
907 let (lo, hi) = range.split_once('-')?;
908 let (lo, hi) = (
909 usize::from_str_radix(lo, 16).ok()?,
910 usize::from_str_radix(hi, 16).ok()?,
911 );
912 if addr >= lo && addr < hi {
913 // `perms` is `rwxp`-style: the second character is write.
914 let writable = perms.as_bytes().get(1) == Some(&b'w');
915 return Some((lo, hi, writable));
916 }
917 }
918 None
919 }
920
921 /// What a thread's stack ACTUALLY is, read from
922 /// `/proc/self/task/<tid>/maps` rather than assumed from a default.
923 ///
924 /// The number the budget's reasoning rests on, measured two ways:
925 ///
926 /// * a thread spawned with an EXPLICIT size gets AT LEAST that size --
927 /// the control that says the parse finds stacks at all, and the shape
928 /// [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] relies on;
929 /// * the DEFAULT -- no `stack_size`, i.e. what a library consumer's
930 /// `std::thread::spawn` gets, and what libtest gives a test thread when
931 /// `RUST_MIN_STACK` is unset -- is at least 2 MiB.
932 ///
933 /// Both are floors, because [`stack_region`] can only report a lower bound.
934 /// That is the right direction: the budget's claim is that no caller gets
935 /// LESS than 2 MiB, and a floor is what proves it.
936 ///
937 /// Exact figures measured on this runtime, for the report: 2101248 bytes
938 /// with the repo's `.cargo/config.toml` cap lifted, 67112960 with it
939 /// applied. A library consumer gets the first, and that is the one the
940 /// budget is sized for.
941 #[test]
942 fn test_threads_get_the_stack_they_are_given() {
943 const EXPLICIT: usize = 1024 * 1024;
944 let handle = std::thread::Builder::new()
945 .stack_size(EXPLICIT)
946 .spawn(|| {
947 let tid = std::process::id();
948 let marker = 0u8;
949 let here = &marker as *const u8 as usize;
950 let (lo, hi, rw) =
951 stack_region(tid, here).expect("this thread's own stack is in its maps");
952 (lo, hi, rw)
953 })
954 .expect("spawn");
955 let (lo, hi, rw) = handle.join().expect("the probe thread returned");
956 let size = hi - lo;
957 assert!(
958 size >= EXPLICIT,
959 "a thread spawned with stack_size({EXPLICIT}) has a {size}-byte \
960 stack mapping; the runtime gave it less than it was promised, so \
961 the maps parse is finding the wrong region"
962 );
963 assert!(
964 rw,
965 "the mapping holding an explicitly-1-MiB thread's frame is not \
966 writable -- a thread stack is read-write, so the maps parse found \
967 the wrong region"
968 );
969
970 let tid = std::process::id();
971 let marker = 0u8;
972 let here = &marker as *const u8 as usize;
973 let (lo, hi, rw) =
974 stack_region(tid, here).expect("this test thread's stack is in its maps");
975 let size = hi - lo;
976 assert!(
977 rw,
978 "a default test thread's stack mapping is not writable -- the maps \
979 parse found the wrong region"
980 );
981 assert!(
982 size >= 2 * 1024 * 1024,
983 "a default test thread's stack measured {size} bytes, under the \
984 2 MiB floor the by-value budget is derived from; the smallest \
985 stack a caller can hand this crate just got smaller and the bound \
986 needs re-deriving"
987 );
988 eprintln!(
989 "TESTTHREADSTACK default tid={tid} region=[{lo:x},{hi:x}) size>={size} \
990 (2101248 measured exactly with the repo cap lifted, 67112960 with it)"
991 );
992 }
993}