forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB35bdf35Tahinli2 months ago3757 commits

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