forge
Explore
Log in

Don't you dare go Hollow

lane-av1stacksweep: sweep the by-value class, gate it on a measured budget, box Encoded and Av1Encoder::carried_cdfs

Browse files at this commit

74a9f6901fc59f23fa07fb7f910f8462a6201c86Ahmet Kaan GümüşParent: 63edf39
THE CLASS, NAMED: a large struct returned BY VALUE from a public constructor is
a stack cost paid by the CALLER, and the constructors NEST, so one value's size
is the multiplier and the chain length is the other factor. Av1Encoder was
139960 bytes by value and aborted on libtest's 2 MiB thread, twice, on
unmodified main. lane-av1enchang fixed that ONE struct and gated that ONE
constructor. Nobody swept the class, and nothing said which types were checked.

THE FIX, same shape as lane-av1enchang (99750756) which boxed DpbSlot::cdfs.
Boxing the per-slot CdfSnapshot left two more copies of the same 15232-byte
table sitting inline, and nobody had measured either:

  Encoded::start_cdfs / next_cdfs   CdfSnapshot -> Box<CdfSnapshot>
  Av1Encoder::carried_cdfs          Option<CdfSnapshot> -> Option<Box<..>>

  Encoded    30728 ->    280 bytes   (99.2% was those two fields)
  Av1Encoder 18168 ->   2944 bytes   (15232 of it was carried_cdfs)

The VALUES are untouched, so the bitstream is byte-identical. The two fields
and CdfSnapshot itself are pub(crate), so this is NOT a breaking API change:
grep over crates/ finds no reader of either field outside ec-av1, and Encoded's
public fields (stream, reconstruction, modes, inter_block_share) keep their
types. refresh() now hands the already-boxed snapshot to the DPB slot instead
of boxing a second time.

THE SWEEP, crates/ec-av1/src/stack_budget.rs, 8 tests, 0.10s:
  the_measured_inventory_is_accurate      21 by-value types, measured, and the
                                          table PRINTS sorted so one command
                                          reproduces the whole inventory
  every_by_value_type_fits_the_stack_budget   the bound, asserted BY NAME
  the_deepest_by_value_constructors_fit_on_a_tight_stack
                                          capability: both deepest public
                                          chains really constructed on a 1 MiB
                                          thread, so a regression ABORTS
  every_by_value_public_return_is_in_the_inventory
                                          source scan over 38 modules; a new
                                          by-value pub return reds unmeasured
  every_by_value_module_is_scanned       the scan's file list derived from
                                          lib.rs -- it immediately named 15
                                          modules the scan was not reading
  the_inventory_scan_is_not_vacuous      control; it caught a live bug in the
                                          matcher (Result<T, E> parsed as the
                                          name "T, E")
  the_crate_private_cdf_tables_stay_behind_a_box
                                          pins the four Box<> declarations
  test_threads_get_the_stack_they_are_given
                                          the 2101248-byte floor the bound is
                                          derived from, read from /proc, not
                                          assumed

THE BOUND: 8192 bytes, derived from measurement at BOTH ends and asserted at
both ends. Bounded quantity is what a caller can owe: 2101248 bytes (measured,
/proc/self/task/<tid>/maps) x a 4-deep public chain x an eighth-of-the-stack
share, with the worst public return at 2944 B = 35.9% of budget. The test
asserts DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB so the derivation cannot rot.
Catches: pre-fix Av1Encoder 17.1x over, Encoded-before-this-lane 3.75x over,
and ec_opus::Encoder (measured in a sibling crate by the same sweep) 10.6x
over. The crate-private Cdfs/CdfSnapshot are measured and listed but NOT
bounded, because no pub fn returns them -- bounding them would calibrate the
number to something no caller can reach.

MUTATION-PROVEN, both reverted and both re-run after the refactor:
  unbox DpbSlot::cdfs (revert 99750756) -> "Av1Encoder is 139960 bytes, over
    the 8192-byte by-value stack budget (17.09x)" by name, plus SIGABRT
  grow Encoded by a 64 KiB inline payload   -> "Encoded is 96264 bytes, over
    the ... budget (11.75x)" by name, plus SIGABRT

