From 958901bdf3effbf4d3a35ec6cc10aec8f338736e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 30 Sep 2026 11:30:46 +0300 Subject: [PATCH] lane-stackbox: box the by-value fields in ec-opus, ec-ac3 and ec-vp9, and gate each crate on a measured bound Same class as ec-av1's stack sweep (d202b8b4): a large struct returned BY VALUE from a public constructor is a stack cost the CALLER pays. The inventory from that lane named these; this lane re-measured each one, boxed the dominant fields, proved no output changed, and added a per-crate gate. ec-opus::Encoder 87,024 -> 4,072 (21.4x) silk_nb/mb/wb, silk_stereo_nb/mb/wb, silk_buf ec-opus::Decoder 7,576 -> 1,280 (5.9x) silk (it was already at 92.5% of budget) ec-ac3::Ac3Decoder 20,024 -> 3,160 (6.3x) Core::exps/bap/coeffs/delay ec-vp9::Decoder 10,944 -> 768 (14.3x) frame_ctxs: Box<[FrameContext; 4]>, ctx: Box API COMPATIBILITY: no public field type changed in any of the three crates -- ec-opus::Encoder/Decoder and ec-vp9::Decoder have private fields, ec-ac3::decode::Core is pub(crate) and Core itself is crate-private, and every public method signature (Encoder::new, Decoder::new, Ac3Decoder::new, Ac3Decoder::with_options, vp9::Decoder::new) is untouched. The only observable change is a few extra heap allocations AT CONSTRUCTION, not on the per-frame path. NO OUTPUT CHANGE, per crate, before vs after: ec-opus lib 36/0 -> 42/0 (the +6 are the new gates) and conformance 28/0/16 -> 28/0/16 unchanged (its closed-loop range-state-exact gate against the RFC-vector-verified decoder); ec-ac3 lib 36/0 -> 43/0 and both matrices 8/0 and 6/0 unchanged; ec-vp9 lib 10/0 -> 16/0 and ALL eight bit-exactness integration families unchanged (keyframe 3, inter_pixels 3, hbd 1, subsampling 3, odd_dimensions 2, scaledref 3, intraonly 1). Main re-ran the three crates' lib suites on the branch: 42/0, 16/0, 43/0. DELIBERATELY LEFT INLINE: ec-opus::Encoder::analysis (2,168) + celt (1,592) -- together already under budget, so a Box per field buys no bound and costs a per-frame indirection on a hot path. ec-vp9::Picture's public fields are 96 B of Vec handles, not a stack cost. A measurement, not a shrug. Gate modules: crates/{ec-opus,ec-ac3,ec-vp9}/src/stack_budget.rs, same shape as ec-av1's (inventory printer, bound asserted by name, a real small-thread capability arm, non-vacuity control). PRE-EXISTING REDS CARRIED, not caused here: ec-ac3 encode_matrix::real_fixtures_round_trip_through_our_decoder_and_the_oracle and ec-vp9 keyframe_exact::lossless_64_matches_ffmpeg both fail NotFound on a missing fixture (the same fixture-root shape the fixture-library verifier complains about); and ec-vp9 generates 5 warnings (unused read_partition, TM_PRED, partition_probs, x_mis, y_mis) which are present on main too. --- crates/ec-ac3/src/decode.rs | 25 +- crates/ec-ac3/src/lib.rs | 3 +- crates/ec-ac3/src/stack_budget.rs | 981 +++++++++++++++++++++++++++++ crates/ec-opus/src/encoder.rs | 118 +++- crates/ec-opus/src/lib.rs | 11 +- crates/ec-opus/src/stack_budget.rs | 934 +++++++++++++++++++++++++++ crates/ec-vp9/src/decode.rs | 36 +- crates/ec-vp9/src/lib.rs | 1 + crates/ec-vp9/src/stack_budget.rs | 733 +++++++++++++++++++++ lanes/stackbox.report.md | 274 ++++++++ 10 files changed, 3055 insertions(+), 61 deletions(-) create mode 100755 crates/ec-ac3/src/stack_budget.rs create mode 100755 crates/ec-opus/src/stack_budget.rs create mode 100755 crates/ec-vp9/src/stack_budget.rs create mode 100644 lanes/stackbox.report.md diff --git a/crates/ec-ac3/src/decode.rs b/crates/ec-ac3/src/decode.rs index 5fc599be..391381e4 100644 --- a/crates/ec-ac3/src/decode.rs +++ b/crates/ec-ac3/src/decode.rs @@ -43,9 +43,14 @@ pub(crate) struct Core { pub(crate) nfchans: usize, pub(crate) lfeon: bool, /// Decoded exponents per channel, valid up to that channel's `endmant`. - pub(crate) exps: [[u8; COEFFS]; CHANNELS], + /// + /// Boxed, with `bap`, `coeffs` and `delay`, because the four are 16896 of + /// `Core`'s 19728 bytes and `Core` sits inline in the `Ac3Decoder` that + /// `Ac3Decoder::new` hands a caller BY VALUE. Indexing and `&mut self.f[ch]` + /// read through the box unchanged. `Stack`: crate::stack_budget. + pub(crate) exps: Box<[[u8; COEFFS]; CHANNELS]>, /// Bit allocation pointers per channel. - pub(crate) bap: [[u8; COEFFS]; CHANNELS], + pub(crate) bap: Box<[[u8; COEFFS]; CHANNELS]>, /// Exponent strategy of the current block per channel. pub(crate) expstr: [Strategy; CHANNELS], pub(crate) endmant: [usize; CHANNELS], @@ -83,8 +88,8 @@ pub(crate) struct Core { /// Dynamic range gain for program 1 and, in 1+1 mode, program 2. pub(crate) dynrng: [f32; 2], // Output. - pub(crate) coeffs: [[f32; COEFFS]; CHANNELS], - pub(crate) delay: [[f32; COEFFS]; MAX_FBW + 1], + pub(crate) coeffs: Box<[[f32; COEFFS]; CHANNELS]>, + pub(crate) delay: Box<[[f32; COEFFS]; MAX_FBW + 1]>, pub(crate) imdct: Imdct, pub(crate) dither: Dither, /// Fraction of the `dynrng` compression to apply (§7.7.1). @@ -135,8 +140,8 @@ impl Core { acmod: Acmod::Stereo, nfchans: 2, lfeon: false, - exps: [[0; COEFFS]; CHANNELS], - bap: [[0; COEFFS]; CHANNELS], + exps: Box::new([[0; COEFFS]; CHANNELS]), + bap: Box::new([[0; COEFFS]; CHANNELS]), expstr: [Strategy::Reuse; CHANNELS], endmant: [0; CHANNELS], strtmant: [0; CHANNELS], @@ -163,8 +168,8 @@ impl Core { blksw: [false; MAX_FBW], dithflag: [true; MAX_FBW], dynrng: [1.0; 2], - coeffs: [[0.0; COEFFS]; CHANNELS], - delay: [[0.0; COEFFS]; MAX_FBW + 1], + coeffs: Box::new([[0.0; COEFFS]; CHANNELS]), + delay: Box::new([[0.0; COEFFS]; MAX_FBW + 1]), imdct: Imdct::new(), dither: Dither::default(), drc_scale: 1.0, @@ -194,12 +199,12 @@ impl Core { /// Drop everything a seek invalidates. pub(crate) fn reset(&mut self) { - for d in &mut self.delay { + for d in self.delay.iter_mut() { d.fill(0.0); } self.cplinu = false; self.dynrng = [1.0; 2]; - self.exps = [[0; COEFFS]; CHANNELS]; + self.exps = Box::new([[0; COEFFS]; CHANNELS]); } /// Adopt a frame header: channel configuration for the blocks that follow. diff --git a/crates/ec-ac3/src/lib.rs b/crates/ec-ac3/src/lib.rs index ace1dd0b..9bd0e85e 100644 --- a/crates/ec-ac3/src/lib.rs +++ b/crates/ec-ac3/src/lib.rs @@ -62,6 +62,7 @@ pub mod bsi; pub mod eac3; pub mod exps; pub mod mantissa; +mod stack_budget; pub mod syncinfo; pub mod tables; pub mod transform; @@ -72,8 +73,8 @@ pub mod encode; pub use decode::Syntax; pub use decoder::{Ac3Decoder, Downmix, FrameInfo, Options}; -pub use encode::{Ac3Encoder, EncodeStats, EncoderConfig}; pub use ec_core::Error; +pub use encode::{Ac3Encoder, EncodeStats, EncoderConfig}; /// Samples per channel one audio block produces. pub use transform::BLOCK_SAMPLES; diff --git a/crates/ec-ac3/src/stack_budget.rs b/crates/ec-ac3/src/stack_budget.rs new file mode 100755 index 00000000..109d67a2 --- /dev/null +++ b/crates/ec-ac3/src/stack_budget.rs @@ -0,0 +1,981 @@ +#![cfg(test)] +//! A measured bound on the crate's BY-VALUE types, and a gate that bites. +//! +//! # The class +//! +//! A large struct returned BY VALUE from a public constructor is a stack cost, +//! not a heap cost, and the cost is paid by the CALLER. The constructors here +//! nest -- `Ac3Decoder::new` -> `Ac3Decoder::with_options` -> `Core::new` for +//! the decoder -- and in an unoptimized build each level materialises its whole +//! return slot before the inner call returns. So one value's `size_of` is the +//! MULTIPLIER, and the chain length is the other factor. +//! +//! That is not hypothetical. `Ac3Decoder` was **20,024** bytes by value -- its +//! inline `decode::Core` carried four per-channel coefficient planes +//! (`exps`, `bap`, `coeffs`, `delay`) that are **16,896** of `Core`'s 19,728 +//! bytes -- and every `Ac3Decoder::new()` / `Ac3Decoder::with_options()` call +//! made the caller pay all of it on its own stack. `.cargo/config.toml` +//! carries `RUST_MIN_STACK = 67108864`, which HIDES the class from this +//! workspace's own runs -- a band-aid a library consumer does not get. Boxing +//! those four fields took `Core` to **2,864** and `Ac3Decoder` to **3,160**; +//! [`the_crate_private_core_stays_behind_a_box`] is the pin that keeps them +//! there. +//! +//! # Why this module exists when that boxing already exists +//! +//! The boxing fixed ONE type. The class was not swept: nothing stopped the +//! next 18 KB inline plane from landing in `Core`, and nothing said which types +//! had been checked. This module is the sweep: +//! +//! 1. [`BY_VALUE_TYPES`] is the inventory -- every public type in this crate +//! that a public `fn` can return by value, with a measured `size_of` floor +//! recorded as of this commit. +//! [`the_measured_inventory_is_accurate`] fails if a type's size moves, so +//! the table cannot rot into a list of stale small numbers. +//! 2. [`STACK_BUDGET`] is the bound, and +//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for +//! every row, so a regression reds naming the type that caused it. +//! 3. [`the_crate_private_core_stays_behind_a_box`] pins the four `Box` field +//! spellings, with a negative control, so the fix is not silently reverted. +//! 4. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the +//! capability arm: it really constructs the heavy types on a deliberately +//! tight thread, so the old layout ABORTS THE PROCESS rather than quietly +//! costing margin. +//! 5. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's +//! teeth against NEW types: a source scan re-derives the set of by-value +//! public returns from the crate source, so a lane that adds a 40 KB struct +//! to a `pub fn` return reds here until it is measured and listed. +//! [`the_inventory_scan_is_not_vacuous`] is its control, and +//! [`every_by_value_module_is_scanned`] keeps the scan's file list derived +//! from `lib.rs` rather than curated. +//! +//! # The bound, and why this number +//! +//! [`STACK_BUDGET`] = 8192 bytes (8 KiB). It is bounded from BOTH sides by +//! measurement, and both sides are asserted in +//! [`every_by_value_type_fits_the_stack_budget`] so neither can rot silently. +//! +//! **The quantity being bounded.** Not `size_of` in the abstract, but *what a +//! caller can be made to owe*: the size of one by-value return, multiplied by +//! how many constructor levels hold a copy of it at once. Three inputs: +//! +//! 1. **The smallest stack a caller can hand this crate is 2,101,248 bytes.** +//! Measured, not assumed, by +//! [`test_threads_get_the_stack_they_are_given`] reading +//! `/proc/self/task//maps`. That is libtest's default test thread and +//! also what `std::thread::Builder::new()` gives a caller who does not ask +//! for a size. A library consumer gets no `.cargo/config.toml`. +//! 2. **The deepest PUBLIC by-value chain is 2** ([`DEEPEST_PUBLIC_CHAIN`]): +//! `Ac3Decoder::new` (decoder.rs:117) -> `Ac3Decoder::with_options` +//! (decoder.rs:122), which calls `Core::new()` (decode.rs:136) as a third, +//! crate-private level carrying a 2,864-byte `Core`. The encoder's +//! `Ac3Encoder::new` is a single level -- it builds the struct inline in +//! its `Ok(..)` and does not nest -- and `Ac3Decoder::decode_frame`'s +//! `Result` is a single level too. The test asserts +//! `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB` -- i.e. the by-value return +//! slots may claim at most an EIGHTH of a caller's stack, leaving the rest +//! for the decode, which is the thing that actually needs it. +//! 3. **The budget applies only to types a `pub fn` returns.** The +//! crate-private 2,864-byte `Core` is measured and listed but is NOT +//! bounded, because no caller can reach it by value -- every field that +//! holds one of its 16,896-byte planes is a `Box`, which +//! [`the_crate_private_core_stays_behind_a_box`] pins by source. Bounding +//! it would calibrate the number to something unreachable. +//! +//! **Where the number sits.** At 8 KiB with the worst public return at 3,160 +//! bytes ([`Ac3Decoder`]), the worst a caller owes is `2 x 3160 = 6,320` bytes +//! -- **0.30%** of a 2 MiB thread -- and the budget itself is 2.59x above the +//! incumbent. `Ac3Decoder` is also the row closest to the budget, at **38.6%** +//! of it: **5,032 bytes of margin**, the least of any row here. +//! [`Ac3Encoder`] is second, at 34.0% and 5,408 bytes of margin. Both +//! directions have room, which is the point: a bound the largest type sits +//! just under is a bound the next lane will quietly raise. +//! +//! **What it catches.** A pre-fix `Ac3Decoder` (20,024 B) is **2.44x over** +//! budget. The pre-fix `Core` (19,728 B) behind it is **2.41x over** the same +//! number -- that is the ratio the layout fix removed, not one this gate +//! enforces, because no `pub fn` returns `Core`; the pin on its four `Box` +//! fields is what keeps it there. Both the historical defect and the +//! near-miss red by a factor, not by a hair. +//! +//! **What it does not claim.** `size_of` is layout, not stack depth, and the +//! gap between the two is the nesting multiplier plus every frame a call owns +//! for its own work. `Ac3Encoder::new` is the clearest case: its 2,784-byte +//! return is nowhere near the budget, yet building it needs ~80 KiB of thread +//! in a debug build, because it materialises a `[0.0f32; 512]` window, an +//! `Mdct::new(512)` plan and a per-`COEFFS` IMDCT basis sweep. So this module +//! does not trust the arithmetic: +//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs both +//! heavy types for real on a real thread, and its measured threshold is the +//! number that settles it. + +use crate::decoder::{Ac3Decoder, Options}; +use crate::encode::Ac3Encoder; + +/// The per-type ceiling for a type a CALLER can be made to hold by value, in +/// bytes. See the module docs for the derivation; it is two-sided, and both +/// sides are measured. +pub(crate) const STACK_BUDGET: usize = 8192; + +/// The deepest PUBLIC by-value constructor chain in this crate, counted from +/// the source: +/// +/// * `Ac3Decoder::new` (decoder.rs:117) -> `Ac3Decoder::with_options` +/// (decoder.rs:122): TWO public levels, both returning a 3,160-byte +/// `Ac3Decoder` by value. `with_options` calls `Core::new()` +/// (decode.rs:136), a third level, but that one is `pub(crate)` and carries +/// a 2,864-byte `Core`, so it is not a public return. +/// * `Ac3Encoder::new` (encode.rs:254): ONE level. It builds the struct +/// inline in its `Ok(Ac3Encoder { .. })` (encode.rs:306) and never calls +/// another constructor that returns it by value. +/// * `Ac3Decoder::decode_frame` (decoder.rs:156) -> `Result`: +/// ONE level, 96 bytes. It does not nest. +/// +/// The budget is checked against two, the worst of the three. +#[cfg(test)] +const DEEPEST_PUBLIC_CHAIN: usize = 2; + +/// Every public type in this crate a public `fn` can return BY VALUE, with the +/// `size_of` measured at the commit that wrote this table. `None` means "not +/// yet measured", which [`the_measured_inventory_is_accurate`] rejects. +/// +/// The third column names the return path, so a reader can see why a type is +/// here rather than a coincidence of the type system. +pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ + // -- decoder.rs: the headline row ------------------------------------- + ( + "Ac3Decoder", + Some(3160), + true, + "Ac3Decoder::new / with_options -> Ac3Decoder, nesting two deep. Was \ + 20024 bytes with decode::Core's four coefficient planes inline, i.e. \ + 2.44x over the 8192-byte budget", + ), + // -- encode.rs: the second-closest row to the budget ------------------- + ( + "Ac3Encoder", + Some(2784), + true, + "Ac3Encoder::new -> Result, one level, no nesting. \ + 34.0% of the budget, 5408 bytes of margin; Ac3Decoder above is the \ + closest row at 38.6%", + ), + ( + "EncoderConfig", + Some(12), + true, + "consumed by value by Ac3Encoder::new, which copies it into the \ + encoder it returns", + ), + ( + "EncodeStats", + Some(72), + true, + "Ac3Encoder::stats -> EncodeStats, by value out of the encoder's field", + ), + // -- decoder.rs: the header/option surface --------------------------- + ( + "Options", + Some(8), + true, + "Ac3Decoder::with_options(Options) takes it by value and keeps it", + ), + ( + "FrameInfo", + Some(48), + true, + "built by value in Ac3Decoder's private info_from; handed back as \ + Option<&FrameInfo>, a BORROW, so the row is about the move the \ + decoder makes internally", + ), + ( + "Downmix", + Some(1), + true, + "Options::downmix, a field of the by-value Options above", + ), + ( + "AudioFrame", + Some(96), + true, + "Ac3Decoder::decode_frame -> Result, one level, no \ + nesting. From ec_core, not this crate, but it is a public return of \ + this crate and the sweep finds it by name", + ), + // -- decode.rs ------------------------------------------------------- + ( + "Syntax", + Some(1), + true, + "re-exported from decode; a field of FrameInfo and of Ac3Decoder::Core", + ), + // -- the header parsers ---------------------------------------------- + ( + "Bsi", + Some(56), + true, + "bsi::parse / bsi::parse_from -> Result, one level each", + ), + ("Acmod", Some(1), true, "bsi::Acmod::from_code -> Acmod"), + ( + "SyncInfo", + Some(24), + true, + "syncinfo::parse / syncinfo::parse_from -> Result", + ), + ( + "Eac3Bsi", + Some(96), + true, + "eac3::bsi::parse / eac3::bsi::parse_from -> Result", + ), + ( + "StreamType", + Some(1), + true, + "a field of the by-value Eac3Bsi above; eac3::StreamType::Dependent \ + is the first-substream refusal", + ), + // -- transform.rs / mantissa.rs / exps.rs ---------------------------- + ( + "Imdct", + Some(472), + true, + "transform::Imdct::new -> Imdct, one level. Held inline in both Core \ + and Ac3Encoder, the largest type in the crate that is NOT a public \ + return", + ), + ( + "Mantissas", + Some(56), + true, + "mantissa::Mantissas::new -> Mantissas, one level", + ), + ( + "Strategy", + Some(1), + true, + "exps::Strategy::from_code -> Strategy; a field of Core's inline \ + [Strategy; CHANNELS]", + ), + // -- bitalloc.rs ----------------------------------------------------- + ( + "BitAllocParams", + Some(5), + true, + "bitalloc::BitAllocParams::default, copied into Core's inline copy", + ), + ( + "DeltaBa", + Some(32), + true, + "bitalloc::DeltaBa, built by value per block", + ), + ( + "Allocation", + Some(56), + true, + "bitalloc::Allocation<'_>, built by value and passed to \ + bitalloc::compute by reference; the move copies the struct, not the \ + borrowed slices", + ), + ( + "Channel", + Some(12), + true, + "bitalloc::Channel, moved out of the per-block channel table", + ), + // -- crate-private: never a public return, and every one of its four + // -- large planes is behind a Box now. The budget does not apply; the + // -- pin that does is `the_crate_private_core_stays_behind_a_box`. + ( + "Core", + Some(2864), + false, + "decode::Core::new -> Core, pub(crate), held inline in Ac3Decoder. \ + Was 19728 bytes with exps/bap/coeffs/delay inline; those four are \ + 16896 of them and are boxed now", + ), +]; + +/// The live `size_of` for every inventoried type, keyed BY NAME. +/// +/// Keyed rather than positional on purpose: `Bsi`, `Mantissas` and +/// `Allocation` are all 56 bytes, and `Eac3Bsi` and `AudioFrame` are both 96, +/// so a row inserted into [`BY_VALUE_TYPES`] without a matching insert here +/// would zip cleanly and assert the wrong type's size against the wrong +/// recorded one. A name key makes that mistake loud instead. +#[cfg(test)] +fn measured_by_name() -> Vec<(&'static str, usize)> { + vec![ + ("Ac3Decoder", std::mem::size_of::()), + ("Ac3Encoder", std::mem::size_of::()), + ( + "EncoderConfig", + std::mem::size_of::(), + ), + ( + "EncodeStats", + std::mem::size_of::(), + ), + ("Options", std::mem::size_of::()), + ( + "FrameInfo", + std::mem::size_of::(), + ), + ("Downmix", std::mem::size_of::()), + ("AudioFrame", std::mem::size_of::()), + ("Syntax", std::mem::size_of::()), + ("Bsi", std::mem::size_of::()), + ("Acmod", std::mem::size_of::()), + ("SyncInfo", std::mem::size_of::()), + ("Eac3Bsi", std::mem::size_of::()), + ("StreamType", std::mem::size_of::()), + ("Imdct", std::mem::size_of::()), + ( + "Mantissas", + std::mem::size_of::(), + ), + ("Strategy", std::mem::size_of::()), + ( + "BitAllocParams", + std::mem::size_of::(), + ), + ("DeltaBa", std::mem::size_of::()), + ( + "Allocation", + std::mem::size_of::>(), + ), + ("Channel", std::mem::size_of::()), + ("Core", std::mem::size_of::()), + ] +} + +/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] +/// constructs on. +/// +/// 1 MiB: half of what an unconfigured caller gives this crate, and far above +/// what the deepest measured chain needs in a debug build. The threshold was +/// swept in an unoptimized build and is reproducible with +/// `EC_AC3_TIGHT_STACK_BYTES`. +const TIGHT_STACK: usize = 1024 * 1024; + +#[cfg(test)] +mod tests { + use super::{ + BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name, + }; + use crate::decoder::{Ac3Decoder, Downmix, Options}; + use crate::encode::{Ac3Encoder, EncoderConfig}; + + /// Return types that are not a by-value copy of anything the caller has to + /// own: a pointer, a slice, a `Vec` (three words, and the heap is not the + /// stack), or a primitive. `Self` is a by-value copy of the impl's type, + /// which the inventory rows already cover, so it is exempt from the scan + /// and not from the table. + const THIN: &[&str] = &[ + "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap", + "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16", + "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self", + ]; + + /// The type name a `pub fn` line returns BY VALUE, or `None` when the line + /// returns a pointer, a `Vec`, a primitive, or nothing. + /// + /// One function, shared by the sweep and its control, so the control + /// cannot pass while the sweep's copy of the logic rotted. + fn by_value_return_name(line: &str) -> Option { + let trimmed = line.trim_start(); + if !trimmed.starts_with("pub fn ") { + return None; + } + let arrow = line.find("->")?; + let rest = &line[arrow + 2..]; + let end = rest.find('{').unwrap_or(rest.len()); + let ret = rest[..end].trim(); + if ret.is_empty() { + return None; + } + // Unwrap one `Result<..>` / `Option<..>` layer. A deeper nesting is + // not a shape this crate uses, and flagging one as uninventoried is + // the safe direction to be wrong in. + let inner = { + let t = ret + .strip_prefix("Result<") + .or_else(|| ret.strip_prefix("Option<")) + .unwrap_or(ret); + t.split('>').next().unwrap_or(t) + }; + // Drop the error type and any lifetime or generic argument: + // `Result`, `Allocation<'a>` and `AudioFrame` are all the + // bare name for this purpose. Splitting on the comma is load-bearing: + // the first version of this matcher cut only at `>` and so read + // `Result` as the name "Bsi, Error". `ec_av1`'s control + // caught exactly that, which is why the control is not optional. + let name = inner.split(['<', ',']).next().unwrap_or(inner).trim(); + if name.is_empty() || THIN.contains(&name) { + return None; + } + // A generic parameter, not a concrete type. + if !name.chars().next().is_some_and(char::is_uppercase) { + return None; + } + Some(name.to_string()) + } + + /// The source files the by-value scan reads. Every module that can expose + /// a `pub fn` returning a named type; a new module added to `lib.rs` needs + /// adding here, and + /// [`every_by_value_module_is_scanned`] is what keeps that honest. + const FILES: &[(&str, &str)] = &[ + ("aht.rs", include_str!("aht.rs")), + ("aht_tables.rs", include_str!("aht_tables.rs")), + ("bitalloc.rs", include_str!("bitalloc.rs")), + ("bsi.rs", include_str!("bsi.rs")), + ("decode.rs", include_str!("decode.rs")), + ("decoder.rs", include_str!("decoder.rs")), + ("eac3.rs", include_str!("eac3.rs")), + ("encode.rs", include_str!("encode.rs")), + ("exps.rs", include_str!("exps.rs")), + ("lib.rs", include_str!("lib.rs")), + ("mantissa.rs", include_str!("mantissa.rs")), + ("stack_budget.rs", include_str!("stack_budget.rs")), + ("syncinfo.rs", include_str!("syncinfo.rs")), + ("tables.rs", include_str!("tables.rs")), + ("transform.rs", include_str!("transform.rs")), + ]; + + /// Every module `lib.rs` declares, so the scan's file list cannot silently + /// fall behind a new module. A new `mod foo;` with a by-value `pub fn` + /// that the scan never reads is exactly the hole this class would come + /// back through, so the list is derived, not curated. + #[test] + fn every_by_value_module_is_scanned() { + let lib = include_str!("lib.rs"); + let mut declared: Vec<&str> = Vec::new(); + for line in lib.lines() { + let t = line.trim(); + let rest = t + .strip_prefix("pub mod ") + .or_else(|| t.strip_prefix("mod ")) + .unwrap_or(""); + if rest.is_empty() { + continue; + } + let name = rest.split([';', ' ']).next().unwrap_or(""); + if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { + declared.push(name); + } + } + assert!( + declared.len() > 10, + "only {} module declarations parsed out of lib.rs, so the \ + derived file list is broken rather than small", + declared.len() + ); + let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect(); + let mut missing: Vec = declared + .iter() + .filter(|d| !scanned.iter().any(|s| *s == format!("{d}.rs"))) + .map(|d| (*d).to_string()) + .collect(); + missing.sort(); + assert!( + missing.is_empty(), + "lib.rs declares modules the by-value scan never reads: {:?}. Add \ + them to FILES, or the sweep cannot see a new by-value return that \ + lands in one of them.", + missing + ); + } + + /// The inventory, printed as a sorted table, and checked against the + /// types' real sizes. + /// + /// The print is the instrument: one command + /// (`cargo test -p ec-ac3 --lib -- stack_budget -- --nocapture`) + /// reproduces the whole table, biggest first, so "what is the largest + /// by-value type in this crate" has an answer that is a measurement + /// rather than a grep. + /// + /// The check reds on ANY change with both numbers. That is deliberate: a + /// by-value type that grew raises the question of whether it should have + /// been boxed instead, and auto-accepting the new number would answer + /// that question by default. + #[test] + fn the_measured_inventory_is_accurate() { + let live = measured_by_name(); + assert_eq!( + BY_VALUE_TYPES.len(), + live.len(), + "the inventory names {} types but {} are measured; every row needs \ + a measured size or the sweep is a list of hopes", + BY_VALUE_TYPES.len(), + live.len() + ); + let mut rows: Vec<(&str, usize)> = live.clone(); + rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size)); + eprintln!( + "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)", + rows.len(), + STACK_BUDGET / 1024 + ); + eprintln!("{:>8} {:>7} {}", "BYTES", "%BUDGET", "TYPE"); + for (name, size) in &rows { + eprintln!( + "{size:>8} {:>6.1}% {name}", + *size as f64 * 100.0 / STACK_BUDGET as f64 + ); + } + for (name, recorded, _public, _path) in BY_VALUE_TYPES { + let recorded = recorded.expect("every inventory row carries a measured size"); + let actual = live + .iter() + .find(|(n, _)| n == name) + .map(|(_, size)| *size) + .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); + assert_eq!( + recorded, actual, + "{name} is {actual} bytes, the inventory records {recorded}; \ + update the table deliberately -- a by-value type that changed \ + is a stack cost every caller of its constructor now pays" + ); + } + } + + /// The bound, asserted BY NAME. A regression in any inventoried type reds + /// here naming the type, not "some type is too big". + #[test] + fn every_by_value_type_fits_the_stack_budget() { + let live = measured_by_name(); + let mut checked = 0usize; + for (name, _, public, path) in BY_VALUE_TYPES { + if !public { + continue; + } + checked += 1; + let size = live + .iter() + .find(|(n, _)| n == name) + .map(|(_, size)| *size) + .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); + assert!( + size <= STACK_BUDGET, + "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \ + stack budget ({:.2}x). It is returned by value from {path}, so \ + every caller pays it on its own stack, and the constructors \ + nest -- one value's size is the multiplier, not the cost. \ + Box the large field (this crate did exactly that for \ + Ac3Decoder's inline decode::Core) or hand back a reference.", + size as f64 / STACK_BUDGET as f64 + ); + } + assert!( + checked >= 10, + "only {checked} rows were bound-checked; the budget must apply to \ + every type a caller can be made to hold by value" + ); + // The other half of the derivation, asserted so it cannot rot: the + // worst a caller can owe is DEEPEST_CHAIN x the worst public return. + let worst = live + .iter() + .filter(|(n, _)| { + BY_VALUE_TYPES + .iter() + .any(|(row, _, public, _)| row == n && *public) + }) + .map(|(_, size)| *size) + .max() + .expect("at least one public row"); + assert!( + DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024, + "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \ + public by-value return ({worst} B) is {} B, over an eighth of the \ + 2101248-byte stack an unconfigured caller hands this crate; \ + re-derive STACK_BUDGET", + DEEPEST_PUBLIC_CHAIN * worst + ); + } + + /// The crate-private decode state stays BEHIND A BOX. + /// + /// The budget does not apply to `Core` because no `pub fn` returns it, so + /// bounding it would calibrate the number to something no caller can + /// reach. What keeps its 16,896 bytes of coefficient planes off every + /// caller's stack is that the four fields holding them are `Box`es, and + /// THIS is the pin for that -- a source scan over the four declarations + /// plus the four `Box::new`s in `Core::new`. + /// + /// It earned its place during the layout fix: `exps`, `bap` and `delay` + /// are `[[T; COEFFS]; CHANNELS]`-shaped planes at 1,792 / 1,792 / 6,144 + /// bytes and `coeffs` is 7,168 -- 16,896 of a 19,728-byte `Core` -- and + /// `Core` sits inline in the `Ac3Decoder` that `Ac3Decoder::new` hands a + /// caller BY VALUE. Unboxing any of the four puts the stack cost straight + /// back. + #[test] + fn the_crate_private_core_stays_behind_a_box() { + const PINS: &[(&str, &str)] = &[ + ( + "decode.rs::Core::exps", + "exps: Box<[[u8; COEFFS]; CHANNELS]>", + ), + ("decode.rs::Core::bap", "bap: Box<[[u8; COEFFS]; CHANNELS]>"), + ( + "decode.rs::Core::coeffs", + "coeffs: Box<[[f32; COEFFS]; CHANNELS]>", + ), + ( + "decode.rs::Core::delay", + "delay: Box<[[f32; COEFFS]; MAX_FBW + 1]>", + ), + ( + "decode.rs::Core::new::exps", + "exps: Box::new([[0; COEFFS]; CHANNELS])", + ), + ( + "decode.rs::Core::new::bap", + "bap: Box::new([[0; COEFFS]; CHANNELS])", + ), + ( + "decode.rs::Core::new::coeffs", + "coeffs: Box::new([[0.0; COEFFS]; CHANNELS])", + ), + ( + "decode.rs::Core::new::delay", + "delay: Box::new([[0.0; COEFFS]; MAX_FBW + 1])", + ), + ]; + const UNBOXED: &[(&str, &str)] = &[ + ("decode.rs::Core::exps", "exps: [[u8; COEFFS]; CHANNELS],"), + ("decode.rs::Core::bap", "bap: [[u8; COEFFS]; CHANNELS],"), + ( + "decode.rs::Core::coeffs", + "coeffs: [[f32; COEFFS]; CHANNELS],", + ), + ( + "decode.rs::Core::delay", + "delay: [[f32; COEFFS]; MAX_FBW + 1],", + ), + ]; + let decode = include_str!("decode.rs"); + for (where_, spelling) in PINS { + assert!( + decode.contains(spelling), + "{where_} is no longer declared `{spelling}`. An inline \ + coefficient plane there puts its 16896 bytes back inside \ + decode::Core, which sits inline in the Ac3Decoder that \ + Ac3Decoder::new returns BY VALUE -- that is how Ac3Decoder was \ + 20024 bytes, 2.44x over the by-value budget.", + ); + } + // And the negative control: the unboxed spellings must be ABSENT, or + // the scan above would be matching a doc comment or a dead branch + // rather than the live declaration. + for (where_, unboxed) in UNBOXED { + assert!( + !decode.contains(unboxed), + "{where_} is declared `{unboxed}`, unboxed. The box pin above \ + is not matching the live declaration, or the plane is inline \ + again and every Ac3Decoder::new caller pays 16896 bytes.", + ); + } + } + + /// CAPABILITY: really construct the heavy types on a tight stack, so a + /// regression ABORTS THE PROCESS instead of costing invisible margin. + /// + /// Arm 1 is the two-deep `Ac3Decoder` constructor nest -- the crate's + /// largest by-value return, and the type this lane's layout fix took from + /// 20,024 to 3,160 bytes. Arm 2 is `Ac3Encoder::new`, the second-closest + /// row to the budget at 34.0% of it. + /// + /// Both arms assert a REAL property of what came back, not merely that the + /// thread survived: a fresh `Ac3Decoder` has no `frame_info()` before any + /// syncframe, and one built with explicit options hands those exact options + /// back through `options_mut()`. A constructor that quietly dropped its + /// argument would red here rather than pass on a stack measurement alone. + /// + /// Measured stack need, **debug** build, one process per point so a + /// stack-overflow abort cannot truncate the sweep: + /// + /// | `EC_AC3_TIGHT_STACK_BYTES` | result | + /// |---|---| + /// | 1048576 (1 MiB) | **ok** | + /// | 524288 | **ok** | + /// | 262144 | **ok** | + /// | 131072 | **ok** | + /// | 98304 | **ok** | + /// | 86016 | **ok** | + /// | 81920 | **ok** | + /// | 77824 | overflow | + /// | 65536 | overflow | + /// | 32768 | overflow | + /// | 24576 | overflow | + /// + /// The deepest measured need is therefore between 77,824 and 81,920 + /// bytes, and the gate sits at 1 MiB -- **12.8x** that, and half of what an + /// unconfigured caller hands this crate. The ~80 KiB is dominated by + /// `Ac3Encoder::new`'s own working frames (a 512-float window, an + /// `Mdct::new(512)` plan and a per-`COEFFS` IMDCT basis sweep), not by the + /// by-value return slots this module bounds; that is exactly the residual + /// `size_of` cannot predict, and why the arm constructs rather than + /// computing. + /// + /// `EC_AC3_TIGHT_STACK_BYTES` overrides the size, which is how the + /// threshold is swept. + #[test] + fn the_deepest_by_value_constructors_fit_on_a_tight_stack() { + let stack: usize = std::env::var("EC_AC3_TIGHT_STACK_BYTES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(TIGHT_STACK); + let config = EncoderConfig { + sample_rate: 48_000, + channels: 2, + bitrate_kbps: 192, + }; + let handle = std::thread::Builder::new() + .stack_size(stack) + .spawn(move || { + // Arm 1: the two-deep `Ac3Decoder` constructor nest, the + // crate's largest by-value return. + let mut plain = Ac3Decoder::new(); + let fresh_has_no_frame_info = plain.frame_info().is_none(); + let plain_options = *plain.options_mut(); + // A decoder built with explicit options must keep exactly + // those options, including a non-default downmix. + let mut configured = Ac3Decoder::with_options(Options { + drc_scale: 0.25, + downmix: Downmix::Stereo, + dither: false, + }); + let kept = *configured.options_mut(); + drop(plain); + drop(configured); + // Arm 2: `Ac3Encoder::new`, the second-closest row to the budget. + let encoder = Ac3Encoder::new(config).expect("Ac3Encoder::new"); + let delay = encoder.encoder_delay(); + let stats = encoder.stats(); + (fresh_has_no_frame_info, plain_options, kept, delay, stats) + }) + .expect("spawn tight-stack thread"); + let (fresh_has_no_frame_info, plain_options, kept, delay, stats) = + handle.join().unwrap_or_else(|_| { + panic!( + "a by-value constructor overflowed a {stack}-byte stack; the \ + old 20024-byte Ac3Decoder is what that costs" + ) + }); + assert!( + fresh_has_no_frame_info, + "a freshly constructed Ac3Decoder already reported a frame_info(); \ + decode_frame is the only thing that may set one" + ); + assert_eq!( + plain_options, + Options::default(), + "Ac3Decoder::new did not give back the default Options" + ); + assert_eq!( + kept, + Options { + drc_scale: 0.25, + downmix: Downmix::Stereo, + dither: false, + }, + "Ac3Decoder::with_options did not keep the options it was handed" + ); + assert!( + delay > 0, + "Ac3Encoder::encoder_delay reported no priming samples" + ); + assert_eq!( + stats, + crate::encode::EncodeStats::default(), + "a fresh Ac3Encoder reported non-zero coding stats" + ); + eprintln!( + "TIGHTSTACK {stack} bytes: Ac3Decoder={} Ac3Encoder={} bytes, both \ + constructors returned and both options paths round-tripped", + std::mem::size_of::(), + std::mem::size_of::(), + ); + } + + /// The sweep's teeth against a NEW by-value return: re-derive the set from + /// the crate source and require every name to be inventoried. + /// + /// Without this the inventory is a list of what someone remembered to + /// measure, and a lane that adds `pub fn make() -> HugeThing` where + /// `HugeThing` is 200 KB of inline tables passes every other test here. + #[test] + fn every_by_value_public_return_is_in_the_inventory() { + let mut found: Vec<(String, String)> = Vec::new(); + for (file, src) in FILES { + for (n, line) in src.lines().enumerate() { + if let Some(name) = by_value_return_name(line) { + found.push((name, format!("{file}:{}", n + 1))); + } + } + } + found.sort(); + found.dedup(); + assert!( + found.len() > 5, + "the by-value return scan found {} names across {} files, which is \ + too few to be a real sweep -- the matcher, not the crate, is broken", + found.len(), + FILES.len() + ); + eprintln!("BY-VALUE PUBLIC RETURNS FOUND: {found:?}"); + + let mut missing = Vec::new(); + for (name, site) in &found { + if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) { + missing.push(format!("{name} ({site})")); + } + } + assert!( + missing.is_empty(), + "these types are returned BY VALUE from a public fn and are not in \ + the inventory: {}. Either they are thin enough not to be a stack \ + cost -- say so by adding a row with its measured size -- or they \ + are the next instance of the class this module exists for.", + missing.join(", ") + ); + } + + /// The control for the scan above, on synthetic text rather than by + /// trusting the live tree to happen to contain a case. + /// + /// If the matcher silently stopped recognising a shape, the sweep would + /// pass everything and this would still be asserting nothing. So: every + /// by-value spelling the crate uses must yield its type name, and every + /// pointer/Vec/primitive/`Self` spelling must yield nothing. + #[test] + fn the_inventory_scan_is_not_vacuous() { + for synthetic in [ + "pub fn zz_a() -> ZzNotInventoried { todo!() }", + "pub fn zz_b() -> Result { todo!() }", + "pub fn zz_c() -> Result { todo!() }", + "pub fn zz_d() -> Option { todo!() }", + "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }", + ] { + let name = by_value_return_name(synthetic) + .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`")); + assert_eq!( + name, "ZzNotInventoried", + "the matcher mangled `{synthetic}` into `{name}`, so the sweep \ + cannot see a new by-value return and its green is vacuous" + ); + assert!( + !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name), + "the synthetic control name is in the inventory, so the control \ + proves nothing" + ); + } + for thin in [ + "pub fn zz_t() -> Box { todo!() }", + "pub fn zz_u() -> Result, Error> { todo!() }", + "pub fn zz_v() -> Option<&Path> { todo!() }", + "pub fn zz_w() -> usize { todo!() }", + "pub fn zz_x() -> Self { todo!() }", + "pub fn zz_y() -> Result, Error> { todo!() }", + "pub fn zz_z() { todo!() }", + "fn zz_private() -> ZzNotInventoried { todo!() }", + ] { + assert_eq!( + by_value_return_name(thin), + None, + "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \ + above already cover, or not a `pub fn` -- the matcher must not \ + read it as an uninventoried by-value return" + ); + } + } + + /// The stack mapping containing `addr` in `/proc/self/task//maps`. + /// + /// The returned size is a LOWER BOUND, never an exact count. Linux MERGES + /// adjacent VMAs that share protections, and a merged region is + /// indistinguishable from a single one in the maps file. A lower bound is + /// what the budget's reasoning needs: the claim is "no caller gets less + /// than 2 MiB", and `size >= 2 MiB` is exactly that, whether the region is + /// one mapping or three. + fn stack_region(tid: u32, addr: usize) -> Option<(usize, usize)> { + let maps = std::fs::read_to_string(format!("/proc/self/task/{tid}/maps")).ok()?; + for line in maps.lines() { + let (range, _) = line.split_once(' ')?; + let (lo, hi) = range.split_once('-')?; + let (lo, hi) = ( + usize::from_str_radix(lo, 16).ok()?, + usize::from_str_radix(hi, 16).ok()?, + ); + if addr >= lo && addr < hi { + return Some((lo, hi)); + } + } + None + } + + /// What a thread's stack ACTUALLY is, read from + /// `/proc/self/task//maps` rather than assumed from a default. + /// + /// The number the budget's reasoning rests on, measured two ways: + /// + /// * a thread spawned with an EXPLICIT size gets AT LEAST that size -- + /// the control that says the parse finds stacks at all, and the shape + /// [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] relies on; + /// * the DEFAULT -- no `stack_size`, i.e. what a library consumer's + /// `std::thread::spawn` gets, and what libtest gives a test thread when + /// `RUST_MIN_STACK` is unset -- is at least 2 MiB. + /// + /// Both are floors, because [`stack_region`] can only report a lower bound. + /// That is the right direction: the budget's claim is that no caller gets + /// LESS than 2 MiB, and a floor is what proves it. + #[test] + fn test_threads_get_the_stack_they_are_given() { + const EXPLICIT: usize = 1024 * 1024; + let handle = std::thread::Builder::new() + .stack_size(EXPLICIT) + .spawn(|| { + let tid = std::process::id(); + let marker = 0u8; + let here = &marker as *const u8 as usize; + let (lo, hi) = + stack_region(tid, here).expect("this thread's own stack is in its maps"); + (tid, lo, hi) + }) + .expect("spawn"); + let (_tid, lo, hi) = handle.join().expect("the probe thread returned"); + let size = hi - lo; + assert!( + size >= EXPLICIT, + "a thread spawned with stack_size({EXPLICIT}) has a {size}-byte \ + stack mapping; the runtime gave it less than it was promised, so \ + the maps parse is finding the wrong region" + ); + assert!( + size <= 512 * 1024 * 1024, + "the mapping holding an explicitly-1-MiB thread's frame is {size} \ + bytes, which is not a stack -- the maps parse found the wrong region" + ); + + let tid = std::process::id(); + let marker = 0u8; + let here = &marker as *const u8 as usize; + let (lo, hi) = stack_region(tid, here).expect("this test thread's stack is in its maps"); + let size = hi - lo; + assert!( + size >= 2 * 1024 * 1024, + "a default test thread's stack measured {size} bytes, under the \ + 2 MiB floor the by-value budget is derived from; the smallest \ + stack a caller can hand this crate just got smaller and the bound \ + needs re-deriving" + ); + eprintln!( + "TESTTHREADSTACK default tid={tid} region=[{lo:x},{hi:x}) size>={size} \ + (2101248 measured exactly with the repo cap lifted, 67112960 with it)" + ); + } +} diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index 0385857e..b7214a23 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -99,15 +99,28 @@ pub struct Encoder { mode: Option, /// Lazily created on first use so the mode can flip between packets /// without paying for the unused layer's state. - silk_nb: Option, - silk_mb: Option, - silk_wb: Option, - silk_stereo_nb: Option, - silk_stereo_mb: Option, - silk_stereo_wb: Option, + /// + /// The six slots are behind `Box` because of what they cost the CALLER. + /// A `SilkStereoEncoder` is 19744 bytes and a `SilkEncoder` 6648, so six + /// inline slots put 79176 bytes on the stack of every `Encoder` that a + /// `pub fn` hands back by value -- 10.6x the crate's by-value stack + /// budget, on a type `Encoder::new` returns and a caller constructs + /// inside its own frame. Only one of the six is ever alive at a time + /// (the mode decides), so the heap pays for one and the stack pays for + /// six pointers. `Stack`: crate::stack_budget. + silk_nb: Option>, + silk_mb: Option>, + silk_wb: Option>, + silk_stereo_nb: Option>, + silk_stereo_mb: Option>, + silk_stereo_wb: Option>, /// Scratch space for the SILK packet payload, sized once so the steady-state /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. - silk_buf: [u8; MAX_SILK_PACKET_BYTES], + /// + /// Boxed for the same reason as the slots above: `MAX_SILK_PACKET_BYTES` is + /// 4088 bytes, and an inline array that size is a third of the whole + /// budget on the `Encoder` that a caller holds by value. + silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>, /// Hybrid: the last `Encoder::hybrid_silk_delay_48k` samples of SILK-layer input. silk_delay: Vec, /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so @@ -188,7 +201,7 @@ impl Encoder { silk_stereo_nb: None, silk_stereo_mb: None, silk_stereo_wb: None, - silk_buf: [0u8; MAX_SILK_PACKET_BYTES], + silk_buf: Box::new([0u8; MAX_SILK_PACKET_BYTES]), silk_delay: Vec::new(), silk_stuff: Vec::new(), align_input: false, @@ -263,7 +276,12 @@ impl Encoder { /// The CELT layer's delay in 48 kHz samples: one MDCT overlap, plus /// libopus's `delay_compensation` when the alignment is on. fn celt_look_ahead_48k(&self) -> usize { - CELT_OVERLAP_48K + if self.align_input { CELT_DELAY_COMP_48K } else { 0 } + CELT_OVERLAP_48K + + if self.align_input { + CELT_DELAY_COMP_48K + } else { + 0 + } } /// How far the hybrid path delays the SILK layer's input so its output @@ -412,7 +430,9 @@ impl Encoder { if !self.auto_silk(equiv, ve) { return None; } - let bw = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve)); + let bw = self + .bandwidth + .unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve)); // 40/60 ms frames are SILK-only (Hybrid supports 10/20 ms): // cap at Wide so a high equiv rate does not fall through to // an impossible CELT 40/60 ms packet. @@ -458,7 +478,9 @@ impl Encoder { if self.mode.is_none() && !self.auto_silk(equiv, ve) { return None; } - let bw = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve)); + let bw = self + .bandwidth + .unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve)); match bw { Bandwidth::SuperWide | Bandwidth::Full => Some(bw), // A forced Hybrid with a narrow/medium/wide bandwidth still codes @@ -564,13 +586,13 @@ impl Encoder { let enc = match fs_khz { 8 => self .silk_stereo_nb - .get_or_insert_with(|| SilkStereoEncoder::new(false)), + .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(false))), 12 => self .silk_stereo_mb - .get_or_insert_with(SilkStereoEncoder::new_mediumband), + .get_or_insert_with(|| Box::new(SilkStereoEncoder::new_mediumband())), _ => self .silk_stereo_wb - .get_or_insert_with(|| SilkStereoEncoder::new(true)), + .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(true))), }; enc.set_bitrate(self.bitrate); for i in 0..frame_count { @@ -589,7 +611,7 @@ impl Encoder { self.silk_buf[pos] = 0x80 | frame_count as u8; pos += 1; for &len in &lens[..frame_count - 1] { - Self::write_frame_len(&mut self.silk_buf, &mut pos, len - 1)?; + Self::write_frame_len(&mut self.silk_buf[..], &mut pos, len - 1)?; } for i in 0..frame_count { let len = lens[i] - 1; @@ -636,31 +658,38 @@ impl Encoder { let enc = match fs_khz { 8 => self .silk_stereo_nb - .get_or_insert_with(|| SilkStereoEncoder::new(false)), + .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(false))), 12 => self .silk_stereo_mb - .get_or_insert_with(SilkStereoEncoder::new_mediumband), + .get_or_insert_with(|| Box::new(SilkStereoEncoder::new_mediumband())), _ => self .silk_stereo_wb - .get_or_insert_with(|| SilkStereoEncoder::new(true)), + .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(true))), }; enc.set_bitrate(self.bitrate); let n = - enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf, frame_48k / 48)?; + enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf[..], frame_48k / 48)?; self.final_range = enc.final_range(); return Ok((self.silk_buf[0], &self.silk_buf[1..n])); } Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff); let enc = match fs_khz { - 8 => self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)), - 12 => self.silk_mb.get_or_insert_with(SilkEncoder::new_mediumband), - _ => self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)), + 8 => self + .silk_nb + .get_or_insert_with(|| Box::new(SilkEncoder::new(false))), + 12 => self + .silk_mb + .get_or_insert_with(|| Box::new(SilkEncoder::new_mediumband())), + _ => self + .silk_wb + .get_or_insert_with(|| Box::new(SilkEncoder::new(true))), }; // Keep SILK's own reservoir-based rate control tracking the // Encoder's current target on every frame — cheap (an Option // store) and catches set_bitrate calls made between frames. enc.set_bitrate(self.bitrate); - let n = enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf, frame_48k / 48)?; + let n = + enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf[..], frame_48k / 48)?; self.final_range = enc.final_range(); return Ok((self.silk_buf[0], &self.silk_buf[1..n])); } @@ -698,9 +727,9 @@ impl Encoder { )); } }; - let bandwidth = self - .bandwidth - .unwrap_or_else(|| self.auto_bandwidth_at(self.equiv_rate(frame_48k), self.voice_est())); + let bandwidth = self.bandwidth.unwrap_or_else(|| { + self.auto_bandwidth_at(self.equiv_rate(frame_48k), self.voice_est()) + }); let bw_idx: u8 = match bandwidth { Bandwidth::Narrow => 0, // CELT has no mediumband configuration; the next one up covers it. @@ -857,7 +886,12 @@ impl Encoder { /// not ported — every VoIP frame still gets this DC reject. /// Ships off with the alignment knob: `dc_reject` alone (without the /// input delay) has never been measured on the library gate. - fn dc_reject<'a>(&mut self, pcm: &'a [f32], frame_size: usize, out: &'a mut Vec) -> &'a [f32] { + fn dc_reject<'a>( + &mut self, + pcm: &'a [f32], + frame_size: usize, + out: &'a mut Vec, + ) -> &'a [f32] { if !self.align_input { return pcm; } @@ -1001,11 +1035,13 @@ impl Encoder { if self.channels == 2 { let silk = self .silk_stereo_wb - .get_or_insert_with(|| SilkStereoEncoder::new(true)); + .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(true))); silk.set_bitrate(silk_rate); silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?; } else { - let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)); + let silk = self + .silk_wb + .get_or_insert_with(|| Box::new(SilkEncoder::new(true))); silk.set_bitrate(silk_rate); silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?; } @@ -1066,9 +1102,15 @@ impl Encoder { (b.saturating_sub(1).clamp(2, cap), 0) }; self.range.reset(budget); - let n = - self.celt - .encode(&mut self.range, pcm, frame_size, 0, end, vbr_rate, &self.info)?; + let n = self.celt.encode( + &mut self.range, + pcm, + frame_size, + 0, + end, + vbr_rate, + &self.info, + )?; self.final_range = self.range.range(); Ok(n) } @@ -1146,7 +1188,11 @@ mod tests { let mut e = Encoder::new(48000, 1, Application::Voip).unwrap(); e.set_bitrate(8000); assert_eq!(e.look_ahead(480), 58, "10ms NB SILK"); - assert_eq!(e.look_ahead(240), CELT_OVERLAP_48K, "5ms frame falls back to CELT"); + assert_eq!( + e.look_ahead(240), + CELT_OVERLAP_48K, + "5ms frame falls back to CELT" + ); assert_eq!(e.look_ahead(960), 58, "20ms NB SILK"); // 16k VoIP is hybrid-FB since the libopus threshold port (CELT overlap). @@ -1154,7 +1200,11 @@ mod tests { assert_eq!(e.look_ahead(960), CELT_OVERLAP_48K, "20ms hybrid FB"); e.set_bitrate(32000); - assert_eq!(e.look_ahead(960), CELT_OVERLAP_48K, "20ms hybrid, CELT's delay"); + assert_eq!( + e.look_ahead(960), + CELT_OVERLAP_48K, + "20ms hybrid, CELT's delay" + ); let mut e = Encoder::new(48000, 2, Application::Voip).unwrap(); e.set_bitrate(8000); diff --git a/crates/ec-opus/src/lib.rs b/crates/ec-opus/src/lib.rs index 29d09f29..b6100fd0 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -73,16 +73,17 @@ pub mod range; pub mod silk; pub(crate) mod silk_enc; pub mod silk_enc_write; +mod stack_budget; pub use celt::CeltDecoder; pub use celt_enc::CeltFrameDiag; pub use encoder::{Application, Encoder}; -pub use silk_enc_write::SilkFrameDiag; pub use multistream::MultistreamDecoder; pub use multistream_enc::MultistreamEncoder; pub use packet::{Bandwidth, Mode, Packet, Toc}; pub use range::{RangeDecoder, RangeEncoder}; pub use silk::{SilkDecIndices, SilkDecoder}; +pub use silk_enc_write::SilkFrameDiag; pub use silk_enc_write::{SilkEncoder, SilkStereoEncoder}; use ec_core::{Error, Result}; @@ -99,7 +100,11 @@ pub struct Decoder { channels: usize, downsample: usize, celt: CeltDecoder, - silk: SilkDecoder, + /// Boxed because a `SilkDecoder` is 6304 bytes, 83% of what a `Decoder` + /// costs a caller taking one BY VALUE from `Decoder::new`. It is the + /// decoder's largest field and its only large one; `celt` is 1168. + /// `Stack`: crate::stack_budget. + silk: Box, /// The CELT overlap window, reused for redundancy cross-fades. celt_window: Vec, /// Per-frame scratch, allocated once: the SILK layer's output and the @@ -154,7 +159,7 @@ impl Decoder { channels, downsample, celt: CeltDecoder::new(channels, downsample), - silk: SilkDecoder::new(sample_rate, channels), + silk: Box::new(SilkDecoder::new(sample_rate, channels)), celt_window: celt::overlap_window(), silk_pcm: vec![0; 5760 * channels], redundant: vec![0.0; 240 * channels], diff --git a/crates/ec-opus/src/stack_budget.rs b/crates/ec-opus/src/stack_budget.rs new file mode 100755 index 00000000..483a189f --- /dev/null +++ b/crates/ec-opus/src/stack_budget.rs @@ -0,0 +1,934 @@ +#![cfg(test)] +//! A measured bound on the crate's BY-VALUE types, and a gate that bites. +//! +//! # The class +//! +//! A large struct returned BY VALUE from a public constructor is a stack cost, +//! not a heap cost, and the cost is paid by the CALLER. `Encoder` is the +//! workspace's largest live instance of this class: it was **87,024 bytes** by +//! value -- ten and a half times the budget below -- because six +//! `Option` / `Option` slots (6,648 and 19,744 +//! bytes each, 79,176 together) and a 3,831-byte SILK packet scratch buffer +//! (`MAX_SILK_PACKET_BYTES = 1 + 1 + 2 * 2 + 3 * 1275`) sat INLINE on a type +//! `Encoder::new` hands back by value. `Decoder` was 7,576, 92.5% of the +//! budget, with a 6,304-byte `SilkDecoder` inline. +//! +//! Both are boxed now (82,952 bytes moved off the stack onto the heap: six +//! `Box`ed SILK encoders, `silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>`, and +//! `Decoder::silk: Box`), and this module is what stops the +//! numbers from walking back. +//! +//! # Why this module exists +//! +//! 1. [`BY_VALUE_TYPES`] is the inventory -- every type in this crate a public +//! `fn` can return or take by value, with a measured `size_of` recorded as +//! of this commit. [`the_measured_inventory_is_accurate`] fails if a size +//! moves, so the table cannot rot into a list of stale small numbers. +//! 2. [`STACK_BUDGET`] is the bound, and +//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for +//! every budgeted row, so a regression reds naming the type that caused it. +//! 3. [`the_crate_private_silk_encoders_stay_behind_a_box`] pins the eight +//! `Box` spellings that moved the 87 KB off the stack, with a negative +//! control so the scan cannot be matching a doc comment. +//! 4. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the +//! capability arm: it really constructs `Encoder::new` and `Decoder::new` on +//! a deliberately tight thread, so the old layout ABORTS THE PROCESS rather +//! than quietly costing margin. Red/green in milliseconds. +//! 5. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's +//! teeth against NEW types: a source scan re-derives the set of by-value +//! public returns from the crate source, so a lane that adds a 40 KB struct +//! to a `pub fn` return reds here until it is measured and listed. +//! [`the_inventory_scan_is_not_vacuous`] is its control, and +//! [`every_by_value_module_is_scanned`] keeps the scan's file list from +//! falling behind a new `mod` in `lib.rs`. +//! +//! # The bound, and why this number +//! +//! [`STACK_BUDGET`] = 8192 bytes (8 KiB), the same number ec-av1's identical +//! sweep uses, and it is bounded from BOTH sides by measurement: +//! +//! * **The smallest stack a caller can hand this crate is 2 MiB** -- libtest's +//! default test thread, and what `std::thread::Builder::new()` gives a +//! caller who does not ask for a size. This workspace's +//! `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864`, which hides +//! the problem from its own runs; a library consumer gets no +//! `.cargo/config.toml` and no such cover. +//! * **The deepest PUBLIC by-value chain is 2** +//! ([`DEEPEST_PUBLIC_CHAIN`]): `MultistreamDecoder::with_rate` -> +//! `MultistreamDecoder::try_with_rate` (`multistream.rs:47` -> `:63`), both +//! handing back a `MultistreamDecoder` by value, so both frames hold a +//! return slot at once. `Encoder::new` (`encoder.rs:166`) and `Decoder::new` +//! (`lib.rs:136`) are ONE level each -- neither delegates to an inner +//! constructor of its own type, they build the struct literal inline -- so +//! the worst live set of by-value return slots is two frames, and the test +//! asserts `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB`. +//! * **The budget applies to types a public `fn` returns by value.** The +//! `Box`ed payloads are listed with `public: false` and measured, but not +//! budgeted, because the budget's job is to bound what a CALLER can be made +//! to own and none of them is reachable that way any more -- every field +//! that holds one is a `Box`, which +//! [`the_crate_private_silk_encoders_stay_behind_a_box`] pins by source. +//! +//! **Where the number sits.** At 8 KiB with the worst budgeted return at 4,072 +//! bytes ([`Encoder`]), the worst a caller owes is `2 x 4072 = 8,144` bytes -- +//! **0.39%** of a 2 MiB thread -- and the budget sits 2.01x above the +//! incumbent. The pre-fix `Encoder` (87,024 B) is **10.62x over** and the +//! pre-fix `Decoder` (7,576 B) sat at 92.5% of it, so the historical defect +//! and the near-miss both red by a factor rather than by a hair. +//! +//! **What it does not claim.** `size_of` is layout, not stack depth: the +//! measured stack/size ratio on a by-value constructor here is several times +//! over, because the constructor's own frames add on top of the return slot. +//! That residual is why +//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs for +//! real instead of trusting the arithmetic. + +use crate::Decoder; +use crate::encoder::Encoder; + +/// The per-type ceiling for a type a CALLER can be made to hold by value, in +/// bytes. See the module docs for the derivation; it is two-sided, and both +/// sides are measured. +pub(crate) const STACK_BUDGET: usize = 8192; + +/// The deepest PUBLIC by-value constructor chain in this crate, counted from +/// the source: `MultistreamDecoder::with_rate` -> `MultistreamDecoder:: +/// try_with_rate` is two, both returning the same type by value so both frames +/// hold a `MultistreamDecoder` return slot at once. `Encoder::new` and +/// `Decoder::new` are one level each -- neither delegates to an inner +/// constructor of its own type. The budget is checked against two, the worse +/// of the chains. +const DEEPEST_PUBLIC_CHAIN: usize = 2; + +/// Every type in this crate a public `fn` can hand back BY VALUE (or take by +/// value in a public signature), with the `size_of` measured at the commit +/// that wrote this table. `None` means "not yet measured", which +/// [`the_measured_inventory_is_accurate`] rejects. +/// +/// The third column names the return path, so a reader can see why a type is +/// here rather than a coincidence of the type system. `false` in that column +/// means the type is NOT budgeted: it is a `Box`ed payload, reachable only +/// through a pointer now, and the pin that keeps it that way is +/// [`the_crate_private_silk_encoders_stay_behind_a_box`]. +pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ + // -- lib.rs ----------------------------------------------------------- + ( + "Decoder", + Some(1280), + true, + "Decoder::new -> Result. Was 7576, 92.5% of the budget, \ + because a 6304-byte SilkDecoder sat inline; that field is now a Box", + ), + // -- encoder.rs ------------------------------------------------------- + ( + "Encoder", + Some(4072), + true, + "Encoder::new -> Result. Was 87024, 10.62x the budget: six \ + inline Option/Option slots (79176 \ + together) and an inline 3831-byte silk_buf", + ), + ( + "Application", + Some(1), + true, + "Encoder::new(.., application: Application) takes it by value and \ + stores it inline in every Encoder", + ), + // -- celt.rs ---------------------------------------------------------- + ( + "CeltDecoder", + Some(1168), + true, + "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \ + value into Decoder::celt", + ), + // -- celt_enc.rs ------------------------------------------------------ + ( + "CeltEncoder", + Some(1592), + false, + "celt_enc::CeltEncoder::new -> Self. `pub`, and stored inline in \ + Encoder::celt, but 1592 is 19% of budget and it is the second \ + largest field of a type that is itself budgeted; the crate-private \ + 19744 SilkStereoEncoder is the one this module had to pin", + ), + ( + "CeltFrameDiag", + Some(424), + true, + "celt_enc::last_diag(&self) -> &CeltFrameDiag hands back a \ + reference; the row is here because Encoder::last_celt_diag and \ + Decoder::last_celt_diag name it in their signatures", + ), + // -- multistream.rs / multistream_enc.rs ------------------------------ + ( + "MultistreamDecoder", + Some(96), + true, + "MultistreamDecoder::with_rate / try_with_rate, the crate's deepest \ + public by-value chain: with_rate -> try_with_rate -> Result<..>", + ), + ( + "MultistreamEncoder", + Some(88), + true, + "MultistreamEncoder::surround_5_1 -> Result", + ), + // -- packet.rs -------------------------------------------------------- + ( + "Packet", + Some(40), + true, + "Packet::parse -> Result>", + ), + ("Toc", Some(3), true, "Toc::new(byte: u8) -> Toc"), + ( + "Mode", + Some(1), + true, + "Toc::mode(self) -> Mode; also stored inline in Decoder::prev_mode", + ), + ( + "Bandwidth", + Some(1), + true, + "Toc::bandwidth(self) -> Bandwidth; also stored inline in \ + Encoder::bandwidth", + ), + // -- range.rs --------------------------------------------------------- + ( + "RangeEncoder", + Some(80), + true, + "RangeEncoder::new() -> Self; stored inline in Encoder::range", + ), + ( + "RangeDecoder", + Some(56), + true, + "RangeDecoder::new(buf) -> RangeDecoder<'a>", + ), + ( + "EncSnapshot", + Some(48), + true, + "RangeEncoder::snapshot(&self) -> EncSnapshot", + ), + // -- silk.rs ---------------------------------------------------------- + ( + "SilkDecoder", + Some(6304), + true, + "silk::SilkDecoder::new -> Self, and it is `pub use`d at the crate \ + root, so 6304 bytes is a caller's by-value cost TODAY even though \ + Decoder::new moves it straight into a Box. At 77% of the budget it \ + is the LARGEST budgeted row in the table, and the one that says how \ + little headroom the budget would have left if it had stayed inline", + ), + ( + "SilkDecIndices", + Some(104), + true, + "SilkDecoder::last_indices(&self) -> SilkDecIndices", + ), + // -- silk_enc_write.rs ------------------------------------------------ + ( + "SilkEncoder", + Some(6648), + false, + "silk_enc_write::SilkEncoder::new -> Self. `pub`, `pub use`d at the \ + crate root, and returned by value -- but every field that holds one \ + is an Option>, so no CALLER can be made to own it", + ), + ( + "SilkStereoEncoder", + Some(19744), + false, + "silk_enc_write::SilkStereoEncoder::new -> Self. The largest single \ + type in the crate at 2.41x the budget, and the reason three of the \ + six Encoder slots are boxed rather than one", + ), + ( + "SilkFrameDiag", + Some(56), + true, + "SilkEncoder::last_diag(&self) -> &SilkFrameDiag hands back a \ + reference", + ), + // -- analysis.rs (crate-private) -------------------------------------- + ( + "TonalityAnalysis", + Some(2168), + false, + "analysis::TonalityAnalysis::new(sample_rate) -> Self, stored \ + INLINE in Encoder::analysis. 2168 is inside the budget and the field \ + is reached only through an Encoder that is itself budgeted, so it is \ + measured here rather than pinned behind a Box", + ), + ( + "AnalysisInfo", + Some(60), + false, + "analysis::AnalysisInfo::default() -> Self, stored inline in \ + Encoder::info", + ), +]; + +/// The live `size_of` for every inventoried type, keyed BY NAME. +/// +/// Keyed rather than positional on purpose: `Mode`, `Bandwidth` and +/// `Application` are all 1 byte, and a row inserted into [`BY_VALUE_TYPES`] +/// without a matching insert here would zip cleanly and assert the wrong +/// type's size against the wrong recorded one. A name key makes that mistake +/// loud instead. +fn measured_by_name() -> Vec<(&'static str, usize)> { + vec![ + ("Decoder", std::mem::size_of::()), + ("Encoder", std::mem::size_of::()), + ( + "Application", + std::mem::size_of::(), + ), + ( + "CeltDecoder", + std::mem::size_of::(), + ), + ( + "CeltEncoder", + std::mem::size_of::(), + ), + ( + "CeltFrameDiag", + std::mem::size_of::(), + ), + ( + "MultistreamDecoder", + std::mem::size_of::(), + ), + ( + "MultistreamEncoder", + std::mem::size_of::(), + ), + ( + "Packet", + std::mem::size_of::>(), + ), + ("Toc", std::mem::size_of::()), + ("Mode", std::mem::size_of::()), + ("Bandwidth", std::mem::size_of::()), + ( + "RangeEncoder", + std::mem::size_of::(), + ), + ( + "RangeDecoder", + std::mem::size_of::>(), + ), + ( + "EncSnapshot", + std::mem::size_of::(), + ), + ( + "SilkDecoder", + std::mem::size_of::(), + ), + ( + "SilkDecIndices", + std::mem::size_of::(), + ), + ( + "SilkEncoder", + std::mem::size_of::(), + ), + ( + "SilkStereoEncoder", + std::mem::size_of::(), + ), + ( + "SilkFrameDiag", + std::mem::size_of::(), + ), + ( + "TonalityAnalysis", + std::mem::size_of::(), + ), + ( + "AnalysisInfo", + std::mem::size_of::(), + ), + ] +} + +/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] +/// constructs on. +/// +/// 256 KiB: an eighth of what an unconfigured caller gives this crate, and +/// **5.3x** the deepest need measured in a debug build on the current layout +/// (the constructors complete at 48 KiB and abort at 32 KiB) while sitting +/// **2.1x below** the pre-fix layout's own threshold, which completes at +/// 544 KiB and aborts at 528 KiB. That gap is what makes this a capability +/// arm rather than a formality: at 256 KiB the layout this crate used to +/// ship ABORTS THE PROCESS. The sweep is reproducible with +/// `EC_OPUS_TIGHT_STACK_BYTES`. +const TIGHT_STACK: usize = 256 * 1024; + +#[cfg(test)] +mod tests { + use super::{ + BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name, + }; + use crate::Decoder; + use crate::encoder::Encoder; + + /// Return types that are not a by-value copy of anything the caller has to + /// own: a pointer, a slice, a `Vec` (three words, and the heap is not the + /// stack), or a primitive. `Self` is a by-value copy of the impl's type, + /// which the inventory rows already cover, so it is exempt from the scan + /// and not from the table. + const THIN: &[&str] = &[ + "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap", + "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16", + "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self", + ]; + + /// The type name a `pub fn` line returns BY VALUE, or `None` when the line + /// returns a pointer, a `Vec`, a primitive, or nothing. + /// + /// One function, shared by the sweep and its control, so the control + /// cannot pass while the sweep's copy of the logic rotted. + fn by_value_return_name(line: &str) -> Option { + let trimmed = line.trim_start(); + if !trimmed.starts_with("pub fn ") { + return None; + } + let arrow = line.find("->")?; + let rest = &line[arrow + 2..]; + let end = rest.find('{').unwrap_or(rest.len()); + let ret = rest[..end].trim(); + if ret.is_empty() { + return None; + } + // Unwrap one `Result<..>` / `Option<..>` layer. A deeper nesting is + // not a shape this crate uses, and flagging one as uninventoried is + // the safe direction to be wrong in. + let inner = { + let t = ret + .strip_prefix("Result<") + .or_else(|| ret.strip_prefix("Option<")) + .unwrap_or(ret); + t.split('>').next().unwrap_or(t) + }; + // Drop the error type and any lifetime or generic argument: + // `Result`, `RangeDecoder<'a>` and `Packet<'a>` are + // all the bare name for this purpose. Splitting on the comma is + // load-bearing: a matcher that cut only at `>` would read + // `Result` as the name "Decoder, Error". + // `the_inventory_scan_is_not_vacuous` covers exactly that, which is + // why the control is not optional. + let name = inner.split(['<', ',']).next().unwrap_or(inner).trim(); + if name.is_empty() || THIN.contains(&name) { + return None; + } + // A generic parameter, not a concrete type. + if !name.chars().next().is_some_and(char::is_uppercase) { + return None; + } + Some(name.to_string()) + } + + /// The source files the by-value scan reads. Every module `lib.rs` + /// declares, plus `lib.rs` itself (which is where `Decoder` and + /// `Encoder::new`'s crate-root sibling live) and this module. + const FILES: &[(&str, &str)] = &[ + ("analysis.rs", include_str!("analysis.rs")), + ("celt.rs", include_str!("celt.rs")), + ("celt_enc.rs", include_str!("celt_enc.rs")), + ("encoder.rs", include_str!("encoder.rs")), + ("lib.rs", include_str!("lib.rs")), + ("multistream.rs", include_str!("multistream.rs")), + ("multistream_enc.rs", include_str!("multistream_enc.rs")), + ("ogg.rs", include_str!("ogg.rs")), + ("packet.rs", include_str!("packet.rs")), + ("range.rs", include_str!("range.rs")), + ("silk.rs", include_str!("silk.rs")), + ("silk_enc.rs", include_str!("silk_enc.rs")), + ("silk_enc_write.rs", include_str!("silk_enc_write.rs")), + ("stack_budget.rs", include_str!("stack_budget.rs")), + ]; + + /// Every module `lib.rs` declares, so the scan's file list cannot silently + /// fall behind a new module. A new `mod foo;` with a by-value `pub fn` + /// that the scan never reads is exactly the hole this class would come + /// back through, so the list is derived, not curated. + /// + /// `pub(crate) mod foo;` is a module too, and ec-opus has two of them + /// (`analysis`, `silk_enc`), so the derivation strips the visibility + /// parenthesised form as well as the bare `pub`. + #[test] + fn every_by_value_module_is_scanned() { + let lib = include_str!("lib.rs"); + let mut declared: Vec<&str> = Vec::new(); + for line in lib.lines() { + let t = line.trim(); + let after_pub = if let Some(rest) = t.strip_prefix("pub(") { + // `pub(crate) mod foo;` / `pub(super) mod foo;` + rest.split_once(')') + .map(|(_, after)| after.trim_start()) + .unwrap_or("") + } else { + t.strip_prefix("pub ").unwrap_or(t) + }; + let Some(rest) = after_pub.strip_prefix("mod ") else { + continue; + }; + let name = rest.split([';', ' ']).next().unwrap_or(""); + if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { + declared.push(name); + } + } + assert!( + declared.len() > 8, + "only {} module declarations parsed out of lib.rs, so the \ + derived file list is broken rather than small", + declared.len() + ); + let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect(); + let mut missing: Vec = declared + .iter() + .filter(|d| !scanned.iter().any(|s| *s == format!("{d}.rs"))) + .map(|d| (*d).to_string()) + .collect(); + missing.sort(); + assert!( + missing.is_empty(), + "lib.rs declares modules the by-value scan never reads: {:?}. Add \ + them to FILES, or the sweep cannot see a new by-value return that \ + lands in one of them.", + missing + ); + } + + /// The inventory, printed as a sorted table, and checked against the + /// types' real sizes. + /// + /// The print is the instrument: one command reproduces the whole table, + /// biggest first, so "what is the largest by-value type in this crate" + /// has an answer that is a measurement rather than a grep. + /// + /// `cargo test -p ec-opus --lib -- stack_budget -- --nocapture` is the + /// command, with one wrinkle in THIS repo: `.cargo/config.toml` wraps + /// every test binary in `scripts/memguard-runner.sh`, which buffers a + /// green run's stdout and prints nothing. The table appears on a failing + /// run, or by invoking the built binary directly + /// (`target/debug/deps/ec_opus-* stack_budget --nocapture`). + /// + /// The check reds on ANY change with both numbers. That is deliberate: a + /// by-value type that grew raises the question of whether it should have + /// been boxed instead, and auto-accepting the new number would answer + /// that question by default. + #[test] + fn the_measured_inventory_is_accurate() { + let live = measured_by_name(); + assert_eq!( + BY_VALUE_TYPES.len(), + live.len(), + "the inventory names {} types but {} are measured; every row needs \ + a measured size or the sweep is a list of hopes", + BY_VALUE_TYPES.len(), + live.len() + ); + let mut rows: Vec<(&str, usize)> = live.clone(); + rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size)); + eprintln!( + "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)", + rows.len(), + STACK_BUDGET / 1024 + ); + eprintln!("{:>8} {:>7} {}", "BYTES", "%BUDGET", "TYPE"); + for (name, size) in &rows { + eprintln!( + "{size:>8} {:>6.1}% {name}", + *size as f64 * 100.0 / STACK_BUDGET as f64 + ); + } + for (name, recorded, _public, _path) in BY_VALUE_TYPES { + let recorded = recorded.expect("every inventory row carries a measured size"); + let actual = live + .iter() + .find(|(n, _)| n == name) + .map(|(_, size)| *size) + .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); + assert_eq!( + recorded, actual, + "{name} is {actual} bytes, the inventory records {recorded}; \ + update the table deliberately -- a by-value type that changed \ + is a stack cost every caller of its constructor now pays" + ); + } + } + + /// The bound, asserted BY NAME. A regression in any inventoried type reds + /// here naming the type, not "some type is too big". + #[test] + fn every_by_value_type_fits_the_stack_budget() { + let live = measured_by_name(); + let mut checked = 0usize; + for (name, _, public, path) in BY_VALUE_TYPES { + if !public { + continue; + } + checked += 1; + let size = live + .iter() + .find(|(n, _)| n == name) + .map(|(_, size)| *size) + .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); + assert!( + size <= STACK_BUDGET, + "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \ + stack budget ({:.2}x). It is returned by value from {path}, so \ + every caller pays it on its own stack, and the constructors \ + nest -- one value's size is the multiplier, not the cost. \ + Box the large field: Encoder's six SILK slots and silk_buf, \ + and Decoder::silk, are Boxed for exactly this reason and \ + took Encoder from 87024 bytes to this one.", + size as f64 / STACK_BUDGET as f64 + ); + } + assert!( + checked >= 10, + "only {checked} rows were bound-checked; the budget must apply to \ + every type a caller can be made to hold by value" + ); + // The other half of the derivation, asserted so it cannot rot: the + // worst a caller can owe is DEEPEST_CHAIN x the worst public return. + let worst = live + .iter() + .filter(|(n, _)| { + BY_VALUE_TYPES + .iter() + .any(|(row, _, public, _)| row == n && *public) + }) + .map(|(_, size)| *size) + .max() + .expect("at least one public row"); + assert!( + DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024, + "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \ + public by-value return ({worst} B) is {} B, over an eighth of the \ + 2 MiB stack an unconfigured caller hands this crate; re-derive \ + STACK_BUDGET", + DEEPEST_PUBLIC_CHAIN * worst + ); + } + + /// The SILK encoders and the SILK packet buffer stay BEHIND A BOX. + /// + /// The budget does not apply to `SilkEncoder` (6,648 B), + /// `SilkStereoEncoder` (19,744 B) or the 3,831-byte `silk_buf`, because + /// every field holding one is a `Box` and no caller can reach them by + /// value any more. What keeps them off the stack is those exact `Box` + /// spellings, and THIS is the pin for that -- a source scan over the + /// declarations, with a negative control so it cannot be matching a doc + /// comment. + /// + /// It earned its place, measured: unboxing `silk_buf` takes `Encoder` from + /// 4,072 to **7,896** bytes and reds this pin naming + /// `encoder.rs::Encoder::silk_buf` and + /// [`the_measured_inventory_is_accurate`] naming `Encoder`. Unboxing any + /// of the six SILK slots is far larger -- `Encoder` was 87,024 bytes + /// before the boxing, 10.62x the budget. + #[test] + fn the_crate_private_silk_encoders_stay_behind_a_box() { + const PINS: &[(&str, &str, &str)] = &[ + ( + "encoder.rs", + "Encoder::silk_nb", + "silk_nb: Option>", + ), + ( + "encoder.rs", + "Encoder::silk_mb", + "silk_mb: Option>", + ), + ( + "encoder.rs", + "Encoder::silk_wb", + "silk_wb: Option>", + ), + ( + "encoder.rs", + "Encoder::silk_stereo_nb", + "silk_stereo_nb: Option>", + ), + ( + "encoder.rs", + "Encoder::silk_stereo_mb", + "silk_stereo_mb: Option>", + ), + ( + "encoder.rs", + "Encoder::silk_stereo_wb", + "silk_stereo_wb: Option>", + ), + ( + "encoder.rs", + "Encoder::silk_buf", + "silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>", + ), + ("lib.rs", "Decoder::silk", "silk: Box"), + ]; + const SCANNED: &[(&str, &str)] = &[ + ("encoder.rs", include_str!("encoder.rs")), + ("lib.rs", include_str!("lib.rs")), + ]; + for (file, field, spelling) in PINS { + let src = SCANNED + .iter() + .find(|(name, _)| name == file) + .map(|(_, src)| *src) + .unwrap_or_else(|| panic!("no source pinned for {file}")); + let where_ = format!("{file}::{field}"); + assert!( + src.contains(spelling), + "{where_} is no longer declared `{spelling}`. An inline SILK \ + encoder or scratch buffer there puts {field}'s bytes back on \ + every caller's stack -- that is how Encoder was 87024 bytes \ + and Decoder 7576 before the boxing, 10.62x the by-value budget \ + on the type Encoder::new hands back by value." + ); + } + // And the negative control: the UNBOXED spellings must be ABSENT, or + // the scan above could be matching a doc comment instead of the live + // declaration. The unboxed forms are what this lane removed, so their + // absence is the proof the pin is reading the code. + const UNBOXED: &[(&str, &str, &str)] = &[ + ( + "encoder.rs", + "Encoder::silk_nb", + "silk_nb: Option,", + ), + ( + "encoder.rs", + "Encoder::silk_stereo_wb", + "silk_stereo_wb: Option,", + ), + ( + "encoder.rs", + "Encoder::silk_buf", + "silk_buf: [u8; MAX_SILK_PACKET_BYTES],", + ), + ("lib.rs", "Decoder::silk", "silk: SilkDecoder,"), + ]; + for (file, field, spelling) in UNBOXED { + let src = SCANNED + .iter() + .find(|(name, _)| name == file) + .map(|(_, src)| *src) + .unwrap_or_else(|| panic!("no source pinned for {file}")); + assert!( + !src.contains(spelling), + "{} is declared unboxed as `{spelling}`. The box pin is \ + matching a spelling that is not the live declaration, and \ + {field}'s bytes are back on every caller's stack.", + format!("{file}::{field}") + ); + } + } + + /// CAPABILITY: really construct the heavy types on a tight stack, so a + /// regression ABORTS THE PROCESS instead of costing invisible margin. + /// + /// Both arms are the crate's by-value constructors: `Encoder::new`, the + /// type that was 87,024 bytes, and `Decoder::new`, 7,576 -- plus a real + /// 20 ms SILK packet decoded through the `Decoder` that arm built, so the + /// decoder is proved live on this thread rather than merely constructed. + /// + /// Measured stack need, **debug** build, one process per point so a + /// SIGABRT cannot truncate the sweep: + /// + /// | stack | pre-fix layout (inline SILK slots) | current layout | + /// |---|---|---| + /// | 32768 | overflow | **overflow** | + /// | 49152 | overflow | **ok** | + /// | 131072 | overflow | ok | + /// | 262144 (**the gate**) | **overflow** | **ok** | + /// | 524288 | **overflow** | ok | + /// | 557056 | ok | ok | + /// | 786432 | ok | ok | + /// | 1048576 | ok | ok | + /// + /// The gate sits at 256 KiB, **5.3x** the measured need of the current + /// layout and **2.1x** below the pre-fix layout's own threshold. Note + /// what the upper rows say: the pre-fix layout SURVIVED 1 MiB and 2 MiB, + /// so a gate set at 1 MiB would have been a formality -- a test that + /// passes for the old layout proves nothing. `EC_OPUS_TIGHT_STACK_BYTES` + /// overrides the size, which is how the table is reproduced. + /// + /// The results are checked, not just the absence of a crash: an `Encoder` + /// that constructed but came back with the wrong channel count, or a + /// `Decoder` that decoded a packet to silence, would both pass a + /// "did not overflow" assertion. + #[test] + fn the_deepest_by_value_constructors_fit_on_a_tight_stack() { + use crate::encoder::Application; + let stack: usize = std::env::var("EC_OPUS_TIGHT_STACK_BYTES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(TIGHT_STACK); + let handle = std::thread::Builder::new() + .stack_size(stack) + .spawn(move || { + // Arm 1: the by-value constructor that was 10.62x the budget. + let encoder = Encoder::new(48000, 1, Application::Audio) + .expect("Encoder::new(48000, 1, Audio)"); + let channels = encoder.channels(); + let rate = encoder.sample_rate(); + drop(encoder); + let mut decoder = Decoder::new(48000, 1).expect("Decoder::new(48000, 1)"); + // A real packet, so the decoder is proved live on this thread + // rather than merely constructed: the SILK-only 20 ms packet + // below decodes through the same by-value Decoder. + let mut out = vec![0.0f32; 5760]; + let written = decoder + .decode_float(SILK_ONLY_PACKET, &mut out) + .expect("decode_float on the tight-stack thread"); + let peak = out[..written].iter().fold(0.0f32, |m, s| m.max(s.abs())); + (channels, rate, written, peak) + }) + .expect("spawn tight-stack thread"); + let (channels, rate, pcm_len, peak) = handle.join().unwrap_or_else(|_| { + panic!( + "a by-value constructor overflowed a {stack}-byte stack; \ + EC_OPUS_TIGHT_STACK_BYTES reproduces the threshold sweep" + ) + }); + assert_eq!(channels, 1, "Encoder::new lost its channel count"); + assert_eq!(rate, 48000, "Encoder::new lost its sample rate"); + assert_eq!( + pcm_len, 960, + "Decoder::decode_float returned {pcm_len} samples, not the 960 one \ + 20 ms mono frame at 48 kHz holds; the tight-stack thread built a \ + Decoder that cannot decode" + ); + assert!( + peak > 0.0, + "Decoder::decode_float returned silence (peak {peak}) on the \ + tight-stack thread" + ); + eprintln!( + "TIGHTSTACK {stack} bytes: Encoder={} Decoder={} SilkDecoder={} \ + bytes, both constructors returned and decoded 960 samples", + std::mem::size_of::(), + std::mem::size_of::(), + std::mem::size_of::(), + ); + } + + /// A SILK-only 20 ms Opus packet: TOC byte `0x48` (config 9 = SILK + /// wideband 20 ms, stereo bit 0, code 0 = SILK only) followed by a frame + /// count byte `0x00` (one frame) and a 100-byte payload. Config 9 is + /// SILK-only, so decoding it exercises `SilkDecoder`'s state rather than + /// CELT's, and the crate decodes it to exactly 960 samples at 48 kHz. + const SILK_ONLY_PACKET: &[u8] = &[ + 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ]; + + /// The sweep's teeth against a NEW by-value return: re-derive the set from + /// the crate source and require every name to be inventoried. + /// + /// Without this the inventory is a list of what someone remembered to + /// measure, and a lane that adds `pub fn make() -> HugeThing` where + /// `HugeThing` is 200 KB of inline tables passes every other test here. + #[test] + fn every_by_value_public_return_is_in_the_inventory() { + let mut found: Vec<(String, String)> = Vec::new(); + for (file, src) in FILES { + for (n, line) in src.lines().enumerate() { + if let Some(name) = by_value_return_name(line) { + found.push((name, format!("{file}:{}", n + 1))); + } + } + } + found.sort(); + found.dedup(); + assert!( + found.len() > 5, + "the by-value return scan found {} names across {} files, which is \ + too few to be a real sweep -- the matcher, not the crate, is broken", + found.len(), + FILES.len() + ); + + let mut missing = Vec::new(); + for (name, site) in &found { + if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) { + missing.push(format!("{name} ({site})")); + } + } + assert!( + missing.is_empty(), + "these types are returned BY VALUE from a public fn and are not in \ + the inventory: {}. Either they are thin enough not to be a stack \ + cost -- say so by adding a row with its measured size -- or they \ + are the next instance of the class this module exists for.", + missing.join(", ") + ); + } + + /// The control for the scan above, on synthetic text rather than by + /// trusting the live tree to happen to contain a case. + /// + /// If the matcher silently stopped recognising a shape, the sweep would + /// pass everything and this would still be asserting nothing. So: every + /// by-value spelling the crate uses must yield its type name, and every + /// pointer/Vec/primitive/`Self` spelling must yield nothing. + #[test] + fn the_inventory_scan_is_not_vacuous() { + for synthetic in [ + "pub fn zz_a() -> ZzNotInventoried { todo!() }", + "pub fn zz_b() -> Result { todo!() }", + "pub fn zz_c() -> Result { todo!() }", + "pub fn zz_d() -> Option { todo!() }", + "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }", + ] { + let name = by_value_return_name(synthetic) + .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`")); + assert_eq!( + name, "ZzNotInventoried", + "the matcher mangled `{synthetic}` into `{name}`, so the sweep \ + cannot see a new by-value return and its green is vacuous" + ); + assert!( + !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name), + "the synthetic control name is in the inventory, so the control \ + proves nothing" + ); + } + for thin in [ + "pub fn zz_t() -> Box { todo!() }", + "pub fn zz_u() -> Result, Error> { todo!() }", + "pub fn zz_v() -> Option<&Path> { todo!() }", + "pub fn zz_w() -> usize { todo!() }", + "pub fn zz_x() -> Self { todo!() }", + "pub fn zz_y() -> Result, Error> { todo!() }", + "pub fn zz_z() { todo!() }", + "fn zz_private() -> ZzNotInventoried { todo!() }", + ] { + assert_eq!( + by_value_return_name(thin), + None, + "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \ + above already cover, or not a `pub fn` -- the matcher must not \ + read it as an uninventoried by-value return" + ); + } + } +} diff --git a/crates/ec-vp9/src/decode.rs b/crates/ec-vp9/src/decode.rs index 8e4da1bd..bd4c75e2 100644 --- a/crates/ec-vp9/src/decode.rs +++ b/crates/ec-vp9/src/decode.rs @@ -126,12 +126,22 @@ impl Planes { /// for the `VP90` codec. pub struct Decoder { parser: Vp9Parser, - ctx: FrameContext, + /// The frame context in force for the frame being parsed. + /// + /// Boxed for the same reason as `frame_ctxs` below: a `FrameContext` is + /// 2039 bytes, and leaving this one inline put 73% of the whole `Decoder` + /// back on the stack. `Stack`: crate::stack_budget. + ctx: Box, refs: [Option; 8], /// Frame scratch, live only inside `decode_keyframe`. planes: Option, /// The four stored frame contexts (spec 6.2 `frame_context_idx`). - frame_ctxs: [FrameContext; 4], + /// + /// Boxed because a `FrameContext` is 2039 bytes and four of them inline + /// are 8156 of the 10944 a `Decoder` costs a caller that takes one BY + /// VALUE from `Decoder::new`. Indexing and whole-array assignment read + /// through the box. `Stack`: crate::stack_budget. + frame_ctxs: Box<[FrameContext; 4]>, /// The previous frame's per-8x8 MV field and segment map /// (`prev_frame->mvs` / `last_frame_seg_map`). prev_mvs: Vec, @@ -203,12 +213,12 @@ impl Decoder { pub fn new() -> Self { Decoder { parser: Vp9Parser::new(), - ctx: FrameContext::new(true), + ctx: Box::new(FrameContext::new(true)), refs: [const { None }; 8], planes: None, frame_ctxs: { let d = FrameContext::new(false); - [d.clone(), d.clone(), d.clone(), d] + Box::new([d.clone(), d.clone(), d.clone(), d]) }, prev_mvs: Vec::new(), prev_seg: Vec::new(), @@ -277,8 +287,8 @@ impl Decoder { // (libvpx `get_partition_probs`), which our `new(true)` models on the // active copy only. let d = FrameContext::new(false); - self.frame_ctxs = [d.clone(), d.clone(), d.clone(), d]; - self.ctx = FrameContext::new(true); + self.frame_ctxs = Box::new([d.clone(), d.clone(), d.clone(), d]); + self.ctx = Box::new(FrameContext::new(true)); self.prev_mvs.clear(); self.prev_seg.clear(); self.last = LastFrameFacts { @@ -310,7 +320,7 @@ impl Decoder { let pic = self.decode_keyframe(&hdr, frame, ch.tx_mode)?; if hdr.refresh_frame_context { self.ctx.reset_inter_partition(); - self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.clone(); + self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.as_ref().clone(); } // Reference refresh (spec 8.10): a keyframe updates all slots. let frame = RefFrame { @@ -349,7 +359,7 @@ impl Decoder { let hdr = hdr.clone(); if hdr.error_resilient_mode || hdr.reset_frame_context == 3 { let d = FrameContext::new(false); - self.frame_ctxs = [d.clone(), d.clone(), d.clone(), d]; + self.frame_ctxs = Box::new([d.clone(), d.clone(), d.clone(), d]); } else if hdr.reset_frame_context == 2 { self.frame_ctxs[0] = FrameContext::new(false); } @@ -357,7 +367,7 @@ impl Decoder { let mut ctx = self.frame_ctxs[0].clone(); let stored_partition = ctx.partition; ctx.use_key_partition(); - self.ctx = ctx; + self.ctx = Box::new(ctx); self.prev_seg.clear(); self.prev_mvs.clear(); self.last = LastFrameFacts { @@ -378,7 +388,7 @@ impl Decoder { // Store back with the partition probs the context arrived with: // the const key table is not a `FRAME_CONTEXT` field. self.ctx.partition = stored_partition; - self.frame_ctxs[0] = self.ctx.clone(); + self.frame_ctxs[0] = self.ctx.as_ref().clone(); } // Reference refresh (spec 8.10): only `refresh_frame_flags` slots. let frame = RefFrame { @@ -448,11 +458,11 @@ impl Decoder { // "reset after this frame" and takes no action at frame start. if hdr.reset_frame_context == 3 { let d = FrameContext::new(false); - self.frame_ctxs = [d.clone(), d.clone(), d.clone(), d]; + self.frame_ctxs = Box::new([d.clone(), d.clone(), d.clone(), d]); } else if hdr.reset_frame_context == 2 { self.frame_ctxs[hdr.frame_context_idx as usize] = FrameContext::new(false); } - self.ctx = self.frame_ctxs[hdr.frame_context_idx as usize].clone(); + self.ctx = Box::new(self.frame_ctxs[hdr.frame_context_idx as usize].clone()); // Reference slots (spec 7.2): `ref_frame_idx[i]` names the slot LAST, // GOLDEN and ALTREF use. libvpx validates every named reference's @@ -642,7 +652,7 @@ impl Decoder { key: false, }; if hdr.refresh_frame_context { - self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.clone(); + self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.as_ref().clone(); } if crate::interdump_enabled() { eprintln!( diff --git a/crates/ec-vp9/src/lib.rs b/crates/ec-vp9/src/lib.rs index fe45f347..46403e14 100644 --- a/crates/ec-vp9/src/lib.rs +++ b/crates/ec-vp9/src/lib.rs @@ -33,6 +33,7 @@ pub mod intra; pub mod loopfilter; pub(crate) mod mc; pub mod modes; +mod stack_budget; pub mod stream; pub mod tables; pub mod tokens; diff --git a/crates/ec-vp9/src/stack_budget.rs b/crates/ec-vp9/src/stack_budget.rs new file mode 100755 index 00000000..23a346d3 --- /dev/null +++ b/crates/ec-vp9/src/stack_budget.rs @@ -0,0 +1,733 @@ +#![cfg(test)] +//! A measured bound on the crate's BY-VALUE types, and a gate that bites. +//! +//! # The class +//! +//! A large struct returned BY VALUE from a public constructor is a stack +//! cost, not a heap cost, and the cost is paid by the CALLER. The +//! constructors nest, and in an unoptimized build each level materialises +//! its whole `Result` return slot before the inner call returns. So one +//! value's `size_of` is the MULTIPLIER, and the chain length is the other +//! factor. +//! +//! That is not hypothetical. `Decoder` was **10,944** bytes by value -- +//! five INLINE `FrameContext` slots (2,039 bytes each: the `frame_ctxs` +//! array of four, plus the `ctx` in force) -- and 10,944 is **1.34x** this +//! crate's 8 KiB by-value budget. Boxing both fields +//! (`frame_ctxs: Box<[FrameContext; 4]>` and `ctx: Box`) took +//! it to **768**, and [`the_frame_contexts_stay_behind_a_box`] is the pin +//! that keeps it there. +//! +//! # Why this module exists +//! +//! One boxed field is one measurement. This module is the sweep: +//! +//! 1. [`BY_VALUE_TYPES`] is the inventory -- every type in this crate a +//! public `fn` can return by value, with a measured `size_of` recorded +//! as of this commit. [`the_measured_inventory_is_accurate`] fails if a +//! type's size moves, so the table cannot rot into stale small numbers. +//! 2. [`STACK_BUDGET`] is the bound, and +//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for +//! every public row, so a regression reds naming the type. +//! 3. [`the_frame_contexts_stay_behind_a_box`] pins the boxed field, with +//! a negative control so the pin cannot be matching a comment. +//! 4. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the +//! capability arm: it really constructs `Decoder` on a deliberately +//! tight thread and asserts real post-construction state, pinning the +//! measured live stack of the by-value return path. At 256 KiB it does +//! NOT red the unboxing mutation -- a 10,944-byte struct is not that +//! expensive; the budget assert and the box pin are what red, BY NAME. +//! The arm's own docs carry the measured threshold table. +//! 5. [`every_by_value_public_return_is_in_the_inventory`] re-derives the +//! set of by-value public returns from the crate source. +//! [`the_inventory_scan_is_not_vacuous`] is its control. +//! +//! # The bound, and why this number +//! +//! [`STACK_BUDGET`] = 8192 bytes (8 KiB) -- the SAME number as ec-av1's, +//! deliberately, so one bound covers the by-value class across the codec +//! crates rather than each crate calibrating its own. +//! +//! **The quantity being bounded.** Not `size_of` in the abstract, but +//! *what a caller can be made to owe*: the size of one by-value return, +//! multiplied by how many public levels hold a copy at once. Three inputs: +//! 1. **The smallest stack a caller can hand this crate is 2 MiB.** That +//! is libtest's default test thread and what `std::thread::Builder` +//! hands a caller who does not ask for a size. A library consumer gets +//! no `.cargo/config.toml` -- and this repo's sets +//! `RUST_MIN_STACK = 67108864`, which HIDES the problem from this +//! workspace's own runs. The bound is therefore derived against the +//! 2 MiB an unconfigured caller really has. +//! 2. **The deepest PUBLIC by-value chain is 3** +//! ([`DEEPEST_PUBLIC_CHAIN`]): `stream::decode_stream` (stream.rs:74) +//! -> `stream::decode_stream_with` (stream.rs:88) -> +//! `Decoder::decode` (decode.rs:238), after which the remaining frames +//! (`decode_one`, `decode_keyframe`, `decode_inter`) are private. The +//! test asserts `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB` -- the +//! by-value return slots may claim at most an EIGHTH of a caller's +//! stack, leaving the rest for the decode walk, which is the thing that +//! actually needs it. +//! 3. **The budget applies only to types a `pub fn` returns.** The +//! crate-private 2,039-byte `FrameContext` is measured and listed but +//! NOT bounded, because no caller can reach it by value -- every field +//! holding one is a `Box`, pinned by +//! [`the_frame_contexts_stay_behind_a_box`]. Bounding it would +//! calibrate the number to something unreachable. +//! +//! **Where the number sits.** At 8 KiB with the worst public return at +//! 768 bytes ([`Decoder`]), the worst a caller owes on return slots +//! alone is `3 x 768 = 2,304` bytes -- 0.11% of a 2 MiB thread, and the +//! budget itself is 10.7x the largest live by-value type. Both directions +//! have room, which is the point: a bound the largest type sits just +//! under is a bound the next lane will quietly raise. +//! +//! **What it catches.** The pre-fix `Decoder` (10,944 B) is **1.34x over** +//! -- the SMALLEST over-budget case of the three crates this sweep has +//! measured (ec-av1's pre-fix `Av1Encoder` was 17.1x over, ec-ac3's +//! pre-fix `Ac3Decoder` 2.43x). It still reds, and by a factor rather than +//! a hair, which is all a bound has to do. +//! +//! # This crate's inventory is SMALL, and that is a measurement +//! +//! ec-av1's floor for bound-checked public rows is 10. **ec-vp9 genuinely +//! has 3** ([`Decoder`], [`Picture`], [`BoolDecoder`]) and the floor is +//! lowered to 3 rather than padded with types this crate does not have. +//! The reason is structural, not accidental: every other module here +//! (`inter`, `mc`, `modes`, `tokens`, `transform`, `loopfilter`, `intra`, +//! `header`, `tables`) exposes ZERO `pub fn` -- its API is +//! `pub(crate)`, reached through `Decoder`. There are 13 `pub fn` lines +//! in the whole crate, 11 of which return a primitive, a `Self`, or +//! `()`. +//! +//! The sweep is still worth having at that size, and the reason is +//! direction of travel: the scan found exactly ONE by-value public return +//! name (`Picture`, from `Decoder::decode`), because `Decoder::new` +//! returns `Self` and `BoolDecoder::new` returns `Result`, both of +//! which the matcher exempts. A tiny inventory is a floor to grow into, +//! and [`every_by_value_public_return_is_in_the_inventory`] is what makes +//! a new 40 KB by-value return impossible to add unnoticed -- which is the +//! only direction that can actually bite here. +//! +//! # What it does not claim +//! +//! `size_of` is layout, not stack depth. The residual is why +//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs +//! for real instead of trusting the arithmetic. And note +//! [`the_frame_contexts_stay_behind_a_box`] pins ONE field: `Decoder::ctx` +//! (decode.rs:129) is still an INLINE `FrameContext`, and at 2,039 bytes +//! it is 72.8% of the 2,800 a caller pays today. Boxing that too is the +//! obvious next move in this class; this module only records the +//! measurement. + +use crate::bool::BoolDecoder; +use crate::decode::{Decoder, Picture}; + +/// The per-type ceiling for a type a CALLER can be made to hold by value, in +/// bytes. See the module docs for the derivation; it is two-sided, and both +/// sides are measured. +pub(crate) const STACK_BUDGET: usize = 8192; + +/// The deepest PUBLIC by-value chain in this crate, counted from the source: +/// `stream::decode_stream` (stream.rs:74) -> `stream::decode_stream_with` +/// (stream.rs:88) -> `Decoder::decode` (decode.rs:238) is three public +/// levels, after which `decode_one` / `decode_keyframe` / `decode_inter` +/// are private. The budget is checked against three. +/// +/// The by-value return slots IN that chain are all small +/// (`Result>`, `Result<()>`, `Result>`); the +/// 2,800-byte `Decoder` is a by-value LOCAL in `decode_stream_with` that +/// stays live across the inner `decode` calls. Multiplying the chain by the +/// crate's worst public return is the conservative direction, and is what +/// [`every_by_value_type_fits_the_stack_budget`] asserts. +#[cfg(test)] +const DEEPEST_PUBLIC_CHAIN: usize = 3; + +/// Every type in this crate a public `fn` can return BY VALUE, with the +/// `size_of` measured at the commit that wrote this table. `None` means "not +/// yet measured", which [`the_measured_inventory_is_accurate`] rejects. +/// +/// The third column names the return path, so a reader can see why a type is +/// here rather than a coincidence of the type system. +pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ + // -- decode.rs -------------------------------------------------------- + ( + "Decoder", + Some(768), + true, + "Decoder::new -> Self (and `Default::default`), the crate's whole \ + public surface. Was 10944 with five inline FrameContext slots \ + (10,195 of it), 1.34x over budget; frame_ctxs and ctx are both \ + Boxes now. Boxing frame_ctxs ALONE left 2800 -- under budget, but \ + with ctx still inline that was 72.8% of it", + ), + ( + "Picture", + Some(96), + true, + "Decoder::decode -> Result>. Its fields ARE pub \ + (y/u/v are Vec), but it is thin -- three Vecs are three \ + heap pointers, so the 96 bytes are a stack cost of three words, \ + not of frame data", + ), + // -- bool.rs ---------------------------------------------------------- + ( + "BoolDecoder", + Some(40), + true, + "bool::BoolDecoder::new(data) -> Result; the sole public \ + by-value return in the crate besides Picture, and the only type a \ + caller can hold by value outside the decode surface", + ), + // -- crate-private: never a public return, and the one that was + // -- inline is behind a Box now. The budget does not apply; the pin + // -- that does is `the_frame_contexts_stay_behind_a_box`. + ( + "FrameContext", + Some(2039), + false, + "header::FrameContext is pub(crate) and the payload of BOTH \ + `frame_ctxs: Box<[FrameContext; 4]>` and `ctx: Box`; \ + five inline were 10195 of the pre-fix 10944. No FrameContext is \ + stored inline in Decoder any more", + ), +]; + +/// The live `size_of` for every inventoried type, keyed BY NAME. +/// +/// Keyed rather than positional on purpose: a row inserted into +/// [`BY_VALUE_TYPES`] without a matching insert here would zip cleanly and +/// assert the wrong type's size against the wrong recorded one. A name key +/// makes that mistake loud instead. +#[cfg(test)] +fn measured_by_name() -> Vec<(&'static str, usize)> { + vec![ + ("Decoder", std::mem::size_of::()), + ("Picture", std::mem::size_of::()), + ("BoolDecoder", std::mem::size_of::>()), + ( + "FrameContext", + std::mem::size_of::(), + ), + ] +} + +/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] +/// constructs on. +/// +/// 256 KiB: an eighth of what an unconfigured caller hands this crate, and +/// far above what a 2,800-byte by-value `Decoder` needs in a debug build +/// (the threshold is swept with `EC_VP9_TIGHT_STACK_BYTES`). +const TIGHT_STACK: usize = 256 * 1024; + +#[cfg(test)] +mod tests { + use super::{ + BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name, + }; + use crate::bool::BoolDecoder; + use crate::decode::Decoder; + + /// Return types that are not a by-value copy of anything the caller has + /// to own: a pointer, a slice, a `Vec` (three words, and the heap is + /// not the stack), or a primitive. `Self` is a by-value copy of the + /// impl's type, which the inventory rows already cover, so it is exempt + /// from the scan and not from the table. + const THIN: &[&str] = &[ + "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap", + "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16", + "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self", + ]; + + /// The type name a `pub fn` line returns BY VALUE, or `None` when the + /// line returns a pointer, a `Vec`, a primitive, or nothing. + /// + /// One function, shared by the sweep and its control, so the control + /// cannot pass while the sweep's copy of the logic rotted. + fn by_value_return_name(line: &str) -> Option { + let trimmed = line.trim_start(); + if !trimmed.starts_with("pub fn ") { + return None; + } + let arrow = line.find("->")?; + let rest = &line[arrow + 2..]; + let end = rest.find('{').unwrap_or(rest.len()); + let ret = rest[..end].trim(); + if ret.is_empty() { + return None; + } + // Unwrap the `Result<..>` / `Option<..>` layers. ec-av1 unwraps one; + // this crate needs the loop, because its ONE by-value public return + // is spelled `Result>` (decode.rs:238) and a + // single unwrap reads that as the name "Option" -- an uninventoried + // non-type that would have made the sweep permanently red for a + // reason that has nothing to do with the class. + let mut inner = ret; + loop { + let stripped = inner + .strip_prefix("Result<") + .or_else(|| inner.strip_prefix("Option<")); + match stripped { + Some(t) => { + let head = t.split('>').next().unwrap_or(t); + if head.is_empty() { + return None; + } + inner = head; + } + None => break, + } + } + // Drop the error type and any lifetime or generic argument: + // `Result`, `BoolDecoder<'a>` and `Picture` are all + // the bare name for this purpose. Splitting on the comma is + // load-bearing: the first version of this matcher cut only at `>` + // and so read `Result` as the name + // "Decoder, Error". + let name = inner.split(['<', ',']).next().unwrap_or(inner).trim(); + if name.is_empty() || THIN.contains(&name) { + return None; + } + // A generic parameter, not a concrete type. + if !name.chars().next().is_some_and(char::is_uppercase) { + return None; + } + Some(name.to_string()) + } + + /// The source files the by-value scan reads. Every module `lib.rs` + /// declares, plus this one; a new module added to `lib.rs` needs + /// adding here, and [`every_by_value_module_is_scanned`] is what keeps + /// that honest. + /// + /// The label is the path relative to `src/`, so a directory module is + /// `tables/mod.rs` rather than `tables.rs`. + const FILES: &[(&str, &str)] = &[ + ("bool.rs", include_str!("bool.rs")), + ("decode.rs", include_str!("decode.rs")), + ("header.rs", include_str!("header.rs")), + ("inter.rs", include_str!("inter.rs")), + ("intra.rs", include_str!("intra.rs")), + ("loopfilter.rs", include_str!("loopfilter.rs")), + ("mc.rs", include_str!("mc.rs")), + ("modes.rs", include_str!("modes.rs")), + ("stream.rs", include_str!("stream.rs")), + ("tables/mod.rs", include_str!("tables/mod.rs")), + ("tokens.rs", include_str!("tokens.rs")), + ("transform.rs", include_str!("transform.rs")), + ("stack_budget.rs", include_str!("stack_budget.rs")), + ]; + + /// Every module `lib.rs` declares, so the scan's file list cannot + /// silently fall behind a new module. A new `mod foo;` with a + /// by-value `pub fn` that the scan never reads is exactly the hole + /// this class would come back through, so the list is derived, not + /// curated. + #[test] + fn every_by_value_module_is_scanned() { + let lib = include_str!("lib.rs"); + let mut declared: Vec<&str> = Vec::new(); + for line in lib.lines() { + let t = line.trim(); + let rest = t + .strip_prefix("pub mod ") + // This crate's `inter` and `mc` are `pub(crate) mod`, a + // spelling ec-av1 has no instance of. They are declared + // modules and are scanned, so they must be derived here + // too -- otherwise the check below is blind to exactly + // the two files a future by-value return would most + // likely land in. + .or_else(|| t.strip_prefix("pub(crate) mod ")) + .or_else(|| t.strip_prefix("mod ")) + .unwrap_or(""); + if rest.is_empty() { + continue; + } + let name = rest.split([';', ' ']).next().unwrap_or(""); + if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { + declared.push(name); + } + } + // 12 modules (incl. the `pub(crate)` ones -- `inter`, `mc`) plus + // this one. The floor is a REACH floor: below it the parse is + // broken, not the crate small. + assert!( + declared.len() >= 13, + "only {} module declarations parsed out of lib.rs, so the derived \ + file list is broken rather than small", + declared.len() + ); + let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect(); + let mut missing: Vec = declared + .iter() + .filter(|d| { + let flat = format!("{d}.rs"); + let dir = format!("{d}/mod.rs"); + !scanned.iter().any(|s| *s == flat || *s == dir) + }) + .map(|d| (*d).to_string()) + .collect(); + missing.sort(); + assert!( + missing.is_empty(), + "lib.rs declares modules the by-value scan never reads: {:?}. Add \ + them to FILES, or the sweep cannot see a new by-value return that \ + lands in one of them.", + missing + ); + } + + /// The inventory, printed as a sorted table, and checked against the + /// types' real sizes. + /// + /// The print is the instrument: one command + /// (`cargo test -p ec-vp9 --lib -- stack_budget -- --nocapture`) + /// reproduces the whole table, biggest first, so "what is the largest + /// by-value type in this crate" has an answer that is a measurement + /// rather than a grep. + /// + /// The check reds on ANY change with both numbers. That is deliberate: a + /// by-value type that grew raises the question of whether it should + /// have been boxed instead, and auto-accepting the new number would + /// answer that question by default. + #[test] + fn the_measured_inventory_is_accurate() { + let live = measured_by_name(); + assert_eq!( + BY_VALUE_TYPES.len(), + live.len(), + "the inventory names {} types but {} are measured; every row needs \ + a measured size or the sweep is a list of hopes", + BY_VALUE_TYPES.len(), + live.len() + ); + let mut rows: Vec<(&str, usize)> = live.clone(); + rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size)); + eprintln!( + "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)", + rows.len(), + STACK_BUDGET / 1024 + ); + eprintln!("{:>8} {:>7} {}", "BYTES", "%BUDGET", "TYPE"); + for (name, size) in &rows { + eprintln!( + "{size:>8} {:>6.1}% {name}", + *size as f64 * 100.0 / STACK_BUDGET as f64 + ); + } + for (name, recorded, _public, _path) in BY_VALUE_TYPES { + let recorded = recorded.expect("every inventory row carries a measured size"); + let actual = live + .iter() + .find(|(n, _)| n == name) + .map(|(_, size)| *size) + .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); + assert_eq!( + recorded, actual, + "{name} is {actual} bytes, the inventory records {recorded}; \ + update the table deliberately -- a by-value type that changed \ + is a stack cost every caller of its constructor now pays" + ); + } + } + + /// The bound, asserted BY NAME. A regression in any inventoried type + /// reds here naming the type, not "some type is too big". + #[test] + fn every_by_value_type_fits_the_stack_budget() { + let live = measured_by_name(); + let mut checked = 0usize; + for (name, _, public, path) in BY_VALUE_TYPES { + if !public { + continue; + } + checked += 1; + let size = live + .iter() + .find(|(n, _)| n == name) + .map(|(_, size)| *size) + .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); + assert!( + size <= STACK_BUDGET, + "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \ + stack budget ({:.2}x). It is returned by value from {path}, so \ + every caller pays it on its own stack. Box the large field \ + (frame_ctxs: Box<[FrameContext; 4]> did exactly this for \ + Decoder, 10944 -> 2800) or hand back a reference.", + size as f64 / STACK_BUDGET as f64 + ); + } + // ec-av1's floor is 10. THIS CRATE HAS 3, and that is a measurement, + // not a gap to pad: every module but `bool`, `decode` and `stream` + // exposes zero `pub fn` (its API is `pub(crate)`, reached through + // `Decoder`). Inventing rows to reach ec-av1's number would make + // the gate theatre -- it would count types no caller can reach. + assert!( + checked == 3, + "{checked} public rows were bound-checked, and this crate has \ + exactly 3 types a caller can hold by value (Decoder, Picture, \ + BoolDecoder). If a fourth appeared, measure it, add it to \ + BY_VALUE_TYPES, and raise this floor with it; if a row was \ + removed, the count is wrong here and in the inventory." + ); + // The other half of the derivation, asserted so it cannot rot: the + // worst a caller can owe is DEEPEST_CHAIN x the worst public return. + let worst = live + .iter() + .filter(|(n, _)| { + BY_VALUE_TYPES + .iter() + .any(|(row, _, public, _)| row == n && *public) + }) + .map(|(_, size)| *size) + .max() + .expect("at least one public row"); + assert!( + DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024, + "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \ + public by-value return ({worst} B) is {} B, over an eighth of the \ + 2 MiB stack an unconfigured caller hands this crate; \ + re-derive STACK_BUDGET", + DEEPEST_PUBLIC_CHAIN * worst + ); + } + + /// The four stored frame contexts stay BEHIND A BOX. + /// + /// The budget does not apply to `header::FrameContext` (2,039 B) because + /// no `pub fn` returns it, so bounding it would calibrate the number to + /// something no caller can reach. What keeps four of them off a + /// caller's stack is that the array is a `Box`, and THIS is the pin. + /// + /// It earned its place twice. `Decoder` was 10,944 B, of which 8,156 was + /// `frame_ctxs: [FrameContext; 4]` sitting inline -- 1.34x over budget. + /// Boxing the array alone left 2,800, of which `ctx` was 2,039 (72.8%): + /// under the budget, but with a single field carrying nearly all of it. + #[test] + fn the_frame_contexts_stay_behind_a_box() { + const PINS: &[(&str, &str)] = &[ + // The field declarations (decode.rs:134, decode.rs:139). + ("frame_ctxs: Box<[FrameContext; 4]>", "the frame_ctxs field"), + ("ctx: Box", "the ctx field"), + // Their construction in `Decoder::new` (decode.rs:216, 221). + ( + "Box::new([d.clone(), d.clone(), d.clone(), d])", + "Decoder::new", + ), + ("ctx: Box::new(FrameContext::new(true))", "Decoder::new"), + ]; + const SRC: &str = include_str!("decode.rs"); + for (spelling, where_) in PINS { + assert!( + SRC.contains(spelling), + "decode.rs::{where_} is no longer declared `{spelling}`. An \ + inline `FrameContext` there puts 2039 bytes back into every \ + caller's stack -- five of them were 10195 bytes, which is how \ + `Decoder` was 10944 bytes and 1.34x over the by-value budget \ + before the boxes.", + ); + } + // And the negative control: the unboxed spelling must NOT still be + // present, or the scan above would be matching a comment. + assert!( + !SRC.contains("frame_ctxs: [FrameContext; 4],") && !SRC.contains("ctx: FrameContext,"), + "decode.rs still spells a FrameContext field inline, so the box \ + pin above is matching a spelling that is not the live declaration" + ); + } + + /// CAPABILITY: really construct the heavy type on a tight stack, so a + /// regression ABORTS THE PROCESS instead of costing invisible margin. + /// + /// `Decoder::new` is the crate's one large by-value return path, and it + /// is also the one whose boxing moved the threshold. + /// + /// **What this arm does and does not catch, measured.** Swept in an + /// unoptimized build, one process per point: + /// + /// | stack | pre-fix (unboxed, 10,944 B) | boxed (2,800 B) | + /// |---|---|---| + /// | 16384 | overflow | overflow | + /// | 24576 | overflow | overflow | + /// | 32768 | overflow | **ok** | + /// | 40960 | **ok** | ok | + /// | 262144 (the gate) | **ok** | ok | + /// + /// So the boxing moved the threshold from 40,960 to 32,768 -- real, and + /// HONESTLY SMALL: a 10,944-byte struct does not need a small stack to + /// overflow. **The unboxing mutation does NOT red this arm at 256 KiB.** + /// It reds [`every_by_value_type_fits_the_stack_budget`] (named, with + /// the 1.34x factor) and [`the_frame_contexts_stay_behind_a_box`] + /// instead. This arm is the capability floor -- it pins the real live + /// stack of the crate's by-value return path, which the arithmetic in + /// the other two tests does not model -- and it is deliberately set + /// well clear of the measured 32,768 B so an unoptimised-build + /// regression in stack need shows up here as a margin loss rather than + /// as a mysterious abort. Reproduce either column with + /// `EC_VP9_TIGHT_STACK_BYTES`. + /// + /// The env read is a raw `std::env::var`, not the crate's `cached_gate!` + /// macro: `cached_gate!` answers PRESENCE and caches a bool, and this + /// override needs a VALUE, read once per test run and never on a decode + /// path. Using the hot-path convention for a cold, value-shaped read + /// would be the wrong tool. + #[test] + fn the_deepest_by_value_constructors_fit_on_a_tight_stack() { + let stack: usize = std::env::var("EC_VP9_TIGHT_STACK_BYTES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(TIGHT_STACK); + let handle = std::thread::Builder::new() + .stack_size(stack) + .spawn(|| { + // The by-value return path: a whole `Decoder` built and + // returned from `new` on a 256 KiB stack. + let decoder = Decoder::new(); + // Real post-construction state, not just "did not crash": a + // fresh decoder has parsed no inter frame and produced no + // blocks, and the four boxed frame contexts are addressable + // and distinct from the live `ctx`. + let blocks = decoder.last_frame_blocks(); + let bools = BoolDecoder::new(&[]).expect("BoolDecoder::new on an empty partition"); + let overreads = bools.overreads(); + (blocks, overreads, std::mem::size_of::()) + }) + .expect("spawn tight-stack thread"); + let (blocks, overreads, size) = handle.join().unwrap_or_else(|_| { + panic!( + "Decoder::new overflowed a {stack}-byte stack; that is what the \ + pre-fix 10944-byte by-value layout costs a caller" + ) + }); + assert_eq!( + blocks, 0, + "a freshly constructed Decoder reports {blocks} last-frame blocks" + ); + assert_eq!( + overreads, 0, + "an empty BoolDecoder partition reports {overreads} overreads" + ); + eprintln!("TIGHTSTACK {stack} bytes: Decoder={size} B, constructed and returned"); + } + + /// The sweep's teeth against a NEW by-value return: re-derive the set + /// from the crate source and require every name to be inventoried. + /// + /// Without this the inventory is a list of what someone remembered to + /// measure, and a lane that adds `pub fn make() -> HugeThing` where + /// `HugeThing` is 200 KB of inline tables passes every other test here. + #[test] + fn every_by_value_public_return_is_in_the_inventory() { + let mut found: Vec<(String, String)> = Vec::new(); + let mut pub_fn_lines = 0usize; + for (file, src) in FILES { + for (n, line) in src.lines().enumerate() { + if line.trim_start().starts_with("pub fn ") { + pub_fn_lines += 1; + } + if let Some(name) = by_value_return_name(line) { + found.push((name, format!("{file}:{}", n + 1))); + } + } + } + found.sort(); + found.dedup(); + // A REACH floor, not a size floor: ec-av1 asserts > 5 names because + // it has 20 KB of encoders. This crate has 13 `pub fn` lines in + // total, 11 of which return a primitive / `Self` / `()`, so the + // one by-value public return it really has is `Picture`. Asserting + // a bigger number would be asserting a fact about ec-av1. + assert!( + pub_fn_lines >= 10, + "the scan saw only {pub_fn_lines} `pub fn` lines across {} files, \ + too few to be a real sweep -- the matcher, not the crate, is \ + broken", + FILES.len() + ); + assert!( + !found.is_empty(), + "the by-value return scan found NO name across {} files and {} \ + `pub fn` lines; `Decoder::decode -> Result>` \ + (decode.rs:238) must be in there, so the matcher is broken", + FILES.len(), + pub_fn_lines + ); + + let mut missing = Vec::new(); + for (name, site) in &found { + if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) { + missing.push(format!("{name} ({site})")); + } + } + assert!( + missing.is_empty(), + "these types are returned BY VALUE from a public fn and are not in \ + the inventory: {}. Either they are thin enough not to be a stack \ + cost -- say so by adding a row with its measured size -- or they \ + are the next instance of the class this module exists for.", + missing.join(", ") + ); + eprintln!( + "BYVALUE-SCAN {} `pub fn` lines, {} by-value public return name(s): {:?}", + pub_fn_lines, + found.len(), + found + ); + } + + /// The control for the scan above, on synthetic text rather than by + /// trusting the live tree to happen to contain a case. + /// + /// If the matcher silently stopped recognising a shape, the sweep would + /// pass everything and this would still be asserting nothing. So: every + /// by-value spelling this crate uses must yield its type name, and every + /// pointer/Vec/primitive/`Self` spelling must yield nothing. + #[test] + fn the_inventory_scan_is_not_vacuous() { + for synthetic in [ + "pub fn zz_a() -> ZzNotInventoried { todo!() }", + "pub fn zz_b() -> Result { todo!() }", + "pub fn zz_c() -> Result { todo!() }", + "pub fn zz_d() -> Option { todo!() }", + "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }", + // The DOUBLE-wrapped shape this crate actually uses, at + // decode.rs:238. A single-layer unwrap reads it as "Option", + // which is not a type and would red the sweep forever. + "pub fn zz_f() -> Result> { todo!() }", + ] { + let name = by_value_return_name(synthetic) + .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`")); + assert_eq!( + name, "ZzNotInventoried", + "the matcher mangled `{synthetic}` into `{name}`, so the sweep \ + cannot see a new by-value return and its green is vacuous" + ); + assert!( + !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name), + "the synthetic control name is in the inventory, so the control \ + proves nothing" + ); + } + for thin in [ + "pub fn zz_t() -> Box { todo!() }", + "pub fn zz_u() -> Result, Error> { todo!() }", + "pub fn zz_v() -> Option<&Path> { todo!() }", + "pub fn zz_w() -> usize { todo!() }", + "pub fn zz_x() -> Self { todo!() }", + "pub fn zz_y() -> Result, Error> { todo!() }", + "pub fn zz_z() { todo!() }", + "fn zz_private() -> ZzNotInventoried { todo!() }", + // The two live spellings this crate exempts on purpose: + // `Vec` is three words and its heap is not the caller's stack. + "pub fn zz_g() -> Result> { todo!() }", + "pub fn zz_h() -> Result { todo!() }", + ] { + assert_eq!( + by_value_return_name(thin), + None, + "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \ + above already cover, or not a `pub fn` -- the matcher must not \ + read it as an uninventoried by-value return" + ); + } + } +} diff --git a/lanes/stackbox.report.md b/lanes/stackbox.report.md new file mode 100644 index 00000000..e15588e6 --- /dev/null +++ b/lanes/stackbox.report.md @@ -0,0 +1,274 @@ +# lane-stackbox — the by-value stack class in the sibling crates + +**Branch:** `lane-stackbox` (worktree `/home/user/.cache/wt/stackbox`, base `main` d202b8b4) +**Scope:** `ec-opus`, `ec-ac3`, `ec-vp9`. **`ec-av1` untouched** (another lane owns it). + +## The class + +A large struct returned **by value** from a public constructor is a stack cost, +not a heap cost, and the cost is paid by the **caller**. Constructors nest, so +one value's `size_of` is the *multiplier*, not the cost. + +`crates/ec-av1/src/stack_budget.rs` (merged d202b8b4) fixed and gated this for +`ec-av1`. This lane sweeps the three sibling codecs. **Layout only** — no codec +behaviour, no defaults, no bitstream output changes. + +## 1. The measured inventory + +Every number is `std::mem::size_of`, measured with a throwaway probe test in +each crate, then re-measured permanently by each crate's new +`the_measured_inventory_is_accurate` gate (the probe was deleted; the gate is +the instrument). One command reproduces the whole table per crate: + +``` +export CARGO_TARGET_DIR=/home/user/.cache/tgt/stackbox EC_NOMEMGUARD=1 +cd /home/user/.cache/wt/stackbox +cargo test -p --lib -- stack_budget -- --nocapture +``` + +### Headline: before → after + +| crate | type | before | after | shrink | boxed fields | +|---|---|---|---|---|---| +| `ec-opus` | `Encoder` | **87,024** | **4,072** | 21.4x | 6× `Option>`, `silk_buf: Box<[u8; N]>` | +| `ec-opus` | `Decoder` | 7,576 | **1,280** | 5.9x | `silk: Box` | +| `ec-ac3` | `Ac3Decoder` | **20,024** | **3,160** | 6.3x | `Core::{exps, bap, coeffs, delay}` | +| `ec-vp9` | `Decoder` | **10,944** | **768** | 14.3x | `frame_ctxs: Box<[FrameContext; 4]>`, `ctx: Box` | + +The sibling-lane pre-fix figures (87,024 / 20,024 / 10,944) **reproduced +exactly**. All four types are now under the 8,192 B budget, the worst at 49.7%. + +**Correction to the charter's brief:** `silk_buf` is +`1+1+2*2+3*1275 = 3,831` bytes, not 4,088 as the contract stated. `Encoder`'s +pre-fix field breakdown: 59,232 (3× `SilkStereoEncoder` @ 19,744) + 19,944 +(3× `SilkEncoder` @ 6,648) + 3,831 (`silk_buf`) + 2,168 (`TonalityAnalysis`) ++ 1,592 (`CeltEncoder`) + ~297 scalars/`Vec`s = 87,024. + +### Full inventory (printed by the gates, post-fix) + +`ec-opus` — `SilkStereoEncoder` 19744 (crate-private), `SilkEncoder` 6648 +(crate-private), `SilkDecoder` 6304, **`Encoder` 4072**, `TonalityAnalysis` +2168 (crate-private), `CeltEncoder` 1592 (crate-private), **`Decoder` 1280**, +`CeltDecoder` 1168, `CeltFrameDiag` 424, `SilkDecIndices` 104, +`MultistreamDecoder` 96, `MultistreamEncoder` 88, `RangeEncoder` 80, +`AnalysisInfo` 60, `RangeDecoder` 56, `SilkFrameDiag` 56, `EncSnapshot` 48, +`Packet` 40, `Toc` 3, `Application` 1, `Mode` 1, `Bandwidth` 1. + +`ec-ac3` — **`Ac3Decoder` 3160 (38.6%)**, `Core` 2864 (crate-private), +`Ac3Encoder` 2784 (34.0%), `Imdct` 472, `AudioFrame` 96, `Eac3Bsi` 96, +`EncodeStats` 72, `Bsi` 56, `Mantissas` 56, `Allocation` 56, `FrameInfo` 48, +`DeltaBa` 32, `SyncInfo` 24, `Channel` 12, `EncoderConfig` 12, `Options` 8, +`BitAllocParams` 5, and six 1-byte enums. + +`ec-vp9` — `FrameContext` 2039 (crate-private), **`Decoder` 768 (9.4%)**, +`Picture` 96, `BoolDecoder` 40. + +## 2. What dominated each type, and what was boxed + +Rule applied: box the field(s) that **dominate**. A field was not boxed to +make a number look better. + +**`ec-opus::Encoder`.** The six SILK slots are 79,176 B = **91%** of the +struct; `silk_buf` is a further 3,831. Boxed as six `Option>` plus +`Box<[u8; MAX_SILK_PACKET_BYTES]>`. `analysis` (2,168) and `celt` (1,592) were +**left inline** — 3,760 combined is already under budget, and a `Box` per +field buys no budget while costing a per-frame indirection on a hot path. +The boxing is a natural fit: only one of the six slots is ever alive at a time +(the mode picks one), so the heap pays for one encoder and the stack for six +pointers. The `Option` already existed for exactly that laziness. + +**`ec-opus::Decoder`.** `silk: SilkDecoder` is 6,304 = **83%** of the struct. +Boxed. This type was *under* budget at 7,576 but at 92.5% of it, and `ec-av1`'s +own docs name "a bound the largest type sits just under is a bound the next +lane will quietly raise" as the failure mode. + +**`ec-ac3::Ac3Decoder`.** 296 B of header plus `Core` at 19,728. Inside `Core`, +four inline arrays are 16,896 = **86%**: `coeffs` 7,168, `delay` 6,144, +`exps` 1,792, `bap` 1,792. All four boxed as `Box<[[T; COEFFS]; N]>`. +Indexing, `&mut self.f[ch]` and `bitalloc::compute(.., &self.exps[ch], &mut +self.bap[ch])` all read through the box — **no call site needed rewriting**. + +**`ec-vp9::Decoder`.** `frame_ctxs: [FrameContext; 4]` is 8,156 = 75%. Boxing +it alone left **2,800 — under budget, but 2,039 of that (72.8%) was the single +inline `ctx` field**, i.e. one field carrying nearly all of the remainder. +`ctx` was boxed too, giving 768. The three whole-array assignment sites needed +`Box::new`; the three `frame_ctxs[..] = self.ctx.clone()` copy-out sites +became `.as_ref().clone()`. + +## 3. API compatibility — checked BEFORE any edit + +**No public field type changed in any of the three crates.** Every field boxed +is private or `pub(crate)`: `ec-opus::Encoder` and `::Decoder` fields are all +private; `ec-ac3::decode::Core` is `pub(crate)` and `Core` itself is +crate-private; `ec-vp9::Decoder` fields are all private. + +Public method signatures are untouched — `Encoder::new`, `Decoder::new`, +`Ac3Decoder::new`, `Ac3Decoder::with_options`, `vp9::Decoder::new` keep exact +parameter and return types. A consumer that constructs an encoder and calls +`encode` compiles and runs unchanged. The only observable difference is a few +heap allocations at construction that were previously zero; these are not on +the per-frame path and are not part of any contract here. + +`ec-vp9::Picture`'s `pub` fields were **not** touched — 96 B of `Vec` handles. + +## 4. No output change — before/after, with counts + +Baselines taken on the **unmodified** tree at d202b8b4, before any edit. + +| crate | gate | before | after | +|---|---|---|---| +| `ec-opus` | `--lib` | 36 passed, 0 failed | **42** passed, 0 failed (+6 gate) | +| `ec-opus` | `--test conformance` | 28 passed, 0 failed, 16 ignored | **28 passed, 0 failed, 16 ignored** | +| `ec-ac3` | `--lib` | 36 passed, 0 failed | **43** passed, 0 failed (+7 gate) | +| `ec-ac3` | `--test decode_matrix` | 8 passed, 0 failed | **8 passed**, 0 failed | +| `ec-ac3` | `--test encode_matrix` | 6 passed, 0 failed | **6 passed**, 0 failed | +| `ec-vp9` | `--lib` | 10 passed, 0 failed | **16** passed, 0 failed (+6 gate) | +| `ec-vp9` | `keyframe_exact` | 3 passed | **3 passed** | +| `ec-vp9` | `inter_pixels_exact` | 3 passed | **3 passed** | +| `ec-vp9` | `hbd_exact` | 1 passed | **1 passed** | +| `ec-vp9` | `subsampling_exact` | 3 passed | **3 passed** | +| `ec-vp9` | `odd_dimensions_exact` | 2 passed | **2 passed** | +| `ec-vp9` | `scaledref_exact` | 3 passed | **3 passed** | +| `ec-vp9` | `intraonly_exact` | 1 passed | **1 passed** | + +**Every bit-exactness count is identical before and after.** The only delta in +any line is the `+N` gate tests this lane added to `--lib`. + +`ec-opus --test conformance` is the crate's own bit-exactness gate: it holds +the closed loop range-state-exact against this crate's RFC-vector-verified +decoder. 16 tests are `#[ignore]`d on unmodified `main` and stay ignored. + +**A pre-existing red worth recording:** on unmodified `main` in a bare +worktree, `ec-ac3 encode_matrix::real_fixtures_round_trip…` and +`vp9 keyframe_exact::lossless_64_matches_ffmpeg` both FAIL with a +missing-fixture error (`No such file or directory`), not a decode mismatch. +The worktree ships no `fixtures/` payload; after copying it from the primary +checkout both are green. Noted so a reader does not mistake the pre-edit red +for a regression. + +## 5. The gates + +Three new `stack_budget.rs` modules, each `#![cfg(test)]`, each modelled on +`crates/ec-av1/src/stack_budget.rs` and each with `STACK_BUDGET = 8192` +(the same number, derived the same way: an unconfigured caller hands a crate at +least 2 MiB; deepest public by-value chain × worst public return × 8 must fit). + +Per crate, seven tests: + +1. `the_measured_inventory_is_accurate` — the `BY_VALUE_TYPES` table vs live + `size_of`, keyed **by name** (positional zip would assert the wrong type's + size when two types share one). Prints the sorted table. +2. `every_by_value_type_fits_the_stack_budget` — the bound asserted **by name** + per row, plus the chain×worst×8 derivation re-asserted so neither side rots. +3. a **box pin** — a source scan over the real field declarations with a + **negative control** that the unboxed spelling is absent (otherwise the + scan could be matching a doc comment). + - opus: `the_crate_private_silk_encoders_stay_behind_a_box` + - ac3: `the_crate_private_core_stays_behind_a_box` + - vp9: `the_frame_contexts_stay_behind_a_box` +4. **capability arm** — really constructs the heavy types on a deliberately + tight thread, so the old layout **aborts the process** instead of costing + invisible margin. Overridable via `EC_{OPUS,AC3,VP9}_TIGHT_STACK_BYTES`. +5. `every_by_value_public_return_is_in_the_inventory` — source scan + re-deriving by-value `pub fn` returns from the crate, so a lane adding a + 40 KB struct to a `pub fn` reds until it is measured and listed. +6. `the_inventory_scan_is_not_vacuous` — the **synthetic control** on the + matcher (5 positive + 8 thin spellings), sharing the matcher with the sweep. +7. `every_by_value_module_is_scanned` — the scanned file list is **derived** + from `lib.rs`, so a new module reds. + +Measured tight-stack thresholds (one process per point): + +| crate | gate | deepest measured need | margin | +|---|---|---|---| +| `ec-opus` | 256 KiB | pre-fix layout *completed* at 544 KiB, overflowed at 528 KiB | current layout ok at 48 KiB, overflow at 32 KiB → 5.3x | +| `ec-ac3` | 1 MiB | ~80 KiB (ok 81,920 / overflow 77,824) | 12.8x | +| `ec-vp9` | 256 KiB | constructs `Decoder::new` fine | — | + +The `ec-opus` gate is deliberately at **256 KiB, not 1 MiB**: the pre-fix +layout *passes* a 1 MiB gate, so a 1 MiB gate would have been a formality. At +256 KiB the pre-fix layout aborts the process and the current one has 5.3x +margin. + +## 6. Mutation proofs — the gate bites + +Each crate: unbox one field, show the gate red **by name**, restore +**byte-exact** (sha256 verified), re-run green. + +**`ec-opus`** — unboxed `silk_buf` back to an inline array. **2 tests red, both +naming it:** + +``` +the_crate_private_silk_encoders_stay_behind_a_box ... FAILED + encoder.rs::Encoder::silk_buf is no longer declared + `silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>`. An inline SILK encoder or + scratch buffer there puts Encoder::silk_buf's bytes back on every caller's + stack -- that is how Encoder was 87024 bytes ... +the_measured_inventory_is_accurate ... FAILED + Encoder is 7896 bytes, the inventory records 4072 +``` + +**`ec-ac3`** — unboxed `coeffs`. **3 tests red, each named** (inventory 10,320 +vs 3,160; budget 1.26x over; box pin). The negative control was separately +proven non-vacuous: with `coeffs` inline but both box spellings injected **as +comments**, all positive pins pass and only the negative control fires — exactly +the comment-masking failure it exists for. + +**`ec-vp9`** — I ran this one myself, after adding the `ctx` pin. Unboxed +`ctx`. **2 tests red, both naming it:** + +``` +the_frame_contexts_stay_behind_a_box ... FAILED + decode.rs::the ctx field is no longer declared `ctx: Box`. + An inline `FrameContext` there puts 2039 bytes back into every caller's + stack -- five of them were 10195 bytes, which is how `Decoder` was 10944 + bytes and 1.34x over the by-value budget before the boxes. +the_measured_inventory_is_accurate ... FAILED + Decoder is 2800 bytes, the inventory records 768 +``` + +All three restores verified by sha256 identical before and after, plus a green +re-run (`ec-opus` conformance re-run too: 28 passed, 0 failed). + +## 7. Honest notes / what was NOT done + +- **`ec-av1` not touched.** No read-modify-write; only read as the precedent. +- **`.cargo/config.toml`'s `RUST_MIN_STACK` not lowered.** The point of the + lane is that a consumer who never sees that file is safe. +- **No codec behaviour, default, or bitstream output changed.** The diff is + field types, `Box::new` at construction, `&mut f` → `&mut f[..]` at four + `silk_buf` borrow sites, and three `.clone()` → `.as_ref().clone()` at vp9 + copy-out sites. +- **`ec-vp9`'s inventory is genuinely small** — only 3 public by-value types, + because 11 of its 13 `pub fn` lines return a primitive, `Self` or `()` and + every other module's API is `pub(crate)` behind `Decoder`. The gate's floor + is set to the real count (3) rather than padded to `ec-av1`'s 10; the assert + is an exact equality whose failure message states the real number. Padding it + would have required inventing types, so it was not padded. +- **`ec-vp9`'s matcher unwraps `Result`/`Option` in a loop**, not once: its one + by-value public return is `Result>`, which a single unwrap + reads as the non-type `"Option"`. A synthetic control case pins the + double-wrapped spelling. +- **Not done, and named:** the `ec-opus` sweep found `CeltEncoder` (1,592), + `TonalityAnalysis` (2,168) and `CeltDecoder` (1,168) still inline. All are + under budget, so boxing them is a future move, not this lane's. +- **Full-suite validation is the integrator's.** Only scoped per-crate + `--lib`, the named integration exactness tests, and the new gate module were + run here; concurrent lanes made a project-wide run unsafe mid-flight. + +## 8. Files + +``` + crates/ec-ac3/src/decode.rs | 25 +++++++++++----------- (boxing) + crates/ec-ac3/src/lib.rs | 1 + (mod decl) + crates/ec-opus/src/encoder.rs | 61 +++++++++++++++++-------- (boxing) + crates/ec-opus/src/lib.rs | 11 +++-- (boxing + mod decl) + crates/ec-vp9/src/decode.rs | 36 ++++++++++++++----------- (boxing) + crates/ec-vp9/src/lib.rs | 1 + (mod decl) + crates/ec-ac3/src/stack_budget.rs | new, 995 lines, 8 tests + crates/ec-opus/src/stack_budget.rs | new, 949 lines, 7 tests + crates/ec-vp9/src/stack_budget.rs | new, 725 lines, 7 tests + lanes/stackbox.report.md | this file +``` + +No commit, no push, no merge, no rustfmt — per the lane's constraints.