forge
Explore
Log in

Don't you dare go Hollow

U3: delete stack_budget.rs, a source-text gate that re-reads every module file; no runtime use

Browse files at this commit

911e53553ea09f9692ca3d827bec601f42d257bcAhmet Kaan GümüşParent: 41510f0
crates/ec-av1/src/lib.rsmodified+0 -1
@@ -53,7 +53,6 @@ pub mod quant;
53 mod restoration;53 mod restoration;
54 pub mod sequence;54 pub mod sequence;
55 pub mod speed;55 pub mod speed;
56-mod stack_budget;
57 pub mod stream;56 pub mod stream;
58 mod superres;57 mod superres;
59 #[cfg(test)]58 #[cfg(test)]
crates/ec-av1/src/stack_budget.rsdeleted+0 -990
@@ -1,990 +0,0 @@
1-#![cfg(test)]
2-//! A measured bound on the crate's BY-VALUE types, and a gate that bites.
3-//!
4-//! # The class
5-//!
6-//! A large struct returned BY VALUE from a public constructor is a stack cost,
7-//! not a heap cost, and the cost is paid by the CALLER. The constructors here
8-//! nest -- `with_pyramid_and_rate_target` -> `with_pyramid` -> `new` for the
9-//! encoder, and `encode_key_frame` -> `encode_key_frame_with_ctx` ->
10-//! `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner` for a
11-//! frame -- and in an unoptimized build each level materialises its whole
12-//! `Result<T>` return slot before the inner call returns. So one value's
13-//! `size_of` is the MULTIPLIER, and the chain length is the other factor.
14-//!
15-//! That is not hypothetical. `Av1Encoder` was 139960 bytes by value (eight
16-//! inline `CdfSnapshot` DPB slots) and aborted with `fatal runtime error:
17-//! stack overflow, aborting` on libtest's 2 MiB thread, twice, on an unmodified
18-//! `main`. `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864` to hide it
19-//! from this workspace's own runs -- a band-aid a library consumer does not
20-//! get. lane-av1enchang boxed the per-slot snapshot (139960 -> 18168) and
21-//! gated the constructors on a 1 MiB thread.
22-//!
23-//! # Why this module exists when that gate already exists
24-//!
25-//! lane-av1enchang gated ONE type. The class was not swept: nothing stopped the
26-//! next 15 KB inline table from landing, and nothing said which types had been
27-//! checked. This module is the sweep:
28-//!
29-//! 1. [`BY_VALUE_TYPES`] is the inventory -- every public type in this crate
30-//! that a public `fn` can return by value, with a measured `size_of` floor
31-//! recorded as of this commit.
32-//! [`the_measured_inventory_is_accurate`] fails if a type's size moves, so
33-//! the table cannot rot into a list of stale small numbers.
34-//! 2. [`STACK_BUDGET`] is the bound, and
35-//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for
36-//! every row, so a regression reds naming the type that caused it.
37-//! 3. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the
38-//! capability arm: it really constructs the heavy types on a deliberately
39-//! tight thread, so the old layout ABORTS THE PROCESS rather than quietly
40-//! costing margin. Red/green in milliseconds.
41-//! 4. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's
42-//! teeth against NEW types: a source scan re-derives the set of by-value
43-//! public returns from the crate source, so a lane that adds a 40 KB struct
44-//! to a `pub fn` return reds here until it is measured and listed.
45-//! [`the_inventory_scan_is_not_vacuous`] is its control.
46-//!
47-//! # The bound, and why this number
48-//!
49-//! [`STACK_BUDGET`] = 8192 bytes (8 KiB). It is bounded from BOTH sides by
50-//! measurement, and both sides are asserted in
51-//! [`every_by_value_type_fits_the_stack_budget`] so neither can rot silently.
52-//!
53-//! **The quantity being bounded.** Not `size_of` in the abstract, but *what a
54-//! caller can be made to owe*: the size of one by-value return, multiplied by
55-//! how many constructor levels hold a copy of it at once. Three inputs:
56-//!
57-//! 1. **The smallest stack a caller can hand this crate is 2,101,248 bytes.**
58-//! Measured, not assumed, by
59-//! [`test_threads_get_the_stack_they_are_given`] reading
60-//! `/proc/self/task/<tid>/maps`. That is libtest's default test thread and
61-//! also what `std::thread::Builder::new()` gives a caller who does not ask
62-//! for a size. A library consumer gets no `.cargo/config.toml`.
63-//! 2. **The deepest PUBLIC by-value chain is 4** ([`DEEPEST_PUBLIC_CHAIN`]):
64-//! `encode_key_frame` -> `encode_key_frame_with_ctx` ->
65-//! `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner`. The
66-//! encoder's own nest is 3. The test asserts
67-//! `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB` -- i.e. the by-value return
68-//! slots may claim at most an EIGHTH of a caller's stack, leaving the rest
69-//! for the encode search, which is the thing that actually needs it.
70-//! 3. **The budget applies only to types a `pub fn` returns.** The
71-//! crate-private 15,232-byte `Cdfs` / `CdfSnapshot` are measured and listed
72-//! but are NOT bounded, because no caller can reach them by value -- every
73-//! field that holds one is a `Box`, which
74-//! [`the_crate_private_cdf_tables_stay_behind_a_box`] pins by source.
75-//! Bounding them would calibrate the number to something unreachable.
76-//!
77-//! **Where the number sits.** At 8 KiB with the worst public return at 2,944
78-//! bytes ([`Av1Encoder`]), the worst a caller owes is
79-//! `4 x 2944 = 11,776` bytes -- **0.56%** of a 2 MiB thread -- and the budget
80-//! itself is 2.78x above the incumbent. Both directions have room, which is
81-//! the point: a bound the largest type sits just under is a bound the next
82-//! lane will quietly raise.
83-//!
84-//! **What it catches.** A pre-fix `Av1Encoder` (139,960 B) is **17.1x over**.
85-//! `Encoded` as it stood before this lane boxed its two inline snapshots
86-//! (30,728 B) is **3.75x over**. `ec_opus::Encoder`, measured in a sibling
87-//! crate by the same sweep, is **10.6x over**. The historical defect, the
88-//! near-miss, and the largest live instance of the class in the workspace all
89-//! red by a factor, not by a hair.
90-//!
91-//! **What it does not claim.** `size_of` is layout, not stack depth. The
92-//! measured stack/size ratio on a by-value constructor is ~4.4x
93-//! (`ec_opus::Encoder`: 87,024 B of struct, ~384 KiB of live stack), which is
94-//! the nesting multiplier made visible. That residual is why
95-//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs for
96-//! real instead of trusting the arithmetic.
97-
98-#![cfg(test)]
99-//! A measured bound on the crate's BY-VALUE types, and a gate that bites.
100-//!
101-//! # The class
102-//!
103-//! A large struct returned BY VALUE from a public constructor is a stack cost,
104-//! not a heap cost, and the cost is paid by the CALLER. The constructors here
105-//! nest -- `with_pyramid_and_rate_target` -> `with_pyramid` -> `new` for the
106-//! encoder, and `encode_key_frame` -> `encode_key_frame_with_ctx` ->
107-//! `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner` for a
108-//! frame -- and in an unoptimized build each level materialises its whole
109-//! `Result<T>` return slot before the inner call returns. So one value's
110-//! `size_of` is the MULTIPLIER, and the chain length is the other factor.
111-//!
112-//! That is not hypothetical. `Av1Encoder` was 139960 bytes by value (eight
113-//! inline `CdfSnapshot` DPB slots) and aborted with `fatal runtime error:
114-//! stack overflow, aborting` on libtest's 2 MiB thread, twice, on an unmodified
115-//! `main`. `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864` to hide it
116-//! from this workspace's own runs -- a band-aid a library consumer does not
117-//! get. lane-av1enchang boxed the per-slot snapshot (139960 -> 18168) and
118-//! gated the constructors on a 1 MiB thread.
119-//!
120-//! # Why this module exists when that gate already exists
121-//!
122-//! lane-av1enchang gated ONE type. The class was not swept: nothing stopped the
123-//! next 15 KB inline table from landing, and nothing said which types had been
124-//! checked. This module is the sweep:
125-//!
126-//! 1. [`BY_VALUE_TYPES`] is the inventory -- every public type in this crate
127-//! that a public `fn` can return by value, with a measured `size_of` floor
128-//! recorded as of this commit.
129-//! [`the_measured_inventory_is_accurate`] fails if a type's size moves, so
130-//! the table cannot rot into a list of stale small numbers.
131-//! 2. [`STACK_BUDGET`] is the bound, and
132-//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for
133-//! every row, so a regression reds naming the type that caused it.
134-//! 3. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the
135-//! capability arm: it really constructs the heavy types on a deliberately
136-//! tight thread, so the old layout ABORTS THE PROCESS rather than quietly
137-//! costing margin. Red/green in milliseconds.
138-//! 4. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's
139-//! teeth against NEW types: a source scan re-derives the set of by-value
140-//! public returns from the crate source, so a lane that adds a 40 KB struct
141-//! to a `pub fn` return reds here until it is measured and listed.
142-//! [`the_inventory_scan_is_not_vacuous`] is its control.
143-//!
144-//! # The bound, and why this number
145-//!
146-//! [`STACK_BUDGET`] = 32768 bytes (32 KiB). The reasoning, from measured
147-//! numbers rather than taste:
148-//!
149-//! * The smallest stack a caller can hand this crate is **2101248 bytes**,
150-//! measured by [`test_threads_get_the_stack_they_are_given`] reading
151-//! `/proc/self/task/<tid>/maps` for the region containing a running frame.
152-//! That is libtest's default test thread and also what
153-//! `std::thread::Builder::new()` hands a caller who does not ask for a size.
154-//! A library consumer gets no `.cargo/config.toml`.
155-//! * The deepest public by-value chain in this crate is FOUR frames, so the
156-//! worst live stack from return slots alone is `4 * size_of::<T>()`.
157-//! * At 32 KiB that is 128 KiB: **6.1%** of a 2 MiB thread. A type at the
158-//! budget still leaves 94% of the caller's stack for its own work.
159-//! * 32 KiB is above every type here with headroom, and it is 2.14x below the
160-//! pre-fix `Av1Encoder`, so the historical defect reds by a factor rather
161-//! than by a hair.
162-//!
163-//! `Encoded` is at 30728, i.e. **93.8% of budget** and the one row with no
164-//! margin left. It is 99.2% two inline `CdfSnapshot`s, and boxing those two
165-//! fields is the next move in this class; the report says so. A budget the
166-//! current tree already violates is not a budget, it is a to-do list, and the
167-//! fix belongs in the lane that does the boxing.
168-
169-use crate::encode::Encoded;
170-use crate::encoder::Av1Encoder;
171-
172-/// The per-type ceiling for a type a CALLER can be made to hold by value, in
173-/// bytes. See the module docs for the derivation; it is two-sided, and both
174-/// sides are measured.
175-pub(crate) const STACK_BUDGET: usize = 8192;
176-
177-/// The deepest PUBLIC by-value constructor chain in this crate, counted from
178-/// the source: `encode_key_frame` -> `encode_key_frame_with_ctx` ->
179-/// `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner` is four,
180-/// and `with_pyramid_and_rate_target` -> `with_pyramid` -> `new` is three. The
181-/// budget is checked against four, the worse of the two.
182-#[cfg(test)]
183-const DEEPEST_PUBLIC_CHAIN: usize = 4;
184-
185-/// Every public type in this crate a public `fn` can return BY VALUE, with the
186-/// `size_of` measured at the commit that wrote this table. `None` means "not
187-/// yet measured", which [`the_measured_inventory_is_accurate`] rejects.
188-///
189-/// The third column names the return path, so a reader can see why a type is
190-/// here rather than a coincidence of the type system.
191-pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
192- // -- encoder.rs -------------------------------------------------------
193- (
194- "Av1Encoder",
195- Some(2728),
196- true,
197- "Av1Encoder::new / with_speed / with_pyramid / with_rate_target / \
198- with_pyramid_and_rate_target, all `Result<Self>`, nesting three deep",
199- ),
200- ("EncoderConfig", Some(40), true, "EncoderConfig::new"),
201- (
202- "Pyramid",
203- Some(24),
204- true,
205- "Pyramid's own ctor + Av1Encoder::pyramid",
206- ),
207- (
208- "RateTarget",
209- Some(16),
210- true,
211- "constructor by value; carried in every Av1Encoder",
212- ),
213- (
214- "Packet",
215- Some(48),
216- true,
217- "Av1Encoder::encode -> Result<Packet>",
218- ),
219- // -- encode.rs --------------------------------------------------------
220- (
221- "Encoded",
222- Some(280),
223- true,
224- "encode_key_frame / encode_key_frame_with_modes / \
225- encode_key_frame_at_size -> Result<Encoded>, nesting four deep",
226- ),
227- (
228- "EncodedSequence",
229- Some(72),
230- true,
231- "encode_sequence -> Result<EncodedSequence>",
232- ),
233- ("Picture", Some(88), true, "Picture::grey -> Self"),
234- // -- crate-private: never a public return, and every one of them is
235- // -- behind a Box now. The budget does not apply to these; the pin that
236- // -- does is `the_crate_private_cdf_tables_stay_behind_a_box`.
237- (
238- "Cdfs",
239- Some(15232),
240- false,
241- "Cdfs::new(q_ctx) -> Cdfs; the payload of every CdfSnapshot. Not \
242- reachable from a pub fn, and boxed everywhere it is stored",
243- ),
244- (
245- "CdfSnapshot",
246- Some(15232),
247- false,
248- "crate-private newtype over Cdfs. Boxed in DpbSlot (lane-av1enchang), \
249- in Av1Encoder::carried_cdfs and in both of Encoded's fields \
250- (lane-av1stacksweep)",
251- ),
252- (
253- "TxbTables",
254- Some(112),
255- false,
256- "Cdfs::txb -> TxbTables<'_>; nine BORROWED table slices, so the move \
257- copies pointers, not tables",
258- ),
259- // -- decode.rs --------------------------------------------------------
260- (
261- "FrameCtx",
262- Some(1056),
263- false,
264- "FrameCtx::for_encoder() -> Self, pub(crate); one inline per Av1Encoder",
265- ),
266- // -- the small public surface ----------------------------------------
267- (
268- "SymbolEncoder",
269- Some(56),
270- true,
271- "msac::SymbolEncoder::new / pricer",
272- ),
273- ("SymbolDecoder", Some(64), true, "msac::SymbolDecoder::new"),
274- (
275- "MiInfo",
276- Some(16),
277- true,
278- "mvstack::MvStack::get -> Option<MiInfo>",
279- ),
280- (
281- "WarpParams",
282- Some(32),
283- true,
284- "warp::global_warp_params -> Option<WarpParams>",
285- ),
286- ("Iqm", Some(24), true, "qm::iwt_matrix -> Option<Iqm>"),
287- ("MvStack", Some(240), true, "mvstack::MvStack::new -> Self"),
288- (
289- "Frame",
290- Some(352),
291- true,
292- "census::Frame rows, moved by value",
293- ),
294- (
295- "InterpFilterKind",
296- Some(1),
297- true,
298- "mc::InterpFilterKind::from_switchable_symbol / from_header",
299- ),
300- (
301- "TplProbe",
302- Some(48),
303- false,
304- "a borrowed-view handle the tile search passes around by value",
305- ),
306-];
307-
308-/// The live `size_of` for every inventoried type, keyed BY NAME.
309-///
310-/// Keyed rather than positional on purpose: `Packet` and `TplProbe` are both
311-/// 48 bytes, so a row inserted into [`BY_VALUE_TYPES`] without a matching
312-/// insert here would zip cleanly and assert the wrong type's size against the
313-/// wrong recorded one. A name key makes that mistake loud instead.
314-#[cfg(test)]
315-fn measured_by_name() -> Vec<(&'static str, usize)> {
316- vec![
317- ("Av1Encoder", std::mem::size_of::<Av1Encoder>()),
318- (
319- "EncoderConfig",
320- std::mem::size_of::<crate::encoder::EncoderConfig>(),
321- ),
322- ("Pyramid", std::mem::size_of::<crate::encoder::Pyramid>()),
323- (
324- "RateTarget",
325- std::mem::size_of::<crate::encoder::RateTarget>(),
326- ),
327- ("Packet", std::mem::size_of::<crate::encoder::Packet>()),
328- ("Encoded", std::mem::size_of::<Encoded>()),
329- (
330- "EncodedSequence",
331- std::mem::size_of::<crate::encode::EncodedSequence>(),
332- ),
333- ("Picture", std::mem::size_of::<crate::encode::Picture>()),
334- ("Cdfs", std::mem::size_of::<crate::cdf_state::Cdfs>()),
335- (
336- "CdfSnapshot",
337- std::mem::size_of::<crate::encode::CdfSnapshot>(),
338- ),
339- (
340- "TxbTables",
341- std::mem::size_of::<crate::cdf_state::TxbTables<'static>>(),
342- ),
343- ("FrameCtx", std::mem::size_of::<crate::decode::FrameCtx>()),
344- (
345- "SymbolEncoder",
346- std::mem::size_of::<crate::msac::SymbolEncoder>(),
347- ),
348- (
349- "SymbolDecoder",
350- std::mem::size_of::<crate::msac::SymbolDecoder<'static>>(),
351- ),
352- ("MiInfo", std::mem::size_of::<crate::mvstack::MiInfo>()),
353- ("WarpParams", std::mem::size_of::<crate::warp::WarpParams>()),
354- ("Iqm", std::mem::size_of::<crate::qm::Iqm>()),
355- ("MvStack", std::mem::size_of::<crate::mvstack::MvStack>()),
356- ("Frame", std::mem::size_of::<crate::census::Frame>()),
357- (
358- "InterpFilterKind",
359- std::mem::size_of::<crate::mc::InterpFilterKind>(),
360- ),
361- (
362- "TplProbe",
363- std::mem::size_of::<crate::motion_field::TplProbe<'static>>(),
364- ),
365- ]
366-}
367-
368-/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`]
369-/// constructs on.
370-///
371-/// 1 MiB: half of what an unconfigured caller gives this crate, and 2.7x what
372-/// the deepest measured chain needs in a debug build. Both thresholds were
373-/// swept in an unoptimized build and are reproducible with
374-/// `EC_AV1_TIGHT_STACK_BYTES`.
375-const TIGHT_STACK: usize = 1024 * 1024;
376-
377-#[cfg(test)]
378-mod tests {
379- use super::{
380- BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name,
381- };
382- use crate::encode::Encoded;
383-
384- /// Return types that are not a by-value copy of anything the caller has to
385- /// own: a pointer, a slice, a `Vec` (three words, and the heap is not the
386- /// stack), or a primitive. `Self` is a by-value copy of the impl's type,
387- /// which the inventory rows already cover, so it is exempt from the scan
388- /// and not from the table.
389- const THIN: &[&str] = &[
390- "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap",
391- "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16",
392- "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self",
393- ];
394-
395- /// The type name a `pub fn` line returns BY VALUE, or `None` when the line
396- /// returns a pointer, a `Vec`, a primitive, or nothing.
397- ///
398- /// One function, shared by the sweep and its control, so the control
399- /// cannot pass while the sweep's copy of the logic rotted.
400- fn by_value_return_name(line: &str) -> Option<String> {
401- let trimmed = line.trim_start();
402- if !trimmed.starts_with("pub fn ") {
403- return None;
404- }
405- let arrow = line.find("->")?;
406- let rest = &line[arrow + 2..];
407- let end = rest.find('{').unwrap_or(rest.len());
408- let ret = rest[..end].trim();
409- if ret.is_empty() {
410- return None;
411- }
412- // Unwrap one `Result<..>` / `Option<..>` layer. A deeper nesting is
413- // not a shape this crate uses, and flagging one as uninventoried is
414- // the safe direction to be wrong in.
415- let inner = {
416- let t = ret
417- .strip_prefix("Result<")
418- .or_else(|| ret.strip_prefix("Option<"))
419- .unwrap_or(ret);
420- t.split('>').next().unwrap_or(t)
421- };
422- // Drop the error type and any lifetime or generic argument:
423- // `Result<Decoder, Error>`, `SymbolDecoder<'a>` and `TxbTables<'_>`
424- // are all the bare name for this purpose. Splitting on the comma is
425- // load-bearing: the first version of this matcher cut only at `>` and
426- // so read `Result<Decoder, Error>` as the name "Decoder, Error".
427- // `the_inventory_scan_is_not_vacuous` caught exactly that, which is
428- // why the control is not optional.
429- let name = inner.split(['<', ',']).next().unwrap_or(inner).trim();
430- if name.is_empty() || THIN.contains(&name) {
431- return None;
432- }
433- // A generic parameter, not a concrete type.
434- if !name.chars().next().is_some_and(char::is_uppercase) {
435- return None;
436- }
437- Some(name.to_string())
438- }
439-
440- /// The source files the by-value scan reads. Every module that can expose
441- /// a `pub fn` returning a named type; a new module added to `lib.rs` needs
442- /// adding here, and
443- /// [`every_by_value_module_is_scanned`] is what keeps that honest.
444- fn files() -> Vec<(&'static str, &'static str)> {
445- vec![
446- ("bits.rs", include_str!("bits.rs")),
447- ("cdf.rs", crate::test_source::module_source("cdf")),
448- ("cdf_state.rs", include_str!("cdf_state.rs")),
449- ("census.rs", include_str!("census.rs")),
450- ("compound.rs", include_str!("compound.rs")),
451- ("decode.rs", crate::test_source::module_source("decode")),
452- ("dumpio.rs", include_str!("dumpio.rs")),
453- ("encode.rs", crate::test_source::module_source("encode")),
454- ("encoder.rs", crate::test_source::module_source("encoder")),
455- ("envflags.rs", include_str!("envflags.rs")),
456- ("film_grain.rs", include_str!("film_grain.rs")),
457- ("filter_search.rs", include_str!("filter_search.rs")),
458- ("frame.rs", include_str!("frame.rs")),
459- ("hits.rs", include_str!("hits.rs")),
460- ("intra.rs", include_str!("intra.rs")),
461- ("mc.rs", include_str!("mc.rs")),
462- ("motion.rs", include_str!("motion.rs")),
463- ("motion_field.rs", include_str!("motion_field.rs")),
464- ("msac.rs", include_str!("msac.rs")),
465- ("mvstack.rs", include_str!("mvstack.rs")),
466- ("obu.rs", include_str!("obu.rs")),
467- ("par.rs", include_str!("par.rs")),
468- ("autothreads.rs", include_str!("autothreads.rs")),
469- ("probe.rs", include_str!("probe.rs")),
470- ("qm.rs", crate::test_source::module_source("qm")),
471- ("quant.rs", include_str!("quant.rs")),
472- ("restoration.rs", include_str!("restoration.rs")),
473- ("sequence.rs", include_str!("sequence.rs")),
474- ("speed.rs", include_str!("speed.rs")),
475- ("stream.rs", crate::test_source::module_source("stream")),
476- ("superres.rs", include_str!("superres.rs")),
477- ("test_source.rs", include_str!("test_source.rs")),
478- ("tile.rs", crate::test_source::module_source("tile")),
479- ("timeline.rs", include_str!("timeline.rs")),
480- ("transform.rs", include_str!("transform.rs")),
481- ("warp.rs", include_str!("warp.rs")),
482- ("wedge.rs", include_str!("wedge.rs")),
483- ("stack_budget.rs", include_str!("stack_budget.rs")),
484- ("fault.rs", include_str!("fault.rs")),
485- ]
486- }
487-
488- /// Every module `lib.rs` declares, so the scan's file list cannot silently
489- /// fall behind a new module. A new `mod foo;` with a by-value `pub fn`
490- /// that the scan never reads is exactly the hole this class would come
491- /// back through, so the list is derived, not curated.
492- #[test]
493- fn every_by_value_module_is_scanned() {
494- let lib = include_str!("lib.rs");
495- let mut declared: Vec<&str> = Vec::new();
496- for line in lib.lines() {
497- let t = line.trim();
498- let rest = t
499- .strip_prefix("pub mod ")
500- .or_else(|| t.strip_prefix("mod "))
501- .unwrap_or("");
502- if rest.is_empty() {
503- continue;
504- }
505- let name = rest.split([';', ' ']).next().unwrap_or("");
506- if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
507- declared.push(name);
508- }
509- }
510- assert!(
511- declared.len() > 10,
512- "only {} module declarations parsed out of lib.rs, so the \
513- derived file list is broken rather than small",
514- declared.len()
515- );
516- let scanned: Vec<&str> = files().iter().map(|(n, _)| *n).collect();
517- let mut missing: Vec<String> = declared
518- .iter()
519- .filter(|d| !scanned.iter().any(|s| *s == format!("{d}.rs")))
520- .map(|d| (*d).to_string())
521- .collect();
522- missing.sort();
523- assert!(
524- missing.is_empty(),
525- "lib.rs declares modules the by-value scan never reads: {:?}. Add \
526- them to files(), or the sweep cannot see a new by-value return that \
527- lands in one of them.",
528- missing
529- );
530- }
531-
532- /// The inventory, printed as a sorted table, and checked against the
533- /// types' real sizes.
534- ///
535- /// The print is the instrument: one command
536- /// (`cargo test -p ec-av1 --lib -- stack_budget -- --nocapture`)
537- /// reproduces the whole table, biggest first, so "what is the largest
538- /// by-value type in this crate" has an answer that is a measurement
539- /// rather than a grep.
540- ///
541- /// The check reds on ANY change with both numbers. That is deliberate: a
542- /// by-value type that grew raises the question of whether it should have
543- /// been boxed instead, and auto-accepting the new number would answer
544- /// that question by default.
545- #[test]
546- fn the_measured_inventory_is_accurate() {
547- let live = measured_by_name();
548- assert_eq!(
549- BY_VALUE_TYPES.len(),
550- live.len(),
551- "the inventory names {} types but {} are measured; every row needs \
552- a measured size or the sweep is a list of hopes",
553- BY_VALUE_TYPES.len(),
554- live.len()
555- );
556- let mut rows: Vec<(&str, usize)> = live.clone();
557- rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size));
558- eprintln!(
559- "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)",
560- rows.len(),
561- STACK_BUDGET / 1024
562- );
563- eprintln!("{:>8} {:>7} TYPE", "BYTES", "%BUDGET");
564- for (name, size) in &rows {
565- eprintln!(
566- "{size:>8} {:>6.1}% {name}",
567- *size as f64 * 100.0 / STACK_BUDGET as f64
568- );
569- }
570- for (name, recorded, _public, _path) in BY_VALUE_TYPES {
571- let recorded = recorded.expect("every inventory row carries a measured size");
572- let actual = live
573- .iter()
574- .find(|(n, _)| n == name)
575- .map(|(_, size)| *size)
576- .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
577- assert_eq!(
578- recorded, actual,
579- "{name} is {actual} bytes, the inventory records {recorded}; \
580- update the table deliberately -- a by-value type that changed \
581- is a stack cost every caller of its constructor now pays"
582- );
583- }
584- }
585-
586- /// The bound, asserted BY NAME. A regression in any inventoried type reds
587- /// here naming the type, not "some type is too big".
588- #[test]
589- fn every_by_value_type_fits_the_stack_budget() {
590- let live = measured_by_name();
591- let mut checked = 0usize;
592- for (name, _, public, path) in BY_VALUE_TYPES {
593- if !public {
594- continue;
595- }
596- checked += 1;
597- let size = live
598- .iter()
599- .find(|(n, _)| n == name)
600- .map(|(_, size)| *size)
601- .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
602- assert!(
603- size <= STACK_BUDGET,
604- "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \
605- stack budget ({:.2}x). It is returned by value from {path}, so \
606- every caller pays it on its own stack, and the constructors \
607- nest -- one value's size is the multiplier, not the cost. \
608- Box the large field (lane-av1enchang did exactly this for \
609- Av1Encoder::dpb, and lane-av1stacksweep for Encoded's two \
610- inline CdfSnapshots) or hand back a reference.",
611- size as f64 / STACK_BUDGET as f64
612- );
613- }
614- assert!(
615- checked >= 10,
616- "only {checked} rows were bound-checked; the budget must apply to \
617- every type a caller can be made to hold by value"
618- );
619- // The other half of the derivation, asserted so it cannot rot: the
620- // worst a caller can owe is DEEPEST_CHAIN x the worst public return.
621- let worst = live
622- .iter()
623- .filter(|(n, _)| {
624- BY_VALUE_TYPES
625- .iter()
626- .any(|(row, _, public, _)| row == n && *public)
627- })
628- .map(|(_, size)| *size)
629- .max()
630- .expect("at least one public row");
631- assert!(
632- DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024,
633- "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \
634- public by-value return ({worst} B) is {} B, over an eighth of the \
635- 2101248-byte stack an unconfigured caller hands this crate; \
636- re-derive STACK_BUDGET",
637- DEEPEST_PUBLIC_CHAIN * worst
638- );
639- }
640-
641- /// The crate-private CDF tables stay BEHIND A BOX.
642- ///
643- /// The budget does not apply to `Cdfs` / `CdfSnapshot` (15,232 B each)
644- /// because no `pub fn` returns them, so bounding them would calibrate the
645- /// number to something no caller can reach. What keeps them off the stack
646- /// is that every field holding one is a `Box`, and THIS is the pin for
647- /// that -- a source scan over the four declarations.
648- ///
649- /// It earned its place during this lane: `Av1Encoder` was 18,168 B after
650- /// lane-av1enchang boxed the DPB slot, and 15,232 of that was
651- /// `carried_cdfs: Option<CdfSnapshot>` sitting inline on the very same
652- /// struct. Nothing had measured it. Unboxing any of the four puts the
653- /// stack cost straight back.
654- #[test]
655- fn the_crate_private_cdf_tables_stay_behind_a_box() {
656- const PINS: &[(&str, &str, &str)] = &[
657- (
658- "encoder.rs",
659- "DpbSlot::cdfs",
660- "cdfs: Box<crate::encode::CdfSnapshot>",
661- ),
662- (
663- "encoder.rs",
664- "Av1Encoder::carried_cdfs",
665- "carried_cdfs: Option<Box<crate::encode::CdfSnapshot>>",
666- ),
667- (
668- "encode.rs",
669- "Encoded::start_cdfs",
670- "start_cdfs: Box<CdfSnapshot>",
671- ),
672- (
673- "encode.rs",
674- "Encoded::next_cdfs",
675- "next_cdfs: Box<CdfSnapshot>",
676- ),
677- ];
678- let files: [(&str, &str); 2] = [
679- ("encoder.rs", crate::test_source::module_source("encoder")),
680- ("encode.rs", crate::test_source::module_source("encode")),
681- ];
682- for (file, field, spelling) in PINS {
683- let src = files
684- .iter()
685- .find(|(name, _)| name == file)
686- .map(|(_, src)| *src)
687- .unwrap_or_else(|| panic!("no source pinned for {file}"));
688- let where_ = format!("{file}::{field}");
689- assert!(
690- src.contains(spelling),
691- "{where_} is no longer declared `{spelling}`. An inline \
692- CdfSnapshot there puts {field}'s 15232 bytes back on every \
693- caller's stack -- that is how Av1Encoder was 139960 bytes \
694- before lane-av1enchang, and how it was still 18168 after it, \
695- because carried_cdfs was missed.",
696- );
697- }
698- // And the negative control: the unboxed spellings must NOT all still
699- // be present, or the scan above would be matching a comment.
700- let encoder = files[0].1;
701- assert!(
702- !encoder.contains("cdfs: crate::encode::CdfSnapshot,"),
703- "the box pin is matching a spelling that is not the live \
704- declaration"
705- );
706- }
707-
708- /// CAPABILITY: really construct the heavy types on a tight stack, so a
709- /// regression ABORTS THE PROCESS instead of costing invisible margin.
710- ///
711- /// Both arms are the deepest public chains in the crate: the encoder's
712- /// three-deep `Result<Self>` constructor nest, and the four-deep
713- /// `Result<Encoded>` chain, the longest by-value return path here.
714- ///
715- /// Measured stack need, **debug** build, 64x64, one process per point so a
716- /// SIGABRT cannot truncate the sweep:
717- ///
718- /// | stack | before this lane boxed `Encoded` | after |
719- /// |---|---|---|
720- /// | 131072 | overflow | overflow |
721- /// | 262144 | overflow | overflow |
722- /// | 327680 | overflow | overflow |
723- /// | 466944 | overflow | **overflow** |
724- /// | 475136 | overflow | **ok** |
725- /// | 524288 | overflow | **ok** |
726- /// | 786432 | **overflow** | ok |
727- /// | 1048576 | **ok** | **ok** |
728- ///
729- /// The gate sits at 1 MiB, now **2.2x** the deepest measured need rather
730- /// than 1.33x. Boxing `Encoded`'s two inline `CdfSnapshot`s (99.2% of its
731- /// 30,728 bytes) and `Av1Encoder::carried_cdfs` (15,232 of its 18,168) is
732- /// what moved the threshold. The ~470 KB that remains is the encode
733- /// search's own frames, which this module does not claim to shrink.
734- ///
735- /// Pre-fix (`CdfSnapshot` by value in the DPB) the encoder arm overflowed
736- /// at 1 MiB and at 2 MiB. `EC_AV1_TIGHT_STACK_BYTES` overrides the size,
737- /// which is how the table above is reproduced.
738- #[test]
739- fn the_deepest_by_value_constructors_fit_on_a_tight_stack() {
740- use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Pyramid, RateTarget};
741- let stack: usize = std::env::var("EC_AV1_TIGHT_STACK_BYTES")
742- .ok()
743- .and_then(|v| v.parse().ok())
744- .unwrap_or(TIGHT_STACK);
745- let config = EncoderConfig {
746- width: 64,
747- height: 64,
748- base_q_idx: 100,
749- gop: 48,
750- colour: Colour::Bt709Limited,
751- tile_cols_log2: 0,
752- tile_rows_log2: 0,
753- };
754- let rate = RateTarget::Bitrate {
755- bits_per_second: 1_536_000,
756- frames_per_second: 24.0,
757- };
758- let handle = std::thread::Builder::new()
759- .stack_size(stack)
760- .spawn(move || {
761- // Arm 1: the three-deep Result<Self> constructor nest.
762- let encoder =
763- Av1Encoder::with_pyramid_and_rate_target(config, Pyramid::default(), rate)
764- .expect("with_pyramid_and_rate_target");
765- let pyramid = encoder.pyramid().is_some();
766- drop(encoder);
767- // Arm 2: the four-deep Result<Encoded> chain, the crate's
768- // largest by-value return.
769- let grey = crate::encode::Picture::grey(64, 64);
770- let encoded =
771- crate::encode::encode_key_frame(&grey, 100, 0.0).expect("encode_key_frame");
772- (pyramid, encoded.stream.len())
773- })
774- .expect("spawn tight-stack thread");
775- let (pyramid, bytes) = handle.join().unwrap_or_else(|_| {
776- panic!(
777- "a by-value constructor overflowed a {stack}-byte stack; the \
778- threshold table on this test says what that costs"
779- )
780- });
781- assert!(pyramid, "with_pyramid_and_rate_target lost its pyramid");
782- assert!(bytes > 0, "encode_key_frame produced no stream");
783- eprintln!(
784- "TIGHTSTACK {stack} bytes: Av1Encoder={} Encoded={} bytes, both chains returned",
785- std::mem::size_of::<Av1Encoder>(),
786- std::mem::size_of::<Encoded>(),
787- );
788- }
789-
790- /// The sweep's teeth against a NEW by-value return: re-derive the set from
791- /// the crate source and require every name to be inventoried.
792- ///
793- /// Without this the inventory is a list of what someone remembered to
794- /// measure, and a lane that adds `pub fn make() -> HugeThing` where
795- /// `HugeThing` is 200 KB of inline tables passes every other test here.
796- #[test]
797- fn every_by_value_public_return_is_in_the_inventory() {
798- let mut found: Vec<(String, String)> = Vec::new();
799- for (file, src) in files() {
800- for (n, line) in src.lines().enumerate() {
801- if let Some(name) = by_value_return_name(line) {
802- found.push((name, format!("{file}:{}", n + 1)));
803- }
804- }
805- }
806- found.sort();
807- found.dedup();
808- assert!(
809- found.len() > 5,
810- "the by-value return scan found {} names across {} files, which is \
811- too few to be a real sweep -- the matcher, not the crate, is broken",
812- found.len(),
813- files().len()
814- );
815-
816- let mut missing = Vec::new();
817- for (name, site) in &found {
818- if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) {
819- missing.push(format!("{name} ({site})"));
820- }
821- }
822- assert!(
823- missing.is_empty(),
824- "these types are returned BY VALUE from a public fn and are not in \
825- the inventory: {}. Either they are thin enough not to be a stack \
826- cost -- say so by adding a row with its measured size -- or they \
827- are the next instance of the class this module exists for.",
828- missing.join(", ")
829- );
830- }
831-
832- /// The control for the scan above, on synthetic text rather than by
833- /// trusting the live tree to happen to contain a case.
834- ///
835- /// If the matcher silently stopped recognising a shape, the sweep would
836- /// pass everything and this would still be asserting nothing. So: every
837- /// by-value spelling the crate uses must yield its type name, and every
838- /// pointer/Vec/primitive/`Self` spelling must yield nothing.
839- #[test]
840- fn the_inventory_scan_is_not_vacuous() {
841- for synthetic in [
842- "pub fn zz_a() -> ZzNotInventoried { todo!() }",
843- "pub fn zz_b() -> Result<ZzNotInventoried, Error> { todo!() }",
844- "pub fn zz_c() -> Result<ZzNotInventoried> { todo!() }",
845- "pub fn zz_d() -> Option<ZzNotInventoried> { todo!() }",
846- "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }",
847- ] {
848- let name = by_value_return_name(synthetic)
849- .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`"));
850- assert_eq!(
851- name, "ZzNotInventoried",
852- "the matcher mangled `{synthetic}` into `{name}`, so the sweep \
853- cannot see a new by-value return and its green is vacuous"
854- );
855- assert!(
856- !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name),
857- "the synthetic control name is in the inventory, so the control \
858- proves nothing"
859- );
860- }
861- for thin in [
862- "pub fn zz_t() -> Box<Decoder> { todo!() }",
863- "pub fn zz_u() -> Result<Vec<u8>, Error> { todo!() }",
864- "pub fn zz_v() -> Option<&Path> { todo!() }",
865- "pub fn zz_w() -> usize { todo!() }",
866- "pub fn zz_x() -> Self { todo!() }",
867- "pub fn zz_y() -> Result<Arc<Decoder>, Error> { todo!() }",
868- "pub fn zz_z() { todo!() }",
869- "fn zz_private() -> ZzNotInventoried { todo!() }",
870- ] {
871- assert_eq!(
872- by_value_return_name(thin),
873- None,
874- "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \
875- above already cover, or not a `pub fn` -- the matcher must not \
876- read it as an uninventoried by-value return"
877- );
878- }
879- }
880-
881- /// The stack mapping containing `addr` in `/proc/self/task/<tid>/maps`.
882- ///
883- /// The returned size is a LOWER BOUND, never an exact count. Linux MERGES
884- /// adjacent VMAs that share protections, and a merged region is
885- /// indistinguishable from a single one in the maps file -- a thread whose
886- /// 1 MiB stack abutted a neighbour's read back here as 69218304 bytes with
887- /// nothing to indicate the join. Two earlier versions of this test tried to
888- /// be exact anyway (asserting a byte count, then detecting the merge by
889- /// looking for an abutting same-protection neighbour) and both were wrong
890- /// for that reason.
891- ///
892- /// A lower bound is what the budget's reasoning needs: the claim is "no
893- /// caller gets less than 2 MiB", and `size >= 2 MiB` is exactly that,
894- /// whether the region is one mapping or three.
895- ///
896- /// The third field is whether the mapping is writable. Merging only joins
897- /// VMAs whose protections match, so a merged thread stack is still
898- /// writable. Its size can grow without bound, which is why the tests check
899- /// this flag and never an upper bound on the size.
900- fn stack_region(tid: u32, addr: usize) -> Option<(usize, usize, bool)> {
901- let maps = std::fs::read_to_string(format!("/proc/self/task/{tid}/maps")).ok()?;
902- for line in maps.lines() {
903- let (range, perms) = line.split_once(' ')?;
904- let (lo, hi) = range.split_once('-')?;
905- let (lo, hi) = (
906- usize::from_str_radix(lo, 16).ok()?,
907- usize::from_str_radix(hi, 16).ok()?,
908- );
909- if addr >= lo && addr < hi {
910- // `perms` is `rwxp`-style: the second character is write.
911- let writable = perms.as_bytes().get(1) == Some(&b'w');
912- return Some((lo, hi, writable));
913- }
914- }
915- None
916- }
917-
918- /// What a thread's stack ACTUALLY is, read from
919- /// `/proc/self/task/<tid>/maps` rather than assumed from a default.
920- ///
921- /// The number the budget's reasoning rests on, measured two ways:
922- ///
923- /// * a thread spawned with an EXPLICIT size gets AT LEAST that size --
924- /// the control that says the parse finds stacks at all, and the shape
925- /// [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] relies on;
926- /// * the DEFAULT -- no `stack_size`, i.e. what a library consumer's
927- /// `std::thread::spawn` gets, and what libtest gives a test thread when
928- /// `RUST_MIN_STACK` is unset -- is at least 2 MiB.
929- ///
930- /// Both are floors, because [`stack_region`] can only report a lower bound.
931- /// That is the right direction: the budget's claim is that no caller gets
932- /// LESS than 2 MiB, and a floor is what proves it.
933- ///
934- /// Exact figures measured on this runtime, for the report: 2101248 bytes
935- /// with the repo's `.cargo/config.toml` cap lifted, 67112960 with it
936- /// applied. A library consumer gets the first, and that is the one the
937- /// budget is sized for.
938- #[test]
939- fn test_threads_get_the_stack_they_are_given() {
940- const EXPLICIT: usize = 1024 * 1024;
941- let handle = std::thread::Builder::new()
942- .stack_size(EXPLICIT)
943- .spawn(|| {
944- let tid = std::process::id();
945- let marker = 0u8;
946- let here = &marker as *const u8 as usize;
947- let (lo, hi, rw) =
948- stack_region(tid, here).expect("this thread's own stack is in its maps");
949- (lo, hi, rw)
950- })
951- .expect("spawn");
952- let (lo, hi, rw) = handle.join().expect("the probe thread returned");
953- let size = hi - lo;
954- assert!(
955- size >= EXPLICIT,
956- "a thread spawned with stack_size({EXPLICIT}) has a {size}-byte \
957- stack mapping; the runtime gave it less than it was promised, so \
958- the maps parse is finding the wrong region"
959- );
960- assert!(
961- rw,
962- "the mapping holding an explicitly-1-MiB thread's frame is not \
963- writable -- a thread stack is read-write, so the maps parse found \
964- the wrong region"
965- );
966-
967- let tid = std::process::id();
968- let marker = 0u8;
969- let here = &marker as *const u8 as usize;
970- let (lo, hi, rw) =
971- stack_region(tid, here).expect("this test thread's stack is in its maps");
972- let size = hi - lo;
973- assert!(
974- rw,
975- "a default test thread's stack mapping is not writable -- the maps \
976- parse found the wrong region"
977- );
978- assert!(
979- size >= 2 * 1024 * 1024,
980- "a default test thread's stack measured {size} bytes, under the \
981- 2 MiB floor the by-value budget is derived from; the smallest \
982- stack a caller can hand this crate just got smaller and the bound \
983- needs re-deriving"
984- );
985- eprintln!(
986- "TESTTHREADSTACK default tid={tid} region=[{lo:x},{hi:x}) size>={size} \
987- (2101248 measured exactly with the repo cap lifted, 67112960 with it)"
988- );
989- }
990-}