forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.4 MiB35bdf35Tahinli2 months ago3757 commits

stack_budget.rs973 lines, 42.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(2944),
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(1296),
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 const FILES: &[(&str, &str)] = &[
445 ("bits.rs", include_str!("bits.rs")),
446 ("cdf.rs", include_str!("cdf.rs")),
447 ("cdf_state.rs", include_str!("cdf_state.rs")),
448 ("census.rs", include_str!("census.rs")),
449 ("compound.rs", include_str!("compound.rs")),
450 ("decode.rs", include_str!("decode.rs")),
451 ("encode.rs", include_str!("encode.rs")),
452 ("encoder.rs", include_str!("encoder.rs")),
453 ("envflags.rs", include_str!("envflags.rs")),
454 ("film_grain.rs", include_str!("film_grain.rs")),
455 ("filter_search.rs", include_str!("filter_search.rs")),
456 ("frame.rs", include_str!("frame.rs")),
457 ("gate_coverage.rs", include_str!("gate_coverage.rs")),
458 ("hits.rs", include_str!("hits.rs")),
459 ("intra.rs", include_str!("intra.rs")),
460 ("library_fixture.rs", include_str!("library_fixture.rs")),
461 ("mc.rs", include_str!("mc.rs")),
462 ("motion.rs", include_str!("motion.rs")),
463 ("motion_field.rs", include_str!("motion_field.rs")),
464 ("msac.rs", include_str!("msac.rs")),
465 ("mvstack.rs", include_str!("mvstack.rs")),
466 ("obu.rs", include_str!("obu.rs")),
467 ("par.rs", include_str!("par.rs")),
468 ("probe.rs", include_str!("probe.rs")),
469 ("qm.rs", include_str!("qm.rs")),
470 ("quant.rs", include_str!("quant.rs")),
471 ("refusal_inventory.rs", include_str!("refusal_inventory.rs")),
472 ("restoration.rs", include_str!("restoration.rs")),
473 ("sequence.rs", include_str!("sequence.rs")),
474 ("speed.rs", include_str!("speed.rs")),
475 ("stream.rs", include_str!("stream.rs")),
476 ("superres.rs", include_str!("superres.rs")),
477 ("tile.rs", include_str!("tile.rs")),
478 ("timeline.rs", include_str!("timeline.rs")),
479 ("transform.rs", include_str!("transform.rs")),
480 ("warp.rs", include_str!("warp.rs")),
481 ("wedge.rs", include_str!("wedge.rs")),
482 ("stack_budget.rs", include_str!("stack_budget.rs")),
483 ];
484
485 /// Every module `lib.rs` declares, so the scan's file list cannot silently
486 /// fall behind a new module. A new `mod foo;` with a by-value `pub fn`
487 /// that the scan never reads is exactly the hole this class would come
488 /// back through, so the list is derived, not curated.
489 #[test]
490 fn every_by_value_module_is_scanned() {
491 let lib = include_str!("lib.rs");
492 let mut declared: Vec<&str> = Vec::new();
493 for line in lib.lines() {
494 let t = line.trim();
495 let rest = t
496 .strip_prefix("pub mod ")
497 .or_else(|| t.strip_prefix("mod "))
498 .unwrap_or("");
499 if rest.is_empty() {
500 continue;
501 }
502 let name = rest.split([';', ' ']).next().unwrap_or("");
503 if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
504 declared.push(name);
505 }
506 }
507 assert!(
508 declared.len() > 10,
509 "only {} module declarations parsed out of lib.rs, so the \
510 derived file list is broken rather than small",
511 declared.len()
512 );
513 let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect();
514 let mut missing: Vec<String> = declared
515 .iter()
516 .filter(|d| !scanned.iter().any(|s| *s == format!("{d}.rs")))
517 .map(|d| (*d).to_string())
518 .collect();
519 missing.sort();
520 assert!(
521 missing.is_empty(),
522 "lib.rs declares modules the by-value scan never reads: {:?}. Add \
523 them to FILES, or the sweep cannot see a new by-value return that \
524 lands in one of them.",
525 missing
526 );
527 }
528
529 /// The inventory, printed as a sorted table, and checked against the
530 /// types' real sizes.
531 ///
532 /// The print is the instrument: one command
533 /// (`cargo test -p ec-av1 --lib -- stack_budget -- --nocapture`)
534 /// reproduces the whole table, biggest first, so "what is the largest
535 /// by-value type in this crate" has an answer that is a measurement
536 /// rather than a grep.
537 ///
538 /// The check reds on ANY change with both numbers. That is deliberate: a
539 /// by-value type that grew raises the question of whether it should have
540 /// been boxed instead, and auto-accepting the new number would answer
541 /// that question by default.
542 #[test]
543 fn the_measured_inventory_is_accurate() {
544 let live = measured_by_name();
545 assert_eq!(
546 BY_VALUE_TYPES.len(),
547 live.len(),
548 "the inventory names {} types but {} are measured; every row needs \
549 a measured size or the sweep is a list of hopes",
550 BY_VALUE_TYPES.len(),
551 live.len()
552 );
553 let mut rows: Vec<(&str, usize)> = live.clone();
554 rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size));
555 eprintln!(
556 "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)",
557 rows.len(),
558 STACK_BUDGET / 1024
559 );
560 eprintln!("{:>8} {:>7} {}", "BYTES", "%BUDGET", "TYPE");
561 for (name, size) in &rows {
562 eprintln!(
563 "{size:>8} {:>6.1}% {name}",
564 *size as f64 * 100.0 / STACK_BUDGET as f64
565 );
566 }
567 for (name, recorded, _public, _path) in BY_VALUE_TYPES {
568 let recorded = recorded.expect("every inventory row carries a measured size");
569 let actual = live
570 .iter()
571 .find(|(n, _)| n == name)
572 .map(|(_, size)| *size)
573 .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
574 assert_eq!(
575 recorded, actual,
576 "{name} is {actual} bytes, the inventory records {recorded}; \
577 update the table deliberately -- a by-value type that changed \
578 is a stack cost every caller of its constructor now pays"
579 );
580 }
581 }
582
583 /// The bound, asserted BY NAME. A regression in any inventoried type reds
584 /// here naming the type, not "some type is too big".
585 #[test]
586 fn every_by_value_type_fits_the_stack_budget() {
587 let live = measured_by_name();
588 let mut checked = 0usize;
589 for (name, _, public, path) in BY_VALUE_TYPES {
590 if !public {
591 continue;
592 }
593 checked += 1;
594 let size = live
595 .iter()
596 .find(|(n, _)| n == name)
597 .map(|(_, size)| *size)
598 .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
599 assert!(
600 size <= STACK_BUDGET,
601 "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \
602 stack budget ({:.2}x). It is returned by value from {path}, so \
603 every caller pays it on its own stack, and the constructors \
604 nest -- one value's size is the multiplier, not the cost. \
605 Box the large field (lane-av1enchang did exactly this for \
606 Av1Encoder::dpb, and lane-av1stacksweep for Encoded's two \
607 inline CdfSnapshots) or hand back a reference.",
608 size as f64 / STACK_BUDGET as f64
609 );
610 }
611 assert!(
612 checked >= 10,
613 "only {checked} rows were bound-checked; the budget must apply to \
614 every type a caller can be made to hold by value"
615 );
616 // The other half of the derivation, asserted so it cannot rot: the
617 // worst a caller can owe is DEEPEST_CHAIN x the worst public return.
618 let worst = live
619 .iter()
620 .filter(|(n, _)| {
621 BY_VALUE_TYPES
622 .iter()
623 .any(|(row, _, public, _)| row == n && *public)
624 })
625 .map(|(_, size)| *size)
626 .max()
627 .expect("at least one public row");
628 assert!(
629 DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024,
630 "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \
631 public by-value return ({worst} B) is {} B, over an eighth of the \
632 2101248-byte stack an unconfigured caller hands this crate; \
633 re-derive STACK_BUDGET",
634 DEEPEST_PUBLIC_CHAIN * worst
635 );
636 }
637
638 /// The crate-private CDF tables stay BEHIND A BOX.
639 ///
640 /// The budget does not apply to `Cdfs` / `CdfSnapshot` (15,232 B each)
641 /// because no `pub fn` returns them, so bounding them would calibrate the
642 /// number to something no caller can reach. What keeps them off the stack
643 /// is that every field holding one is a `Box`, and THIS is the pin for
644 /// that -- a source scan over the four declarations.
645 ///
646 /// It earned its place during this lane: `Av1Encoder` was 18,168 B after
647 /// lane-av1enchang boxed the DPB slot, and 15,232 of that was
648 /// `carried_cdfs: Option<CdfSnapshot>` sitting inline on the very same
649 /// struct. Nothing had measured it. Unboxing any of the four puts the
650 /// stack cost straight back.
651 #[test]
652 fn the_crate_private_cdf_tables_stay_behind_a_box() {
653 const PINS: &[(&str, &str, &str)] = &[
654 (
655 "encoder.rs",
656 "DpbSlot::cdfs",
657 "cdfs: Box<crate::encode::CdfSnapshot>",
658 ),
659 (
660 "encoder.rs",
661 "Av1Encoder::carried_cdfs",
662 "carried_cdfs: Option<Box<crate::encode::CdfSnapshot>>",
663 ),
664 (
665 "encode.rs",
666 "Encoded::start_cdfs",
667 "start_cdfs: Box<CdfSnapshot>",
668 ),
669 (
670 "encode.rs",
671 "Encoded::next_cdfs",
672 "next_cdfs: Box<CdfSnapshot>",
673 ),
674 ];
675 const FILES: &[(&str, &str)] = &[
676 ("encoder.rs", include_str!("encoder.rs")),
677 ("encode.rs", include_str!("encode.rs")),
678 ];
679 for (file, field, spelling) in PINS {
680 let src = FILES
681 .iter()
682 .find(|(name, _)| name == file)
683 .map(|(_, src)| *src)
684 .unwrap_or_else(|| panic!("no source pinned for {file}"));
685 let where_ = format!("{file}::{field}");
686 assert!(
687 src.contains(spelling),
688 "{where_} is no longer declared `{spelling}`. An inline \
689 CdfSnapshot there puts {field}'s 15232 bytes back on every \
690 caller's stack -- that is how Av1Encoder was 139960 bytes \
691 before lane-av1enchang, and how it was still 18168 after it, \
692 because carried_cdfs was missed.",
693 );
694 }
695 // And the negative control: the unboxed spellings must NOT all still
696 // be present, or the scan above would be matching a comment.
697 let encoder = FILES[0].1;
698 assert!(
699 !encoder.contains("cdfs: crate::encode::CdfSnapshot,"),
700 "the box pin is matching a spelling that is not the live \
701 declaration"
702 );
703 }
704
705 /// CAPABILITY: really construct the heavy types on a tight stack, so a
706 /// regression ABORTS THE PROCESS instead of costing invisible margin.
707 ///
708 /// Both arms are the deepest public chains in the crate: the encoder's
709 /// three-deep `Result<Self>` constructor nest, and the four-deep
710 /// `Result<Encoded>` chain, the longest by-value return path here.
711 ///
712 /// Measured stack need, **debug** build, 64x64, one process per point so a
713 /// SIGABRT cannot truncate the sweep:
714 ///
715 /// | stack | before this lane boxed `Encoded` | after |
716 /// |---|---|---|
717 /// | 131072 | overflow | overflow |
718 /// | 262144 | overflow | overflow |
719 /// | 327680 | overflow | overflow |
720 /// | 466944 | overflow | **overflow** |
721 /// | 475136 | overflow | **ok** |
722 /// | 524288 | overflow | **ok** |
723 /// | 786432 | **overflow** | ok |
724 /// | 1048576 | **ok** | **ok** |
725 ///
726 /// The gate sits at 1 MiB, now **2.2x** the deepest measured need rather
727 /// than 1.33x. Boxing `Encoded`'s two inline `CdfSnapshot`s (99.2% of its
728 /// 30,728 bytes) and `Av1Encoder::carried_cdfs` (15,232 of its 18,168) is
729 /// what moved the threshold. The ~470 KB that remains is the encode
730 /// search's own frames, which this module does not claim to shrink.
731 ///
732 /// Pre-fix (`CdfSnapshot` by value in the DPB) the encoder arm overflowed
733 /// at 1 MiB and at 2 MiB. `EC_AV1_TIGHT_STACK_BYTES` overrides the size,
734 /// which is how the table above is reproduced.
735 #[test]
736 fn the_deepest_by_value_constructors_fit_on_a_tight_stack() {
737 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Pyramid, RateTarget};
738 let stack: usize = std::env::var("EC_AV1_TIGHT_STACK_BYTES")
739 .ok()
740 .and_then(|v| v.parse().ok())
741 .unwrap_or(TIGHT_STACK);
742 let config = EncoderConfig {
743 width: 64,
744 height: 64,
745 base_q_idx: 100,
746 gop: 48,
747 colour: Colour::Bt709Limited,
748 tile_cols_log2: 0,
749 tile_rows_log2: 0,
750 };
751 let rate = RateTarget::Bitrate {
752 bits_per_second: 1_536_000,
753 frames_per_second: 24.0,
754 };
755 let handle = std::thread::Builder::new()
756 .stack_size(stack)
757 .spawn(move || {
758 // Arm 1: the three-deep Result<Self> constructor nest.
759 let encoder =
760 Av1Encoder::with_pyramid_and_rate_target(config, Pyramid::default(), rate)
761 .expect("with_pyramid_and_rate_target");
762 let pyramid = encoder.pyramid().is_some();
763 drop(encoder);
764 // Arm 2: the four-deep Result<Encoded> chain, the crate's
765 // largest by-value return.
766 let grey = crate::encode::Picture::grey(64, 64);
767 let encoded =
768 crate::encode::encode_key_frame(&grey, 100, 0.0).expect("encode_key_frame");
769 (pyramid, encoded.stream.len())
770 })
771 .expect("spawn tight-stack thread");
772 let (pyramid, bytes) = handle.join().unwrap_or_else(|_| {
773 panic!(
774 "a by-value constructor overflowed a {stack}-byte stack; the \
775 threshold table on this test says what that costs"
776 )
777 });
778 assert!(pyramid, "with_pyramid_and_rate_target lost its pyramid");
779 assert!(bytes > 0, "encode_key_frame produced no stream");
780 eprintln!(
781 "TIGHTSTACK {stack} bytes: Av1Encoder={} Encoded={} bytes, both chains returned",
782 std::mem::size_of::<Av1Encoder>(),
783 std::mem::size_of::<Encoded>(),
784 );
785 }
786
787 /// The sweep's teeth against a NEW by-value return: re-derive the set from
788 /// the crate source and require every name to be inventoried.
789 ///
790 /// Without this the inventory is a list of what someone remembered to
791 /// measure, and a lane that adds `pub fn make() -> HugeThing` where
792 /// `HugeThing` is 200 KB of inline tables passes every other test here.
793 #[test]
794 fn every_by_value_public_return_is_in_the_inventory() {
795 let mut found: Vec<(String, String)> = Vec::new();
796 for (file, src) in FILES {
797 for (n, line) in src.lines().enumerate() {
798 if let Some(name) = by_value_return_name(line) {
799 found.push((name, format!("{file}:{}", n + 1)));
800 }
801 }
802 }
803 found.sort();
804 found.dedup();
805 assert!(
806 found.len() > 5,
807 "the by-value return scan found {} names across {} files, which is \
808 too few to be a real sweep -- the matcher, not the crate, is broken",
809 found.len(),
810 FILES.len()
811 );
812
813 let mut missing = Vec::new();
814 for (name, site) in &found {
815 if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) {
816 missing.push(format!("{name} ({site})"));
817 }
818 }
819 assert!(
820 missing.is_empty(),
821 "these types are returned BY VALUE from a public fn and are not in \
822 the inventory: {}. Either they are thin enough not to be a stack \
823 cost -- say so by adding a row with its measured size -- or they \
824 are the next instance of the class this module exists for.",
825 missing.join(", ")
826 );
827 }
828
829 /// The control for the scan above, on synthetic text rather than by
830 /// trusting the live tree to happen to contain a case.
831 ///
832 /// If the matcher silently stopped recognising a shape, the sweep would
833 /// pass everything and this would still be asserting nothing. So: every
834 /// by-value spelling the crate uses must yield its type name, and every
835 /// pointer/Vec/primitive/`Self` spelling must yield nothing.
836 #[test]
837 fn the_inventory_scan_is_not_vacuous() {
838 for synthetic in [
839 "pub fn zz_a() -> ZzNotInventoried { todo!() }",
840 "pub fn zz_b() -> Result<ZzNotInventoried, Error> { todo!() }",
841 "pub fn zz_c() -> Result<ZzNotInventoried> { todo!() }",
842 "pub fn zz_d() -> Option<ZzNotInventoried> { todo!() }",
843 "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }",
844 ] {
845 let name = by_value_return_name(synthetic)
846 .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`"));
847 assert_eq!(
848 name, "ZzNotInventoried",
849 "the matcher mangled `{synthetic}` into `{name}`, so the sweep \
850 cannot see a new by-value return and its green is vacuous"
851 );
852 assert!(
853 !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name),
854 "the synthetic control name is in the inventory, so the control \
855 proves nothing"
856 );
857 }
858 for thin in [
859 "pub fn zz_t() -> Box<Decoder> { todo!() }",
860 "pub fn zz_u() -> Result<Vec<u8>, Error> { todo!() }",
861 "pub fn zz_v() -> Option<&Path> { todo!() }",
862 "pub fn zz_w() -> usize { todo!() }",
863 "pub fn zz_x() -> Self { todo!() }",
864 "pub fn zz_y() -> Result<Arc<Decoder>, Error> { todo!() }",
865 "pub fn zz_z() { todo!() }",
866 "fn zz_private() -> ZzNotInventoried { todo!() }",
867 ] {
868 assert_eq!(
869 by_value_return_name(thin),
870 None,
871 "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \
872 above already cover, or not a `pub fn` -- the matcher must not \
873 read it as an uninventoried by-value return"
874 );
875 }
876 }
877
878 /// The stack mapping containing `addr` in `/proc/self/task/<tid>/maps`.
879 ///
880 /// The returned size is a LOWER BOUND, never an exact count. Linux MERGES
881 /// adjacent VMAs that share protections, and a merged region is
882 /// indistinguishable from a single one in the maps file -- a thread whose
883 /// 1 MiB stack abutted a neighbour's read back here as 69218304 bytes with
884 /// nothing to indicate the join. Two earlier versions of this test tried to
885 /// be exact anyway (asserting a byte count, then detecting the merge by
886 /// looking for an abutting same-protection neighbour) and both were wrong
887 /// for that reason.
888 ///
889 /// A lower bound is what the budget's reasoning needs: the claim is "no
890 /// caller gets less than 2 MiB", and `size >= 2 MiB` is exactly that,
891 /// whether the region is one mapping or three.
892 fn stack_region(tid: u32, addr: usize) -> Option<(usize, usize)> {
893 let maps = std::fs::read_to_string(format!("/proc/self/task/{tid}/maps")).ok()?;
894 for line in maps.lines() {
895 let (range, _) = line.split_once(' ')?;
896 let (lo, hi) = range.split_once('-')?;
897 let (lo, hi) = (
898 usize::from_str_radix(lo, 16).ok()?,
899 usize::from_str_radix(hi, 16).ok()?,
900 );
901 if addr >= lo && addr < hi {
902 return Some((lo, hi));
903 }
904 }
905 None
906 }
907
908 /// What a thread's stack ACTUALLY is, read from
909 /// `/proc/self/task/<tid>/maps` rather than assumed from a default.
910 ///
911 /// The number the budget's reasoning rests on, measured two ways:
912 ///
913 /// * a thread spawned with an EXPLICIT size gets AT LEAST that size --
914 /// the control that says the parse finds stacks at all, and the shape
915 /// [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] relies on;
916 /// * the DEFAULT -- no `stack_size`, i.e. what a library consumer's
917 /// `std::thread::spawn` gets, and what libtest gives a test thread when
918 /// `RUST_MIN_STACK` is unset -- is at least 2 MiB.
919 ///
920 /// Both are floors, because [`stack_region`] can only report a lower bound.
921 /// That is the right direction: the budget's claim is that no caller gets
922 /// LESS than 2 MiB, and a floor is what proves it.
923 ///
924 /// Exact figures measured on this runtime, for the report: 2101248 bytes
925 /// with the repo's `.cargo/config.toml` cap lifted, 67112960 with it
926 /// applied. A library consumer gets the first, and that is the one the
927 /// budget is sized for.
928 #[test]
929 fn test_threads_get_the_stack_they_are_given() {
930 const EXPLICIT: usize = 1024 * 1024;
931 let handle = std::thread::Builder::new()
932 .stack_size(EXPLICIT)
933 .spawn(|| {
934 let tid = std::process::id();
935 let marker = 0u8;
936 let here = &marker as *const u8 as usize;
937 let (lo, hi) =
938 stack_region(tid, here).expect("this thread's own stack is in its maps");
939 (tid, lo, hi)
940 })
941 .expect("spawn");
942 let (_tid, lo, hi) = handle.join().expect("the probe thread returned");
943 let size = hi - lo;
944 assert!(
945 size >= EXPLICIT,
946 "a thread spawned with stack_size({EXPLICIT}) has a {size}-byte \
947 stack mapping; the runtime gave it less than it was promised, so \
948 the maps parse is finding the wrong region"
949 );
950 assert!(
951 size <= 512 * 1024 * 1024,
952 "the mapping holding an explicitly-1-MiB thread's frame is {size} \
953 bytes, which is not a stack -- the maps parse found the wrong region"
954 );
955
956 let tid = std::process::id();
957 let marker = 0u8;
958 let here = &marker as *const u8 as usize;
959 let (lo, hi) = stack_region(tid, here).expect("this test thread's stack is in its maps");
960 let size = hi - lo;
961 assert!(
962 size >= 2 * 1024 * 1024,
963 "a default test thread's stack measured {size} bytes, under the \
964 2 MiB floor the by-value budget is derived from; the smallest \
965 stack a caller can hand this crate just got smaller and the bound \
966 needs re-deriving"
967 );
968 eprintln!(
969 "TESTTHREADSTACK default tid={tid} region=[{lo:x},{hi:x}) size>={size} \
970 (2101248 measured exactly with the repo cap lifted, 67112960 with it)"
971 );
972 }
973}