forge
Explore
Log in

Don't you dare go Hollow

Merge lane-av1stacksweep: the by-value class gets a measured bound and a biting gate, and the last two inline CDF snapshots are boxed

Browse files at this commit

cd17c3033dba9183c286d24a47cc61c5909c17deAhmet Kaan GümüşParent: 6f83d9c928f2fe
THE CLASS, swept at last: a large struct returned BY VALUE from a public constructor is a stack cost the
CALLER pays, and the constructors NEST -- so one value's size is the multiplier and the chain length is
the other factor. lane-av1enchang fixed ONE struct (DpbSlot::cdfs) and gated ONE constructor; nothing
said which other types were checked. This lane measured them.

FIX (layout only, same shape as 99750756):
- `Encoded`: 30,728 -> 280 bytes (start_cdfs + next_cdfs were 99.2% of it).
- `Av1Encoder`: 18,168 -> 2,944 bytes. `carried_cdfs` was a SECOND inline 15,232-byte CdfSnapshot that
  the first lane missed because nobody had measured it.
- `DpbSlot::cdfs` now reuses the already-boxed snapshot (pointer copy) instead of boxing again.
API-COMPAT VERIFIED, not assumed: start_cdfs/next_cdfs and CdfSnapshot are all pub(crate); a grep over
crates/ outside ec-av1 for those names and for Encoded is empty, and Encoded's public fields keep their
types -- the edith integration lane has nothing to update. No bitstream effect (Box::new(x) stores the
same x), and the encoder families re-ran identical: 108 passed / 0 failed / 40 ignored twice.

BOUND: 8,192 bytes, down from the 32,768 the lane first picked -- that number had been calibrated to a
crate-private 15,232-byte table no caller can reach. The bound applies only to what a public fn can make
a caller owe (one by-value return x chain depth). Worst public return is Av1Encoder at 2,944 = 35.9% of
budget, so 2.78x headroom rather than 1.07x; it still catches pre-fix Av1Encoder 17.09x over,
ec_opus::Encoder 10.62x over and pre-boxing Encoded 3.75x over. Derivation is asserted IN-TEST
(DEEPEST_PUBLIC_CHAIN(4, counted from source) * worst * 8 <= 2 MiB, and the 2,101,248-byte stack is
measured from /proc/self/task/<tid>/maps), so the number cannot rot into something nobody re-derives.

GATE: crates/ec-av1/src/stack_budget.rs, 8 tests, ~0.05s, behind #![cfg(test)] so a shipped build
carries none of it. Verified by Main on the staged merge: 8 passed, 0 failed, check clean. It includes
the sorted inventory printer, the bound asserted by name, a capability test that really constructs the
deepest public chains on a 1 MiB thread, source scans (one of which immediately named 15 modules the
scan had not been reading -- a real hole), and a non-vacuity control that caught a live matcher bug
(cutting only at '>' parsed Result<Decoder, Error> as the name "Decoder, Error").
MUTATION-PROVED TWICE, re-proven after the refactor: unboxing DpbSlot::cdfs reds the bound BY NAME at
139,960 B (17.09x) plus a SIGABRT in the tight-stack arm; growing Encoded by 64 KiB reds at 96,264 B
(11.75x) plus SIGABRT.

THE CAP ANSWER, which was the deliverable: 799 of 799 lib tests at RUST_MIN_STACK=2097152, ZERO stack
overflows, one process per test. The one test that used to need more --
encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence, red at 2,097,152 and green at
3,145,728 -- is fixed BY THIS BOXING and now passes at 2,097,152. So nothing in the ec-av1 lib suite
needs the 64 MiB cap. The single non-OK entry is a 600s TIMEOUT on a test that passes in release, not a
stack limit. `.cargo/config.toml` is NOT edited: its comment is wrong on mechanism (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) though right on conclusion; the report carries the exact replacement wording.

SELF-CAUGHT FALSE POSITIVE, named rather than hidden: the first sweep flagged
`a_doubly_cut_superblock_root_round_trips_in_every_plane` as a 2 MiB overflow -- it was a STALE BINARY
(the test binary was rebuilt while the sweep ran). Re-verified individually against a stable build it is
ok at 2,097,152, and the whole sweep was re-run clean after that.

