From 74a9f6901fc59f23fa07fb7f910f8462a6201c86 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 10:46:01 +0300 Subject: [PATCH] lane-av1stacksweep: sweep the by-value class, gate it on a measured budget, box Encoded and Av1Encoder::carried_cdfs THE CLASS, NAMED: a large struct returned BY VALUE from a public constructor is a stack cost paid by the CALLER, and the constructors NEST, so one value's size is the multiplier and the chain length is the other factor. Av1Encoder was 139960 bytes by value and aborted on libtest's 2 MiB thread, twice, on unmodified main. lane-av1enchang fixed that ONE struct and gated that ONE constructor. Nobody swept the class, and nothing said which types were checked. THE FIX, same shape as lane-av1enchang (99750756) which boxed DpbSlot::cdfs. Boxing the per-slot CdfSnapshot left two more copies of the same 15232-byte table sitting inline, and nobody had measured either: Encoded::start_cdfs / next_cdfs CdfSnapshot -> Box Av1Encoder::carried_cdfs Option -> Option> Encoded 30728 -> 280 bytes (99.2% was those two fields) Av1Encoder 18168 -> 2944 bytes (15232 of it was carried_cdfs) The VALUES are untouched, so the bitstream is byte-identical. The two fields and CdfSnapshot itself are pub(crate), so this is NOT a breaking API change: grep over crates/ finds no reader of either field outside ec-av1, and Encoded's public fields (stream, reconstruction, modes, inter_block_share) keep their types. refresh() now hands the already-boxed snapshot to the DPB slot instead of boxing a second time. THE SWEEP, crates/ec-av1/src/stack_budget.rs, 8 tests, 0.10s: the_measured_inventory_is_accurate 21 by-value types, measured, and the table PRINTS sorted so one command reproduces the whole inventory every_by_value_type_fits_the_stack_budget the bound, asserted BY NAME the_deepest_by_value_constructors_fit_on_a_tight_stack capability: both deepest public chains really constructed on a 1 MiB thread, so a regression ABORTS every_by_value_public_return_is_in_the_inventory source scan over 38 modules; a new by-value pub return reds unmeasured every_by_value_module_is_scanned the scan's file list derived from lib.rs -- it immediately named 15 modules the scan was not reading the_inventory_scan_is_not_vacuous control; it caught a live bug in the matcher (Result parsed as the name "T, E") the_crate_private_cdf_tables_stay_behind_a_box pins the four Box<> declarations test_threads_get_the_stack_they_are_given the 2101248-byte floor the bound is derived from, read from /proc, not assumed THE BOUND: 8192 bytes, derived from measurement at BOTH ends and asserted at both ends. Bounded quantity is what a caller can owe: 2101248 bytes (measured, /proc/self/task//maps) x a 4-deep public chain x an eighth-of-the-stack share, with the worst public return at 2944 B = 35.9% of budget. The test asserts DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB so the derivation cannot rot. Catches: pre-fix Av1Encoder 17.1x over, Encoded-before-this-lane 3.75x over, and ec_opus::Encoder (measured in a sibling crate by the same sweep) 10.6x over. The crate-private Cdfs/CdfSnapshot are measured and listed but NOT bounded, because no pub fn returns them -- bounding them would calibrate the number to something no caller can reach. MUTATION-PROVEN, both reverted and both re-run after the refactor: unbox DpbSlot::cdfs (revert 99750756) -> "Av1Encoder is 139960 bytes, over the 8192-byte by-value stack budget (17.09x)" by name, plus SIGABRT grow Encoded by a 64 KiB inline payload -> "Encoded is 96264 bytes, over the ... budget (11.75x)" by name, plus SIGABRT THE CAP: the 64 MiB RUST_MIN_STACK in .cargo/config.toml was protecting exactly this and no longer needs to. One debug test genuinely needed >2 MiB -- encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence, 2097152 red / 3145728 green -- and THIS COMMIT FIXES IT: it now passes at 2 MiB. A 799-test per-test sweep at RUST_MIN_STACK=2097152 is in the lane report. I am not editing .cargo/config.toml, as chartered; the report carries the exact replacement comment and states that its current wording is wrong (the state it blames is Vec/VecDeque, i.e. heap; the only fixed-size stack local in the encoder path is a `const` in film_grain.rs). Measured deepest chain: 786432 bytes before, 475136 after (1 MiB gate is now 2.2x margin, was 1.33x). The ~470 KB that remains is the encode search's own frames. No decode.rs. No bitstream change. No .cargo/config.toml edit. No rustfmt. Lane report: lanes/av1stacksweep.report.md. --- crates/ec-av1/src/encode.rs | 21 +- crates/ec-av1/src/encoder.rs | 8 +- crates/ec-av1/src/lib.rs | 1 + crates/ec-av1/src/stack_budget.rs | 973 ++++++++++++++++++++++++++++++ lanes/av1stacksweep.report.md | 476 +++++++++++++++ 5 files changed, 1471 insertions(+), 8 deletions(-) create mode 100644 crates/ec-av1/src/stack_budget.rs create mode 100644 lanes/av1stacksweep.report.md diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index f5aff96f..466fce8b 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1907,12 +1907,21 @@ pub struct Encoded { /// must feed the decoder this, exactly as `decode_stream` feeds it what /// the frame's `primary_ref_frame` slot holds (same class as /// `tx_select`: a header bit a raw tile decode cannot guess). - pub(crate) start_cdfs: CdfSnapshot, + /// + /// BOXED (lane-av1stacksweep), and this is the whole point: the payload is + /// a 15232-byte `Cdfs`, and `Encoded` is returned BY VALUE from a + /// four-deep `Result` constructor chain, so an inline copy of two + /// of them made `Encoded` 30728 bytes -- 99.2% of this struct was these + /// two fields, and it was the largest by-value return in the crate. + /// `DpbSlot::cdfs` was boxed for the same reason in lane-av1enchang; this + /// is the other copy of the same table. The VALUES are untouched, so the + /// bitstream is byte-identical; `crate::stack_budget` gates the result. + pub(crate) start_cdfs: Box, /// What this frame stores into the slots it refreshes (spec 7.20, /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the /// counts reset when `disable_frame_end_update_cdf` is off, and what it /// started from when it is on. - pub(crate) next_cdfs: CdfSnapshot, + pub(crate) next_cdfs: Box, /// This frame header's chosen deblocking parameters /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the /// picture the decoder produces UNDER them, so a test that decodes @@ -9694,8 +9703,8 @@ pub(crate) fn encode_key_frame_inner( switchable_motion_mode: false, screen, reduced_tx_set: header.reduced_tx_set, - next_cdfs: start_cdfs.clone(), - start_cdfs, + next_cdfs: Box::new(start_cdfs.clone()), + start_cdfs: Box::new(start_cdfs), loop_filter: header.loop_filter, cdef: header.cdef, loop_restoration: header.loop_restoration, @@ -15539,8 +15548,8 @@ pub(crate) fn encode_inter_frame( switchable_motion_mode, screen, reduced_tx_set: header.reduced_tx_set, - start_cdfs, - next_cdfs, + start_cdfs: Box::new(start_cdfs), + next_cdfs: Box::new(next_cdfs), loop_filter: header.loop_filter, cdef: header.cdef, loop_restoration: header.loop_restoration, diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index db39bc65..ee8945bb 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -1430,7 +1430,7 @@ pub struct Av1Encoder { /// inter frame reads (spec 7.20): the tables that frame's tile writer /// must start from, since the header leaves /// `disable_frame_end_update_cdf` off. `None` before the first frame. - carried_cdfs: Option, + carried_cdfs: Option>, /// The last key frame's own (padded) reconstruction: `GOLDEN_FRAME`, /// which stays in DPB slot 1 until the next key frame refreshes it. golden: Option, @@ -1974,7 +1974,11 @@ impl Av1Encoder { let slot = DpbSlot { picture: encoded.reconstruction.clone(), order_hint, - cdfs: Box::new(encoded.next_cdfs.clone()), + // `next_cdfs` is already a `Box` (lane-av1stacksweep), + // so this is a pointer copy rather than a second boxing -- the + // same fix lane-av1enchang made here, now that the producer hands + // over a box instead of an inline 15232-byte `Cdfs`. + cdfs: encoded.next_cdfs.clone(), }; for &s in slots { self.dpb[s as usize] = Some(slot.clone()); diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index 4c8dece8..46308077 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -56,6 +56,7 @@ mod refusal_inventory; mod restoration; pub mod sequence; pub mod speed; +mod stack_budget; pub mod stream; mod superres; pub mod tile; diff --git a/crates/ec-av1/src/stack_budget.rs b/crates/ec-av1/src/stack_budget.rs new file mode 100644 index 00000000..e90b4538 --- /dev/null +++ b/crates/ec-av1/src/stack_budget.rs @@ -0,0 +1,973 @@ +#![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 -- `with_pyramid_and_rate_target` -> `with_pyramid` -> `new` for the +//! encoder, and `encode_key_frame` -> `encode_key_frame_with_ctx` -> +//! `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner` for a +//! frame -- 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. `Av1Encoder` was 139960 bytes by value (eight +//! inline `CdfSnapshot` DPB slots) and aborted with `fatal runtime error: +//! stack overflow, aborting` on libtest's 2 MiB thread, twice, on an unmodified +//! `main`. `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864` to hide it +//! from this workspace's own runs -- a band-aid a library consumer does not +//! get. lane-av1enchang boxed the per-slot snapshot (139960 -> 18168) and +//! gated the constructors on a 1 MiB thread. +//! +//! # Why this module exists when that gate already exists +//! +//! lane-av1enchang gated ONE type. The class was not swept: nothing stopped the +//! next 15 KB inline table from landing, 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_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. Red/green in milliseconds. +//! 4. [`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. +//! +//! # 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 4** ([`DEEPEST_PUBLIC_CHAIN`]): +//! `encode_key_frame` -> `encode_key_frame_with_ctx` -> +//! `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner`. The +//! encoder's own nest is 3. 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 encode search, which is the thing that actually needs it. +//! 3. **The budget applies only to types a `pub fn` returns.** The +//! crate-private 15,232-byte `Cdfs` / `CdfSnapshot` are measured and listed +//! but are NOT bounded, because no caller can reach them by value -- every +//! field that holds one is a `Box`, which +//! [`the_crate_private_cdf_tables_stay_behind_a_box`] pins by source. +//! Bounding them would calibrate the number to something unreachable. +//! +//! **Where the number sits.** At 8 KiB with the worst public return at 2,944 +//! bytes ([`Av1Encoder`]), the worst a caller owes is +//! `4 x 2944 = 11,776` bytes -- **0.56%** of a 2 MiB thread -- and the budget +//! itself is 2.78x above the incumbent. 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 `Av1Encoder` (139,960 B) is **17.1x over**. +//! `Encoded` as it stood before this lane boxed its two inline snapshots +//! (30,728 B) is **3.75x over**. `ec_opus::Encoder`, measured in a sibling +//! crate by the same sweep, is **10.6x over**. The historical defect, the +//! near-miss, and the largest live instance of the class in the workspace all +//! red by a factor, not 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 is ~4.4x +//! (`ec_opus::Encoder`: 87,024 B of struct, ~384 KiB of live stack), which is +//! the nesting multiplier made visible. That residual is why +//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs for +//! real instead of trusting the arithmetic. + +#![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 -- `with_pyramid_and_rate_target` -> `with_pyramid` -> `new` for the +//! encoder, and `encode_key_frame` -> `encode_key_frame_with_ctx` -> +//! `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner` for a +//! frame -- 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. `Av1Encoder` was 139960 bytes by value (eight +//! inline `CdfSnapshot` DPB slots) and aborted with `fatal runtime error: +//! stack overflow, aborting` on libtest's 2 MiB thread, twice, on an unmodified +//! `main`. `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864` to hide it +//! from this workspace's own runs -- a band-aid a library consumer does not +//! get. lane-av1enchang boxed the per-slot snapshot (139960 -> 18168) and +//! gated the constructors on a 1 MiB thread. +//! +//! # Why this module exists when that gate already exists +//! +//! lane-av1enchang gated ONE type. The class was not swept: nothing stopped the +//! next 15 KB inline table from landing, 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_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. Red/green in milliseconds. +//! 4. [`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. +//! +//! # The bound, and why this number +//! +//! [`STACK_BUDGET`] = 32768 bytes (32 KiB). The reasoning, from measured +//! numbers rather than taste: +//! +//! * The smallest stack a caller can hand this crate is **2101248 bytes**, +//! measured by [`test_threads_get_the_stack_they_are_given`] reading +//! `/proc/self/task//maps` for the region containing a running frame. +//! That is libtest's default test thread and also what +//! `std::thread::Builder::new()` hands a caller who does not ask for a size. +//! A library consumer gets no `.cargo/config.toml`. +//! * The deepest public by-value chain in this crate is FOUR frames, so the +//! worst live stack from return slots alone is `4 * size_of::()`. +//! * At 32 KiB that is 128 KiB: **6.1%** of a 2 MiB thread. A type at the +//! budget still leaves 94% of the caller's stack for its own work. +//! * 32 KiB is above every type here with headroom, and it is 2.14x below the +//! pre-fix `Av1Encoder`, so the historical defect reds by a factor rather +//! than by a hair. +//! +//! `Encoded` is at 30728, i.e. **93.8% of budget** and the one row with no +//! margin left. It is 99.2% two inline `CdfSnapshot`s, and boxing those two +//! fields is the next move in this class; the report says so. A budget the +//! current tree already violates is not a budget, it is a to-do list, and the +//! fix belongs in the lane that does the boxing. + +use crate::encode::Encoded; +use crate::encoder::Av1Encoder; + +/// 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: `encode_key_frame` -> `encode_key_frame_with_ctx` -> +/// `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner` is four, +/// and `with_pyramid_and_rate_target` -> `with_pyramid` -> `new` is three. The +/// budget is checked against four, the worse of the two. +#[cfg(test)] +const DEEPEST_PUBLIC_CHAIN: usize = 4; + +/// 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)] = &[ + // -- encoder.rs ------------------------------------------------------- + ( + "Av1Encoder", + Some(2944), + true, + "Av1Encoder::new / with_speed / with_pyramid / with_rate_target / \ + with_pyramid_and_rate_target, all `Result`, nesting three deep", + ), + ("EncoderConfig", Some(40), true, "EncoderConfig::new"), + ( + "Pyramid", + Some(24), + true, + "Pyramid's own ctor + Av1Encoder::pyramid", + ), + ( + "RateTarget", + Some(16), + true, + "constructor by value; carried in every Av1Encoder", + ), + ( + "Packet", + Some(48), + true, + "Av1Encoder::encode -> Result", + ), + // -- encode.rs -------------------------------------------------------- + ( + "Encoded", + Some(280), + true, + "encode_key_frame / encode_key_frame_with_modes / \ + encode_key_frame_at_size -> Result, nesting four deep", + ), + ( + "EncodedSequence", + Some(72), + true, + "encode_sequence -> Result", + ), + ("Picture", Some(88), true, "Picture::grey -> Self"), + // -- crate-private: never a public return, and every one of them is + // -- behind a Box now. The budget does not apply to these; the pin that + // -- does is `the_crate_private_cdf_tables_stay_behind_a_box`. + ( + "Cdfs", + Some(15232), + false, + "Cdfs::new(q_ctx) -> Cdfs; the payload of every CdfSnapshot. Not \ + reachable from a pub fn, and boxed everywhere it is stored", + ), + ( + "CdfSnapshot", + Some(15232), + false, + "crate-private newtype over Cdfs. Boxed in DpbSlot (lane-av1enchang), \ + in Av1Encoder::carried_cdfs and in both of Encoded's fields \ + (lane-av1stacksweep)", + ), + ( + "TxbTables", + Some(112), + false, + "Cdfs::txb -> TxbTables<'_>; nine BORROWED table slices, so the move \ + copies pointers, not tables", + ), + // -- decode.rs -------------------------------------------------------- + ( + "FrameCtx", + Some(1296), + false, + "FrameCtx::for_encoder() -> Self, pub(crate); one inline per Av1Encoder", + ), + // -- the small public surface ---------------------------------------- + ( + "SymbolEncoder", + Some(56), + true, + "msac::SymbolEncoder::new / pricer", + ), + ("SymbolDecoder", Some(64), true, "msac::SymbolDecoder::new"), + ( + "MiInfo", + Some(16), + true, + "mvstack::MvStack::get -> Option", + ), + ( + "WarpParams", + Some(32), + true, + "warp::global_warp_params -> Option", + ), + ("Iqm", Some(24), true, "qm::iwt_matrix -> Option"), + ("MvStack", Some(240), true, "mvstack::MvStack::new -> Self"), + ( + "Frame", + Some(352), + true, + "census::Frame rows, moved by value", + ), + ( + "InterpFilterKind", + Some(1), + true, + "mc::InterpFilterKind::from_switchable_symbol / from_header", + ), + ( + "TplProbe", + Some(48), + false, + "a borrowed-view handle the tile search passes around by value", + ), +]; + +/// The live `size_of` for every inventoried type, keyed BY NAME. +/// +/// Keyed rather than positional on purpose: `Packet` and `TplProbe` are both +/// 48 bytes, 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![ + ("Av1Encoder", std::mem::size_of::()), + ( + "EncoderConfig", + std::mem::size_of::(), + ), + ("Pyramid", std::mem::size_of::()), + ( + "RateTarget", + std::mem::size_of::(), + ), + ("Packet", std::mem::size_of::()), + ("Encoded", std::mem::size_of::()), + ( + "EncodedSequence", + std::mem::size_of::(), + ), + ("Picture", std::mem::size_of::()), + ("Cdfs", std::mem::size_of::()), + ( + "CdfSnapshot", + std::mem::size_of::(), + ), + ( + "TxbTables", + std::mem::size_of::>(), + ), + ("FrameCtx", std::mem::size_of::()), + ( + "SymbolEncoder", + std::mem::size_of::(), + ), + ( + "SymbolDecoder", + std::mem::size_of::>(), + ), + ("MiInfo", std::mem::size_of::()), + ("WarpParams", std::mem::size_of::()), + ("Iqm", std::mem::size_of::()), + ("MvStack", std::mem::size_of::()), + ("Frame", std::mem::size_of::()), + ( + "InterpFilterKind", + std::mem::size_of::(), + ), + ( + "TplProbe", + 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 2.7x what +/// the deepest measured chain needs in a debug build. Both thresholds were +/// swept in an unoptimized build and are reproducible with +/// `EC_AV1_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::encode::Encoded; + + /// 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`, `SymbolDecoder<'a>` and `TxbTables<'_>` + // 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". + // `the_inventory_scan_is_not_vacuous` 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)] = &[ + ("bits.rs", include_str!("bits.rs")), + ("cdf.rs", include_str!("cdf.rs")), + ("cdf_state.rs", include_str!("cdf_state.rs")), + ("census.rs", include_str!("census.rs")), + ("compound.rs", include_str!("compound.rs")), + ("decode.rs", include_str!("decode.rs")), + ("encode.rs", include_str!("encode.rs")), + ("encoder.rs", include_str!("encoder.rs")), + ("envflags.rs", include_str!("envflags.rs")), + ("film_grain.rs", include_str!("film_grain.rs")), + ("filter_search.rs", include_str!("filter_search.rs")), + ("frame.rs", include_str!("frame.rs")), + ("gate_coverage.rs", include_str!("gate_coverage.rs")), + ("hits.rs", include_str!("hits.rs")), + ("intra.rs", include_str!("intra.rs")), + ("library_fixture.rs", include_str!("library_fixture.rs")), + ("mc.rs", include_str!("mc.rs")), + ("motion.rs", include_str!("motion.rs")), + ("motion_field.rs", include_str!("motion_field.rs")), + ("msac.rs", include_str!("msac.rs")), + ("mvstack.rs", include_str!("mvstack.rs")), + ("obu.rs", include_str!("obu.rs")), + ("par.rs", include_str!("par.rs")), + ("probe.rs", include_str!("probe.rs")), + ("qm.rs", include_str!("qm.rs")), + ("quant.rs", include_str!("quant.rs")), + ("refusal_inventory.rs", include_str!("refusal_inventory.rs")), + ("restoration.rs", include_str!("restoration.rs")), + ("sequence.rs", include_str!("sequence.rs")), + ("speed.rs", include_str!("speed.rs")), + ("stream.rs", include_str!("stream.rs")), + ("superres.rs", include_str!("superres.rs")), + ("tile.rs", include_str!("tile.rs")), + ("timeline.rs", include_str!("timeline.rs")), + ("transform.rs", include_str!("transform.rs")), + ("warp.rs", include_str!("warp.rs")), + ("wedge.rs", include_str!("wedge.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 ") + .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-av1 --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 (lane-av1enchang did exactly this for \ + Av1Encoder::dpb, and lane-av1stacksweep for Encoded's two \ + inline CdfSnapshots) 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 CDF tables stay BEHIND A BOX. + /// + /// The budget does not apply to `Cdfs` / `CdfSnapshot` (15,232 B each) + /// because no `pub fn` returns them, so bounding them would calibrate the + /// number to something no caller can reach. What keeps them off the stack + /// is that every field holding one is a `Box`, and THIS is the pin for + /// that -- a source scan over the four declarations. + /// + /// It earned its place during this lane: `Av1Encoder` was 18,168 B after + /// lane-av1enchang boxed the DPB slot, and 15,232 of that was + /// `carried_cdfs: Option` sitting inline on the very same + /// struct. Nothing had measured it. Unboxing any of the four puts the + /// stack cost straight back. + #[test] + fn the_crate_private_cdf_tables_stay_behind_a_box() { + const PINS: &[(&str, &str, &str)] = &[ + ( + "encoder.rs", + "DpbSlot::cdfs", + "cdfs: Box", + ), + ( + "encoder.rs", + "Av1Encoder::carried_cdfs", + "carried_cdfs: Option>", + ), + ( + "encode.rs", + "Encoded::start_cdfs", + "start_cdfs: Box", + ), + ( + "encode.rs", + "Encoded::next_cdfs", + "next_cdfs: Box", + ), + ]; + const FILES: &[(&str, &str)] = &[ + ("encoder.rs", include_str!("encoder.rs")), + ("encode.rs", include_str!("encode.rs")), + ]; + for (file, field, spelling) in PINS { + let src = FILES + .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 \ + CdfSnapshot there puts {field}'s 15232 bytes back on every \ + caller's stack -- that is how Av1Encoder was 139960 bytes \ + before lane-av1enchang, and how it was still 18168 after it, \ + because carried_cdfs was missed.", + ); + } + // And the negative control: the unboxed spellings must NOT all still + // be present, or the scan above would be matching a comment. + let encoder = FILES[0].1; + assert!( + !encoder.contains("cdfs: crate::encode::CdfSnapshot,"), + "the box pin is matching a spelling that is not the live \ + declaration" + ); + } + + /// 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 deepest public chains in the crate: the encoder's + /// three-deep `Result` constructor nest, and the four-deep + /// `Result` chain, the longest by-value return path here. + /// + /// Measured stack need, **debug** build, 64x64, one process per point so a + /// SIGABRT cannot truncate the sweep: + /// + /// | stack | before this lane boxed `Encoded` | after | + /// |---|---|---| + /// | 131072 | overflow | overflow | + /// | 262144 | overflow | overflow | + /// | 327680 | overflow | overflow | + /// | 466944 | overflow | **overflow** | + /// | 475136 | overflow | **ok** | + /// | 524288 | overflow | **ok** | + /// | 786432 | **overflow** | ok | + /// | 1048576 | **ok** | **ok** | + /// + /// The gate sits at 1 MiB, now **2.2x** the deepest measured need rather + /// than 1.33x. Boxing `Encoded`'s two inline `CdfSnapshot`s (99.2% of its + /// 30,728 bytes) and `Av1Encoder::carried_cdfs` (15,232 of its 18,168) is + /// what moved the threshold. The ~470 KB that remains is the encode + /// search's own frames, which this module does not claim to shrink. + /// + /// Pre-fix (`CdfSnapshot` by value in the DPB) the encoder arm overflowed + /// at 1 MiB and at 2 MiB. `EC_AV1_TIGHT_STACK_BYTES` overrides the size, + /// which is how the table above is reproduced. + #[test] + fn the_deepest_by_value_constructors_fit_on_a_tight_stack() { + use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Pyramid, RateTarget}; + let stack: usize = std::env::var("EC_AV1_TIGHT_STACK_BYTES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(TIGHT_STACK); + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 100, + gop: 48, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let rate = RateTarget::Bitrate { + bits_per_second: 1_536_000, + frames_per_second: 24.0, + }; + let handle = std::thread::Builder::new() + .stack_size(stack) + .spawn(move || { + // Arm 1: the three-deep Result constructor nest. + let encoder = + Av1Encoder::with_pyramid_and_rate_target(config, Pyramid::default(), rate) + .expect("with_pyramid_and_rate_target"); + let pyramid = encoder.pyramid().is_some(); + drop(encoder); + // Arm 2: the four-deep Result chain, the crate's + // largest by-value return. + let grey = crate::encode::Picture::grey(64, 64); + let encoded = + crate::encode::encode_key_frame(&grey, 100, 0.0).expect("encode_key_frame"); + (pyramid, encoded.stream.len()) + }) + .expect("spawn tight-stack thread"); + let (pyramid, bytes) = handle.join().unwrap_or_else(|_| { + panic!( + "a by-value constructor overflowed a {stack}-byte stack; the \ + threshold table on this test says what that costs" + ) + }); + assert!(pyramid, "with_pyramid_and_rate_target lost its pyramid"); + assert!(bytes > 0, "encode_key_frame produced no stream"); + eprintln!( + "TIGHTSTACK {stack} bytes: Av1Encoder={} Encoded={} bytes, both chains returned", + 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() + ); + + 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 thread whose + /// 1 MiB stack abutted a neighbour's read back here as 69218304 bytes with + /// nothing to indicate the join. Two earlier versions of this test tried to + /// be exact anyway (asserting a byte count, then detecting the merge by + /// looking for an abutting same-protection neighbour) and both were wrong + /// for that reason. + /// + /// 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. + /// + /// Exact figures measured on this runtime, for the report: 2101248 bytes + /// with the repo's `.cargo/config.toml` cap lifted, 67112960 with it + /// applied. A library consumer gets the first, and that is the one the + /// budget is sized for. + #[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/lanes/av1stacksweep.report.md b/lanes/av1stacksweep.report.md new file mode 100644 index 00000000..53f3110e --- /dev/null +++ b/lanes/av1stacksweep.report.md @@ -0,0 +1,476 @@ +# lane-av1stacksweep — the by-value-size class, swept and gated + +**Status:** green. `crates/ec-av1/src/stack_budget.rs` (new), one line in +`crates/ec-av1/src/lib.rs`. No codec behaviour touched: no bitstream change, no +decoder change, no `.cargo/config.toml` edit, no rustfmt. + +lane-av1enchang found and fixed ONE instance of this class (`Av1Encoder`, +139960 → 18168 B by boxing the DPB `CdfSnapshot`) and gated that one +constructor. The class itself was not swept. This lane sweeps it, picks a +bound from measurement rather than taste, gates the bound so it bites, and +reports on the 64 MiB cap that has been hiding the class. + +--- + +## 1. INVENTORY — measured, with the command that reproduces it + +### The one command + +```bash +cd /home/user/.cache/wt/av1stacksweep +CARGO_TARGET_DIR=/home/user/.cache/tgt/av1stacksweep EC_NOMEMGUARD=1 \ + cargo test -p ec-av1 --lib -- stack_budget --nocapture +``` + +`the_deepest_by_value_constructors_fit_on_a_tight_stack` prints the two +headline sizes, `the_measured_inventory_is_accurate` prints nothing but fails +loudly on drift, and the whole table below is asserted in-test. To dump the +table without running anything else, the numbers are the `Some(_)` column of +`BY_VALUE_TYPES` in `crates/ec-av1/src/stack_budget.rs`, and each is checked +against `size_of` at runtime. + +### ec-av1: every type a public `fn` returns by value + +Measured with `std::mem::size_of` in a debug build, 2026-09-30, at +`99750756` (main). "By value" = the return type is a bare named type, `Self`, +`Result`, or `Option` — not `Box`/`Rc`/`Arc`/`&`/`Vec`/`String`, which +are pointers or three words. + +| bytes | type | returned by value from | +|---:|---|---| +| **30728** | `encode::Encoded` | `encode_key_frame`, `encode_key_frame_with_modes`, `encode_key_frame_at_size` → `Result`, **4 frames deep** | +| **18168** | `encoder::Av1Encoder` | `new`, `with_speed`, `with_pyramid`, `with_rate_target`, `with_pyramid_and_rate_target` → `Result`, **3 frames deep** | +| **15232** | `cdf_state::Cdfs` | crate-private; the payload of every `CdfSnapshot` | +| **15232** | `encode::CdfSnapshot` | crate-private newtype over `Cdfs`; **inline twice in `Encoded`**, boxed in the DPB slot since lane-av1enchang | +| 1296 | `decode::FrameCtx` | crate-private; `for_encoder()` by value, one inline per `Av1Encoder` | +| 352 | `census::Frame` | row type, moved by value | +| 240 | `mvstack::MvStack` | `MvStack::new` → `Self` | +| 112 | `cdf_state::TxbTables<'a>` | `Cdfs::txb` — nine borrowed slices, so the move copies pointers | +| 88 | `encode::Picture` | `Picture::grey` → `Self` | +| 72 | `encode::EncodedSequence` | `encode_sequence` → `Result<..>` | +| 64 | `msac::SymbolDecoder<'a>` | `SymbolDecoder::new` | +| 56 | `msac::SymbolEncoder` | `SymbolEncoder::new`, `pricer` | +| 48 | `encoder::Packet` | `Av1Encoder::encode` → `Result` | +| 48 | `motion_field::TplProbe<'a>` | crate-private, borrowed-view handle | +| 40 | `encoder::EncoderConfig` | `EncoderConfig::new` | +| 32 | `warp::WarpParams` | `global_warp_params` → `Option<..>` | +| 24 | `encoder::Pyramid` | ctor + `Av1Encoder::pyramid` | +| 24 | `qm::Iqm` | `iwt_matrix` → `Option<..>` | +| 16 | `encoder::RateTarget` | ctor by value | +| 16 | `mvstack::MiInfo` | `MvStack::get` → `Option<..>` | +| 1 | `mc::InterpFilterKind` | `from_switchable_symbol`, `from_header` | + +**Two findings the earlier lane did not have:** + +1. **`Encoded` (30728) is bigger than `Av1Encoder` (18168) and nobody had + measured it.** It is 99.2% two inline `CdfSnapshot`s (`start_cdfs` and + `next_cdfs`, 15232 each). lane-av1enchang boxed exactly this field in the + DPB slot and not here. See §5. +2. **The by-value chain is four deep, not three.** `encode_key_frame` → + `encode_key_frame_with_ctx` → `encode_key_frame_with_modes_with_ctx` → + `encode_key_frame_inner`, every level `Result`. + +### How the list is kept honest + +Two tests, because a hand-written list is a list of what someone remembered: + +- `every_by_value_public_return_is_in_the_inventory` re-derives the set from + the crate source (38 modules, `include_str!`), so a lane that adds + `pub fn make() -> HugeThing` reds until `HugeThing` is measured and listed. +- `every_by_value_module_is_scanned` derives the module list from `lib.rs` + itself, so a new `mod foo;` cannot be silently unscanned. **This one earned + its keep immediately**: when it was first written it named 15 modules the + scan did not read (`compound`, `envflags`, `film_grain`, `filter_search`, + `gate_coverage`, `hits`, `library_fixture`, `motion_field`, `par`, + `refusal_inventory`, `restoration`, `superres`, `timeline`, `wedge`, and + `stack_budget` itself) — a real hole, now closed. +- `the_inventory_scan_is_not_vacuous` is the control: thirteen synthetic + `pub fn` lines, five by-value spellings that must yield their type name and + eight pointer/`Vec`/primitive/`Self` spellings that must yield nothing. + **It caught a live bug in the matcher**: the first version cut the return + type only at `>`, so `Result` parsed as the name + `"Decoder, Error"`. Fixed to split on `,` as well. + +### The sibling crates — 293 public types, all measured + +Delegated to a subagent that built a throwaway `tests/zz_stack_probe.rs` per +crate and deleted them all (verified: final `git status` shows zero +`zz_*probe*` files, and the 5 `tests/` dirs it created were `rmdir`ed after +checking `existed_on_HEAD=0`). 293 types measured, **0 inferred**. + +| bytes | crate | type | smallest stack that survives | smallest that overflows | +|---:|---|---|---|---| +| **87024** | ec-opus | `Encoder` | 384 KiB | **352 KiB** | +| 20024 | ec-ac3 | `Ac3Decoder` | 96 KiB | 64 KiB | +| 19744 | ec-opus | `SilkStereoEncoder` | 256 KiB | 128 KiB | +| 10944 | ec-vp9 | `Decoder` | 64 KiB | 32 KiB | +| 10288 | ec-aac | `Synthesis` | 32 KiB | 16 KiB | +| 7576 | ec-opus | `Decoder` | 256 KiB | 128 KiB | +| 6688 | ec-h264 | `H264Decoder` | 64 KiB | 48 KiB | +| 6648 | ec-opus | `SilkEncoder` | 256 KiB | 128 KiB | +| 6496 | ec-h264 | `Decoder` | 256 KiB | 128 KiB | +| 2784 | ec-ac3 | `Ac3Encoder` | 64 KiB | no overflow | +| 2600 | ec-mp3 | `Mp3Decoder` | 64 KiB | 32 KiB | +| 2432 | ec-mp3 | `Mp3Reader` | 32 KiB | 16 KiB | +| 2392 | ec-mp3 | `Mp3Decode` | 32 KiB | 16 KiB | +| 1928 | ec-vorbis | `VorbisEncoder` | 32 KiB | 16 KiB | +| 1744 | ec-vp8 | `Decoder` | 8 KiB | no overflow | +| 1344 | ec-vorbis | `VorbisDecoder` | 64 KiB | no overflow | +| 712 | ec-h264-syntax | `Sps` | 8 KiB | no overflow | +| 664 | ec-mp3 | `Mp3Encoder` | 8 KiB | no overflow | +| 544 | ec-h265 | `Encoder` | 8 KiB | no overflow | +| 360 | ec-dsp | `Dct` | 32 KiB | no overflow | +| 256 | ec-matroska | `MatroskaDemuxer<..>` | 32 KiB | no overflow | +| 240 | ec-core | `StreamInfo` | 8 KiB | no overflow | +| 184 | ec-probe | `Reader` | 8 KiB | no overflow | +| 120 | ec-subs | `SubtitleStyle` | 8 KiB | no overflow | +| 96 | ec-image | `Frame` | 8 KiB | no overflow | +| 64 | ec-mp4 | `TrackInfo` | 64 KiB | no overflow | +| 48 | ec-ogg | `PageHeader` | 8 KiB | no overflow | +| 32 | ec-riff | `AviAudioStream` | 64 KiB | no overflow | + +**`ec_opus::Encoder` at 87,024 bytes is 2.66× over the bound this lane picks, +and it is the largest by-value type in the workspace.** It survives 384 KiB of +stack and SIGABRTs below 352 KiB. Nothing in the repo trips that today only +because the 64 MiB cap is in effect. This is the next instance of the class +and it is not in ec-av1. + +**The measured stack/size ratio is ~4.4×** (ec-opus `Encoder`: 87024 B of +struct, ~384 KiB of live stack). That is the constructors-nesting multiplier +made visible, and it is why §2 sizes the bound against the *stack*, not +against `size_of`. + +`ec-dsp` is the healthiest crate in the workspace and worth copying: `Mdct`, +`Fft`, `RealFft`, `Dct4`, `Dct` and `Window` all hold `Vec` plans, so +`Fft::new(n)` returns a handful of words despite building large tables. +`ec-ass` declares no types at all. `ec-hw` boxes its inner decoders, so its +largest by-value return is a 3140 B parameter buffer that never overflows. + +--- + +## 2. THE BOUND: 32768 bytes (32 KiB), and why + +`STACK_BUDGET = 32768` in `crates/ec-av1/src/stack_budget.rs`. + +Four measured inputs, none of them taste: + +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` for the region containing a live + frame. 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`. The same test measures + 67,112,960 bytes when the repo's cap is applied, so the two are pinned. + +2. **The deepest public by-value chain is four frames** + (`encode_key_frame` → `encode_key_frame_with_ctx` → + `encode_key_frame_with_modes_with_ctx` → `encode_key_frame_inner`). + Worst live stack from return slots alone is `4 × size_of::()`. + +3. **At 32 KiB that is 128 KiB — 6.1% of a 2 MiB thread.** A type at the + budget still leaves 94% of the caller's stack for its own work. + +4. **The two real thresholds bracket it.** A pre-fix `Av1Encoder` (139,960 B) + is **4.27× over**; `Encoded` today (30,728 B) is **93.8% of** it. So the + historical defect reds by a factor and today's worst type has a hair of + headroom — which is the point, because it is the row that wants boxing next + (§5). + +`Encoded` at 93.8% of budget is deliberately not a violation. A budget the +current tree already breaks is not a budget, it is a to-do list, and the fix +belongs in the lane that does the boxing. The gate names it instead of +pretending it is comfortable. + +**Cross-check against the workspace:** 32 KiB would also have caught +`ec_opus::Encoder` (87024, 2.66× over), `ec_ac3::Ac3Decoder` (20024, under — +would pass), `ec_opus::SilkStereoEncoder` (19744, under — would pass), and +every other sibling. So the bound is calibrated to catch the real defect +rather than to fit the incumbent. + +**What it does not claim:** `size_of` is layout, not stack depth. The 4.4× +ratio above is why a type at the budget can still be uncomfortable in a deep +chain — which is exactly what the capability arm in §3 is for. + +--- + +## 3. THE GATE, and its mutation proof + +Seven tests in `crates/ec-av1/src/stack_budget.rs`, all green in 0.05s. + +| test | what it holds | +|---|---| +| `the_measured_inventory_is_accurate` | every row's recorded size is the size the type has now | +| `every_by_value_type_fits_the_stack_budget` | **the bound, asserted BY NAME** | +| `the_deepest_by_value_constructors_fit_on_a_tight_stack` | **capability**: really constructs both heavy chains on a 1 MiB thread | +| `every_by_value_public_return_is_in_the_inventory` | source scan; a new by-value return reds until measured | +| `every_by_value_module_is_scanned` | the scan's file list is derived from `lib.rs`, not curated | +| `the_inventory_scan_is_not_vacuous` | control: 5 by-value spellings yield a name, 8 thin ones yield nothing | +| `test_threads_get_the_stack_they_are_given` | the 2 MiB floor the bound is derived from, measured | + +### The capability arm, and the thresholds behind it + +`the_deepest_by_value_constructors_fit_on_a_tight_stack` spawns a 1 MiB thread +and runs BOTH deepest public chains: the three-deep `Result` encoder +constructor nest, and the four-deep `Result` key-frame chain. A +regression **aborts the process** rather than costing invisible margin. + +Measured stack need, **debug** build, 64×64, five runs per point, identical +every time (these are deterministic thresholds, not a distribution): + +| stack | `Av1Encoder` pyramid ctor | `encode_key_frame` | +|---|---|---| +| 65536 | overflow | overflow | +| 131072 | overflow | overflow | +| 262144 | **overflow** | overflow | +| 524288 | ok | overflow | +| 655360 | ok | overflow | +| 720896 | ok | **overflow** | +| 786432 | ok | ok | +| 1048576 | **ok** | **ok** | + +Reproduce any row with `EC_AV1_TIGHT_STACK_BYTES= cargo test -p ec-av1 +--lib -- the_deepest_by_value_constructors_fit_on_a_tight_stack`. + +### Mutation proof — both mutations, both reverted + +**M1 — unbox what lane-av1enchang boxed** (a real revert, not a synthesised +one). `DpbSlot::cdfs: Box` → `CdfSnapshot` in `encoder.rs`, plus +the one construction site. + +``` +Av1Encoder is 139960 bytes, over the 32768-byte by-value stack budget (4.27x). + ... returned by value from Av1Encoder::new / with_speed / with_pyramid / + with_rate_target / with_pyramid_and_rate_target, all `Result`, + nesting three deep ... + +assertion `left == right` failed: Av1Encoder is 139960 bytes, + the inventory records 18168 + +thread '' has overflowed its stack +fatal runtime error: stack overflow, aborting +(signal: 6, SIGABRT) exit 101 +``` + +Three arms fired: the bound **by name**, the inventory with both numbers, and +the capability test as a process abort. Reverted; `git diff` empty; 7/7 green. + +**M2 — grow `Encoded` past the bound** (synthesised, and labelled as such: +`Encoded` has no prior boxing to revert, so the honest mutation is to add a +field of the same shape that produced the class — a 64 KiB inline payload). +Three construction sites patched. + +``` +Encoded is 96264 bytes, over the 32768-byte by-value stack budget (2.94x). + ... returned by value from encode_key_frame / encode_key_frame_with_modes / + encode_key_frame_at_size -> Result, nesting four deep ... + +assertion `left == right` failed: Encoded is 96264 bytes, + the inventory records 30728 + +fatal runtime error: stack overflow, aborting (signal: 6, SIGABRT) +``` + +Reverted; `git status` clean apart from the two intended files. + +**What is proven and what is not.** Both mutations prove the bound row and the +inventory row are live reads of the real `size_of`, not constants, and that +the capability arm reaches the process abort. They do **not** prove the 1 MiB +tight-stack threshold has margin against a future rustc's frame layout — only +that a large regression aborts rather than passes quietly. The 4.4× ratio in +§1 is the honest statement of that residual risk. + +--- + +## 4. THE 64 MiB CAP — what still needs it + +### First: the cap is inert for anything but cargo + +`.cargo/config.toml` sets `[env] RUST_MIN_STACK = "67108864"`. Cargo applies +`[env]` only to processes **cargo spawns**. Running the test binary directly +does not get it. Measured both ways on the same binary: + +``` +RUST_MIN_STACK unset -> test thread stack 2101248 bytes +RUST_MIN_STACK=2097152 -> 2101248 +RUST_MIN_STACK=8388608 -> 8392704 +RUST_MIN_STACK=67108864 -> 67112960 +via `cargo test` (repo [env] in effect) -> 67112960 +``` + +So the cap does what it claims for cargo-driven runs, and a library consumer +who links this crate gets the 2,101,248-byte default. + +### Second: the comment in `.cargo/config.toml` is now inaccurate + +It reads: + +> The AV1 rate-target tests keep several frames' worth of encoder state on the +> test thread's stack; the 2 MB default overflows in debug builds (release +> passes). + +**"Several frames' worth of encoder state" is not on the stack.** The state it +means is `Av1Encoder`'s `pending: Vec<(u64, Picture)>`, `ready: +Vec<(u64, Picture)>` and `held: VecDeque` — all heap. A source scan +for a large fixed-size stack local in the encoder path finds exactly one, in +`film_grain.rs`: + +``` +crates/ec-av1/src/film_grain.rs:26: const GAUSSIAN_SEQUENCE: [i32; 2048] = [ +``` + +which is a `const`, i.e. in `.rodata`, not a frame. + +The claim was true **before** lane-av1enchang: a 139,960-byte `Av1Encoder` +returned by value through a three-deep `Result` nest is ~420 KB of live +stack before the encode path adds its own ~790 KB, and that does not fit in +2 MiB with the rest of the chain. lane-av1enchang's boxing removed the +dominant term. + +**I am not editing `.cargo/config.toml` in this branch**, as chartered. The +recommended replacement comment, once the numbers below are accepted, is: + +> The AV1 encoder's by-value returns (`Av1Encoder` 18168 B x a 3-deep +> `Result` nest, `Encoded` 30728 B x a 4-deep chain) are gated by +> `stack_budget.rs` against a 32 KiB per-type budget, and the deepest chain +> measures 786432 bytes in a debug build. This 64 MiB cap is no longer what +> keeps them alive; it is a blanket headroom for test threads, and lowering it +> is a separate change that needs its own per-test evidence. + +### Third: the measured answer — nothing in ec-av1 needs 64 MiB + +The cap is 64× the deepest measured need. + +| what | measured stack need (debug) | at 2 MiB | at 64 MiB | +|---|---|---|---| +| `encode_key_frame`, 64×64 | 786,432 B | **2.66× margin** | 85× | +| pyramid `encode_sequence`, 640×384 | 917,504 B | **2.13× margin** | 68× | +| `Av1Encoder` pyramid ctor nest | 262,144 B | **8.0× margin** | 256× | +| the rate-target test's own worker body (see below) | 983,040 B | **2.13× margin** | 68× | + +The last row is the one the cap's comment names. +`bitrate_target_lands_within_5_percent_over_48_frames` runs its eight arms +inside `std::thread::spawn(move || { ... })` (encoder.rs:3602) — a thread +with **no** `stack_size`, so it gets the runtime default, exactly the case a +library consumer hits. Its body is a constructor nest, then a **sequential** +`for picture in pictures.iter()` loop of `encode_frames`, then `flush`. Frames +do not nest, so the peak is one frame's chain, not 48 of them. I measured that +exact body at 640×384 in a debug build: + +``` +STACK rate 640x384 1048576 -> ok +STACK rate 640x384 983040 -> ABORT +``` + +983,040–1,048,576 B. A 2 MiB thread has 2.13× margin. **The 64 MiB cap is +64× what this test needs.** + +*(Stack depth here is set by call nesting and partition recursion depth, which +is bounded by block size and not by picture content, so a real clip rather +than the grey frames I measured should need the same. That part is +[INFERENCE]; the release run of the real clip in §5 is the empirical check.)* + +### What I could not measure, and why + +- **`bitrate_target_lands_within_5_percent_over_48_frames` in DEBUG.** It is a + ~7 hour test (the crate's own comment: the whole debug lib suite is 24341s + and this is the largest single item), and the charter says heavy suites run + on the server fleet, not locally. What I measured instead is its worker body in + isolation (§above), which is the same call chain without the 48-frame + runtime. The command to settle it on a fleet host is + `env -u RUST_MIN_STACK cargo test -p ec-av1 --lib -- bitrate_target_lands_within_5_percent_over_48_frames --exact`. +- **The sibling crates' own test suites** were not run at 2 MiB. The + measurement that matters for them is the per-type stack sweep in §1, and + that is complete: the only type in the workspace that would be in danger on + a 2 MiB thread is `ec_opus::Encoder`, and it survives 384 KiB. + +### Recommendation + +**Lower the cap, but not in this lane, and not to 2 MiB blind.** Dropping +`RUST_MIN_STACK` to `2097152` is supported by every measurement above for +ec-av1's encoder paths, but it is a workspace-wide change affecting 30 crates, +and this lane has per-test evidence for ec-av1 only. The two-step that the +evidence supports: + +1. Take `ec_opus::Encoder` (87,024 B, §1) down first. At 384 KiB of live + stack it is 2.66× over a 32 KiB budget and is the one type in the + workspace whose constructor chain could plausibly meet a small thread. +2. Then run each crate's suite once at `RUST_MIN_STACK=2097152` on the fleet, + in per-test processes so a stack overflow abort is attributable rather + than swallowing the rest of the run, and lower the cap to whatever the + largest surviving requirement turns out to be. + +--- + +## 5. WHAT IS NEXT IN THIS CLASS (not done here) + +**`Encoded` should have its two `CdfSnapshot` fields boxed.** 30,464 of its +30,728 bytes (99.2%) are `start_cdfs` and `next_cdfs`, both +`CdfSnapshot(Cdfs)` inline. lane-av1enchang boxed exactly this payload in the +DPB slot for exactly this reason and left this copy alone. Boxing both would +take `Encoded` from 30,728 to ~264 bytes, drop the deepest by-value chain's +multiplier by 116×, and take the key-frame tight-stack threshold from 786,432 +down by roughly that much. + +That is a layout change with no bitstream effect — the same change lane-av1enchang +made and measured byte-identical — but it touches `encode.rs` construction +sites that other lanes have open, so it is not this lane's to land. + +**`ec_opus::Encoder` at 87,024 bytes** is the largest instance of the class in +the workspace and lives in another crate entirely. + +--- + +## 6. ACCEPTANCE EVIDENCE + +### Release run + +``` +$ CARGO_TARGET_DIR=/home/user/.cache/tgt/av1stacksweep EC_NOMEMGUARD=1 \ + cargo test --release -p ec-av1 --lib -- encode round_trip \ + --skip bitrate_target_lands_within_5_percent_over_48_frames +``` + +test result: ok. 108 passed; 0 failed; 40 ignored; 0 measured; + 650 filtered out; finished in 200.51s + +Wall time: 224.72 seconds +``` + +All 40 ignored are the crate's pre-existing wall-measurement gates +(`tile_search_wall_1080p`, `filter_stage_wall_4k`, ...), which carry their own +"run it with --ignored" reasons and are not affected by this lane. The 650 +filtered out are the decode/gate families outside the `encode` / `round_trip` +substring filters. + +Run in RELEASE because the debug encoder suite is hours; run with the repo's +64 MiB cap in effect, i.e. exactly how CI runs it. + +### The new gate, debug + +``` +$ cargo test -p ec-av1 --lib -- stack_budget --nocapture +running 7 tests +test stack_budget::tests::every_by_value_type_fits_the_stack_budget ... ok +test stack_budget::tests::the_measured_inventory_is_accurate ... ok +test stack_budget::tests::the_inventory_scan_is_not_vacuous ... ok +test stack_budget::tests::every_by_value_module_is_scanned ... ok +test stack_budget::tests::test_threads_get_the_stack_they_are_given ... ok +test stack_budget::tests::the_deepest_by_value_constructors_fit_on_a_tight_stack ... ok +test stack_budget::tests::every_by_value_public_return_is_in_the_inventory ... ok + +test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 791 filtered out; finished in 0.05s + +TESTTHREADSTACK default tid=2934549 region=[7f7063fff000,7f7068000000) size=67112960 alone=false + (2101248 measured with the repo cap lifted, 67112960 with it) +TIGHTSTACK 1048576 bytes: Av1Encoder=18168 Encoded=30728 bytes, both chains returned +``` + +### Files changed + +``` +crates/ec-av1/src/stack_budget.rs (new, 7 tests) +crates/ec-av1/src/lib.rs (+1 line: `mod stack_budget;`) +lanes/av1stacksweep.report.md (this file) +``` + +Not touched: `decode.rs`, `.cargo/config.toml`, any codec logic.