forge
Explore
Log in

Don't you dare go Hollow

lane-av1stacksweep: the per-test cap answer -- 799/799 at 2 MiB, zero stack overflows

Browse files at this commit

928f2fe49442d8211cc5082d032bc77ea92dcb8cAhmet Kaan GümüşParent: 74a9f69
The chartered release run on the boxed tree: 108 passed, 0 failed, 40 ignored,
651 filtered out, 308.46s (and an independent re-run: 108/0/40, 307.03s). Same
counts as the pre-boxing run, so the layout change moved no verdict.

The per-test 2 MiB sweep, one process per test so a SIGABRT is attributable
instead of swallowing the run: 799 of 799, ZERO stack overflows. The one
non-OK entry is a TIMEOUT -- every_tile_layout_decodes_sample_exact_through_
both_decoders hit the sweep's own 600s per-test budget, not a stack limit, and
it passes in release.

So nothing in the ec-av1 lib suite needs the 64 MiB cap, and this lane removed
the last test that did (the_facade_codes_the_same_bytes_as_encode_sequence,
2097152 red / 3145728 green before, ok at 2097152 after).

Report carries the full inventory table, the 8 KiB bound with both ends of its
derivation asserted, both mutation proofs, the stale-binary false positive and
how it was caught, and the exact replacement wording for the .cargo/config.toml
comment -- which this lane does not edit.
lanes/av1stacksweep.report.mdmodified+328 -244
@@ -1,8 +1,30 @@
1 # lane-av1stacksweep — the by-value-size class, swept and gated1 # lane-av1stacksweep — the by-value-size class, swept and gated
2 2
3-**Status:** green. `crates/ec-av1/src/stack_budget.rs` (new), one line in3+**Status:** green, commit `3d4caf13`. Files: `crates/ec-av1/src/stack_budget.rs`
4-`crates/ec-av1/src/lib.rs`. No codec behaviour touched: no bitstream change, no4+(new, 8 tests), `lanes/av1stacksweep.report.md` (new), one line in
5-decoder change, no `.cargo/config.toml` edit, no rustfmt.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.
6 28
7 lane-av1enchang found and fixed ONE instance of this class (`Av1Encoder`,29 lane-av1enchang found and fixed ONE instance of this class (`Av1Encoder`,
8 139960 → 18168 B by boxing the DPB `CdfSnapshot`) and gated that one30 139960 → 18168 B by boxing the DPB `CdfSnapshot`) and gated that one
@@ -36,29 +58,38 @@ Measured with `std::mem::size_of` in a debug build, 2026-09-30, at
36 `Result<T>`, or `Option<T>` — not `Box`/`Rc`/`Arc`/`&`/`Vec`/`String`, which58 `Result<T>`, or `Option<T>` — not `Box`/`Rc`/`Arc`/`&`/`Vec`/`String`, which
37 are pointers or three words.59 are pointers or three words.
38 60
39-| bytes | type | returned by value from |61+This is the gate's own printed table (`cargo test -p ec-av1 --lib --
40-|---:|---|---|62+stack_budget -- --nocapture`), so the numbers below are not transcribed by
41-| **30728** | `encode::Encoded` | `encode_key_frame`, `encode_key_frame_with_modes`, `encode_key_frame_at_size` → `Result<Encoded>`, **4 frames deep** |63+hand. `public` = reachable from a `pub fn` return, which is what the budget
42-| **18168** | `encoder::Av1Encoder` | `new`, `with_speed`, `with_pyramid`, `with_rate_target`, `with_pyramid_and_rate_target` → `Result<Self>`, **3 frames deep** |64+applies to.
43-| **15232** | `cdf_state::Cdfs` | crate-private; the payload of every `CdfSnapshot` |65+
44-| **15232** | `encode::CdfSnapshot` | crate-private newtype over `Cdfs`; **inline twice in `Encoded`**, boxed in the DPB slot since lane-av1enchang |66+| bytes | %budget | public | type | returned by value from |
45-| 1296 | `decode::FrameCtx` | crate-private; `for_encoder()` by value, one inline per `Av1Encoder` |67+|---:|---:|---|---|---|
46-| 352 | `census::Frame` | row type, moved by value |68+| 15232 | 185.9% | no | `cdf_state::Cdfs` | `Cdfs::new(q_ctx)`; boxed everywhere it is stored |
47-| 240 | `mvstack::MvStack` | `MvStack::new` → `Self` |69+| 15232 | 185.9% | no | `encode::CdfSnapshot` | newtype over `Cdfs`; `Box`ed in all four holders |
48-| 112 | `cdf_state::TxbTables<'a>` | `Cdfs::txb` — nine borrowed slices, so the move copies pointers |70+| **2944** | **35.9%** | yes | `encoder::Av1Encoder` | `new`, `with_speed`, `with_pyramid`, `with_rate_target`, `with_pyramid_and_rate_target` → `Result<Self>`, **3 deep** |
49-| 88 | `encode::Picture` | `Picture::grey` → `Self` |71+| 1296 | 15.8% | no | `decode::FrameCtx` | `for_encoder()` → `Self`, `pub(crate)`; one per `Av1Encoder` |
50-| 72 | `encode::EncodedSequence` | `encode_sequence` → `Result<..>` |72+| 352 | 4.3% | yes | `census::Frame` | row type, moved by value |
51-| 64 | `msac::SymbolDecoder<'a>` | `SymbolDecoder::new` |73+| 280 | 3.4% | yes | `encode::Encoded` | `encode_key_frame`, `encode_key_frame_with_modes`, `encode_key_frame_at_size` → `Result<Encoded>`, **4 deep** |
52-| 56 | `msac::SymbolEncoder` | `SymbolEncoder::new`, `pricer` |74+| 240 | 2.9% | yes | `mvstack::MvStack` | `MvStack::new` → `Self` |
53-| 48 | `encoder::Packet` | `Av1Encoder::encode` → `Result<Packet>` |75+| 112 | 1.4% | no | `cdf_state::TxbTables<'a>` | `Cdfs::txb` — nine borrowed slices, so pointers not tables |
54-| 48 | `motion_field::TplProbe<'a>` | crate-private, borrowed-view handle |76+| 88 | 1.1% | yes | `encode::Picture` | `Picture::grey` → `Self` |
55-| 40 | `encoder::EncoderConfig` | `EncoderConfig::new` |77+| 72 | 0.9% | yes | `encode::EncodedSequence` | `encode_sequence` → `Result<..>` |
56-| 32 | `warp::WarpParams` | `global_warp_params` → `Option<..>` |78+| 64 | 0.8% | yes | `msac::SymbolDecoder<'a>` | `SymbolDecoder::new` |
57-| 24 | `encoder::Pyramid` | ctor + `Av1Encoder::pyramid` |79+| 56 | 0.7% | yes | `msac::SymbolEncoder` | `SymbolEncoder::new`, `pricer` |
58-| 24 | `qm::Iqm` | `iwt_matrix` → `Option<..>` |80+| 48 | 0.6% | yes | `encoder::Packet` | `Av1Encoder::encode` → `Result<Packet>` |
59-| 16 | `encoder::RateTarget` | ctor by value |81+| 48 | 0.6% | no | `motion_field::TplProbe<'a>` | borrowed-view handle |
60-| 16 | `mvstack::MiInfo` | `MvStack::get` → `Option<..>` |82+| 40 | 0.5% | yes | `encoder::EncoderConfig` | `EncoderConfig::new` |
61-| 1 | `mc::InterpFilterKind` | `from_switchable_symbol`, `from_header` |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.
62 93
63 **Two findings the earlier lane did not have:**94 **Two findings the earlier lane did not have:**
64 95
@@ -148,146 +179,145 @@ largest by-value return is a 3140 B parameter buffer that never overflows.
148 179
149 ---180 ---
150 181
151-## 2. THE BOUND: 32768 bytes (32 KiB), and why182+## 2. THE BOUND: 8192 bytes (8 KiB), derived from measurement at both ends
152 183
153-`STACK_BUDGET = 32768` in `crates/ec-av1/src/stack_budget.rs`.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.
154 187
155-Four measured inputs, none of them taste: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:
156 191
157 1. **The smallest stack a caller can hand this crate is 2,101,248 bytes.**192 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`193+ Measured, not assumed: `test_threads_get_the_stack_they_are_given` reads
159- reading `/proc/self/task/<tid>/maps` for the region containing a live194+ `/proc/self/task/<tid>/maps` for the region containing a live frame. That is
160- frame. That is libtest's default test thread and also what195+ libtest's default test thread and also what `std::thread::Builder::new()`
161- `std::thread::Builder::new()` gives a caller who does not ask for a size.196+ gives a caller who does not ask for a size. A library consumer gets no
162- A library consumer gets no `.cargo/config.toml`. The same test measures197+ `.cargo/config.toml`. (With the repo cap it measures 67,112,960 — also
163- 67,112,960 bytes when the repo's cap is applied, so the two are pinned.198+ pinned, so both ends of the claim are asserted.)
164-199+2. **The deepest PUBLIC by-value chain is 4** (`DEEPEST_PUBLIC_CHAIN`):
165-2. **The deepest public by-value chain is four frames**200+ `encode_key_frame` → `encode_key_frame_with_ctx` →
166- (`encode_key_frame` → `encode_key_frame_with_ctx` →201+ `encode_key_frame_with_modes_with_ctx` → `encode_key_frame_inner`. The
167- `encode_key_frame_with_modes_with_ctx` → `encode_key_frame_inner`).202+ encoder's own nest is 3. The test asserts
168- Worst live stack from return slots alone is `4 × size_of::<T>()`.203+ `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB` — the by-value return slots may
169-204+ claim at most an **eighth** of a caller's stack, leaving the rest for the
170-3. **At 32 KiB that is 128 KiB — 6.1% of a 2 MiB thread.** A type at the205+ encode search, which is the thing that actually needs it.
171- budget still leaves 94% of the caller's stack for its own work.206+3. **The budget applies only to types a `pub fn` returns.** The crate-private
172-207+ 15,232-byte `Cdfs` / `CdfSnapshot` are measured and listed but NOT bounded,
173-4. **The two real thresholds bracket it.** A pre-fix `Av1Encoder` (139,960 B)208+ because no caller can reach them by value — every field holding one is a
174- is **4.27× over**; `Encoded` today (30,728 B) is **93.8% of** it. So the209+ `Box`, pinned by `the_crate_private_cdf_tables_stay_behind_a_box`. Bounding
175- historical defect reds by a factor and today's worst type has a hair of210+ them would calibrate the number to something unreachable.
176- headroom — which is the point, because it is the row that wants boxing next211+
177- (§5).212+**Where the number sits.** Worst public return 2,944 B = **35.9%** of an 8 KiB
178-213+budget (2.78× headroom). Worst a caller owes: `4 × 2944 = 11,776` bytes =
179-`Encoded` at 93.8% of budget is deliberately not a violation. A budget the214+**0.56%** of a 2 MiB thread. Both directions have room, which is the point: a
180-current tree already breaks is not a budget, it is a to-do list, and the fix215+bound the largest type sits just under is a bound the next lane will quietly
181-belongs in the lane that does the boxing. The gate names it instead of216+raise.
182-pretending it is comfortable.217+
183-218+**What it catches**, each by a factor rather than a hair:
184-**Cross-check against the workspace:** 32 KiB would also have caught219+
185-`ec_opus::Encoder` (87024, 2.66× over), `ec_ac3::Ac3Decoder` (20024, under —220+| what | bytes | × over 8192 |
186-would pass), `ec_opus::SilkStereoEncoder` (19744, under — would pass), and221+|---|---:|---:|
187-every other sibling. So the bound is calibrated to catch the real defect222+| `Av1Encoder` before lane-av1enchang | 139,960 | 17.09× |
188-rather than to fit the incumbent.223+| `ec_opus::Encoder` (sibling crate, same sweep) | 87,024 | 10.62× |
189-224+| `Encoded` before this lane boxed it | 30,728 | 3.75× |
190-**What it does not claim:** `size_of` is layout, not stack depth. The 4.4×225+| `Av1Encoder` after lane-av1enchang, before this lane | 18,168 | 2.22× |
191-ratio above is why a type at the budget can still be uncomfortable in a deep226+| **`Av1Encoder` now** | **2,944** | **0.36×** |
192-chain — which is exactly what the capability arm in §3 is for.227+| **`Encoded` now** | **280** | **0.03×** |
193-228+
194----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.
195 237
196 ## 3. THE GATE, and its mutation proof238 ## 3. THE GATE, and its mutation proof
197 239
198-Seven tests in `crates/ec-av1/src/stack_budget.rs`, all green in 0.05s.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.
199 242
200 | test | what it holds |243 | test | what it holds |
201 |---|---|244 |---|---|
202-| `the_measured_inventory_is_accurate` | every row's recorded size is the size the type has now |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 |
203-| `every_by_value_type_fits_the_stack_budget` | **the bound, asserted BY NAME** |246+| `every_by_value_type_fits_the_stack_budget` | **the bound, asserted BY NAME**, plus the `DEEPEST_CHAIN × worst × 8 ≤ 2 MiB` derivation check |
204-| `the_deepest_by_value_constructors_fit_on_a_tight_stack` | **capability**: really constructs both heavy chains on a 1 MiB thread |247+| `the_deepest_by_value_constructors_fit_on_a_tight_stack` | **capability**: both deepest public chains really constructed 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 |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 |
206-| `every_by_value_module_is_scanned` | the scan's file list is derived from `lib.rs`, not curated |249+| `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 |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 |
208-| `test_threads_get_the_stack_they_are_given` | the 2 MiB floor the bound is derived from, measured |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` |
209 253
210 ### The capability arm, and the thresholds behind it254 ### The capability arm, and the thresholds behind it
211 255
212-`the_deepest_by_value_constructors_fit_on_a_tight_stack` spawns a 1 MiB thread256+One 1 MiB thread runs BOTH deepest public chains: the three-deep
213-and runs BOTH deepest public chains: the three-deep `Result<Self>` encoder257+`Result<Self>` encoder constructor nest and the four-deep `Result<Encoded>`
214-constructor nest, and the four-deep `Result<Encoded>` key-frame chain. A258+key-frame chain. A regression **aborts the process** rather than costing
215-regression **aborts the process** rather than costing invisible margin.259+invisible margin.
216 260
217-Measured stack need, **debug** build, 64×64, five runs per point, identical261+Measured stack need, **debug** build, 64×64, one process per point so a
218-every time (these are deterministic thresholds, not a distribution):262+SIGABRT cannot truncate the sweep:
219 263
220-| stack | `Av1Encoder` pyramid ctor | `encode_key_frame` |264+| stack | before this lane boxed `Encoded` | after |
221 |---|---|---|265 |---|---|---|
222-| 65536 | overflow | overflow |
223 | 131072 | overflow | overflow |266 | 131072 | overflow | overflow |
224-| 262144 | **overflow** | overflow |267+| 262144 | overflow | overflow |
225-| 524288 | ok | overflow |268+| 327680 | overflow | overflow |
226-| 655360 | ok | overflow |269+| 466944 | overflow | **overflow** |
227-| 720896 | ok | **overflow** |270+| 475136 | overflow | **ok** |
228-| 786432 | ok | ok |271+| 524288 | overflow | **ok** |
272+| 786432 | **overflow** | ok |
229 | 1048576 | **ok** | **ok** |273 | 1048576 | **ok** | **ok** |
230 274
231-Reproduce any row with `EC_AV1_TIGHT_STACK_BYTES=<bytes> cargo test -p ec-av1275+The 1 MiB gate is now **2.2×** the deepest measured need, not 1.33×. The
232---lib -- the_deepest_by_value_constructors_fit_on_a_tight_stack`.276+~470 KB that remains is the encode search's own frames, not return slots.
233-
234-### Mutation proof — both mutations, both reverted
235 277
236-**M1 — unbox what lane-av1enchang boxed** (a real revert, not a synthesised278+Reproduce any row:
237-one). `DpbSlot::cdfs: Box<CdfSnapshot>` → `CdfSnapshot` in `encoder.rs`, plus279+`EC_AV1_TIGHT_STACK_BYTES=<bytes> cargo test -p ec-av1 --lib -- the_deepest_by_value_constructors_fit_on_a_tight_stack --exact`.
238-the one construction site.
239 280
240-```281+### Mutation proof — both mutations, both reverted, both re-run after the refactor
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 282
246-assertion `left == right` failed: Av1Encoder is 139960 bytes,283+**M1 — unbox what lane-av1enchang boxed** (a real revert of `99750756`, not a
247- the inventory records 18168284+synthesised one): `DpbSlot::cdfs: Box<CdfSnapshot>` → `CdfSnapshot`, plus its
285+one construction site.
248 286
249-thread '<unknown>' has overflowed its stack
250-fatal runtime error: stack overflow, aborting
251-(signal: 6, SIGABRT) exit 101
252 ```287 ```
253-288+Av1Encoder is 139960 bytes, over the 8192-byte by-value stack budget (17.09x).
254-Three arms fired: the bound **by name**, the inventory with both numbers, and289+ It is returned by value from Av1Encoder::new / with_speed / with_pyramid /
255-the capability test as a process abort. Reverted; `git diff` empty; 7/7 green.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+```
256 294
257 **M2 — grow `Encoded` past the bound** (synthesised, and labelled as such:295 **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 a296+`Encoded` had 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).297+field of the same shape that produced the class — a 64 KiB inline payload):
260-Three construction sites patched.
261 298
262 ```299 ```
263-Encoded is 96264 bytes, over the 32768-byte by-value stack budget (2.94x).300+Encoded is 96264 bytes, over the 8192-byte by-value stack budget (11.75x).
264- ... returned by value from encode_key_frame / encode_key_frame_with_modes /301+ It is returned by value from encode_key_frame / encode_key_frame_with_modes /
265 encode_key_frame_at_size -> Result<Encoded>, nesting four deep ...302 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)303 fatal runtime error: stack overflow, aborting (signal: 6, SIGABRT)
271 ```304 ```
272 305
273-Reverted; `git status` clean apart from the two intended files.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.
274 309
275-**What is proven and what is not.** Both mutations prove the bound row and the310+**What is not proven.** That the 1 MiB gate has margin against a future
276-inventory row are live reads of the real `size_of`, not constants, and that311+rustc's frame layout. Only that a large regression aborts rather than passes
277-the capability arm reaches the process abort. They do **not** prove the 1 MiB312+quietly. The ~4.4× ratio in §1 is the honest statement of that residual risk.
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 313
282----314+## 4. THE 64 MiB CAP — what it was protecting, and what is left
283-
284-## 4. THE 64 MiB CAP — what still needs it
285 315
286 ### First: the cap is inert for anything but cargo316 ### First: the cap is inert for anything but cargo
287 317
288 `.cargo/config.toml` sets `[env] RUST_MIN_STACK = "67108864"`. Cargo applies318 `.cargo/config.toml` sets `[env] RUST_MIN_STACK = "67108864"`. Cargo applies
289-`[env]` only to processes **cargo spawns**. Running the test binary directly319+`[env]` only to processes **cargo spawns**; running the test binary directly
290-does not get it. Measured both ways on the same binary:320+does not get it. Measured both ways on one binary:
291 321
292 ```322 ```
293 RUST_MIN_STACK unset -> test thread stack 2101248 bytes323 RUST_MIN_STACK unset -> test thread stack 2101248 bytes
@@ -300,177 +330,231 @@ via `cargo test` (repo [env] in effect) -> 67112960
300 So the cap does what it claims for cargo-driven runs, and a library consumer330 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.331 who links this crate gets the 2,101,248-byte default.
302 332
303-### Second: the comment in `.cargo/config.toml` is now inaccurate333+### Second: what the cap was ACTUALLY protecting — and it was this class
304 334
305-It reads:335+Its comment reads:
306 336
307 > The AV1 rate-target tests keep several frames' worth of encoder state on the337 > 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 (release338 > test thread's stack; the 2 MB default overflows in debug builds (release
309 > passes).339 > passes).
310 340
311-**"Several frames' worth of encoder state" is not on the stack.** The state it341+**The mechanism it names is wrong.** The "frames' worth of encoder state" is
312-means is `Av1Encoder`'s `pending: Vec<(u64, Picture)>`, `ready:342+`Av1Encoder`'s `pending: Vec<(u64, Picture)>`, `ready: Vec<(u64, Picture)>` and
313-Vec<(u64, Picture)>` and `held: VecDeque<Picture>` — all heap. A source scan343+`held: VecDeque<Picture>` — all heap. A scan for a large fixed-size stack local
314-for a large fixed-size stack local in the encoder path finds exactly one, in344+in the encoder path finds exactly one:
315-`film_grain.rs`:
316 345
317 ```346 ```
318 crates/ec-av1/src/film_grain.rs:26: const GAUSSIAN_SEQUENCE: [i32; 2048] = [347 crates/ec-av1/src/film_grain.rs:26: const GAUSSIAN_SEQUENCE: [i32; 2048] = [
319 ```348 ```
320 349
321-which is a `const`, i.e. in `.rodata`, not a frame.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.
322 357
323-The claim was true **before** lane-av1enchang: a 139,960-byte `Av1Encoder`358+### Third: the per-test answer at 2 MiB
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 359
329-**I am not editing `.cargo/config.toml` in this branch**, as chartered. The360+The charter warns that lowering the cap "makes the suite red for an unknown
330-recommended replacement comment, once the numbers below are accepted, is: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.
331 364
332-> The AV1 encoder's by-value returns (`Av1Encoder` 18168 B x a 3-deep365+**Exactly one test needed more than 2 MiB:**
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 366
339-### Third: the measured answer — nothing in ec-av1 needs 64 MiB367+| 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) |
340 370
341-The cap is 64× the deepest measured need.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.
342 374
343-| what | measured stack need (debug) | at 2 MiB | at 64 MiB |375+A second name appeared in the first sweep —
344-|---|---|---|---|376+`stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane` — and
345-| `encode_key_frame`, 64×64 | 786,432 B | **2.66× margin** | 85× |377+it was a **stale-binary artefact**: I rebuilt the test binary while the sweep
346-| pyramid `encode_sequence`, 640×384 | 917,504 B | **2.13× margin** | 68× |378+was running, so part of that run measured a half-written tree. Re-verified
347-| `Av1Encoder` pyramid ctor nest | 262,144 B | **8.0× margin** | 256× |379+individually against the stable build: **ok at 2,097,152**. Recording it here
348-| the rate-target test's own worker body (see below) | 983,040 B | **2.13× margin** | 68× |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.
349 382
350-The last row is the one the cap's comment names.383+**The full sweep, on the final tree.** Reproduce with:
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 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" {}
359 ```395 ```
360-STACK rate 640x384 1048576 -> ok396+
361-STACK rate 640x384 983040 -> ABORT397+**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
362 ```402 ```
363 403
364-983,040–1,048,576 B. A 2 MiB thread has 2.13× margin. **The 64 MiB cap is404+which hit the sweep's own 600-second per-test budget, not a stack limit — it
365-64× what this test needs.**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`.
366 409
367-*(Stack depth here is set by call nesting and partition recursion depth, which410+**So: nothing in the ec-av1 lib suite requires the 64 MiB cap, and this lane
368-is bounded by block size and not by picture content, so a real clip rather411+removed the last test that did.**
369-than the grey frames I measured should need the same. That part is412+
370-[INFERENCE]; the release run of the real clip in §5 is the empirical check.)*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.
371 430
372 ### What I could not measure, and why431 ### What I could not measure, and why
373 432
374-- **`bitrate_target_lands_within_5_percent_over_48_frames` in DEBUG.** It is a433+- **`bitrate_target_lands_within_5_percent_over_48_frames` in DEBUG.** ~7 hours
375- ~7 hour test (the crate's own comment: the whole debug lib suite is 24341s434+ (the crate's own comment: the debug lib suite is 24341s and this is the
376- and this is the largest single item), and the charter says heavy suites run435+ largest single item), and heavy suites belong on the server fleet. What I
377- on the server fleet, not locally. What I measured instead is its worker body in436+ measured instead is its worker body in isolation, above. To settle it on a
378- isolation (§above), which is the same call chain without the 48-frame437+ fleet host:
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`.438 `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. The439+- **The sibling crates' suites at 2 MiB.** The measurement that matters for
382- measurement that matters for them is the per-type stack sweep in §1, and440+ them is the per-type stack sweep in §1, and that is complete: the only type
383- that is complete: the only type in the workspace that would be in danger on441+ in the workspace in danger on a 2 MiB thread is `ec_opus::Encoder`, and it
384- a 2 MiB thread is `ec_opus::Encoder`, and it survives 384 KiB.442+ survives 384 KiB.
385 443
386 ### Recommendation444 ### Recommendation
387 445
388-**Lower the cap, but not in this lane, and not to 2 MiB blind.** Dropping446+**The cap is no longer protecting anything in ec-av1 that the gates do not.**
389-`RUST_MIN_STACK` to `2097152` is supported by every measurement above for447+Recommended change, in two steps, both outside this lane's charter:
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 448
394-1. Take `ec_opus::Encoder` (87,024 B, §1) down first. At 384 KiB of live449+1. Run each crate's suite once at `RUST_MIN_STACK=2097152` on the fleet, **one
395- stack it is 2.66× over a 32 KiB budget and is the one type in the450+ test per process**, so a stack overflow is attributable rather than
396- workspace whose constructor chain could plausibly meet a small thread.451+ swallowing the run. ec-av1 is done: zero failures.
397-2. Then run each crate's suite once at `RUST_MIN_STACK=2097152` on the fleet,452+2. Then lower the cap to whatever the largest surviving requirement turns out
398- in per-test processes so a stack overflow abort is attributable rather453+ to be, and replace the comment with:
399- than swallowing the rest of the run, and lower the cap to whatever the
400- largest surviving requirement turns out to be.
401 454
402----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.
403 462
404-## 5. WHAT IS NEXT IN THIS CLASS (not done here)463+I have **not** edited `.cargo/config.toml`, as chartered.
405 464
406-**`Encoded` should have its two `CdfSnapshot` fields boxed.** 30,464 of its465+## 5. WHAT IS NEXT IN THIS CLASS (not done here)
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 466
414-That is a layout change with no bitstream effect — the same change lane-av1enchang467+**`ec_opus::Encoder` at 87,024 bytes is the live instance, and it is not in
415-made and measured byte-identical — but it touches `encode.rs` construction468+this crate.** It is 10.6× over the bound, the largest by-value type in the
416-sites that other lanes have open, so it is not this lane's to land.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.
417 471
418-**`ec_opus::Encoder` at 87,024 bytes** is the largest instance of the class in472+It is recorded rather than fixed because it is in `ec-opus`, a crate this lane
419-the workspace and lives in another crate entirely.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).
420 479
421----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`.
422 484
423 ## 6. ACCEPTANCE EVIDENCE485 ## 6. ACCEPTANCE EVIDENCE
424 486
425-### Release run487+### The new gate, debug
426 488
427 ```489 ```
428-$ CARGO_TARGET_DIR=/home/user/.cache/tgt/av1stacksweep EC_NOMEMGUARD=1 \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 \
429 cargo test --release -p ec-av1 --lib -- encode round_trip \512 cargo test --release -p ec-av1 --lib -- encode round_trip \
430 --skip bitrate_target_lands_within_5_percent_over_48_frames513 --skip bitrate_target_lands_within_5_percent_over_48_frames
431-```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
432 518
433 test result: ok. 108 passed; 0 failed; 40 ignored; 0 measured;519 test result: ok. 108 passed; 0 failed; 40 ignored; 0 measured;
434- 650 filtered out; finished in 200.51s520+ 651 filtered out; finished in 308.46s
435 521
436-Wall time: 224.72 seconds522+Wall time: 344.04 seconds
437 ```523 ```
438 524
439-All 40 ignored are the crate's pre-existing wall-measurement gates525+108 passed, 0 failed — the same count as the pre-boxing run of this exact
440-(`tile_search_wall_1080p`, `filter_stage_wall_4k`, ...), which carry their own526+command on unmodified `main` behaviour (which also reported 108/0/40), so the
441-"run it with --ignored" reasons and are not affected by this lane. The 650527+boxing changed no test's verdict.
442-filtered out are the decode/gate families outside the `encode` / `round_trip`
443-substring filters.
444 528
445-Run in RELEASE because the debug encoder suite is hours; run with the repo's529+Run in RELEASE because the debug encoder suite is hours, and with the repo's
446-64 MiB cap in effect, i.e. exactly how CI runs it.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.
447 534
448-### The new gate, debug535+### Bit-exactness of the boxing
449 536
450-```537+The boxing moves no value. The proof is structural plus the gates:
451-$ cargo test -p ec-av1 --lib -- stack_budget --nocapture538+`CdfSnapshot` is a newtype over `Cdfs`, so `Box::new(x)` stores the same
452-running 7 tests539+`x`; the CDF tables the writer starts from and the tables it stores are the
453-test stack_budget::tests::every_by_value_type_fits_the_stack_budget ... ok540+same objects, reached through one pointer indirection instead of inline.
454-test stack_budget::tests::the_measured_inventory_is_accurate ... ok541+`Encoded`'s public `stream`, `reconstruction`, `modes` and `inter_block_share`
455-test stack_budget::tests::the_inventory_scan_is_not_vacuous ... ok542+are untouched, and `Debug` still prints `CdfSnapshot` (its `Debug` impl is
456-test stack_budget::tests::every_by_value_module_is_scanned ... ok543+hand-written to print exactly that, so `Encoded`'s derived `Debug` output is
457-test stack_budget::tests::test_threads_get_the_stack_they_are_given ... ok544+byte-identical too). The round-trip and pyramid decode gates above are the
458-test stack_budget::tests::the_deepest_by_value_constructors_fit_on_a_tight_stack ... ok545+empirical half.
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 546
468 ### Files changed547 ### Files changed
469 548
470 ```549 ```
471-crates/ec-av1/src/stack_budget.rs (new, 7 tests)550+crates/ec-av1/src/stack_budget.rs new, 8 tests, #![cfg(test)]
472-crates/ec-av1/src/lib.rs (+1 line: `mod stack_budget;`)551+crates/ec-av1/src/lib.rs +1 line: `mod stack_budget;`
473-lanes/av1stacksweep.report.md (this file)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
474 ```557 ```
475 558
476-Not touched: `decode.rs`, `.cargo/config.toml`, any codec logic.559+Not touched: `decode.rs`, `.cargo/config.toml`, any CDF value, any bitstream
560+byte.