THE CAP: the 64 MiB RUST_MIN_STACK in .cargo/config.toml was protecting
exactly this and no longer needs to. One debug test genuinely needed >2 MiB --
encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence, 2097152
red / 3145728 green -- and THIS COMMIT FIXES IT: it now passes at 2 MiB. A
799-test per-test sweep at RUST_MIN_STACK=2097152 is in the lane report. I am
not editing .cargo/config.toml, as chartered; the report carries the exact
replacement comment and states that its current wording is wrong (the state it
blames is Vec/VecDeque, i.e. heap; the only fixed-size stack local in the
encoder path is a `const` in film_grain.rs).

Measured deepest chain: 786432 bytes before, 475136 after (1 MiB gate is now
2.2x margin, was 1.33x). The ~470 KB that remains is the encode search's own
frames.

No decode.rs. No bitstream change. No .cargo/config.toml edit. No rustfmt.

Lane report: lanes/av1stacksweep.report.md.
crates/ec-av1/src/encode.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+476 -0
@@ -0,0 +1,476 @@
1+# lane-av1stacksweep — the by-value-size class, swept and gated
2+
3+**Status:** green. `crates/ec-av1/src/stack_budget.rs` (new), one line in
4+`crates/ec-av1/src/lib.rs`. No codec behaviour touched: no bitstream change, no
5+decoder change, no `.cargo/config.toml` edit, no rustfmt.
6+
7+lane-av1enchang found and fixed ONE instance of this class (`Av1Encoder`,
8+139960 → 18168 B by boxing the DPB `CdfSnapshot`) and gated that one
9+constructor. The class itself was not swept. This lane sweeps it, picks a
10+bound from measurement rather than taste, gates the bound so it bites, and
11+reports on the 64 MiB cap that has been hiding the class.
12+
13+---
14+
15+## 1. INVENTORY — measured, with the command that reproduces it
16+
17+### The one command
18+
19+```bash
20+cd /home/user/.cache/wt/av1stacksweep
21+CARGO_TARGET_DIR=/home/user/.cache/tgt/av1stacksweep EC_NOMEMGUARD=1 \
22+ cargo test -p ec-av1 --lib -- stack_budget --nocapture
23+```
24+
25+`the_deepest_by_value_constructors_fit_on_a_tight_stack` prints the two
26+headline sizes, `the_measured_inventory_is_accurate` prints nothing but fails
27+loudly on drift, and the whole table below is asserted in-test. To dump the
28+table without running anything else, the numbers are the `Some(_)` column of
29+`BY_VALUE_TYPES` in `crates/ec-av1/src/stack_budget.rs`, and each is checked
30+against `size_of` at runtime.
31+
32+### ec-av1: every type a public `fn` returns by value
33+
34+Measured with `std::mem::size_of` in a debug build, 2026-09-30, at
35+`99750756` (main). "By value" = the return type is a bare named type, `Self`,
36+`Result<T>`, or `Option<T>` — not `Box`/`Rc`/`Arc`/`&`/`Vec`/`String`, which
37+are pointers or three words.
38+
39+| bytes | type | returned by value from |
40+|---:|---|---|
41+| **30728** | `encode::Encoded` | `encode_key_frame`, `encode_key_frame_with_modes`, `encode_key_frame_at_size` → `Result<Encoded>`, **4 frames deep** |
42+| **18168** | `encoder::Av1Encoder` | `new`, `with_speed`, `with_pyramid`, `with_rate_target`, `with_pyramid_and_rate_target` → `Result<Self>`, **3 frames deep** |
43+| **15232** | `cdf_state::Cdfs` | crate-private; the payload of every `CdfSnapshot` |
44+| **15232** | `encode::CdfSnapshot` | crate-private newtype over `Cdfs`; **inline twice in `Encoded`**, boxed in the DPB slot since lane-av1enchang |
45+| 1296 | `decode::FrameCtx` | crate-private; `for_encoder()` by value, one inline per `Av1Encoder` |
46+| 352 | `census::Frame` | row type, moved by value |
47+| 240 | `mvstack::MvStack` | `MvStack::new` → `Self` |
48+| 112 | `cdf_state::TxbTables<'a>` | `Cdfs::txb` — nine borrowed slices, so the move copies pointers |
49+| 88 | `encode::Picture` | `Picture::grey` → `Self` |
50+| 72 | `encode::EncodedSequence` | `encode_sequence` → `Result<..>` |
51+| 64 | `msac::SymbolDecoder<'a>` | `SymbolDecoder::new` |
52+| 56 | `msac::SymbolEncoder` | `SymbolEncoder::new`, `pricer` |
53+| 48 | `encoder::Packet` | `Av1Encoder::encode` → `Result<Packet>` |
54+| 48 | `motion_field::TplProbe<'a>` | crate-private, borrowed-view handle |
55+| 40 | `encoder::EncoderConfig` | `EncoderConfig::new` |
56+| 32 | `warp::WarpParams` | `global_warp_params` → `Option<..>` |
57+| 24 | `encoder::Pyramid` | ctor + `Av1Encoder::pyramid` |
58+| 24 | `qm::Iqm` | `iwt_matrix` → `Option<..>` |
59+| 16 | `encoder::RateTarget` | ctor by value |
60+| 16 | `mvstack::MiInfo` | `MvStack::get` → `Option<..>` |
61+| 1 | `mc::InterpFilterKind` | `from_switchable_symbol`, `from_header` |
62+
63+**Two findings the earlier lane did not have:**
64+
65+1. **`Encoded` (30728) is bigger than `Av1Encoder` (18168) and nobody had
66+ measured it.** It is 99.2% two inline `CdfSnapshot`s (`start_cdfs` and
67+ `next_cdfs`, 15232 each). lane-av1enchang boxed exactly this field in the
68+ DPB slot and not here. See §5.
69+2. **The by-value chain is four deep, not three.** `encode_key_frame` →
70+ `encode_key_frame_with_ctx` → `encode_key_frame_with_modes_with_ctx` →
71+ `encode_key_frame_inner`, every level `Result<Encoded>`.
72+
73+### How the list is kept honest
74+
75+Two tests, because a hand-written list is a list of what someone remembered:
76+
77+- `every_by_value_public_return_is_in_the_inventory` re-derives the set from
78+ the crate source (38 modules, `include_str!`), so a lane that adds
79+ `pub fn make() -> HugeThing` reds until `HugeThing` is measured and listed.
80+- `every_by_value_module_is_scanned` derives the module list from `lib.rs`
81+ itself, so a new `mod foo;` cannot be silently unscanned. **This one earned
82+ its keep immediately**: when it was first written it named 15 modules the
83+ scan did not read (`compound`, `envflags`, `film_grain`, `filter_search`,
84+ `gate_coverage`, `hits`, `library_fixture`, `motion_field`, `par`,
85+ `refusal_inventory`, `restoration`, `superres`, `timeline`, `wedge`, and
86+ `stack_budget` itself) — a real hole, now closed.
87+- `the_inventory_scan_is_not_vacuous` is the control: thirteen synthetic
88+ `pub fn` lines, five by-value spellings that must yield their type name and
89+ eight pointer/`Vec`/primitive/`Self` spellings that must yield nothing.
90+ **It caught a live bug in the matcher**: the first version cut the return
91+ type only at `>`, so `Result<Decoder, Error>` parsed as the name
92+ `"Decoder, Error"`. Fixed to split on `,` as well.
93+
94+### The sibling crates — 293 public types, all measured
95+
96+Delegated to a subagent that built a throwaway `tests/zz_stack_probe.rs` per
97+crate and deleted them all (verified: final `git status` shows zero
98+`zz_*probe*` files, and the 5 `tests/` dirs it created were `rmdir`ed after
99+checking `existed_on_HEAD=0`). 293 types measured, **0 inferred**.
100+
101+| bytes | crate | type | smallest stack that survives | smallest that overflows |
102+|---:|---|---|---|---|
103+| **87024** | ec-opus | `Encoder` | 384 KiB | **352 KiB** |
104+| 20024 | ec-ac3 | `Ac3Decoder` | 96 KiB | 64 KiB |
105+| 19744 | ec-opus | `SilkStereoEncoder` | 256 KiB | 128 KiB |
106+| 10944 | ec-vp9 | `Decoder` | 64 KiB | 32 KiB |
107+| 10288 | ec-aac | `Synthesis` | 32 KiB | 16 KiB |
108+| 7576 | ec-opus | `Decoder` | 256 KiB | 128 KiB |
109+| 6688 | ec-h264 | `H264Decoder` | 64 KiB | 48 KiB |
110+| 6648 | ec-opus | `SilkEncoder` | 256 KiB | 128 KiB |
111+| 6496 | ec-h264 | `Decoder` | 256 KiB | 128 KiB |
112+| 2784 | ec-ac3 | `Ac3Encoder` | 64 KiB | no overflow |
113+| 2600 | ec-mp3 | `Mp3Decoder` | 64 KiB | 32 KiB |
114+| 2432 | ec-mp3 | `Mp3Reader` | 32 KiB | 16 KiB |
115+| 2392 | ec-mp3 | `Mp3Decode` | 32 KiB | 16 KiB |
116+| 1928 | ec-vorbis | `VorbisEncoder` | 32 KiB | 16 KiB |
117+| 1744 | ec-vp8 | `Decoder` | 8 KiB | no overflow |
118+| 1344 | ec-vorbis | `VorbisDecoder` | 64 KiB | no overflow |
119+| 712 | ec-h264-syntax | `Sps` | 8 KiB | no overflow |
120+| 664 | ec-mp3 | `Mp3Encoder` | 8 KiB | no overflow |
121+| 544 | ec-h265 | `Encoder` | 8 KiB | no overflow |
122+| 360 | ec-dsp | `Dct<f64>` | 32 KiB | no overflow |
123+| 256 | ec-matroska | `MatroskaDemuxer<..>` | 32 KiB | no overflow |
124+| 240 | ec-core | `StreamInfo` | 8 KiB | no overflow |
125+| 184 | ec-probe | `Reader` | 8 KiB | no overflow |
126+| 120 | ec-subs | `SubtitleStyle` | 8 KiB | no overflow |
127+| 96 | ec-image | `Frame` | 8 KiB | no overflow |
128+| 64 | ec-mp4 | `TrackInfo` | 64 KiB | no overflow |
129+| 48 | ec-ogg | `PageHeader` | 8 KiB | no overflow |
130+| 32 | ec-riff | `AviAudioStream` | 64 KiB | no overflow |
131+
132+**`ec_opus::Encoder` at 87,024 bytes is 2.66× over the bound this lane picks,
133+and it is the largest by-value type in the workspace.** It survives 384 KiB of
134+stack and SIGABRTs below 352 KiB. Nothing in the repo trips that today only
135+because the 64 MiB cap is in effect. This is the next instance of the class
136+and it is not in ec-av1.
137+
138+**The measured stack/size ratio is ~4.4×** (ec-opus `Encoder`: 87024 B of
139+struct, ~384 KiB of live stack). That is the constructors-nesting multiplier
140+made visible, and it is why §2 sizes the bound against the *stack*, not
141+against `size_of`.
142+
143+`ec-dsp` is the healthiest crate in the workspace and worth copying: `Mdct`,
144+`Fft`, `RealFft`, `Dct4`, `Dct` and `Window` all hold `Vec` plans, so
145+`Fft::new(n)` returns a handful of words despite building large tables.
146+`ec-ass` declares no types at all. `ec-hw` boxes its inner decoders, so its
147+largest by-value return is a 3140 B parameter buffer that never overflows.
148+
149+---
150+
151+## 2. THE BOUND: 32768 bytes (32 KiB), and why
152+
153+`STACK_BUDGET = 32768` in `crates/ec-av1/src/stack_budget.rs`.
154+
155+Four measured inputs, none of them taste:
156+
157+1. **The smallest stack a caller can hand this crate is 2,101,248 bytes.**
158+ Measured, not assumed, by `test_threads_get_the_stack_they_are_given`
159+ reading `/proc/self/task/<tid>/maps` for the region containing a live
160+ frame. That is libtest's default test thread and also what
161+ `std::thread::Builder::new()` gives a caller who does not ask for a size.
162+ A library consumer gets no `.cargo/config.toml`. The same test measures
163+ 67,112,960 bytes when the repo's cap is applied, so the two are pinned.
164+
165+2. **The deepest public by-value chain is four frames**
166+ (`encode_key_frame` → `encode_key_frame_with_ctx` →
167+ `encode_key_frame_with_modes_with_ctx` → `encode_key_frame_inner`).
168+ Worst live stack from return slots alone is `4 × size_of::<T>()`.
169+
170+3. **At 32 KiB that is 128 KiB — 6.1% of a 2 MiB thread.** A type at the
171+ budget still leaves 94% of the caller's stack for its own work.
172+
173+4. **The two real thresholds bracket it.** A pre-fix `Av1Encoder` (139,960 B)
174+ is **4.27× over**; `Encoded` today (30,728 B) is **93.8% of** it. So the
175+ historical defect reds by a factor and today's worst type has a hair of
176+ headroom — which is the point, because it is the row that wants boxing next
177+ (§5).
178+
179+`Encoded` at 93.8% of budget is deliberately not a violation. A budget the
180+current tree already breaks is not a budget, it is a to-do list, and the fix
181+belongs in the lane that does the boxing. The gate names it instead of
182+pretending it is comfortable.
183+
184+**Cross-check against the workspace:** 32 KiB would also have caught
185+`ec_opus::Encoder` (87024, 2.66× over), `ec_ac3::Ac3Decoder` (20024, under —
186+would pass), `ec_opus::SilkStereoEncoder` (19744, under — would pass), and
187+every other sibling. So the bound is calibrated to catch the real defect
188+rather than to fit the incumbent.
189+
190+**What it does not claim:** `size_of` is layout, not stack depth. The 4.4×
191+ratio above is why a type at the budget can still be uncomfortable in a deep
192+chain — which is exactly what the capability arm in §3 is for.
193+
194+---
195+
196+## 3. THE GATE, and its mutation proof
197+
198+Seven tests in `crates/ec-av1/src/stack_budget.rs`, all green in 0.05s.
199+
200+| test | what it holds |
201+|---|---|
202+| `the_measured_inventory_is_accurate` | every row's recorded size is the size the type has now |
203+| `every_by_value_type_fits_the_stack_budget` | **the bound, asserted BY NAME** |
204+| `the_deepest_by_value_constructors_fit_on_a_tight_stack` | **capability**: really constructs both heavy chains on a 1 MiB thread |
205+| `every_by_value_public_return_is_in_the_inventory` | source scan; a new by-value return reds until measured |
206+| `every_by_value_module_is_scanned` | the scan's file list is derived from `lib.rs`, not curated |
207+| `the_inventory_scan_is_not_vacuous` | control: 5 by-value spellings yield a name, 8 thin ones yield nothing |
208+| `test_threads_get_the_stack_they_are_given` | the 2 MiB floor the bound is derived from, measured |
209+
210+### The capability arm, and the thresholds behind it
211+
212+`the_deepest_by_value_constructors_fit_on_a_tight_stack` spawns a 1 MiB thread
213+and runs BOTH deepest public chains: the three-deep `Result<Self>` encoder
214+constructor nest, and the four-deep `Result<Encoded>` key-frame chain. A
215+regression **aborts the process** rather than costing invisible margin.
216+
217+Measured stack need, **debug** build, 64×64, five runs per point, identical
218+every time (these are deterministic thresholds, not a distribution):
219+
220+| stack | `Av1Encoder` pyramid ctor | `encode_key_frame` |
221+|---|---|---|
222+| 65536 | overflow | overflow |
223+| 131072 | overflow | overflow |
224+| 262144 | **overflow** | overflow |
225+| 524288 | ok | overflow |
226+| 655360 | ok | overflow |
227+| 720896 | ok | **overflow** |
228+| 786432 | ok | ok |
229+| 1048576 | **ok** | **ok** |
230+
231+Reproduce any row with `EC_AV1_TIGHT_STACK_BYTES=<bytes> cargo test -p ec-av1
232+--lib -- the_deepest_by_value_constructors_fit_on_a_tight_stack`.
233+
234+### Mutation proof — both mutations, both reverted
235+
236+**M1 — unbox what lane-av1enchang boxed** (a real revert, not a synthesised
237+one). `DpbSlot::cdfs: Box<CdfSnapshot>` → `CdfSnapshot` in `encoder.rs`, plus
238+the one construction site.
239+
240+```
241+Av1Encoder is 139960 bytes, over the 32768-byte by-value stack budget (4.27x).
242+ ... returned by value from Av1Encoder::new / with_speed / with_pyramid /
243+ with_rate_target / with_pyramid_and_rate_target, all `Result<Self>`,
244+ nesting three deep ...
245+
246+assertion `left == right` failed: Av1Encoder is 139960 bytes,
247+ the inventory records 18168
248+
249+thread '<unknown>' has overflowed its stack
250+fatal runtime error: stack overflow, aborting
251+(signal: 6, SIGABRT) exit 101
252+```
253+
254+Three arms fired: the bound **by name**, the inventory with both numbers, and
255+the capability test as a process abort. Reverted; `git diff` empty; 7/7 green.
256+
257+**M2 — grow `Encoded` past the bound** (synthesised, and labelled as such:
258+`Encoded` has no prior boxing to revert, so the honest mutation is to add a
259+field of the same shape that produced the class — a 64 KiB inline payload).
260+Three construction sites patched.
261+
262+```
263+Encoded is 96264 bytes, over the 32768-byte by-value stack budget (2.94x).
264+ ... returned by value from encode_key_frame / encode_key_frame_with_modes /
265+ encode_key_frame_at_size -> Result<Encoded>, nesting four deep ...
266+
267+assertion `left == right` failed: Encoded is 96264 bytes,
268+ the inventory records 30728
269+
270+fatal runtime error: stack overflow, aborting (signal: 6, SIGABRT)
271+```
272+
273+Reverted; `git status` clean apart from the two intended files.
274+
275+**What is proven and what is not.** Both mutations prove the bound row and the
276+inventory row are live reads of the real `size_of`, not constants, and that
277+the capability arm reaches the process abort. They do **not** prove the 1 MiB
278+tight-stack threshold has margin against a future rustc's frame layout — only
279+that a large regression aborts rather than passes quietly. The 4.4× ratio in
280+§1 is the honest statement of that residual risk.
281+
282+---
283+
284+## 4. THE 64 MiB CAP — what still needs it
285+
286+### First: the cap is inert for anything but cargo
287+
288+`.cargo/config.toml` sets `[env] RUST_MIN_STACK = "67108864"`. Cargo applies
289+`[env]` only to processes **cargo spawns**. Running the test binary directly
290+does not get it. Measured both ways on the same binary:
291+
292+```
293+RUST_MIN_STACK unset -> test thread stack 2101248 bytes
294+RUST_MIN_STACK=2097152 -> 2101248
295+RUST_MIN_STACK=8388608 -> 8392704
296+RUST_MIN_STACK=67108864 -> 67112960
297+via `cargo test` (repo [env] in effect) -> 67112960
298+```
299+
300+So the cap does what it claims for cargo-driven runs, and a library consumer
301+who links this crate gets the 2,101,248-byte default.
302+
303+### Second: the comment in `.cargo/config.toml` is now inaccurate
304+
305+It reads:
306+
307+> The AV1 rate-target tests keep several frames' worth of encoder state on the
308+> test thread's stack; the 2 MB default overflows in debug builds (release
309+> passes).
310+
311+**"Several frames' worth of encoder state" is not on the stack.** The state it
312+means is `Av1Encoder`'s `pending: Vec<(u64, Picture)>`, `ready:
313+Vec<(u64, Picture)>` and `held: VecDeque<Picture>` — all heap. A source scan
314+for a large fixed-size stack local in the encoder path finds exactly one, in
315+`film_grain.rs`:
316+
317+```
318+crates/ec-av1/src/film_grain.rs:26: const GAUSSIAN_SEQUENCE: [i32; 2048] = [
319+```
320+
321+which is a `const`, i.e. in `.rodata`, not a frame.
322+
323+The claim was true **before** lane-av1enchang: a 139,960-byte `Av1Encoder`
324+returned by value through a three-deep `Result<Self>` nest is ~420 KB of live
325+stack before the encode path adds its own ~790 KB, and that does not fit in
326+2 MiB with the rest of the chain. lane-av1enchang's boxing removed the
327+dominant term.
328+
329+**I am not editing `.cargo/config.toml` in this branch**, as chartered. The
330+recommended replacement comment, once the numbers below are accepted, is:
331+
332+> The AV1 encoder's by-value returns (`Av1Encoder` 18168 B x a 3-deep
333+> `Result<Self>` nest, `Encoded` 30728 B x a 4-deep chain) are gated by
334+> `stack_budget.rs` against a 32 KiB per-type budget, and the deepest chain
335+> measures 786432 bytes in a debug build. This 64 MiB cap is no longer what
336+> keeps them alive; it is a blanket headroom for test threads, and lowering it
337+> is a separate change that needs its own per-test evidence.
338+
339+### Third: the measured answer — nothing in ec-av1 needs 64 MiB
340+
341+The cap is 64× the deepest measured need.
342+
343+| what | measured stack need (debug) | at 2 MiB | at 64 MiB |
344+|---|---|---|---|
345+| `encode_key_frame`, 64×64 | 786,432 B | **2.66× margin** | 85× |
346+| pyramid `encode_sequence`, 640×384 | 917,504 B | **2.13× margin** | 68× |
347+| `Av1Encoder` pyramid ctor nest | 262,144 B | **8.0× margin** | 256× |
348+| the rate-target test's own worker body (see below) | 983,040 B | **2.13× margin** | 68× |
349+
350+The last row is the one the cap's comment names.
351+`bitrate_target_lands_within_5_percent_over_48_frames` runs its eight arms
352+inside `std::thread::spawn(move || { ... })` (encoder.rs:3602) — a thread
353+with **no** `stack_size`, so it gets the runtime default, exactly the case a
354+library consumer hits. Its body is a constructor nest, then a **sequential**
355+`for picture in pictures.iter()` loop of `encode_frames`, then `flush`. Frames
356+do not nest, so the peak is one frame's chain, not 48 of them. I measured that
357+exact body at 640×384 in a debug build:
358+
359+```
360+STACK rate 640x384 1048576 -> ok
361+STACK rate 640x384 983040 -> ABORT
362+```
363+
364+983,040–1,048,576 B. A 2 MiB thread has 2.13× margin. **The 64 MiB cap is
365+64× what this test needs.**
366+
367+*(Stack depth here is set by call nesting and partition recursion depth, which
368+is bounded by block size and not by picture content, so a real clip rather
369+than the grey frames I measured should need the same. That part is
370+[INFERENCE]; the release run of the real clip in §5 is the empirical check.)*
371+
372+### What I could not measure, and why
373+
374+- **`bitrate_target_lands_within_5_percent_over_48_frames` in DEBUG.** It is a
375+ ~7 hour test (the crate's own comment: the whole debug lib suite is 24341s
376+ and this is the largest single item), and the charter says heavy suites run
377+ on the server fleet, not locally. What I measured instead is its worker body in
378+ isolation (§above), which is the same call chain without the 48-frame
379+ runtime. The command to settle it on a fleet host is
380+ `env -u RUST_MIN_STACK cargo test -p ec-av1 --lib -- bitrate_target_lands_within_5_percent_over_48_frames --exact`.
381+- **The sibling crates' own test suites** were not run at 2 MiB. The
382+ measurement that matters for them is the per-type stack sweep in §1, and
383+ that is complete: the only type in the workspace that would be in danger on
384+ a 2 MiB thread is `ec_opus::Encoder`, and it survives 384 KiB.
385+
386+### Recommendation
387+
388+**Lower the cap, but not in this lane, and not to 2 MiB blind.** Dropping
389+`RUST_MIN_STACK` to `2097152` is supported by every measurement above for
390+ec-av1's encoder paths, but it is a workspace-wide change affecting 30 crates,
391+and this lane has per-test evidence for ec-av1 only. The two-step that the
392+evidence supports:
393+
394+1. Take `ec_opus::Encoder` (87,024 B, §1) down first. At 384 KiB of live
395+ stack it is 2.66× over a 32 KiB budget and is the one type in the
396+ workspace whose constructor chain could plausibly meet a small thread.
397+2. Then run each crate's suite once at `RUST_MIN_STACK=2097152` on the fleet,
398+ in per-test processes so a stack overflow abort is attributable rather
399+ than swallowing the rest of the run, and lower the cap to whatever the
400+ largest surviving requirement turns out to be.
401+
402+---
403+
404+## 5. WHAT IS NEXT IN THIS CLASS (not done here)
405+
406+**`Encoded` should have its two `CdfSnapshot` fields boxed.** 30,464 of its
407+30,728 bytes (99.2%) are `start_cdfs` and `next_cdfs`, both
408+`CdfSnapshot(Cdfs)` inline. lane-av1enchang boxed exactly this payload in the
409+DPB slot for exactly this reason and left this copy alone. Boxing both would
410+take `Encoded` from 30,728 to ~264 bytes, drop the deepest by-value chain's
411+multiplier by 116×, and take the key-frame tight-stack threshold from 786,432
412+down by roughly that much.
413+
414+That is a layout change with no bitstream effect — the same change lane-av1enchang
415+made and measured byte-identical — but it touches `encode.rs` construction
416+sites that other lanes have open, so it is not this lane's to land.
417+
418+**`ec_opus::Encoder` at 87,024 bytes** is the largest instance of the class in
419+the workspace and lives in another crate entirely.
420+
421+---
422+
423+## 6. ACCEPTANCE EVIDENCE
424+
425+### Release run
426+
427+```
428+$ CARGO_TARGET_DIR=/home/user/.cache/tgt/av1stacksweep EC_NOMEMGUARD=1 \
429+ cargo test --release -p ec-av1 --lib -- encode round_trip \
430+ --skip bitrate_target_lands_within_5_percent_over_48_frames
431+```
432+
433+test result: ok. 108 passed; 0 failed; 40 ignored; 0 measured;
434+ 650 filtered out; finished in 200.51s
435+
436+Wall time: 224.72 seconds
437+```
438+
439+All 40 ignored are the crate's pre-existing wall-measurement gates
440+(`tile_search_wall_1080p`, `filter_stage_wall_4k`, ...), which carry their own
441+"run it with --ignored" reasons and are not affected by this lane. The 650
442+filtered out are the decode/gate families outside the `encode` / `round_trip`
443+substring filters.
444+
445+Run in RELEASE because the debug encoder suite is hours; run with the repo's
446+64 MiB cap in effect, i.e. exactly how CI runs it.
447+
448+### The new gate, debug
449+
450+```
451+$ cargo test -p ec-av1 --lib -- stack_budget --nocapture
452+running 7 tests
453+test stack_budget::tests::every_by_value_type_fits_the_stack_budget ... ok
454+test stack_budget::tests::the_measured_inventory_is_accurate ... ok
455+test stack_budget::tests::the_inventory_scan_is_not_vacuous ... ok
456+test stack_budget::tests::every_by_value_module_is_scanned ... ok
457+test stack_budget::tests::test_threads_get_the_stack_they_are_given ... ok
458+test stack_budget::tests::the_deepest_by_value_constructors_fit_on_a_tight_stack ... ok
459+test stack_budget::tests::every_by_value_public_return_is_in_the_inventory ... ok
460+
461+test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 791 filtered out; finished in 0.05s
462+
463+TESTTHREADSTACK default tid=2934549 region=[7f7063fff000,7f7068000000) size=67112960 alone=false
464+ (2101248 measured with the repo cap lifted, 67112960 with it)
465+TIGHTSTACK 1048576 bytes: Av1Encoder=18168 Encoded=30728 bytes, both chains returned
466+```
467+
468+### Files changed
469+
470+```
471+crates/ec-av1/src/stack_budget.rs (new, 7 tests)
472+crates/ec-av1/src/lib.rs (+1 line: `mod stack_budget;`)
473+lanes/av1stacksweep.report.md (this file)
474+```
475+
476+Not touched: `decode.rs`, `.cargo/config.toml`, any codec logic.