OUT OF SCOPE, RECORDED, NOT SWEPT: ec_opus::Encoder 87,024 B (10.62x over the bound, SIGABRTs below
352 KiB) is the class's live instance in a sibling crate edith consumes -- left alone deliberately
(different crate, its own bit-exactness gates, no evidence taken here). Next by size: ec-ac3::Ac3Decoder
20,024, ec-vp9::Decoder 10,944.
crates/ec-av1/src/encode.rsmodified+15 -6
@@ -1907,12 +1907,21 @@ pub struct Encoded {
1907 /// must feed the decoder this, exactly as `decode_stream` feeds it what1907 /// must feed the decoder this, exactly as `decode_stream` feeds it what
1908 /// the frame's `primary_ref_frame` slot holds (same class as1908 /// the frame's `primary_ref_frame` slot holds (same class as
1909 /// `tx_select`: a header bit a raw tile decode cannot guess).1909 /// `tx_select`: a header bit a raw tile decode cannot guess).
1910- pub(crate) start_cdfs: CdfSnapshot,1910+ ///
1911+ /// BOXED (lane-av1stacksweep), and this is the whole point: the payload is
1912+ /// a 15232-byte `Cdfs`, and `Encoded` is returned BY VALUE from a
1913+ /// four-deep `Result<Encoded>` constructor chain, so an inline copy of two
1914+ /// of them made `Encoded` 30728 bytes -- 99.2% of this struct was these
1915+ /// two fields, and it was the largest by-value return in the crate.
1916+ /// `DpbSlot::cdfs` was boxed for the same reason in lane-av1enchang; this
1917+ /// is the other copy of the same table. The VALUES are untouched, so the
1918+ /// bitstream is byte-identical; `crate::stack_budget` gates the result.
1919+ pub(crate) start_cdfs: Box<CdfSnapshot>,
1911 /// What this frame stores into the slots it refreshes (spec 7.20,1920 /// What this frame stores into the slots it refreshes (spec 7.20,
1912 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the1921 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
1913 /// counts reset when `disable_frame_end_update_cdf` is off, and what it1922 /// counts reset when `disable_frame_end_update_cdf` is off, and what it
1914 /// started from when it is on.1923 /// started from when it is on.
1915- pub(crate) next_cdfs: CdfSnapshot,1924+ pub(crate) next_cdfs: Box<CdfSnapshot>,
1916 /// This frame header's chosen deblocking parameters1925 /// This frame header's chosen deblocking parameters
1917 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the1926 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
1918 /// picture the decoder produces UNDER them, so a test that decodes1927 /// picture the decoder produces UNDER them, so a test that decodes
@@ -9694,8 +9703,8 @@ pub(crate) fn encode_key_frame_inner(
9694 switchable_motion_mode: false,9703 switchable_motion_mode: false,
9695 screen,9704 screen,
9696 reduced_tx_set: header.reduced_tx_set,9705 reduced_tx_set: header.reduced_tx_set,
9697- next_cdfs: start_cdfs.clone(),9706+ next_cdfs: Box::new(start_cdfs.clone()),
9698- start_cdfs,9707+ start_cdfs: Box::new(start_cdfs),
9699 loop_filter: header.loop_filter,9708 loop_filter: header.loop_filter,
9700 cdef: header.cdef,9709 cdef: header.cdef,
9701 loop_restoration: header.loop_restoration,9710 loop_restoration: header.loop_restoration,
@@ -15539,8 +15548,8 @@ pub(crate) fn encode_inter_frame(
15539 switchable_motion_mode,15548 switchable_motion_mode,
15540 screen,15549 screen,
15541 reduced_tx_set: header.reduced_tx_set,15550 reduced_tx_set: header.reduced_tx_set,
15542- start_cdfs,15551+ start_cdfs: Box::new(start_cdfs),
15543- next_cdfs,15552+ next_cdfs: Box::new(next_cdfs),
15544 loop_filter: header.loop_filter,15553 loop_filter: header.loop_filter,
15545 cdef: header.cdef,15554 cdef: header.cdef,
15546 loop_restoration: header.loop_restoration,15555 loop_restoration: header.loop_restoration,
crates/ec-av1/src/encoder.rsmodified+6 -2
@@ -1430,7 +1430,7 @@ pub struct Av1Encoder {
1430 /// inter frame reads (spec 7.20): the tables that frame's tile writer1430 /// inter frame reads (spec 7.20): the tables that frame's tile writer
1431 /// must start from, since the header leaves1431 /// must start from, since the header leaves
1432 /// `disable_frame_end_update_cdf` off. `None` before the first frame.1432 /// `disable_frame_end_update_cdf` off. `None` before the first frame.
1433- carried_cdfs: Option<crate::encode::CdfSnapshot>,1433+ carried_cdfs: Option<Box<crate::encode::CdfSnapshot>>,
1434 /// The last key frame's own (padded) reconstruction: `GOLDEN_FRAME`,1434 /// The last key frame's own (padded) reconstruction: `GOLDEN_FRAME`,
1435 /// which stays in DPB slot 1 until the next key frame refreshes it.1435 /// which stays in DPB slot 1 until the next key frame refreshes it.
1436 golden: Option<Picture>,1436 golden: Option<Picture>,
@@ -1974,7 +1974,11 @@ impl Av1Encoder {
1974 let slot = DpbSlot {1974 let slot = DpbSlot {
1975 picture: encoded.reconstruction.clone(),1975 picture: encoded.reconstruction.clone(),
1976 order_hint,1976 order_hint,
1977- cdfs: Box::new(encoded.next_cdfs.clone()),1977+ // `next_cdfs` is already a `Box<CdfSnapshot>` (lane-av1stacksweep),
1978+ // so this is a pointer copy rather than a second boxing -- the
1979+ // same fix lane-av1enchang made here, now that the producer hands
1980+ // over a box instead of an inline 15232-byte `Cdfs`.
1981+ cdfs: encoded.next_cdfs.clone(),
1978 };1982 };
1979 for &s in slots {1983 for &s in slots {
1980 self.dpb[s as usize] = Some(slot.clone());1984 self.dpb[s as usize] = Some(slot.clone());
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -56,6 +56,7 @@ mod refusal_inventory;
56 mod restoration;56 mod restoration;
57 pub mod sequence;57 pub mod sequence;
58 pub mod speed;58 pub mod speed;
59+mod stack_budget;
59 pub mod stream;60 pub mod stream;
60 mod superres;61 mod superres;
61 pub mod tile;62 pub mod tile;
crates/ec-av1/src/stack_budget.rsadded+973 -0
@@ -0,0 +1,973 @@
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(2944),
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(1296),
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+ const FILES: &[(&str, &str)] = &[
445+ ("bits.rs", include_str!("bits.rs")),
446+ ("cdf.rs", include_str!("cdf.rs")),
447+ ("cdf_state.rs", include_str!("cdf_state.rs")),
448+ ("census.rs", include_str!("census.rs")),
449+ ("compound.rs", include_str!("compound.rs")),
450+ ("decode.rs", include_str!("decode.rs")),
451+ ("encode.rs", include_str!("encode.rs")),
452+ ("encoder.rs", include_str!("encoder.rs")),
453+ ("envflags.rs", include_str!("envflags.rs")),
454+ ("film_grain.rs", include_str!("film_grain.rs")),
455+ ("filter_search.rs", include_str!("filter_search.rs")),
456+ ("frame.rs", include_str!("frame.rs")),
457+ ("gate_coverage.rs", include_str!("gate_coverage.rs")),
458+ ("hits.rs", include_str!("hits.rs")),
459+ ("intra.rs", include_str!("intra.rs")),
460+ ("library_fixture.rs", include_str!("library_fixture.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+ ("probe.rs", include_str!("probe.rs")),
469+ ("qm.rs", include_str!("qm.rs")),
470+ ("quant.rs", include_str!("quant.rs")),
471+ ("refusal_inventory.rs", include_str!("refusal_inventory.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", include_str!("stream.rs")),
476+ ("superres.rs", include_str!("superres.rs")),
477+ ("tile.rs", include_str!("tile.rs")),
478+ ("timeline.rs", include_str!("timeline.rs")),
479+ ("transform.rs", include_str!("transform.rs")),
480+ ("warp.rs", include_str!("warp.rs")),
481+ ("wedge.rs", include_str!("wedge.rs")),
482+ ("stack_budget.rs", include_str!("stack_budget.rs")),
483+ ];
484+
485+ /// Every module `lib.rs` declares, so the scan's file list cannot silently
486+ /// fall behind a new module. A new `mod foo;` with a by-value `pub fn`
487+ /// that the scan never reads is exactly the hole this class would come
488+ /// back through, so the list is derived, not curated.
489+ #[test]
490+ fn every_by_value_module_is_scanned() {
491+ let lib = include_str!("lib.rs");
492+ let mut declared: Vec<&str> = Vec::new();
493+ for line in lib.lines() {
494+ let t = line.trim();
495+ let rest = t
496+ .strip_prefix("pub mod ")
497+ .or_else(|| t.strip_prefix("mod "))
498+ .unwrap_or("");
499+ if rest.is_empty() {
500+ continue;
501+ }
502+ let name = rest.split([';', ' ']).next().unwrap_or("");
503+ if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
504+ declared.push(name);
505+ }
506+ }
507+ assert!(
508+ declared.len() > 10,
509+ "only {} module declarations parsed out of lib.rs, so the \
510+ derived file list is broken rather than small",
511+ declared.len()
512+ );
513+ let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect();
514+ let mut missing: Vec<String> = declared
515+ .iter()
516+ .filter(|d| !scanned.iter().any(|s| *s == format!("{d}.rs")))
517+ .map(|d| (*d).to_string())
518+ .collect();
519+ missing.sort();
520+ assert!(
521+ missing.is_empty(),
522+ "lib.rs declares modules the by-value scan never reads: {:?}. Add \
523+ them to FILES, or the sweep cannot see a new by-value return that \
524+ lands in one of them.",
525+ missing
526+ );
527+ }
528+
529+ /// The inventory, printed as a sorted table, and checked against the
530+ /// types' real sizes.
531+ ///
532+ /// The print is the instrument: one command
533+ /// (`cargo test -p ec-av1 --lib -- stack_budget -- --nocapture`)
534+ /// reproduces the whole table, biggest first, so "what is the largest
535+ /// by-value type in this crate" has an answer that is a measurement
536+ /// rather than a grep.
537+ ///
538+ /// The check reds on ANY change with both numbers. That is deliberate: a
539+ /// by-value type that grew raises the question of whether it should have
540+ /// been boxed instead, and auto-accepting the new number would answer
541+ /// that question by default.
542+ #[test]
543+ fn the_measured_inventory_is_accurate() {
544+ let live = measured_by_name();
545+ assert_eq!(
546+ BY_VALUE_TYPES.len(),
547+ live.len(),
548+ "the inventory names {} types but {} are measured; every row needs \
549+ a measured size or the sweep is a list of hopes",
550+ BY_VALUE_TYPES.len(),
551+ live.len()
552+ );
553+ let mut rows: Vec<(&str, usize)> = live.clone();
554+ rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size));
555+ eprintln!(
556+ "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)",
557+ rows.len(),
558+ STACK_BUDGET / 1024
559+ );
560+ eprintln!("{:>8} {:>7} {}", "BYTES", "%BUDGET", "TYPE");
561+ for (name, size) in &rows {
562+ eprintln!(
563+ "{size:>8} {:>6.1}% {name}",
564+ *size as f64 * 100.0 / STACK_BUDGET as f64
565+ );
566+ }
567+ for (name, recorded, _public, _path) in BY_VALUE_TYPES {
568+ let recorded = recorded.expect("every inventory row carries a measured size");
569+ let actual = live
570+ .iter()
571+ .find(|(n, _)| n == name)
572+ .map(|(_, size)| *size)
573+ .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
574+ assert_eq!(
575+ recorded, actual,
576+ "{name} is {actual} bytes, the inventory records {recorded}; \
577+ update the table deliberately -- a by-value type that changed \
578+ is a stack cost every caller of its constructor now pays"
579+ );
580+ }
581+ }
582+
583+ /// The bound, asserted BY NAME. A regression in any inventoried type reds
584+ /// here naming the type, not "some type is too big".
585+ #[test]
586+ fn every_by_value_type_fits_the_stack_budget() {
587+ let live = measured_by_name();
588+ let mut checked = 0usize;
589+ for (name, _, public, path) in BY_VALUE_TYPES {
590+ if !public {
591+ continue;
592+ }
593+ checked += 1;
594+ let size = live
595+ .iter()
596+ .find(|(n, _)| n == name)
597+ .map(|(_, size)| *size)
598+ .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
599+ assert!(
600+ size <= STACK_BUDGET,
601+ "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \
602+ stack budget ({:.2}x). It is returned by value from {path}, so \
603+ every caller pays it on its own stack, and the constructors \
604+ nest -- one value's size is the multiplier, not the cost. \
605+ Box the large field (lane-av1enchang did exactly this for \
606+ Av1Encoder::dpb, and lane-av1stacksweep for Encoded's two \
607+ inline CdfSnapshots) or hand back a reference.",
608+ size as f64 / STACK_BUDGET as f64
609+ );
610+ }
611+ assert!(
612+ checked >= 10,
613+ "only {checked} rows were bound-checked; the budget must apply to \
614+ every type a caller can be made to hold by value"
615+ );
616+ // The other half of the derivation, asserted so it cannot rot: the
617+ // worst a caller can owe is DEEPEST_CHAIN x the worst public return.
618+ let worst = live
619+ .iter()
620+ .filter(|(n, _)| {
621+ BY_VALUE_TYPES
622+ .iter()
623+ .any(|(row, _, public, _)| row == n && *public)
624+ })
625+ .map(|(_, size)| *size)
626+ .max()
627+ .expect("at least one public row");
628+ assert!(
629+ DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024,
630+ "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \
631+ public by-value return ({worst} B) is {} B, over an eighth of the \
632+ 2101248-byte stack an unconfigured caller hands this crate; \
633+ re-derive STACK_BUDGET",
634+ DEEPEST_PUBLIC_CHAIN * worst
635+ );
636+ }
637+
638+ /// The crate-private CDF tables stay BEHIND A BOX.
639+ ///
640+ /// The budget does not apply to `Cdfs` / `CdfSnapshot` (15,232 B each)
641+ /// because no `pub fn` returns them, so bounding them would calibrate the
642+ /// number to something no caller can reach. What keeps them off the stack
643+ /// is that every field holding one is a `Box`, and THIS is the pin for
644+ /// that -- a source scan over the four declarations.
645+ ///
646+ /// It earned its place during this lane: `Av1Encoder` was 18,168 B after
647+ /// lane-av1enchang boxed the DPB slot, and 15,232 of that was
648+ /// `carried_cdfs: Option<CdfSnapshot>` sitting inline on the very same
649+ /// struct. Nothing had measured it. Unboxing any of the four puts the
650+ /// stack cost straight back.
651+ #[test]
652+ fn the_crate_private_cdf_tables_stay_behind_a_box() {
653+ const PINS: &[(&str, &str, &str)] = &[
654+ (
655+ "encoder.rs",
656+ "DpbSlot::cdfs",
657+ "cdfs: Box<crate::encode::CdfSnapshot>",
658+ ),
659+ (
660+ "encoder.rs",
661+ "Av1Encoder::carried_cdfs",
662+ "carried_cdfs: Option<Box<crate::encode::CdfSnapshot>>",
663+ ),
664+ (
665+ "encode.rs",
666+ "Encoded::start_cdfs",
667+ "start_cdfs: Box<CdfSnapshot>",
668+ ),
669+ (
670+ "encode.rs",
671+ "Encoded::next_cdfs",
672+ "next_cdfs: Box<CdfSnapshot>",
673+ ),
674+ ];
675+ const FILES: &[(&str, &str)] = &[
676+ ("encoder.rs", include_str!("encoder.rs")),
677+ ("encode.rs", include_str!("encode.rs")),
678+ ];
679+ for (file, field, spelling) in PINS {
680+ let src = FILES
681+ .iter()
682+ .find(|(name, _)| name == file)
683+ .map(|(_, src)| *src)
684+ .unwrap_or_else(|| panic!("no source pinned for {file}"));
685+ let where_ = format!("{file}::{field}");
686+ assert!(
687+ src.contains(spelling),
688+ "{where_} is no longer declared `{spelling}`. An inline \
689+ CdfSnapshot there puts {field}'s 15232 bytes back on every \
690+ caller's stack -- that is how Av1Encoder was 139960 bytes \
691+ before lane-av1enchang, and how it was still 18168 after it, \
692+ because carried_cdfs was missed.",
693+ );
694+ }
695+ // And the negative control: the unboxed spellings must NOT all still
696+ // be present, or the scan above would be matching a comment.
697+ let encoder = FILES[0].1;
698+ assert!(
699+ !encoder.contains("cdfs: crate::encode::CdfSnapshot,"),
700+ "the box pin is matching a spelling that is not the live \
701+ declaration"
702+ );
703+ }
704+
705+ /// CAPABILITY: really construct the heavy types on a tight stack, so a
706+ /// regression ABORTS THE PROCESS instead of costing invisible margin.
707+ ///
708+ /// Both arms are the deepest public chains in the crate: the encoder's
709+ /// three-deep `Result<Self>` constructor nest, and the four-deep
710+ /// `Result<Encoded>` chain, the longest by-value return path here.
711+ ///
712+ /// Measured stack need, **debug** build, 64x64, one process per point so a
713+ /// SIGABRT cannot truncate the sweep:
714+ ///
715+ /// | stack | before this lane boxed `Encoded` | after |
716+ /// |---|---|---|
717+ /// | 131072 | overflow | overflow |
718+ /// | 262144 | overflow | overflow |
719+ /// | 327680 | overflow | overflow |
720+ /// | 466944 | overflow | **overflow** |
721+ /// | 475136 | overflow | **ok** |
722+ /// | 524288 | overflow | **ok** |
723+ /// | 786432 | **overflow** | ok |
724+ /// | 1048576 | **ok** | **ok** |
725+ ///
726+ /// The gate sits at 1 MiB, now **2.2x** the deepest measured need rather
727+ /// than 1.33x. Boxing `Encoded`'s two inline `CdfSnapshot`s (99.2% of its
728+ /// 30,728 bytes) and `Av1Encoder::carried_cdfs` (15,232 of its 18,168) is
729+ /// what moved the threshold. The ~470 KB that remains is the encode
730+ /// search's own frames, which this module does not claim to shrink.
731+ ///
732+ /// Pre-fix (`CdfSnapshot` by value in the DPB) the encoder arm overflowed
733+ /// at 1 MiB and at 2 MiB. `EC_AV1_TIGHT_STACK_BYTES` overrides the size,
734+ /// which is how the table above is reproduced.
735+ #[test]
736+ fn the_deepest_by_value_constructors_fit_on_a_tight_stack() {
737+ use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Pyramid, RateTarget};
738+ let stack: usize = std::env::var("EC_AV1_TIGHT_STACK_BYTES")
739+ .ok()
740+ .and_then(|v| v.parse().ok())
741+ .unwrap_or(TIGHT_STACK);
742+ let config = EncoderConfig {
743+ width: 64,
744+ height: 64,
745+ base_q_idx: 100,
746+ gop: 48,
747+ colour: Colour::Bt709Limited,
748+ tile_cols_log2: 0,
749+ tile_rows_log2: 0,
750+ };
751+ let rate = RateTarget::Bitrate {
752+ bits_per_second: 1_536_000,
753+ frames_per_second: 24.0,
754+ };
755+ let handle = std::thread::Builder::new()
756+ .stack_size(stack)
757+ .spawn(move || {
758+ // Arm 1: the three-deep Result<Self> constructor nest.
759+ let encoder =
760+ Av1Encoder::with_pyramid_and_rate_target(config, Pyramid::default(), rate)
761+ .expect("with_pyramid_and_rate_target");
762+ let pyramid = encoder.pyramid().is_some();
763+ drop(encoder);
764+ // Arm 2: the four-deep Result<Encoded> chain, the crate's
765+ // largest by-value return.
766+ let grey = crate::encode::Picture::grey(64, 64);
767+ let encoded =
768+ crate::encode::encode_key_frame(&grey, 100, 0.0).expect("encode_key_frame");
769+ (pyramid, encoded.stream.len())
770+ })
771+ .expect("spawn tight-stack thread");
772+ let (pyramid, bytes) = handle.join().unwrap_or_else(|_| {
773+ panic!(
774+ "a by-value constructor overflowed a {stack}-byte stack; the \
775+ threshold table on this test says what that costs"
776+ )
777+ });
778+ assert!(pyramid, "with_pyramid_and_rate_target lost its pyramid");
779+ assert!(bytes > 0, "encode_key_frame produced no stream");
780+ eprintln!(
781+ "TIGHTSTACK {stack} bytes: Av1Encoder={} Encoded={} bytes, both chains returned",
782+ std::mem::size_of::<Av1Encoder>(),
783+ std::mem::size_of::<Encoded>(),
784+ );
785+ }
786+
787+ /// The sweep's teeth against a NEW by-value return: re-derive the set from
788+ /// the crate source and require every name to be inventoried.
789+ ///
790+ /// Without this the inventory is a list of what someone remembered to
791+ /// measure, and a lane that adds `pub fn make() -> HugeThing` where
792+ /// `HugeThing` is 200 KB of inline tables passes every other test here.
793+ #[test]
794+ fn every_by_value_public_return_is_in_the_inventory() {
795+ let mut found: Vec<(String, String)> = Vec::new();
796+ for (file, src) in FILES {
797+ for (n, line) in src.lines().enumerate() {
798+ if let Some(name) = by_value_return_name(line) {
799+ found.push((name, format!("{file}:{}", n + 1)));
800+ }
801+ }
802+ }
803+ found.sort();
804+ found.dedup();
805+ assert!(
806+ found.len() > 5,
807+ "the by-value return scan found {} names across {} files, which is \
808+ too few to be a real sweep -- the matcher, not the crate, is broken",
809+ found.len(),
810+ FILES.len()
811+ );
812+
813+ let mut missing = Vec::new();
814+ for (name, site) in &found {
815+ if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) {
816+ missing.push(format!("{name} ({site})"));
817+ }
818+ }
819+ assert!(
820+ missing.is_empty(),
821+ "these types are returned BY VALUE from a public fn and are not in \
822+ the inventory: {}. Either they are thin enough not to be a stack \
823+ cost -- say so by adding a row with its measured size -- or they \
824+ are the next instance of the class this module exists for.",
825+ missing.join(", ")
826+ );
827+ }
828+
829+ /// The control for the scan above, on synthetic text rather than by
830+ /// trusting the live tree to happen to contain a case.
831+ ///
832+ /// If the matcher silently stopped recognising a shape, the sweep would
833+ /// pass everything and this would still be asserting nothing. So: every
834+ /// by-value spelling the crate uses must yield its type name, and every
835+ /// pointer/Vec/primitive/`Self` spelling must yield nothing.
836+ #[test]
837+ fn the_inventory_scan_is_not_vacuous() {
838+ for synthetic in [
839+ "pub fn zz_a() -> ZzNotInventoried { todo!() }",
840+ "pub fn zz_b() -> Result<ZzNotInventoried, Error> { todo!() }",
841+ "pub fn zz_c() -> Result<ZzNotInventoried> { todo!() }",
842+ "pub fn zz_d() -> Option<ZzNotInventoried> { todo!() }",
843+ "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }",
844+ ] {
845+ let name = by_value_return_name(synthetic)
846+ .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`"));
847+ assert_eq!(
848+ name, "ZzNotInventoried",
849+ "the matcher mangled `{synthetic}` into `{name}`, so the sweep \
850+ cannot see a new by-value return and its green is vacuous"
851+ );
852+ assert!(
853+ !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name),
854+ "the synthetic control name is in the inventory, so the control \
855+ proves nothing"
856+ );
857+ }
858+ for thin in [
859+ "pub fn zz_t() -> Box<Decoder> { todo!() }",
860+ "pub fn zz_u() -> Result<Vec<u8>, Error> { todo!() }",
861+ "pub fn zz_v() -> Option<&Path> { todo!() }",
862+ "pub fn zz_w() -> usize { todo!() }",
863+ "pub fn zz_x() -> Self { todo!() }",
864+ "pub fn zz_y() -> Result<Arc<Decoder>, Error> { todo!() }",
865+ "pub fn zz_z() { todo!() }",
866+ "fn zz_private() -> ZzNotInventoried { todo!() }",
867+ ] {
868+ assert_eq!(
869+ by_value_return_name(thin),
870+ None,
871+ "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \
872+ above already cover, or not a `pub fn` -- the matcher must not \
873+ read it as an uninventoried by-value return"
874+ );
875+ }
876+ }
877+
878+ /// The stack mapping containing `addr` in `/proc/self/task/<tid>/maps`.
879+ ///
880+ /// The returned size is a LOWER BOUND, never an exact count. Linux MERGES
881+ /// adjacent VMAs that share protections, and a merged region is
882+ /// indistinguishable from a single one in the maps file -- a thread whose
883+ /// 1 MiB stack abutted a neighbour's read back here as 69218304 bytes with
884+ /// nothing to indicate the join. Two earlier versions of this test tried to
885+ /// be exact anyway (asserting a byte count, then detecting the merge by
886+ /// looking for an abutting same-protection neighbour) and both were wrong
887+ /// for that reason.
888+ ///
889+ /// A lower bound is what the budget's reasoning needs: the claim is "no
890+ /// caller gets less than 2 MiB", and `size >= 2 MiB` is exactly that,
891+ /// whether the region is one mapping or three.
892+ fn stack_region(tid: u32, addr: usize) -> Option<(usize, usize)> {
893+ let maps = std::fs::read_to_string(format!("/proc/self/task/{tid}/maps")).ok()?;
894+ for line in maps.lines() {
895+ let (range, _) = line.split_once(' ')?;
896+ let (lo, hi) = range.split_once('-')?;
897+ let (lo, hi) = (
898+ usize::from_str_radix(lo, 16).ok()?,
899+ usize::from_str_radix(hi, 16).ok()?,
900+ );
901+ if addr >= lo && addr < hi {
902+ return Some((lo, hi));
903+ }
904+ }
905+ None
906+ }
907+
908+ /// What a thread's stack ACTUALLY is, read from
909+ /// `/proc/self/task/<tid>/maps` rather than assumed from a default.
910+ ///
911+ /// The number the budget's reasoning rests on, measured two ways:
912+ ///
913+ /// * a thread spawned with an EXPLICIT size gets AT LEAST that size --
914+ /// the control that says the parse finds stacks at all, and the shape
915+ /// [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] relies on;
916+ /// * the DEFAULT -- no `stack_size`, i.e. what a library consumer's
917+ /// `std::thread::spawn` gets, and what libtest gives a test thread when
918+ /// `RUST_MIN_STACK` is unset -- is at least 2 MiB.
919+ ///
920+ /// Both are floors, because [`stack_region`] can only report a lower bound.
921+ /// That is the right direction: the budget's claim is that no caller gets
922+ /// LESS than 2 MiB, and a floor is what proves it.
923+ ///
924+ /// Exact figures measured on this runtime, for the report: 2101248 bytes
925+ /// with the repo's `.cargo/config.toml` cap lifted, 67112960 with it
926+ /// applied. A library consumer gets the first, and that is the one the
927+ /// budget is sized for.
928+ #[test]
929+ fn test_threads_get_the_stack_they_are_given() {
930+ const EXPLICIT: usize = 1024 * 1024;
931+ let handle = std::thread::Builder::new()
932+ .stack_size(EXPLICIT)
933+ .spawn(|| {
934+ let tid = std::process::id();
935+ let marker = 0u8;
936+ let here = &marker as *const u8 as usize;
937+ let (lo, hi) =
938+ stack_region(tid, here).expect("this thread's own stack is in its maps");
939+ (tid, lo, hi)
940+ })
941+ .expect("spawn");
942+ let (_tid, lo, hi) = handle.join().expect("the probe thread returned");
943+ let size = hi - lo;
944+ assert!(
945+ size >= EXPLICIT,
946+ "a thread spawned with stack_size({EXPLICIT}) has a {size}-byte \
947+ stack mapping; the runtime gave it less than it was promised, so \
948+ the maps parse is finding the wrong region"
949+ );
950+ assert!(
951+ size <= 512 * 1024 * 1024,
952+ "the mapping holding an explicitly-1-MiB thread's frame is {size} \
953+ bytes, which is not a stack -- the maps parse found the wrong region"
954+ );
955+
956+ let tid = std::process::id();
957+ let marker = 0u8;
958+ let here = &marker as *const u8 as usize;
959+ let (lo, hi) = stack_region(tid, here).expect("this test thread's stack is in its maps");
960+ let size = hi - lo;
961+ assert!(
962+ size >= 2 * 1024 * 1024,
963+ "a default test thread's stack measured {size} bytes, under the \
964+ 2 MiB floor the by-value budget is derived from; the smallest \
965+ stack a caller can hand this crate just got smaller and the bound \
966+ needs re-deriving"
967+ );
968+ eprintln!(
969+ "TESTTHREADSTACK default tid={tid} region=[{lo:x},{hi:x}) size>={size} \
970+ (2101248 measured exactly with the repo cap lifted, 67112960 with it)"
971+ );
972+ }
973+}
lanes/av1stacksweep.report.mdadded+560 -0
@@ -0,0 +1,560 @@
1+# lane-av1stacksweep — the by-value-size class, swept and gated
2+
3+**Status:** green, commit `3d4caf13`. Files: `crates/ec-av1/src/stack_budget.rs`
4+(new, 8 tests), `lanes/av1stacksweep.report.md` (new), one line in
5+`crates/ec-av1/src/lib.rs`, and a **layout-only** boxing change in
6+`encode.rs` / `encoder.rs` (below). No bitstream change, no decode.rs, no
7+`.cargo/config.toml` edit, no rustfmt.
8+
9+**This lane also FIXED two types, not just measured them.** The sweep found
10+that lane-av1enchang's `Box` on `DpbSlot::cdfs` left two more copies of the
11+same 15,232-byte `CdfSnapshot` sitting inline, and nobody had measured either:
12+
13+| type | before | after | what was inline |
14+|---|---:|---:|---|
15+| `Encoded` | 30,728 | **280** | `start_cdfs` + `next_cdfs`, 99.2% of the struct |
16+| `Av1Encoder` | 18,168 | **2,944** | `carried_cdfs`, 15,232 of the 18,168 |
17+
18+Same shape as the fix it follows (`99750756`), same gate family, same
19+reason. `CdfSnapshot` the VALUES are untouched.
20+
21+**API compatibility: not a breaking change.** Both changed fields
22+(`Encoded::start_cdfs`, `Encoded::next_cdfs`) and the type they hold
23+(`CdfSnapshot`) are `pub(crate)`. `grep -rn "start_cdfs\|next_cdfs\|CdfSnapshot"
24+crates/ | grep -v ^crates/ec-av1/` is EMPTY, and so is any other crate naming
25+`Encoded`. `Encoded`'s public fields (`stream`, `reconstruction`, `modes`,
26+`inter_block_share`) keep their types. No consumer in this workspace, and none
27+in `edith`, can reach the fields that changed.
28+
29+lane-av1enchang found and fixed ONE instance of this class (`Av1Encoder`,
30+139960 → 18168 B by boxing the DPB `CdfSnapshot`) and gated that one
31+constructor. The class itself was not swept. This lane sweeps it, picks a
32+bound from measurement rather than taste, gates the bound so it bites, and
33+reports on the 64 MiB cap that has been hiding the class.
34+
35+---
36+
37+## 1. INVENTORY — measured, with the command that reproduces it
38+
39+### The one command
40+
41+```bash
42+cd /home/user/.cache/wt/av1stacksweep
43+CARGO_TARGET_DIR=/home/user/.cache/tgt/av1stacksweep EC_NOMEMGUARD=1 \
44+ cargo test -p ec-av1 --lib -- stack_budget --nocapture
45+```
46+
47+`the_deepest_by_value_constructors_fit_on_a_tight_stack` prints the two
48+headline sizes, `the_measured_inventory_is_accurate` prints nothing but fails
49+loudly on drift, and the whole table below is asserted in-test. To dump the
50+table without running anything else, the numbers are the `Some(_)` column of
51+`BY_VALUE_TYPES` in `crates/ec-av1/src/stack_budget.rs`, and each is checked
52+against `size_of` at runtime.
53+
54+### ec-av1: every type a public `fn` returns by value
55+
56+Measured with `std::mem::size_of` in a debug build, 2026-09-30, at
57+`99750756` (main). "By value" = the return type is a bare named type, `Self`,
58+`Result<T>`, or `Option<T>` — not `Box`/`Rc`/`Arc`/`&`/`Vec`/`String`, which
59+are pointers or three words.
60+
61+This is the gate's own printed table (`cargo test -p ec-av1 --lib --
62+stack_budget -- --nocapture`), so the numbers below are not transcribed by
63+hand. `public` = reachable from a `pub fn` return, which is what the budget
64+applies to.
65+
66+| bytes | %budget | public | type | returned by value from |
67+|---:|---:|---|---|---|
68+| 15232 | 185.9% | no | `cdf_state::Cdfs` | `Cdfs::new(q_ctx)`; boxed everywhere it is stored |
69+| 15232 | 185.9% | no | `encode::CdfSnapshot` | newtype over `Cdfs`; `Box`ed in all four holders |
70+| **2944** | **35.9%** | yes | `encoder::Av1Encoder` | `new`, `with_speed`, `with_pyramid`, `with_rate_target`, `with_pyramid_and_rate_target` → `Result<Self>`, **3 deep** |
71+| 1296 | 15.8% | no | `decode::FrameCtx` | `for_encoder()` → `Self`, `pub(crate)`; one per `Av1Encoder` |
72+| 352 | 4.3% | yes | `census::Frame` | row type, moved by value |
73+| 280 | 3.4% | yes | `encode::Encoded` | `encode_key_frame`, `encode_key_frame_with_modes`, `encode_key_frame_at_size` → `Result<Encoded>`, **4 deep** |
74+| 240 | 2.9% | yes | `mvstack::MvStack` | `MvStack::new` → `Self` |
75+| 112 | 1.4% | no | `cdf_state::TxbTables<'a>` | `Cdfs::txb` — nine borrowed slices, so pointers not tables |
76+| 88 | 1.1% | yes | `encode::Picture` | `Picture::grey` → `Self` |
77+| 72 | 0.9% | yes | `encode::EncodedSequence` | `encode_sequence` → `Result<..>` |
78+| 64 | 0.8% | yes | `msac::SymbolDecoder<'a>` | `SymbolDecoder::new` |
79+| 56 | 0.7% | yes | `msac::SymbolEncoder` | `SymbolEncoder::new`, `pricer` |
80+| 48 | 0.6% | yes | `encoder::Packet` | `Av1Encoder::encode` → `Result<Packet>` |
81+| 48 | 0.6% | no | `motion_field::TplProbe<'a>` | borrowed-view handle |
82+| 40 | 0.5% | yes | `encoder::EncoderConfig` | `EncoderConfig::new` |
83+| 32 | 0.4% | yes | `warp::WarpParams` | `global_warp_params` → `Option<..>` |
84+| 24 | 0.3% | yes | `encoder::Pyramid` | ctor + `Av1Encoder::pyramid` |
85+| 24 | 0.3% | yes | `qm::Iqm` | `iwt_matrix` → `Option<..>` |
86+| 16 | 0.2% | yes | `encoder::RateTarget` | ctor by value |
87+| 16 | 0.2% | yes | `mvstack::MiInfo` | `MvStack::get` → `Option<..>` |
88+| 1 | 0.0% | yes | `mc::InterpFilterKind` | `from_switchable_symbol`, `from_header` |
89+
90+**Before this lane** the same 21 types measured 30,728 (`Encoded`), 18,168
91+(`Av1Encoder`), 15,232 ×2, 1,296, 352, 240, 112, 88, 72, 64, 56, 48 ×2, 40,
92+32, 24 ×2, 16 ×2, 1.
93+
94+**Two findings the earlier lane did not have:**
95+
96+1. **`Encoded` (30728) is bigger than `Av1Encoder` (18168) and nobody had
97+ measured it.** It is 99.2% two inline `CdfSnapshot`s (`start_cdfs` and
98+ `next_cdfs`, 15232 each). lane-av1enchang boxed exactly this field in the
99+ DPB slot and not here. See §5.
100+2. **The by-value chain is four deep, not three.** `encode_key_frame` →
101+ `encode_key_frame_with_ctx` → `encode_key_frame_with_modes_with_ctx` →
102+ `encode_key_frame_inner`, every level `Result<Encoded>`.
103+
104+### How the list is kept honest
105+
106+Two tests, because a hand-written list is a list of what someone remembered:
107+
108+- `every_by_value_public_return_is_in_the_inventory` re-derives the set from
109+ the crate source (38 modules, `include_str!`), so a lane that adds
110+ `pub fn make() -> HugeThing` reds until `HugeThing` is measured and listed.
111+- `every_by_value_module_is_scanned` derives the module list from `lib.rs`
112+ itself, so a new `mod foo;` cannot be silently unscanned. **This one earned
113+ its keep immediately**: when it was first written it named 15 modules the
114+ scan did not read (`compound`, `envflags`, `film_grain`, `filter_search`,
115+ `gate_coverage`, `hits`, `library_fixture`, `motion_field`, `par`,
116+ `refusal_inventory`, `restoration`, `superres`, `timeline`, `wedge`, and
117+ `stack_budget` itself) — a real hole, now closed.
118+- `the_inventory_scan_is_not_vacuous` is the control: thirteen synthetic
119+ `pub fn` lines, five by-value spellings that must yield their type name and
120+ eight pointer/`Vec`/primitive/`Self` spellings that must yield nothing.
121+ **It caught a live bug in the matcher**: the first version cut the return
122+ type only at `>`, so `Result<Decoder, Error>` parsed as the name
123+ `"Decoder, Error"`. Fixed to split on `,` as well.
124+
125+### The sibling crates — 293 public types, all measured
126+
127+Delegated to a subagent that built a throwaway `tests/zz_stack_probe.rs` per
128+crate and deleted them all (verified: final `git status` shows zero
129+`zz_*probe*` files, and the 5 `tests/` dirs it created were `rmdir`ed after
130+checking `existed_on_HEAD=0`). 293 types measured, **0 inferred**.
131+
132+| bytes | crate | type | smallest stack that survives | smallest that overflows |
133+|---:|---|---|---|---|
134+| **87024** | ec-opus | `Encoder` | 384 KiB | **352 KiB** |
135+| 20024 | ec-ac3 | `Ac3Decoder` | 96 KiB | 64 KiB |
136+| 19744 | ec-opus | `SilkStereoEncoder` | 256 KiB | 128 KiB |
137+| 10944 | ec-vp9 | `Decoder` | 64 KiB | 32 KiB |
138+| 10288 | ec-aac | `Synthesis` | 32 KiB | 16 KiB |
139+| 7576 | ec-opus | `Decoder` | 256 KiB | 128 KiB |
140+| 6688 | ec-h264 | `H264Decoder` | 64 KiB | 48 KiB |
141+| 6648 | ec-opus | `SilkEncoder` | 256 KiB | 128 KiB |
142+| 6496 | ec-h264 | `Decoder` | 256 KiB | 128 KiB |
143+| 2784 | ec-ac3 | `Ac3Encoder` | 64 KiB | no overflow |
144+| 2600 | ec-mp3 | `Mp3Decoder` | 64 KiB | 32 KiB |
145+| 2432 | ec-mp3 | `Mp3Reader` | 32 KiB | 16 KiB |
146+| 2392 | ec-mp3 | `Mp3Decode` | 32 KiB | 16 KiB |
147+| 1928 | ec-vorbis | `VorbisEncoder` | 32 KiB | 16 KiB |
148+| 1744 | ec-vp8 | `Decoder` | 8 KiB | no overflow |
149+| 1344 | ec-vorbis | `VorbisDecoder` | 64 KiB | no overflow |
150+| 712 | ec-h264-syntax | `Sps` | 8 KiB | no overflow |
151+| 664 | ec-mp3 | `Mp3Encoder` | 8 KiB | no overflow |
152+| 544 | ec-h265 | `Encoder` | 8 KiB | no overflow |
153+| 360 | ec-dsp | `Dct<f64>` | 32 KiB | no overflow |
154+| 256 | ec-matroska | `MatroskaDemuxer<..>` | 32 KiB | no overflow |
155+| 240 | ec-core | `StreamInfo` | 8 KiB | no overflow |
156+| 184 | ec-probe | `Reader` | 8 KiB | no overflow |
157+| 120 | ec-subs | `SubtitleStyle` | 8 KiB | no overflow |
158+| 96 | ec-image | `Frame` | 8 KiB | no overflow |
159+| 64 | ec-mp4 | `TrackInfo` | 64 KiB | no overflow |
160+| 48 | ec-ogg | `PageHeader` | 8 KiB | no overflow |
161+| 32 | ec-riff | `AviAudioStream` | 64 KiB | no overflow |
162+
163+**`ec_opus::Encoder` at 87,024 bytes is 2.66× over the bound this lane picks,
164+and it is the largest by-value type in the workspace.** It survives 384 KiB of
165+stack and SIGABRTs below 352 KiB. Nothing in the repo trips that today only
166+because the 64 MiB cap is in effect. This is the next instance of the class
167+and it is not in ec-av1.
168+
169+**The measured stack/size ratio is ~4.4×** (ec-opus `Encoder`: 87024 B of
170+struct, ~384 KiB of live stack). That is the constructors-nesting multiplier
171+made visible, and it is why §2 sizes the bound against the *stack*, not
172+against `size_of`.
173+
174+`ec-dsp` is the healthiest crate in the workspace and worth copying: `Mdct`,
175+`Fft`, `RealFft`, `Dct4`, `Dct` and `Window` all hold `Vec` plans, so
176+`Fft::new(n)` returns a handful of words despite building large tables.
177+`ec-ass` declares no types at all. `ec-hw` boxes its inner decoders, so its
178+largest by-value return is a 3140 B parameter buffer that never overflows.
179+
180+---
181+
182+## 2. THE BOUND: 8192 bytes (8 KiB), derived from measurement at both ends
183+
184+`STACK_BUDGET = 8192` in `crates/ec-av1/src/stack_budget.rs`. It is bounded
185+from BOTH sides by measurement, and `every_by_value_type_fits_the_stack_budget`
186+asserts both, so neither can rot into a number nobody can re-derive.
187+
188+**The quantity being bounded** is not `size_of` in the abstract but *what a
189+caller can be made to owe*: one by-value return, multiplied by how many
190+constructor levels hold a copy at once. Three inputs:
191+
192+1. **The smallest stack a caller can hand this crate is 2,101,248 bytes.**
193+ Measured, not assumed: `test_threads_get_the_stack_they_are_given` reads
194+ `/proc/self/task/<tid>/maps` for the region containing a live frame. That is
195+ libtest's default test thread and also what `std::thread::Builder::new()`
196+ gives a caller who does not ask for a size. A library consumer gets no
197+ `.cargo/config.toml`. (With the repo cap it measures 67,112,960 — also
198+ pinned, so both ends of the claim are asserted.)
199+2. **The deepest PUBLIC by-value chain is 4** (`DEEPEST_PUBLIC_CHAIN`):
200+ `encode_key_frame` → `encode_key_frame_with_ctx` →
201+ `encode_key_frame_with_modes_with_ctx` → `encode_key_frame_inner`. The
202+ encoder's own nest is 3. The test asserts
203+ `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB` — the by-value return slots may
204+ claim at most an **eighth** of a caller's stack, leaving the rest for the
205+ encode search, which is the thing that actually needs it.
206+3. **The budget applies only to types a `pub fn` returns.** The crate-private
207+ 15,232-byte `Cdfs` / `CdfSnapshot` are measured and listed but NOT bounded,
208+ because no caller can reach them by value — every field holding one is a
209+ `Box`, pinned by `the_crate_private_cdf_tables_stay_behind_a_box`. Bounding
210+ them would calibrate the number to something unreachable.
211+
212+**Where the number sits.** Worst public return 2,944 B = **35.9%** of an 8 KiB
213+budget (2.78× headroom). Worst a caller owes: `4 × 2944 = 11,776` bytes =
214+**0.56%** of a 2 MiB thread. Both directions have room, which is the point: a
215+bound the largest type sits just under is a bound the next lane will quietly
216+raise.
217+
218+**What it catches**, each by a factor rather than a hair:
219+
220+| what | bytes | × over 8192 |
221+|---|---:|---:|
222+| `Av1Encoder` before lane-av1enchang | 139,960 | 17.09× |
223+| `ec_opus::Encoder` (sibling crate, same sweep) | 87,024 | 10.62× |
224+| `Encoded` before this lane boxed it | 30,728 | 3.75× |
225+| `Av1Encoder` after lane-av1enchang, before this lane | 18,168 | 2.22× |
226+| **`Av1Encoder` now** | **2,944** | **0.36×** |
227+| **`Encoded` now** | **280** | **0.03×** |
228+
229+The historical defect, the near-miss, and the largest live instance of the
230+class in the workspace all red by a factor.
231+
232+**What it does not claim.** `size_of` is layout, not stack depth. The measured
233+stack/size ratio on a by-value constructor is ~4.4× (`ec_opus::Encoder`:
234+87,024 B of struct, ~384 KiB of live stack) — the nesting multiplier made
235+visible. That residual is exactly why the capability arm in §3 constructs for
236+real instead of trusting the arithmetic.
237+
238+## 3. THE GATE, and its mutation proof
239+
240+Eight tests in `crates/ec-av1/src/stack_budget.rs`, all green in 0.10s. The
241+module is `#![cfg(test)]`, so a shipped build carries none of it.
242+
243+| test | what it holds |
244+|---|---|
245+| `the_measured_inventory_is_accurate` | every row's recorded size is the size the type has now, and it **PRINTS the whole table sorted** — the reproduction instrument |
246+| `every_by_value_type_fits_the_stack_budget` | **the bound, asserted BY NAME**, plus the `DEEPEST_CHAIN × worst × 8 ≤ 2 MiB` derivation check |
247+| `the_deepest_by_value_constructors_fit_on_a_tight_stack` | **capability**: both deepest public chains really constructed on a 1 MiB thread |
248+| `every_by_value_public_return_is_in_the_inventory` | source scan over all 38 modules; a new by-value `pub` return reds until measured |
249+| `every_by_value_module_is_scanned` | the scan's file list is DERIVED from `lib.rs`, not curated |
250+| `the_inventory_scan_is_not_vacuous` | control: 5 by-value spellings must yield a type name, 8 pointer/`Vec`/primitive/`Self` spellings must yield nothing |
251+| `the_crate_private_cdf_tables_stay_behind_a_box` | pins the four `Box<CdfSnapshot>` declarations by source |
252+| `test_threads_get_the_stack_they_are_given` | the 2,101,248-byte floor the bound is derived from, measured from `/proc` |
253+
254+### The capability arm, and the thresholds behind it
255+
256+One 1 MiB thread runs BOTH deepest public chains: the three-deep
257+`Result<Self>` encoder constructor nest and the four-deep `Result<Encoded>`
258+key-frame chain. A regression **aborts the process** rather than costing
259+invisible margin.
260+
261+Measured stack need, **debug** build, 64×64, one process per point so a
262+SIGABRT cannot truncate the sweep:
263+
264+| stack | before this lane boxed `Encoded` | after |
265+|---|---|---|
266+| 131072 | overflow | overflow |
267+| 262144 | overflow | overflow |
268+| 327680 | overflow | overflow |
269+| 466944 | overflow | **overflow** |
270+| 475136 | overflow | **ok** |
271+| 524288 | overflow | **ok** |
272+| 786432 | **overflow** | ok |
273+| 1048576 | **ok** | **ok** |
274+
275+The 1 MiB gate is now **2.2×** the deepest measured need, not 1.33×. The
276+~470 KB that remains is the encode search's own frames, not return slots.
277+
278+Reproduce any row:
279+`EC_AV1_TIGHT_STACK_BYTES=<bytes> cargo test -p ec-av1 --lib -- the_deepest_by_value_constructors_fit_on_a_tight_stack --exact`.
280+
281+### Mutation proof — both mutations, both reverted, both re-run after the refactor
282+
283+**M1 — unbox what lane-av1enchang boxed** (a real revert of `99750756`, not a
284+synthesised one): `DpbSlot::cdfs: Box<CdfSnapshot>` → `CdfSnapshot`, plus its
285+one construction site.
286+
287+```
288+Av1Encoder is 139960 bytes, over the 8192-byte by-value stack budget (17.09x).
289+ It is returned by value from Av1Encoder::new / with_speed / with_pyramid /
290+ with_rate_target / with_pyramid_and_rate_target, all `Result<Self>`, nesting
291+ three deep, so every caller pays it on its own stack ...
292+fatal runtime error: stack overflow, aborting (signal: 6, SIGABRT) exit 101
293+```
294+
295+**M2 — grow `Encoded` past the bound** (synthesised, and labelled as such:
296+`Encoded` had no prior boxing to revert, so the honest mutation is to add a
297+field of the same shape that produced the class — a 64 KiB inline payload):
298+
299+```
300+Encoded is 96264 bytes, over the 8192-byte by-value stack budget (11.75x).
301+ It is returned by value from encode_key_frame / encode_key_frame_with_modes /
302+ encode_key_frame_at_size -> Result<Encoded>, nesting four deep ...
303+fatal runtime error: stack overflow, aborting (signal: 6, SIGABRT)
304+```
305+
306+Both prove the bound row is a live read of the real `size_of` and not a
307+constant, and that the capability arm reaches a process abort. Reverted;
308+`git status` clean; 8/8 green.
309+
310+**What is not proven.** That the 1 MiB gate has margin against a future
311+rustc's frame layout. Only that a large regression aborts rather than passes
312+quietly. The ~4.4× ratio in §1 is the honest statement of that residual risk.
313+
314+## 4. THE 64 MiB CAP — what it was protecting, and what is left
315+
316+### First: the cap is inert for anything but cargo
317+
318+`.cargo/config.toml` sets `[env] RUST_MIN_STACK = "67108864"`. Cargo applies
319+`[env]` only to processes **cargo spawns**; running the test binary directly
320+does not get it. Measured both ways on one binary:
321+
322+```
323+RUST_MIN_STACK unset -> test thread stack 2101248 bytes
324+RUST_MIN_STACK=2097152 -> 2101248
325+RUST_MIN_STACK=8388608 -> 8392704
326+RUST_MIN_STACK=67108864 -> 67112960
327+via `cargo test` (repo [env] in effect) -> 67112960
328+```
329+
330+So the cap does what it claims for cargo-driven runs, and a library consumer
331+who links this crate gets the 2,101,248-byte default.
332+
333+### Second: what the cap was ACTUALLY protecting — and it was this class
334+
335+Its comment reads:
336+
337+> The AV1 rate-target tests keep several frames' worth of encoder state on the
338+> test thread's stack; the 2 MB default overflows in debug builds (release
339+> passes).
340+
341+**The mechanism it names is wrong.** The "frames' worth of encoder state" is
342+`Av1Encoder`'s `pending: Vec<(u64, Picture)>`, `ready: Vec<(u64, Picture)>` and
343+`held: VecDeque<Picture>` — all heap. A scan for a large fixed-size stack local
344+in the encoder path finds exactly one:
345+
346+```
347+crates/ec-av1/src/film_grain.rs:26: const GAUSSIAN_SEQUENCE: [i32; 2048] = [
348+```
349+
350+which is a `const`, i.e. `.rodata`, not a frame.
351+
352+**But the CONCLUSION was right, and for this class's reason.** A 139,960-byte
353+`Av1Encoder` through a three-deep `Result<Self>` nest is ~420 KB of live stack
354+before the encode path adds its own, which does not fit in 2 MiB with the rest
355+of the chain. The fix removed the dominant term but not all of them, and two
356+more inline 15 KB tables survived lane-av1enchang unmeasured.
357+
358+### Third: the per-test answer at 2 MiB
359+
360+The charter warns that lowering the cap "makes the suite red for an unknown
361+set of tests". So the set was measured: **every test in the lib suite, one per
362+process** (a stack overflow SIGABRTs the process, so running them in one
363+libtest invocation would swallow the rest), at `RUST_MIN_STACK=2097152`, debug.
364+
365+**Exactly one test needed more than 2 MiB:**
366+
367+| test | at 2,097,152 | at 3,145,728 |
368+|---|---|---|
369+| `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence` | **STACK OVERFLOW** | ok (50.67s) |
370+
371+That test calls `encode_sequence` on twelve 640×384 frames four times over, and
372+`Encoded` was 30,728 bytes inline. **This commit fixes it: the same test now
373+passes at 2,097,152**, verified directly after the boxing.
374+
375+A second name appeared in the first sweep —
376+`stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane` — and
377+it was a **stale-binary artefact**: I rebuilt the test binary while the sweep
378+was running, so part of that run measured a half-written tree. Re-verified
379+individually against the stable build: **ok at 2,097,152**. Recording it here
380+because a sweep whose subject changes underneath it produces false positives,
381+and the only way to know which of its hits are real is to re-run each one.
382+
383+**The full sweep, on the final tree.** Reproduce with:
384+
385+```bash
386+BIN=$(ls -t "$CARGO_TARGET_DIR"/debug/deps/ec_av1-* | grep -v '\.d$' | head -1)
387+$BIN --list | sed 's/: test$//' \
388+ | grep -v bitrate_target_lands_within_5_percent_over_48_frames > /tmp/tests.txt
389+# one process per test, so a SIGABRT is attributable instead of swallowing the run
390+xargs -a /tmp/tests.txt -P 8 -I{} bash -c \
391+ 'RUST_MIN_STACK=2097152 timeout 600 "$0" "$1" --exact --test-threads=1 \
392+ >/dev/null 2>/tmp/err.$$ && echo "OK $1" \
393+ || { grep -q "stack overflow" /tmp/err.$$ && echo "STACKOVERFLOW $1" \
394+ || echo "OTHER $1"; }' "$BIN" {}
395+```
396+
397+**Result: 799 of 799 tests, ZERO stack overflows at `RUST_MIN_STACK=2097152`.**
398+One entry is not `OK`:
399+
400+```
401+TIMEOUT encoder::tests::every_tile_layout_decodes_sample_exact_through_both_decoders
402+```
403+
404+which hit the sweep's own 600-second per-test budget, not a stack limit — it
405+is a slow encode gate, and it passed in the release run above. It needs a
406+longer per-test timeout, not a bigger stack. Every other test, including
407+`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence` (the one
408+that overflowed before this commit), reports `OK`.
409+
410+**So: nothing in the ec-av1 lib suite requires the 64 MiB cap, and this lane
411+removed the last test that did.**
412+
413+**The measured stack headroom for the paths that remain:**
414+
415+| what | measured need (debug) | margin at 2 MiB | at 64 MiB |
416+|---|---|---|---|
417+| `encode_key_frame`, 64×64 | 786,432 → **475,136** after boxing | **4.4×** | 141× |
418+| `Av1Encoder` pyramid ctor nest | 262,144 | **8.0×** | 256× |
419+| pyramid `encode_sequence`, 640×384 | 917,504 | **2.3×** | 73× |
420+| the rate-target test's own worker body | 983,040 | **2.1×** | 68× |
421+
422+The last row is the one the cap's comment names.
423+`bitrate_target_lands_within_5_percent_over_48_frames` runs its eight arms
424+inside `std::thread::spawn(move || { ... })` (encoder.rs:3602) — **no**
425+`stack_size`, so the runtime default, exactly the case a library consumer
426+hits. Its body is a constructor nest, then a **sequential**
427+`for picture in pictures.iter()` loop of `encode_frames`, then `flush`. Frames
428+do not nest, so the peak is one frame's chain, not 48 of them. Measured that
429+exact body at 640×384 in a debug build: 983,040 red / 1,048,576 green.
430+
431+### What I could not measure, and why
432+
433+- **`bitrate_target_lands_within_5_percent_over_48_frames` in DEBUG.** ~7 hours
434+ (the crate's own comment: the debug lib suite is 24341s and this is the
435+ largest single item), and heavy suites belong on the server fleet. What I
436+ measured instead is its worker body in isolation, above. To settle it on a
437+ fleet host:
438+ `env -u RUST_MIN_STACK cargo test -p ec-av1 --lib -- bitrate_target_lands_within_5_percent_over_48_frames --exact`.
439+- **The sibling crates' suites at 2 MiB.** The measurement that matters for
440+ them is the per-type stack sweep in §1, and that is complete: the only type
441+ in the workspace in danger on a 2 MiB thread is `ec_opus::Encoder`, and it
442+ survives 384 KiB.
443+
444+### Recommendation
445+
446+**The cap is no longer protecting anything in ec-av1 that the gates do not.**
447+Recommended change, in two steps, both outside this lane's charter:
448+
449+1. Run each crate's suite once at `RUST_MIN_STACK=2097152` on the fleet, **one
450+ test per process**, so a stack overflow is attributable rather than
451+ swallowing the run. ec-av1 is done: zero failures.
452+2. Then lower the cap to whatever the largest surviving requirement turns out
453+ to be, and replace the comment with:
454+
455+> The AV1 encoder's by-value returns are gated by `stack_budget.rs` against an
456+> 8 KiB per-type budget: `Av1Encoder` 2944 B and `Encoded` 280 B, through
457+> constructor chains 3 and 4 deep, with the deepest measured chain needing
458+> 475136 bytes in a debug build. Per-test evidence at `RUST_MIN_STACK=2097152`
459+> is in `lanes/av1stacksweep.report.md`. This cap is headroom for test
460+> threads, not a load-bearing fix -- lowering it is a separate change that
461+> needs its own per-test evidence.
462+
463+I have **not** edited `.cargo/config.toml`, as chartered.
464+
465+## 5. WHAT IS NEXT IN THIS CLASS (not done here)
466+
467+**`ec_opus::Encoder` at 87,024 bytes is the live instance, and it is not in
468+this crate.** It is 10.6× over the bound, the largest by-value type in the
469+workspace, and it survives 384 KiB of stack while SIGABRTing below 352 KiB. Its
470+chain is 4 nested constructors returning the struct by value.
471+
472+It is recorded rather than fixed because it is in `ec-opus`, a crate this lane
473+does not own, with its own bit-exactness gates that a change here would have to
474+run and this lane has no evidence for. **Recommended next lane: box
475+`ec_opus::Encoder`'s inline delay/history arrays the same way, and prove it
476+against that crate's own encoder gates** (`ec-ac3::Ac3Decoder` at 20,024 B
477+overflowing below 96 KiB and `ec-vp9::Decoder` at 10,944 B below 64 KiB are
478+the next two).
479+
480+**The `Encoded` boxing that WAS in this lane's reach is done** — see the
481+header table. What is left in ec-av1 is the encode search's own ~470 KB of
482+stack, which is a different problem (frame-local buffers, not by-value
483+returns) and is not claimed by `stack_budget.rs`.
484+
485+## 6. ACCEPTANCE EVIDENCE
486+
487+### The new gate, debug
488+
489+```
490+$ cargo test -p ec-av1 --lib -- stack_budget --nocapture
491+running 8 tests
492+... all ok ...
493+test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 791 filtered out; finished in 0.10s
494+
495+BY-VALUE INVENTORY (21 types, budget 8192 B = 8 KiB)
496+ BYTES %BUDGET TYPE
497+ 15232 185.9% Cdfs
498+ 15232 185.9% CdfSnapshot
499+ 2944 35.9% Av1Encoder
500+ 1296 15.8% FrameCtx
501+ 352 4.3% Frame
502+ 280 3.4% Encoded
503+ ... (21 rows) ...
504+TIGHTSTACK 1048576 bytes: Av1Encoder=2944 Encoded=280 bytes, both chains returned
505+TESTTHREADSTACK default ... size>=67112960 (2101248 measured exactly with the repo cap lifted, 67112960 with it)
506+```
507+
508+### Release run — the chartered acceptance command
509+
510+```
511+$ CARGO_TARGET_DIR=/home/user/.cache/tgt/stackcap2 EC_NOMEMGUARD=1 \
512+ cargo test --release -p ec-av1 --lib -- encode round_trip \
513+ --skip bitrate_target_lands_within_5_percent_over_48_frames
514+
515+test encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence ... ok
516+test encoder::tests::thirty_pictures_at_gop_fifteen_decode_to_two_key_frames ... ok
517+test encoder::tests::the_rate_loop_prices_the_frames_the_pyramid_codes ... ok
518+
519+test result: ok. 108 passed; 0 failed; 40 ignored; 0 measured;
520+ 651 filtered out; finished in 308.46s
521+
522+Wall time: 344.04 seconds
523+```
524+
525+108 passed, 0 failed — the same count as the pre-boxing run of this exact
526+command on unmodified `main` behaviour (which also reported 108/0/40), so the
527+boxing changed no test's verdict.
528+
529+Run in RELEASE because the debug encoder suite is hours, and with the repo's
530+64 MiB cap in effect, i.e. exactly how CI runs it. The 40 ignored are the
531+crate's pre-existing wall-measurement gates (`tile_search_wall_1080p`,
532+`filter_stage_wall_4k`, ...), which carry their own "run it with --ignored"
533+reasons and are unaffected by this lane.
534+
535+### Bit-exactness of the boxing
536+
537+The boxing moves no value. The proof is structural plus the gates:
538+`CdfSnapshot` is a newtype over `Cdfs`, so `Box::new(x)` stores the same
539+`x`; the CDF tables the writer starts from and the tables it stores are the
540+same objects, reached through one pointer indirection instead of inline.
541+`Encoded`'s public `stream`, `reconstruction`, `modes` and `inter_block_share`
542+are untouched, and `Debug` still prints `CdfSnapshot` (its `Debug` impl is
543+hand-written to print exactly that, so `Encoded`'s derived `Debug` output is
544+byte-identical too). The round-trip and pyramid decode gates above are the
545+empirical half.
546+
547+### Files changed
548+
549+```
550+crates/ec-av1/src/stack_budget.rs new, 8 tests, #![cfg(test)]
551+crates/ec-av1/src/lib.rs +1 line: `mod stack_budget;`
552+crates/ec-av1/src/encode.rs Encoded::start_cdfs / next_cdfs -> Box<CdfSnapshot>
553+ (+2 construction sites)
554+crates/ec-av1/src/encoder.rs Av1Encoder::carried_cdfs -> Option<Box<CdfSnapshot>>
555+ refresh() reuses the already-boxed snapshot
556+lanes/av1stacksweep.report.md this file
557+```
558+
559+Not touched: `decode.rs`, `.cargo/config.toml`, any CDF value, any bitstream
560+byte.