forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB3d2e08fTahinli7 days ago3929 commits

stack_budget.rs879 lines, 38.3 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. `Encoder` is the
8//! workspace's largest live instance of this class: it was **87,024 bytes** by
9//! value -- ten and a half times the budget below -- because six
10//! SILK encoder slots (79,176 bytes together) and a 3,831-byte SILK packet scratch buffer
11//! (`MAX_SILK_PACKET_BYTES = 1 + 1 + 2 * 2 + 3 * 1275`) sat INLINE on a type
12//! `Encoder::new` hands back by value. `Decoder` was 7,576, 92.5% of the
13//! budget, with a 6,304-byte `SilkDecoder` inline.
14//!
15//! Both are boxed now (82,952 bytes moved off the stack onto the heap: the
16//! `Box`ed SILK layer, `silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>`, and
17//! `Decoder::silk: Box<SilkDecoder>`), and this module is what stops the
18//! numbers from walking back.
19//!
20//! # Why this module exists
21//!
22//! 1. [`BY_VALUE_TYPES`] is the inventory -- every type in this crate a public
23//! `fn` can return or take by value, with a measured `size_of` recorded as
24//! of this commit. [`the_measured_inventory_is_accurate`] fails if a size
25//! moves, so the table cannot rot into a list of stale small numbers.
26//! 2. [`STACK_BUDGET`] is the bound, and
27//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for
28//! every budgeted row, so a regression reds naming the type that caused it.
29//! 3. [`the_crate_private_silk_encoders_stay_behind_a_box`] pins the three
30//! `Box` spellings that moved the 87 KB off the stack, with a negative
31//! control so the scan cannot be matching a doc comment.
32//! 4. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the
33//! capability arm: it really constructs `Encoder::new` and `Decoder::new` on
34//! a deliberately tight thread, so the old layout ABORTS THE PROCESS rather
35//! than quietly costing margin. Red/green in milliseconds.
36//! 5. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's
37//! teeth against NEW types: a source scan re-derives the set of by-value
38//! public returns from the crate source, so a lane that adds a 40 KB struct
39//! to a `pub fn` return reds here until it is measured and listed.
40//! [`the_inventory_scan_is_not_vacuous`] is its control, and
41//! [`every_by_value_module_is_scanned`] keeps the scan's file list from
42//! falling behind a new `mod` in `lib.rs`.
43//!
44//! # The bound, and why this number
45//!
46//! [`STACK_BUDGET`] = 8192 bytes (8 KiB), the same number ec-av1's identical
47//! sweep uses, and it is bounded from BOTH sides by measurement:
48//!
49//! * **The smallest stack a caller can hand this crate is 2 MiB** -- libtest's
50//! default test thread, and what `std::thread::Builder::new()` gives a
51//! caller who does not ask for a size. This workspace's
52//! `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864`, which hides
53//! the problem from its own runs; a library consumer gets no
54//! `.cargo/config.toml` and no such cover.
55//! * **The deepest PUBLIC by-value chain is 2**
56//! ([`DEEPEST_PUBLIC_CHAIN`]): `MultistreamDecoder::with_rate` ->
57//! `MultistreamDecoder::try_with_rate` (`multistream.rs:47` -> `:63`), both
58//! handing back a `MultistreamDecoder` by value, so both frames hold a
59//! return slot at once. `Encoder::new` (`encoder.rs:166`) and `Decoder::new`
60//! (`lib.rs:136`) are ONE level each -- neither delegates to an inner
61//! constructor of its own type, they build the struct literal inline -- so
62//! the worst live set of by-value return slots is two frames, and the test
63//! asserts `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB`.
64//! * **The budget applies to types a public `fn` returns by value.** The
65//! `Box`ed payloads are listed with `public: false` and measured, but not
66//! budgeted, because the budget's job is to bound what a CALLER can be made
67//! to own and none of them is reachable that way any more -- every field
68//! that holds one is a `Box`, which
69//! [`the_crate_private_silk_encoders_stay_behind_a_box`] pins by source.
70//!
71//! **Where the number sits.** At 8 KiB with the worst budgeted return at 4,016
72//! bytes ([`Encoder`]), the worst a caller owes is `2 x 4016 = 8,032` bytes --
73//! **0.39%** of a 2 MiB thread -- and the budget sits 2.04x above the
74//! incumbent. The pre-fix `Encoder` (87,024 B) is **10.62x over** and the
75//! pre-fix `Decoder` (7,576 B) sat at 92.5% of it, so the historical defect
76//! and the near-miss both red by a factor rather than by a hair.
77//!
78//! **What it does not claim.** `size_of` is layout, not stack depth: the
79//! measured stack/size ratio on a by-value constructor here is several times
80//! over, because the constructor's own frames add on top of the return slot.
81//! That residual is why
82//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs for
83//! real instead of trusting the arithmetic.
84
85use crate::Decoder;
86use crate::encoder::Encoder;
87
88/// The per-type ceiling for a type a CALLER can be made to hold by value, in
89/// bytes. See the module docs for the derivation; it is two-sided, and both
90/// sides are measured.
91pub(crate) const STACK_BUDGET: usize = 8192;
92
93/// The deepest PUBLIC by-value constructor chain in this crate, counted from
94/// the source: `MultistreamDecoder::with_rate` -> `MultistreamDecoder::
95/// try_with_rate` is two, both returning the same type by value so both frames
96/// hold a `MultistreamDecoder` return slot at once. `Encoder::new` and
97/// `Decoder::new` are one level each -- neither delegates to an inner
98/// constructor of its own type. The budget is checked against two, the worse
99/// of the chains.
100const DEEPEST_PUBLIC_CHAIN: usize = 2;
101
102/// Every type in this crate a public `fn` can hand back BY VALUE (or take by
103/// value in a public signature), with the `size_of` measured at the commit
104/// that wrote this table. `None` means "not yet measured", which
105/// [`the_measured_inventory_is_accurate`] rejects.
106///
107/// The third column names the return path, so a reader can see why a type is
108/// here rather than a coincidence of the type system. `false` in that column
109/// means the type is NOT budgeted: it is a `Box`ed payload, reachable only
110/// through a pointer now, and the pin that keeps it that way is
111/// [`the_crate_private_silk_encoders_stay_behind_a_box`].
112pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
113 // -- lib.rs -----------------------------------------------------------
114 (
115 "Decoder",
116 Some(1568),
117 true,
118 "Decoder::new -> Result<Decoder>. Was 7576, 92.5% of the budget, \
119 because a 6304-byte SilkDecoder sat inline; that field is now a Box",
120 ),
121 // -- encoder.rs -------------------------------------------------------
122 (
123 "Encoder",
124 Some(4016),
125 true,
126 "Encoder::new -> Result<Encoder>. Was 87024, 10.62x the budget: six \
127 inline SILK encoder slots (79176 together) and an inline 3831-byte \
128 silk_buf",
129 ),
130 (
131 "Application",
132 Some(1),
133 true,
134 "Encoder::new(.., application: Application) takes it by value and \
135 stores it inline in every Encoder",
136 ),
137 // -- celt.rs ----------------------------------------------------------
138 (
139 "CeltDecoder",
140 Some(1440),
141 true,
142 "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \
143 value into Decoder::celt",
144 ),
145 // -- celt_enc.rs ------------------------------------------------------
146 (
147 "CeltEncoder",
148 Some(1592),
149 false,
150 "celt_enc::CeltEncoder::new -> Self. `pub`, and stored inline in \
151 Encoder::celt, but 1592 is 19% of budget and it is the second \
152 largest field of a type that is itself budgeted; the crate-private \
153 19744-byte SILK stereo layer is the one this module had to pin",
154 ),
155 (
156 "CeltFrameDiag",
157 Some(424),
158 true,
159 "celt_enc::last_diag(&self) -> &CeltFrameDiag hands back a \
160 reference; the row is here because Encoder::last_celt_diag and \
161 Decoder::last_celt_diag name it in their signatures",
162 ),
163 // -- multistream.rs / multistream_enc.rs ------------------------------
164 (
165 "MultistreamDecoder",
166 Some(120),
167 true,
168 "MultistreamDecoder::with_rate / try_with_rate, the crate's deepest \
169 public by-value chain: with_rate -> try_with_rate -> Result<..>",
170 ),
171 (
172 "MultistreamEncoder",
173 Some(88),
174 true,
175 "MultistreamEncoder::surround_5_1 -> Result<MultistreamEncoder>",
176 ),
177 // -- packet.rs --------------------------------------------------------
178 (
179 "Packet",
180 Some(40),
181 true,
182 "Packet::parse -> Result<Packet<'a>>",
183 ),
184 ("Toc", Some(3), true, "Toc::new(byte: u8) -> Toc"),
185 (
186 "Mode",
187 Some(1),
188 true,
189 "Toc::mode(self) -> Mode; also stored inline in Decoder::prev_mode",
190 ),
191 (
192 "Bandwidth",
193 Some(1),
194 true,
195 "Toc::bandwidth(self) -> Bandwidth; also stored inline in \
196 Encoder::bandwidth",
197 ),
198 // -- range.rs ---------------------------------------------------------
199 (
200 "RangeEncoder",
201 Some(80),
202 true,
203 "RangeEncoder::new() -> Self; stored inline in Encoder::range",
204 ),
205 (
206 "RangeDecoder",
207 Some(56),
208 true,
209 "RangeDecoder::new(buf) -> RangeDecoder<'a>",
210 ),
211 (
212 "EncSnapshot",
213 Some(48),
214 true,
215 "RangeEncoder::snapshot(&self) -> EncSnapshot",
216 ),
217 // -- silk.rs ----------------------------------------------------------
218 (
219 "SilkDecoder",
220 Some(6512),
221 true,
222 "silk::SilkDecoder::new -> Self, and it is `pub use`d at the crate \
223 root, so 6512 bytes is a caller's by-value cost TODAY even though \
224 Decoder::new moves it straight into a Box. At 77% of the budget it \
225 is the LARGEST budgeted row in the table, and the one that says how \
226 little headroom the budget would have left if it had stayed inline",
227 ),
228 (
229 "SilkDecIndices",
230 Some(104),
231 true,
232 "SilkDecoder::last_indices(&self) -> SilkDecIndices",
233 ),
234 // -- analysis.rs (crate-private) --------------------------------------
235 (
236 "TonalityAnalysis",
237 Some(2168),
238 false,
239 "analysis::TonalityAnalysis::new(sample_rate) -> Self, stored \
240 INLINE in Encoder::analysis. 2168 is inside the budget and the field \
241 is reached only through an Encoder that is itself budgeted, so it is \
242 measured here rather than pinned behind a Box",
243 ),
244 (
245 "AnalysisInfo",
246 Some(60),
247 false,
248 "analysis::AnalysisInfo::default() -> Self, stored inline in \
249 Encoder::info",
250 ),
251];
252
253/// The live `size_of` for every inventoried type, keyed BY NAME.
254///
255/// Keyed rather than positional on purpose: `Mode`, `Bandwidth` and
256/// `Application` are all 1 byte, and a row inserted into [`BY_VALUE_TYPES`]
257/// without a matching insert here would zip cleanly and assert the wrong
258/// type's size against the wrong recorded one. A name key makes that mistake
259/// loud instead.
260fn measured_by_name() -> Vec<(&'static str, usize)> {
261 vec![
262 ("Decoder", std::mem::size_of::<Decoder>()),
263 ("Encoder", std::mem::size_of::<Encoder>()),
264 (
265 "Application",
266 std::mem::size_of::<crate::encoder::Application>(),
267 ),
268 (
269 "CeltDecoder",
270 std::mem::size_of::<crate::celt::CeltDecoder>(),
271 ),
272 (
273 "CeltEncoder",
274 std::mem::size_of::<crate::celt_enc::CeltEncoder>(),
275 ),
276 (
277 "CeltFrameDiag",
278 std::mem::size_of::<crate::celt_enc::CeltFrameDiag>(),
279 ),
280 (
281 "MultistreamDecoder",
282 std::mem::size_of::<crate::multistream::MultistreamDecoder>(),
283 ),
284 (
285 "MultistreamEncoder",
286 std::mem::size_of::<crate::multistream_enc::MultistreamEncoder>(),
287 ),
288 (
289 "Packet",
290 std::mem::size_of::<crate::packet::Packet<'static>>(),
291 ),
292 ("Toc", std::mem::size_of::<crate::packet::Toc>()),
293 ("Mode", std::mem::size_of::<crate::packet::Mode>()),
294 ("Bandwidth", std::mem::size_of::<crate::packet::Bandwidth>()),
295 (
296 "RangeEncoder",
297 std::mem::size_of::<crate::range::RangeEncoder>(),
298 ),
299 (
300 "RangeDecoder",
301 std::mem::size_of::<crate::range::RangeDecoder<'static>>(),
302 ),
303 (
304 "EncSnapshot",
305 std::mem::size_of::<crate::range::EncSnapshot>(),
306 ),
307 (
308 "SilkDecoder",
309 std::mem::size_of::<crate::silk::SilkDecoder>(),
310 ),
311 (
312 "SilkDecIndices",
313 std::mem::size_of::<crate::silk::SilkDecIndices>(),
314 ),
315 (
316 "TonalityAnalysis",
317 std::mem::size_of::<crate::analysis::TonalityAnalysis>(),
318 ),
319 (
320 "AnalysisInfo",
321 std::mem::size_of::<crate::analysis::AnalysisInfo>(),
322 ),
323 ]
324}
325
326/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`]
327/// constructs on.
328///
329/// 256 KiB: an eighth of what an unconfigured caller gives this crate, and
330/// **5.3x** the deepest need measured in a debug build on the current layout
331/// (the constructors complete at 48 KiB and abort at 32 KiB) while sitting
332/// **2.1x below** the pre-fix layout's own threshold, which completes at
333/// 544 KiB and aborts at 528 KiB. That gap is what makes this a capability
334/// arm rather than a formality: at 256 KiB the layout this crate used to
335/// ship ABORTS THE PROCESS. The sweep is reproducible with
336/// `EC_OPUS_TIGHT_STACK_BYTES`.
337const TIGHT_STACK: usize = 256 * 1024;
338
339#[cfg(test)]
340mod tests {
341 use super::{
342 BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name,
343 };
344 use crate::Decoder;
345 use crate::encoder::Encoder;
346
347 /// Return types that are not a by-value copy of anything the caller has to
348 /// own: a pointer, a slice, a `Vec` (three words, and the heap is not the
349 /// stack), or a primitive. `Self` is a by-value copy of the impl's type,
350 /// which the inventory rows already cover, so it is exempt from the scan
351 /// and not from the table.
352 const THIN: &[&str] = &[
353 "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap",
354 "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16",
355 "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self",
356 ];
357
358 /// The type name a `pub fn` line returns BY VALUE, or `None` when the line
359 /// returns a pointer, a `Vec`, a primitive, or nothing.
360 ///
361 /// One function, shared by the sweep and its control, so the control
362 /// cannot pass while the sweep's copy of the logic rotted.
363 fn by_value_return_name(line: &str) -> Option<String> {
364 let trimmed = line.trim_start();
365 if !trimmed.starts_with("pub fn ") {
366 return None;
367 }
368 let arrow = line.find("->")?;
369 let rest = &line[arrow + 2..];
370 let end = rest.find('{').unwrap_or(rest.len());
371 let ret = rest[..end].trim();
372 if ret.is_empty() {
373 return None;
374 }
375 // Unwrap one `Result<..>` / `Option<..>` layer. A deeper nesting is
376 // not a shape this crate uses, and flagging one as uninventoried is
377 // the safe direction to be wrong in.
378 let inner = {
379 let t = ret
380 .strip_prefix("Result<")
381 .or_else(|| ret.strip_prefix("Option<"))
382 .unwrap_or(ret);
383 t.split('>').next().unwrap_or(t)
384 };
385 // Drop the error type and any lifetime or generic argument:
386 // `Result<Decoder, Error>`, `RangeDecoder<'a>` and `Packet<'a>` are
387 // all the bare name for this purpose. Splitting on the comma is
388 // load-bearing: a matcher that cut only at `>` would read
389 // `Result<Decoder, Error>` as the name "Decoder, Error".
390 // `the_inventory_scan_is_not_vacuous` covers exactly that, which is
391 // why the control is not optional.
392 let name = inner.split(['<', ',']).next().unwrap_or(inner).trim();
393 if name.is_empty() || THIN.contains(&name) {
394 return None;
395 }
396 // A generic parameter, not a concrete type.
397 if !name.chars().next().is_some_and(char::is_uppercase) {
398 return None;
399 }
400 Some(name.to_string())
401 }
402
403 /// The source files the by-value scan reads. Every module `lib.rs`
404 /// declares, plus `lib.rs` itself (which is where `Decoder` and
405 /// `Encoder::new`'s crate-root sibling live) and this module.
406 const FILES: &[(&str, &str)] = &[
407 ("analysis.rs", include_str!("analysis.rs")),
408 ("celt.rs", include_str!("celt.rs")),
409 ("celt_enc.rs", include_str!("celt_enc.rs")),
410 ("encoder.rs", include_str!("encoder.rs")),
411 ("lib.rs", include_str!("lib.rs")),
412 ("multistream.rs", include_str!("multistream.rs")),
413 ("multistream_enc.rs", include_str!("multistream_enc.rs")),
414 ("ogg.rs", include_str!("ogg.rs")),
415 ("packet.rs", include_str!("packet.rs")),
416 ("range.rs", include_str!("range.rs")),
417 ("silk.rs", include_str!("silk.rs")),
418 ("silk_fix.rs", include_str!("silk_fix.rs")),
419 ("silk_flp/api.rs", include_str!("silk_flp/api.rs")),
420 ("silk_flp/encode.rs", include_str!("silk_flp/encode.rs")),
421 ("silk_flp/mod.rs", include_str!("silk_flp/mod.rs")),
422 ("silk_flp/nlsf.rs", include_str!("silk_flp/nlsf.rs")),
423 ("silk_flp/nsq.rs", include_str!("silk_flp/nsq.rs")),
424 ("silk_flp/opus.rs", include_str!("silk_flp/opus.rs")),
425 ("silk_flp/pitch.rs", include_str!("silk_flp/pitch.rs")),
426 ("silk_flp/pred.rs", include_str!("silk_flp/pred.rs")),
427 (
428 "silk_flp/resampler.rs",
429 include_str!("silk_flp/resampler.rs"),
430 ),
431 ("silk_flp/shape.rs", include_str!("silk_flp/shape.rs")),
432 ("silk_flp/sigproc.rs", include_str!("silk_flp/sigproc.rs")),
433 ("silk_flp/stereo.rs", include_str!("silk_flp/stereo.rs")),
434 ("silk_flp/vad.rs", include_str!("silk_flp/vad.rs")),
435 ("stack_budget.rs", include_str!("stack_budget.rs")),
436 ];
437
438 /// Every module `lib.rs` declares, so the scan's file list cannot silently
439 /// fall behind a new module. A new `mod foo;` with a by-value `pub fn`
440 /// that the scan never reads is exactly the hole this class would come
441 /// back through, so the list is derived, not curated.
442 ///
443 /// `pub(crate) mod foo;` is a module too, and ec-opus has several of them
444 /// (`analysis`, `silk_fix`, `silk_flp`), so the derivation strips the
445 /// visibility parenthesised form as well as the bare `pub`.
446 #[test]
447 fn every_by_value_module_is_scanned() {
448 let lib = include_str!("lib.rs");
449 let mut declared: Vec<&str> = Vec::new();
450 for line in lib.lines() {
451 let t = line.trim();
452 let after_pub = if let Some(rest) = t.strip_prefix("pub(") {
453 // `pub(crate) mod foo;` / `pub(super) mod foo;`
454 rest.split_once(')')
455 .map(|(_, after)| after.trim_start())
456 .unwrap_or("")
457 } else {
458 t.strip_prefix("pub ").unwrap_or(t)
459 };
460 let Some(rest) = after_pub.strip_prefix("mod ") else {
461 continue;
462 };
463 let name = rest.split([';', ' ']).next().unwrap_or("");
464 if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
465 declared.push(name);
466 }
467 }
468 assert!(
469 declared.len() > 8,
470 "only {} module declarations parsed out of lib.rs, so the \
471 derived file list is broken rather than small",
472 declared.len()
473 );
474 let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect();
475 let mut missing: Vec<String> = declared
476 .iter()
477 .filter(|d| {
478 !scanned
479 .iter()
480 .any(|s| *s == format!("{d}.rs") || s.starts_with(&format!("{d}/")))
481 })
482 .map(|d| (*d).to_string())
483 .collect();
484 missing.sort();
485 assert!(
486 missing.is_empty(),
487 "lib.rs declares modules the by-value scan never reads: {:?}. Add \
488 them to FILES, or the sweep cannot see a new by-value return that \
489 lands in one of them.",
490 missing
491 );
492 }
493
494 /// The inventory, printed as a sorted table, and checked against the
495 /// types' real sizes.
496 ///
497 /// The print is the instrument: one command reproduces the whole table,
498 /// biggest first, so "what is the largest by-value type in this crate"
499 /// has an answer that is a measurement rather than a grep.
500 ///
501 /// `cargo test -p ec-opus --lib -- stack_budget -- --nocapture` is the
502 /// command, with one wrinkle in THIS repo: `.cargo/config.toml` wraps
503 /// every test binary in `scripts/memguard-runner.sh`, which buffers a
504 /// green run's stdout and prints nothing. The table appears on a failing
505 /// run, or by invoking the built binary directly
506 /// (`target/debug/deps/ec_opus-* stack_budget --nocapture`).
507 ///
508 /// The check reds on ANY change with both numbers. That is deliberate: a
509 /// by-value type that grew raises the question of whether it should have
510 /// been boxed instead, and auto-accepting the new number would answer
511 /// that question by default.
512 #[test]
513 fn the_measured_inventory_is_accurate() {
514 let live = measured_by_name();
515 assert_eq!(
516 BY_VALUE_TYPES.len(),
517 live.len(),
518 "the inventory names {} types but {} are measured; every row needs \
519 a measured size or the sweep is a list of hopes",
520 BY_VALUE_TYPES.len(),
521 live.len()
522 );
523 let mut rows: Vec<(&str, usize)> = live.clone();
524 rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size));
525 eprintln!(
526 "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)",
527 rows.len(),
528 STACK_BUDGET / 1024
529 );
530 eprintln!("{:>8} {:>7} TYPE", "BYTES", "%BUDGET");
531 for (name, size) in &rows {
532 eprintln!(
533 "{size:>8} {:>6.1}% {name}",
534 *size as f64 * 100.0 / STACK_BUDGET as f64
535 );
536 }
537 for (name, recorded, _public, _path) in BY_VALUE_TYPES {
538 let recorded = recorded.expect("every inventory row carries a measured size");
539 let actual = live
540 .iter()
541 .find(|(n, _)| n == name)
542 .map(|(_, size)| *size)
543 .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
544 assert_eq!(
545 recorded, actual,
546 "{name} is {actual} bytes, the inventory records {recorded}; \
547 update the table deliberately -- a by-value type that changed \
548 is a stack cost every caller of its constructor now pays"
549 );
550 }
551 }
552
553 /// The bound, asserted BY NAME. A regression in any inventoried type reds
554 /// here naming the type, not "some type is too big".
555 #[test]
556 fn every_by_value_type_fits_the_stack_budget() {
557 let live = measured_by_name();
558 let mut checked = 0usize;
559 for (name, _, public, path) in BY_VALUE_TYPES {
560 if !public {
561 continue;
562 }
563 checked += 1;
564 let size = live
565 .iter()
566 .find(|(n, _)| n == name)
567 .map(|(_, size)| *size)
568 .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
569 assert!(
570 size <= STACK_BUDGET,
571 "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \
572 stack budget ({:.2}x). It is returned by value from {path}, so \
573 every caller pays it on its own stack, and the constructors \
574 nest -- one value's size is the multiplier, not the cost. \
575 Box the large field: Encoder's six SILK slots and silk_buf, \
576 and Decoder::silk, are Boxed for exactly this reason and \
577 took Encoder from 87024 bytes to this one.",
578 size as f64 / STACK_BUDGET as f64
579 );
580 }
581 assert!(
582 checked >= 10,
583 "only {checked} rows were bound-checked; the budget must apply to \
584 every type a caller can be made to hold by value"
585 );
586 // The other half of the derivation, asserted so it cannot rot: the
587 // worst a caller can owe is DEEPEST_CHAIN x the worst public return.
588 let worst = live
589 .iter()
590 .filter(|(n, _)| {
591 BY_VALUE_TYPES
592 .iter()
593 .any(|(row, _, public, _)| row == n && *public)
594 })
595 .map(|(_, size)| *size)
596 .max()
597 .expect("at least one public row");
598 assert!(
599 DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024,
600 "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \
601 public by-value return ({worst} B) is {} B, over an eighth of the \
602 2 MiB stack an unconfigured caller hands this crate; re-derive \
603 STACK_BUDGET",
604 DEEPEST_PUBLIC_CHAIN * worst
605 );
606 }
607
608 /// The SILK encoders and the SILK packet buffer stay BEHIND A BOX.
609 ///
610 /// The SILK layer, the SILK packet buffer and `Decoder::silk` stay BEHIND
611 /// A BOX. Every field holding one is a `Box`, so no caller can reach them
612 /// by value. What keeps them off the stack is those exact `Box` spellings,
613 /// and THIS is the pin for that -- a source scan over the declarations,
614 /// with a negative control so it cannot be matching a doc comment.
615 ///
616 /// It earned its place, measured: unboxing `silk_buf` takes `Encoder` from
617 /// 4,072 to **7,896** bytes and reds this pin naming
618 /// `encoder.rs::Encoder::silk_buf` and
619 /// [`the_measured_inventory_is_accurate`] naming `Encoder`. Unboxing the
620 /// SILK layer is far larger -- `Encoder` was 87,024 bytes before the
621 /// boxing, 10.62x the budget.
622 #[test]
623 fn the_crate_private_silk_encoders_stay_behind_a_box() {
624 const PINS: &[(&str, &str, &str)] = &[
625 (
626 "encoder.rs",
627 "Encoder::silk",
628 "silk: Option<Box<SilkLayer>>",
629 ),
630 (
631 "encoder.rs",
632 "Encoder::silk_buf",
633 "silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>",
634 ),
635 ("lib.rs", "Decoder::silk", "silk: Box<SilkDecoder>"),
636 ];
637 const SCANNED: &[(&str, &str)] = &[
638 ("encoder.rs", include_str!("encoder.rs")),
639 ("lib.rs", include_str!("lib.rs")),
640 ];
641 for (file, field, spelling) in PINS {
642 let src = SCANNED
643 .iter()
644 .find(|(name, _)| name == file)
645 .map(|(_, src)| *src)
646 .unwrap_or_else(|| panic!("no source pinned for {file}"));
647 let where_ = format!("{file}::{field}");
648 assert!(
649 src.contains(spelling),
650 "{where_} is no longer declared `{spelling}`. An inline SILK \
651 encoder or scratch buffer there puts {field}'s bytes back on \
652 every caller's stack -- that is how Encoder was 87024 bytes \
653 and Decoder 7576 before the boxing, 10.62x the by-value budget \
654 on the type Encoder::new hands back by value."
655 );
656 }
657 // And the negative control: the UNBOXED spellings must be ABSENT, or
658 // the scan above could be matching a doc comment instead of the live
659 // declaration. The unboxed forms are what this lane removed, so their
660 // absence is the proof the pin is reading the code.
661 const UNBOXED: &[(&str, &str, &str)] = &[
662 ("encoder.rs", "Encoder::silk", "silk: Option<SilkLayer>,"),
663 (
664 "encoder.rs",
665 "Encoder::silk_buf",
666 "silk_buf: [u8; MAX_SILK_PACKET_BYTES],",
667 ),
668 ("lib.rs", "Decoder::silk", "silk: SilkDecoder,"),
669 ];
670 for (file, field, spelling) in UNBOXED {
671 let src = SCANNED
672 .iter()
673 .find(|(name, _)| name == file)
674 .map(|(_, src)| *src)
675 .unwrap_or_else(|| panic!("no source pinned for {file}"));
676 assert!(
677 !src.contains(spelling),
678 "{file}::{field} is declared unboxed as `{spelling}`. The box pin is \
679 matching a spelling that is not the live declaration, and \
680 {field}'s bytes are back on every caller's stack."
681 );
682 }
683 }
684
685 /// CAPABILITY: really construct the heavy types on a tight stack, so a
686 /// regression ABORTS THE PROCESS instead of costing invisible margin.
687 ///
688 /// Both arms are the crate's by-value constructors: `Encoder::new`, the
689 /// type that was 87,024 bytes, and `Decoder::new`, 7,576 -- plus a real
690 /// 20 ms SILK packet decoded through the `Decoder` that arm built, so the
691 /// decoder is proved live on this thread rather than merely constructed.
692 ///
693 /// Measured stack need, **debug** build, one process per point so a
694 /// SIGABRT cannot truncate the sweep:
695 ///
696 /// | stack | pre-fix layout (inline SILK slots) | current layout |
697 /// |---|---|---|
698 /// | 32768 | overflow | **overflow** |
699 /// | 49152 | overflow | **ok** |
700 /// | 131072 | overflow | ok |
701 /// | 262144 (**the gate**) | **overflow** | **ok** |
702 /// | 524288 | **overflow** | ok |
703 /// | 557056 | ok | ok |
704 /// | 786432 | ok | ok |
705 /// | 1048576 | ok | ok |
706 ///
707 /// The gate sits at 256 KiB, **5.3x** the measured need of the current
708 /// layout and **2.1x** below the pre-fix layout's own threshold. Note
709 /// what the upper rows say: the pre-fix layout SURVIVED 1 MiB and 2 MiB,
710 /// so a gate set at 1 MiB would have been a formality -- a test that
711 /// passes for the old layout proves nothing. `EC_OPUS_TIGHT_STACK_BYTES`
712 /// overrides the size, which is how the table is reproduced.
713 ///
714 /// The results are checked, not just the absence of a crash: an `Encoder`
715 /// that constructed but came back with the wrong channel count, or a
716 /// `Decoder` that decoded a packet to silence, would both pass a
717 /// "did not overflow" assertion.
718 #[test]
719 fn the_deepest_by_value_constructors_fit_on_a_tight_stack() {
720 use crate::encoder::Application;
721 let stack: usize = std::env::var("EC_OPUS_TIGHT_STACK_BYTES")
722 .ok()
723 .and_then(|v| v.parse().ok())
724 .unwrap_or(TIGHT_STACK);
725 let handle = std::thread::Builder::new()
726 .stack_size(stack)
727 .spawn(move || {
728 // Arm 1: the by-value constructor that was 10.62x the budget.
729 let encoder = Encoder::new(48000, 1, Application::Audio)
730 .expect("Encoder::new(48000, 1, Audio)");
731 let channels = encoder.channels();
732 let rate = encoder.sample_rate();
733 drop(encoder);
734 let mut decoder = Decoder::new(48000, 1).expect("Decoder::new(48000, 1)");
735 // A real packet, so the decoder is proved live on this thread
736 // rather than merely constructed: the SILK-only 20 ms packet
737 // below decodes through the same by-value Decoder.
738 let mut out = vec![0.0f32; 5760];
739 let written = decoder
740 .decode_float(SILK_ONLY_PACKET, &mut out)
741 .expect("decode_float on the tight-stack thread");
742 let peak = out[..written].iter().fold(0.0f32, |m, s| m.max(s.abs()));
743 (channels, rate, written, peak)
744 })
745 .expect("spawn tight-stack thread");
746 let (channels, rate, pcm_len, peak) = handle.join().unwrap_or_else(|_| {
747 panic!(
748 "a by-value constructor overflowed a {stack}-byte stack; \
749 EC_OPUS_TIGHT_STACK_BYTES reproduces the threshold sweep"
750 )
751 });
752 assert_eq!(channels, 1, "Encoder::new lost its channel count");
753 assert_eq!(rate, 48000, "Encoder::new lost its sample rate");
754 assert_eq!(
755 pcm_len, 960,
756 "Decoder::decode_float returned {pcm_len} samples, not the 960 one \
757 20 ms mono frame at 48 kHz holds; the tight-stack thread built a \
758 Decoder that cannot decode"
759 );
760 assert!(
761 peak > 0.0,
762 "Decoder::decode_float returned silence (peak {peak}) on the \
763 tight-stack thread"
764 );
765 eprintln!(
766 "TIGHTSTACK {stack} bytes: Encoder={} Decoder={} SilkDecoder={} \
767 bytes, both constructors returned and decoded 960 samples",
768 std::mem::size_of::<Encoder>(),
769 std::mem::size_of::<Decoder>(),
770 std::mem::size_of::<crate::silk::SilkDecoder>(),
771 );
772 }
773
774 /// A SILK-only 20 ms Opus packet: TOC byte `0x48` (config 9 = SILK
775 /// wideband 20 ms, stereo bit 0, code 0 = SILK only) followed by a frame
776 /// count byte `0x00` (one frame) and a 100-byte payload. Config 9 is
777 /// SILK-only, so decoding it exercises `SilkDecoder`'s state rather than
778 /// CELT's, and the crate decodes it to exactly 960 samples at 48 kHz.
779 const SILK_ONLY_PACKET: &[u8] = &[
780 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
781 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
782 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
783 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
784 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
785 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
786 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
787 ];
788
789 /// The sweep's teeth against a NEW by-value return: re-derive the set from
790 /// the crate source and require every name to be inventoried.
791 ///
792 /// Without this the inventory is a list of what someone remembered to
793 /// measure, and a lane that adds `pub fn make() -> HugeThing` where
794 /// `HugeThing` is 200 KB of inline tables passes every other test here.
795 #[test]
796 fn every_by_value_public_return_is_in_the_inventory() {
797 let mut found: Vec<(String, String)> = Vec::new();
798 for (file, src) in FILES {
799 for (n, line) in src.lines().enumerate() {
800 if let Some(name) = by_value_return_name(line) {
801 found.push((name, format!("{file}:{}", n + 1)));
802 }
803 }
804 }
805 found.sort();
806 found.dedup();
807 assert!(
808 found.len() > 5,
809 "the by-value return scan found {} names across {} files, which is \
810 too few to be a real sweep -- the matcher, not the crate, is broken",
811 found.len(),
812 FILES.len()
813 );
814
815 let mut missing = Vec::new();
816 for (name, site) in &found {
817 if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) {
818 missing.push(format!("{name} ({site})"));
819 }
820 }
821 assert!(
822 missing.is_empty(),
823 "these types are returned BY VALUE from a public fn and are not in \
824 the inventory: {}. Either they are thin enough not to be a stack \
825 cost -- say so by adding a row with its measured size -- or they \
826 are the next instance of the class this module exists for.",
827 missing.join(", ")
828 );
829 }
830
831 /// The control for the scan above, on synthetic text rather than by
832 /// trusting the live tree to happen to contain a case.
833 ///
834 /// If the matcher silently stopped recognising a shape, the sweep would
835 /// pass everything and this would still be asserting nothing. So: every
836 /// by-value spelling the crate uses must yield its type name, and every
837 /// pointer/Vec/primitive/`Self` spelling must yield nothing.
838 #[test]
839 fn the_inventory_scan_is_not_vacuous() {
840 for synthetic in [
841 "pub fn zz_a() -> ZzNotInventoried { todo!() }",
842 "pub fn zz_b() -> Result<ZzNotInventoried, Error> { todo!() }",
843 "pub fn zz_c() -> Result<ZzNotInventoried> { todo!() }",
844 "pub fn zz_d() -> Option<ZzNotInventoried> { todo!() }",
845 "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }",
846 ] {
847 let name = by_value_return_name(synthetic)
848 .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`"));
849 assert_eq!(
850 name, "ZzNotInventoried",
851 "the matcher mangled `{synthetic}` into `{name}`, so the sweep \
852 cannot see a new by-value return and its green is vacuous"
853 );
854 assert!(
855 !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name),
856 "the synthetic control name is in the inventory, so the control \
857 proves nothing"
858 );
859 }
860 for thin in [
861 "pub fn zz_t() -> Box<Decoder> { todo!() }",
862 "pub fn zz_u() -> Result<Vec<u8>, Error> { todo!() }",
863 "pub fn zz_v() -> Option<&Path> { todo!() }",
864 "pub fn zz_w() -> usize { todo!() }",
865 "pub fn zz_x() -> Self { todo!() }",
866 "pub fn zz_y() -> Result<Arc<Decoder>, Error> { todo!() }",
867 "pub fn zz_z() { todo!() }",
868 "fn zz_private() -> ZzNotInventoried { todo!() }",
869 ] {
870 assert_eq!(
871 by_value_return_name(thin),
872 None,
873 "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \
874 above already cover, or not a `pub fn` -- the matcher must not \
875 read it as an uninventoried by-value return"
876 );
877 }
878 }
879}