lane-av1enchang: box the DPB CdfSnapshot (Av1Encoder 139960 -> 18168 bytes), gate the tight-stack requirement, and add a measured SLOW-not-hung backstop
Browse files at this commita441af732dacec1e8af4fa5b656adeb48cb07c9aParent: 15ad3942 changed files +646 -27
- crates/ec-av1/src/encoder.rs +236 -27
- lanes/av1enchang.report.md +410 -0
crates/ec-av1/src/encoder.rsmodified+236 -27
| @@ -1477,11 +1477,22 @@ pub struct Av1Encoder { | |||
| 1477 | 1477 | ||
| 1478 | /// One decoded-picture-buffer slot: what a `refresh_frame_flags` bit stores | 1478 | /// One decoded-picture-buffer slot: what a `refresh_frame_flags` bit stores |
| 1479 | /// and what a `ref_frame_idx` entry reads back. | 1479 | /// and what a `ref_frame_idx` entry reads back. |
| 1480 | +/// | ||
| 1481 | +/// lane-av1enchang: the `CdfSnapshot` is BOXED, not held by value. Eight | ||
| 1482 | +/// inline copies made [`Av1Encoder`] 139960 bytes, and that struct is | ||
| 1483 | +/// returned by value through three nested `Result<Self>` constructors | ||
| 1484 | +/// ([`Av1Encoder::with_pyramid_and_rate_target`] -> | ||
| 1485 | +/// [`Av1Encoder::with_pyramid`] -> [`Av1Encoder::new`]), so an unoptimized | ||
| 1486 | +/// build put several of those on the stack at once: the pyramid path | ||
| 1487 | +/// overflowed libtest's 2 MiB test thread and aborted the whole crate suite | ||
| 1488 | +/// with `fatal runtime error: stack overflow`. One heap box per DPB slot | ||
| 1489 | +/// brings the struct from 139960 bytes down to 18168 (measured). The tables' | ||
| 1490 | +/// VALUES are untouched. | ||
| 1480 | #[derive(Debug, Clone)] | 1491 | #[derive(Debug, Clone)] |
| 1481 | struct DpbSlot { | 1492 | struct DpbSlot { |
| 1482 | picture: Picture, | 1493 | picture: Picture, |
| 1483 | order_hint: u32, | 1494 | order_hint: u32, |
| 1484 | - cdfs: crate::encode::CdfSnapshot, | 1495 | + cdfs: Box<crate::encode::CdfSnapshot>, |
| 1485 | } | 1496 | } |
| 1486 | 1497 | ||
| 1487 | /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are | 1498 | /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are |
| @@ -1963,7 +1974,7 @@ impl Av1Encoder { | |||
| 1963 | let slot = DpbSlot { | 1974 | let slot = DpbSlot { |
| 1964 | picture: encoded.reconstruction.clone(), | 1975 | picture: encoded.reconstruction.clone(), |
| 1965 | order_hint, | 1976 | order_hint, |
| 1966 | - cdfs: encoded.next_cdfs.clone(), | 1977 | + cdfs: Box::new(encoded.next_cdfs.clone()), |
| 1967 | }; | 1978 | }; |
| 1968 | for &s in slots { | 1979 | for &s in slots { |
| 1969 | self.dpb[s as usize] = Some(slot.clone()); | 1980 | self.dpb[s as usize] = Some(slot.clone()); |
| @@ -3379,6 +3390,35 @@ mod tests { | |||
| 3379 | ); | 3390 | ); |
| 3380 | } | 3391 | } |
| 3381 | 3392 | ||
| 3393 | + /// One (bitrate, pyramid) arm's tally, built on the worker thread and | ||
| 3394 | + /// handed back through the progress channel | ||
| 3395 | + /// (`bitrate_target_lands_within_5_percent_over_48_frames`). Per LEVEL, | ||
| 3396 | + /// so a miss reads as WHICH level's model is off rather than as one | ||
| 3397 | + /// aggregate percentage. | ||
| 3398 | + struct ArmResult { | ||
| 3399 | + /// [`RateLoop::target`] as the arm's own encoder computed it. | ||
| 3400 | + targets: [f64; 3], | ||
| 3401 | + coded: usize, | ||
| 3402 | + bytes: [usize; 4], | ||
| 3403 | + count: [usize; 4], | ||
| 3404 | + } | ||
| 3405 | + | ||
| 3406 | + impl ArmResult { | ||
| 3407 | + fn take(&mut self, packets: Vec<Packet>) { | ||
| 3408 | + for packet in packets { | ||
| 3409 | + self.coded += packet.data.len(); | ||
| 3410 | + let i = match packet.level { | ||
| 3411 | + Level::Key => 0, | ||
| 3412 | + Level::Arf => 1, | ||
| 3413 | + Level::Leaf => 2, | ||
| 3414 | + Level::ShowExisting => 3, | ||
| 3415 | + }; | ||
| 3416 | + self.bytes[i] += packet.data.len(); | ||
| 3417 | + self.count[i] += 1; | ||
| 3418 | + } | ||
| 3419 | + } | ||
| 3420 | + } | ||
| 3421 | + | ||
| 3382 | /// [`RateTarget::Bitrate`] lands the achieved bitrate within ±5% of the | 3422 | /// [`RateTarget::Bitrate`] lands the achieved bitrate within ±5% of the |
| 3383 | /// target over 48 frames of a real clip, flat and under a pyramid alike, | 3423 | /// target over 48 frames of a real clip, flat and under a pyramid alike, |
| 3384 | /// across a 5x span of bitrates. This is the accuracy claim of the | 3424 | /// across a 5x span of bitrates. This is the accuracy claim of the |
| @@ -3394,6 +3434,103 @@ mod tests { | |||
| 3394 | /// frame are the same at 1.5 and 2 Mbit/s) and the leaves sit at 1 + 12 | 3434 | /// frame are the same at 1.5 and 2 Mbit/s) and the leaves sit at 1 + 12 |
| 3395 | /// `leaf_q_offset`, so this clip cannot be made to spend much past | 3435 | /// `leaf_q_offset`, so this clip cannot be made to spend much past |
| 3396 | /// 2.4 Mbit/s under the default pyramid however the budget is split. | 3436 | /// 2.4 Mbit/s under the default pyramid however the budget is split. |
| 3437 | + /// | ||
| 3438 | + /// # Bounded | ||
| 3439 | + /// | ||
| 3440 | + /// Each arm's encode runs on a worker thread under a per-CALL | ||
| 3441 | + /// wall-clock ceiling, so this gate FAILS rather than hanging when an | ||
| 3442 | + /// encode stops terminating (lane-av1enchang: a 3h20m wedge on one host | ||
| 3443 | + /// and 30min on another, both here, both with the test thread spinning | ||
| 3444 | + /// and no child process for the crate's child timeout to reap). The cost | ||
| 3445 | + /// is real and is why the budget is not tight: the two high bitrate arms | ||
| 3446 | + /// walk `q_idx` from the seed 100 down into the 20s to spend an | ||
| 3447 | + /// 8000-byte budget on a 640x384 clip, and a frame at `q_idx` 25 costs | ||
| 3448 | + /// ~15s in a debug build (~1s optimized) against ~0.5s at `q_idx` 100. | ||
| 3449 | + /// lane-av1enchang: the PYRAMID CONSTRUCTORS fit on a tight stack. | ||
| 3450 | + /// | ||
| 3451 | + /// `Av1Encoder` used to be 139960 bytes BY VALUE, because each of the | ||
| 3452 | + /// eight `DpbSlot`s held a 15 KB `CdfSnapshot` inline. The pyramid | ||
| 3453 | + /// constructors nest three deep -- `with_pyramid_and_rate_target` -> | ||
| 3454 | + /// `with_pyramid` -> `new` -- and each level materialises the struct in | ||
| 3455 | + /// an unoptimized build, so ~840 KB of stack was live at the innermost | ||
| 3456 | + /// `Ok(Self { .. })`. On libtest's default 2 MiB test thread that aborts: | ||
| 3457 | + /// `fatal runtime error: stack overflow, aborting`, reproduced on the | ||
| 3458 | + /// pre-fix binary at `crates/ec-av1/src/encoder.rs:1519` via | ||
| 3459 | + /// `coredumpctl debug`. | ||
| 3460 | + /// | ||
| 3461 | + /// Boxing the snapshot brought the struct to 18168 bytes. This gate pins | ||
| 3462 | + /// that: it builds BOTH constructors on a thread with a deliberately | ||
| 3463 | + /// tight stack, so the old layout ABORTS THE PROCESS and the new one | ||
| 3464 | + /// returns. It runs in milliseconds, where proving the same thing through | ||
| 3465 | + /// the 48-frame gate takes 6m35s. | ||
| 3466 | + /// | ||
| 3467 | + /// Both thresholds were swept, in an unoptimized build: | ||
| 3468 | + /// | ||
| 3469 | + /// | stack | pre-fix (`CdfSnapshot` by value) | post-fix (boxed) | | ||
| 3470 | + /// |---|---|---| | ||
| 3471 | + /// | 256 KiB | overflow | overflow | | ||
| 3472 | + /// | 384 KiB | overflow | ok | | ||
| 3473 | + /// | 512 KiB | overflow | ok | | ||
| 3474 | + /// | 1 MiB | **overflow** | **ok** | | ||
| 3475 | + /// | 2 MiB | **overflow** (libtest's default) | ok | | ||
| 3476 | + /// | 3 MiB | ok | ok | | ||
| 3477 | + /// | ||
| 3478 | + /// 1 MiB is the gate: 2.7x what the boxed layout needs and 2x below what | ||
| 3479 | + /// the old one did, so it is nowhere near either threshold and cannot | ||
| 3480 | + /// flake. The pre-fix row at 1 MiB is the red -- which is also why | ||
| 3481 | + /// `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864`, a | ||
| 3482 | + /// workspace-local band-aid this gate makes unnecessary for this struct. | ||
| 3483 | + /// | ||
| 3484 | + /// `EC_AV1_TIGHT_STACK_BYTES` overrides the size, which is how the sweep | ||
| 3485 | + /// above is reproduced. | ||
| 3486 | + #[test] | ||
| 3487 | + fn the_pyramid_constructors_fit_on_a_tight_stack() { | ||
| 3488 | + // 1 MiB: see the threshold table on this test. Red before the Box, | ||
| 3489 | + // green after, with 2.7x margin either way. | ||
| 3490 | + const STACK: usize = 1024 * 1024; | ||
| 3491 | + let stack: usize = std::env::var("EC_AV1_TIGHT_STACK_BYTES") | ||
| 3492 | + .ok() | ||
| 3493 | + .and_then(|v| v.parse().ok()) | ||
| 3494 | + .unwrap_or(STACK); | ||
| 3495 | + let config = EncoderConfig { | ||
| 3496 | + width: 640, | ||
| 3497 | + height: 384, | ||
| 3498 | + base_q_idx: 100, | ||
| 3499 | + gop: 48, | ||
| 3500 | + colour: Colour::Bt709Limited, | ||
| 3501 | + tile_cols_log2: 0, | ||
| 3502 | + tile_rows_log2: 0, | ||
| 3503 | + }; | ||
| 3504 | + let rate = RateTarget::Bitrate { | ||
| 3505 | + bits_per_second: 1_536_000, | ||
| 3506 | + frames_per_second: 24.0, | ||
| 3507 | + }; | ||
| 3508 | + let handle = std::thread::Builder::new() | ||
| 3509 | + .stack_size(stack) | ||
| 3510 | + .spawn(move || { | ||
| 3511 | + let flat = Av1Encoder::with_rate_target(config, rate) | ||
| 3512 | + .expect("with_rate_target") | ||
| 3513 | + .rate_loop | ||
| 3514 | + .is_some(); | ||
| 3515 | + let pyr = | ||
| 3516 | + Av1Encoder::with_pyramid_and_rate_target(config, Pyramid::default(), rate) | ||
| 3517 | + .expect("with_pyramid_and_rate_target") | ||
| 3518 | + .pyramid | ||
| 3519 | + .is_some(); | ||
| 3520 | + (flat, pyr) | ||
| 3521 | + }) | ||
| 3522 | + .expect("spawn tight-stack thread"); | ||
| 3523 | + let (flat, pyr) = handle | ||
| 3524 | + .join() | ||
| 3525 | + .unwrap_or_else(|_| panic!("the encoder constructors overflowed a {stack}-byte stack")); | ||
| 3526 | + assert!(flat, "with_rate_target lost its rate loop"); | ||
| 3527 | + assert!(pyr, "with_pyramid_and_rate_target lost its pyramid"); | ||
| 3528 | + eprintln!( | ||
| 3529 | + "TIGHTSTACK {stack} bytes: Av1Encoder={} bytes, both constructors returned", | ||
| 3530 | + std::mem::size_of::<Av1Encoder>() | ||
| 3531 | + ); | ||
| 3532 | + } | ||
| 3533 | + | ||
| 3397 | #[test] | 3534 | #[test] |
| 3398 | fn bitrate_target_lands_within_5_percent_over_48_frames() { | 3535 | fn bitrate_target_lands_within_5_percent_over_48_frames() { |
| 3399 | let _knobs = crate::speed::knob_read(); | 3536 | let _knobs = crate::speed::knob_read(); |
| @@ -3407,6 +3544,7 @@ mod tests { | |||
| 3407 | return; | 3544 | return; |
| 3408 | }; | 3545 | }; |
| 3409 | let fps = 24.0; | 3546 | let fps = 24.0; |
| 3547 | + let pictures = std::sync::Arc::new(pictures); | ||
| 3410 | for bits_per_second in [384_000u32, 768_000, 1_536_000, 2_000_000] { | 3548 | for bits_per_second in [384_000u32, 768_000, 1_536_000, 2_000_000] { |
| 3411 | let config = EncoderConfig { | 3549 | let config = EncoderConfig { |
| 3412 | width, | 3550 | width, |
| @@ -3422,32 +3560,104 @@ mod tests { | |||
| 3422 | frames_per_second: fps, | 3560 | frames_per_second: fps, |
| 3423 | }; | 3561 | }; |
| 3424 | for pyramid in [None, Some(Pyramid::default())] { | 3562 | for pyramid in [None, Some(Pyramid::default())] { |
| 3425 | - let mut enc = match pyramid { | 3563 | + let arm = format!("{bits_per_second} bps pyramid {}", pyramid.is_some()); |
| 3426 | - None => Av1Encoder::with_rate_target(config, rate).unwrap(), | 3564 | + // lane-av1enchang: a BACKSTOP, not a fix. This gate is NOT |
| 3427 | - Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(), | 3565 | + // hung and NOT regressed -- it is a ~7 hour test in an |
| 3428 | - }; | 3566 | + // unoptimized build (measured: the whole `ec-av1` lib suite |
| 3429 | - let targets = enc.rate_loop.as_ref().unwrap().target; | 3567 | + // takes 24341s, and this test is the largest single item in |
| 3430 | - let mut coded = 0usize; | 3568 | + // it), and it PASSES. What it lacked was any way to FAIL: a |
| 3431 | - // Per level, so a miss reads as WHICH level's model is off | 3569 | + // future non-terminating encode would wedge the suite for |
| 3432 | - // rather than as one aggregate percentage. | 3570 | + // hours with no diagnostic, which is exactly how wave3j and |
| 3433 | - let (mut bytes, mut count) = ([0usize; 4], [0usize; 4]); | 3571 | + // wave3h were lost. So the arm runs on a worker thread and |
| 3434 | - let mut take = |packets: Vec<Packet>| { | 3572 | + // THIS thread watches a per-CALL deadline, purely so that |
| 3435 | - for packet in packets { | 3573 | + // case reports itself. |
| 3436 | - coded += packet.data.len(); | 3574 | + // |
| 3437 | - let i = match packet.level { | 3575 | + // The budget is PER CALL, not per test, and it is valued from |
| 3438 | - Level::Key => 0, | 3576 | + // a measured run so it cannot turn a correct-but-slow build |
| 3439 | - Level::Arf => 1, | 3577 | + // red. Measured on this gate's own workload (48 frames of |
| 3440 | - Level::Leaf => 2, | 3578 | + // 640x384): one `encode_frames` call is 0.78s..1.04s |
| 3441 | - Level::ShowExisting => 3, | 3579 | + // optimized and 8.6s..12.2s debug on the flat arms. A |
| 3442 | - }; | 3580 | + // PYRAMID call codes a whole mini-GOP at once, so its worst |
| 3443 | - bytes[i] += packet.data.len(); | 3581 | + // single call is `Pyramid::default().mini_gop` frames |
| 3444 | - count[i] += 1; | 3582 | + // (~9), i.e. ~110s debug. 1800s is therefore ~16x that |
| 3583 | + // worst honest call: no plausible host trips it, and a real | ||
| 3584 | + // non-terminating encode is reported in 30 minutes instead | ||
| 3585 | + // of never. `EC_AV1_ENCODE_CALL_BUDGET_SECS` overrides it, | ||
| 3586 | + // which is how the backstop is proven to bite. | ||
| 3587 | + let budget = std::time::Duration::from_secs( | ||
| 3588 | + std::env::var("EC_AV1_ENCODE_CALL_BUDGET_SECS") | ||
| 3589 | + .ok() | ||
| 3590 | + .and_then(|v| v.parse().ok()) | ||
| 3591 | + .unwrap_or(1800), | ||
| 3592 | + ); | ||
| 3593 | + let total = pictures.len() + 1; | ||
| 3594 | + // Shared, not cloned: the 48 decoded frames are ~35 MB of | ||
| 3595 | + // `u16` luma+chroma, and all eight arms want the same ones. | ||
| 3596 | + let pictures = std::sync::Arc::clone(&pictures); | ||
| 3597 | + // `None` is a progress ticket: THIS call returned. `Some` is | ||
| 3598 | + // the arm's result, sent after `flush` -- which is itself a | ||
| 3599 | + // call that can spin, so it needs a ticket too, not a bare | ||
| 3600 | + // `join` that would block forever. | ||
| 3601 | + let (tx, rx) = std::sync::mpsc::channel::<Option<ArmResult>>(); | ||
| 3602 | + let worker = std::thread::spawn(move || { | ||
| 3603 | + let mut enc = match pyramid { | ||
| 3604 | + None => Av1Encoder::with_rate_target(config, rate).unwrap(), | ||
| 3605 | + Some(p) => { | ||
| 3606 | + Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap() | ||
| 3607 | + } | ||
| 3608 | + }; | ||
| 3609 | + let targets = enc.rate_loop.as_ref().unwrap().target; | ||
| 3610 | + let mut out = ArmResult { | ||
| 3611 | + targets, | ||
| 3612 | + coded: 0, | ||
| 3613 | + bytes: [0; 4], | ||
| 3614 | + count: [0; 4], | ||
| 3615 | + }; | ||
| 3616 | + for picture in pictures.iter() { | ||
| 3617 | + out.take(enc.encode_frames(picture).unwrap()); | ||
| 3618 | + if tx.send(None).is_err() { | ||
| 3619 | + return; | ||
| 3620 | + } | ||
| 3621 | + } | ||
| 3622 | + out.take(enc.flush().unwrap()); | ||
| 3623 | + let _ = tx.send(Some(out)); | ||
| 3624 | + }); | ||
| 3625 | + let started = std::time::Instant::now(); | ||
| 3626 | + let mut calls = 0usize; | ||
| 3627 | + let out = loop { | ||
| 3628 | + match rx.recv_timeout(budget) { | ||
| 3629 | + // The result IS the last thing the worker sends, so | ||
| 3630 | + // receiving it means every call returned. A worker | ||
| 3631 | + // that panicked sends nothing and arrives as | ||
| 3632 | + // `Disconnected` below, which re-joins it and | ||
| 3633 | + // surfaces the real panic. | ||
| 3634 | + Ok(Some(out)) => break out, | ||
| 3635 | + Ok(None) => calls += 1, | ||
| 3636 | + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => panic!( | ||
| 3637 | + "AV1 bitrate gate SLOW, NOT HUNG: the {arm} arm's encode did not \ | ||
| 3638 | + return within {}s (arm elapsed {:.0}s, stuck on call {} of {total} \ | ||
| 3639 | + -- the call that never came back). This gate is a ~7 hour test in \ | ||
| 3640 | + an unoptimized build and it PASSES, so a red here is NOT a slow \ | ||
| 3641 | + host: the budget is per CALL and the worst honest call measured \ | ||
| 3642 | + is ~1s optimized / ~110s debug on a pyramid arm, so reaching this \ | ||
| 3643 | + panic means an encode call that is NOT RETURNING. \ | ||
| 3644 | + EC_AV1_ENCODE_CALL_BUDGET_SECS raises the budget.", | ||
| 3645 | + budget.as_secs(), | ||
| 3646 | + started.elapsed().as_secs_f64(), | ||
| 3647 | + calls + 1, | ||
| 3648 | + ), | ||
| 3649 | + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => { | ||
| 3650 | + worker.join().expect("encode worker panicked"); | ||
| 3651 | + panic!("AV1 encode worker for {arm} died without a result"); | ||
| 3652 | + } | ||
| 3445 | } | 3653 | } |
| 3446 | }; | 3654 | }; |
| 3447 | - for picture in &pictures { | 3655 | + let ArmResult { |
| 3448 | - take(enc.encode_frames(picture).unwrap()); | 3656 | + targets, |
| 3449 | - } | 3657 | + coded, |
| 3450 | - take(enc.flush().unwrap()); | 3658 | + bytes, |
| 3659 | + count, | ||
| 3660 | + } = out; | ||
| 3451 | let seconds = frames as f64 / fps; | 3661 | let seconds = frames as f64 / fps; |
| 3452 | let achieved = coded as f64 * 8.0 / seconds; | 3662 | let achieved = coded as f64 * 8.0 / seconds; |
| 3453 | let error = achieved / f64::from(bits_per_second) - 1.0; | 3663 | let error = achieved / f64::from(bits_per_second) - 1.0; |
| @@ -3478,7 +3688,6 @@ mod tests { | |||
| 3478 | } | 3688 | } |
| 3479 | } | 3689 | } |
| 3480 | } | 3690 | } |
| 3481 | - | ||
| 3482 | /// The `BytesPerFrame` controller's own windup bound: no frame's coded | 3691 | /// The `BytesPerFrame` controller's own windup bound: no frame's coded |
| 3483 | /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real | 3692 | /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real |
| 3484 | /// clip's full range of content (so a scene cut can't be the one frame | 3693 | /// clip's full range of content (so a scene cut can't be the one frame |
lanes/av1enchang.report.mdadded+410 -0
| @@ -0,0 +1,410 @@ | |||
| 1 | +# lane-av1enchang — `bitrate_target_lands_within_5_percent_over_48_frames`: a MEASUREMENT, not a hang | ||
| 2 | + | ||
| 3 | +Branch `lane-av1enchang`, off `main` `3698787d`. One source file, | ||
| 4 | +`crates/ec-av1/src/encoder.rs`, plus this report. | ||
| 5 | + | ||
| 6 | +## Verdict | ||
| 7 | + | ||
| 8 | +**The test is not hung, not stuck, and not a regression. It is a ~7 hour test in an | ||
| 9 | +unoptimized build and it PASSES.** The "wedge" was a suite killed mid-test. Coordinator | ||
| 10 | +evidence closes it: `/home/user/gates/wave3e-suite.log` line 180 reads | ||
| 11 | +`test encoder::tests::bitrate_target_lands_within_5_percent_over_48_frames ... ok`, and the | ||
| 12 | +same log ends `test result: ok. 713 passed; 0 failed; 49 ignored; 0 measured; 0 filtered | ||
| 13 | +out; finished in 24341.37s` — 6.76 hours for the whole `ec-av1` lib suite. | ||
| 14 | + | ||
| 15 | +Independently reproduced here, and everything below is measured on this box, not inferred. | ||
| 16 | + | ||
| 17 | +| question | answer | evidence | | ||
| 18 | +|---|---|---| | ||
| 19 | +| Does it terminate? | **yes** | all 8 arms pass, 4m40s optimized, on unmodified `main` | | ||
| 20 | +| Is it a regression? | **no** | same test, same 4 bitrates, byte-identical output at pin `ea8fa18f` | | ||
| 21 | +| Why so slow? | **not a pathology** | `evals_per_search` is flat at 61.3 → 64.9 as `q_idx` falls | | ||
| 22 | +| Is the search degenerating? | **no** | 61.3/64.5/64.9 evals/search across 384k/1.5M/2M — that is the search's designed bound | | ||
| 23 | +| Is the motion-search call count the defect? | **no** | 1,885–2,711 searches/frame over 60 superblocks = 31–45/superblock, bounded | | ||
| 24 | + | ||
| 25 | +## What is landed | ||
| 26 | + | ||
| 27 | +1. **A documented backstop**, valued from a measured run, so a future *non-terminating* | ||
| 28 | + encode fails this gate in 30 minutes instead of wedging a suite for hours. It is not | ||
| 29 | + presented as a fix for the cost, because it is not one. | ||
| 30 | +2. **A real, separately-justified encoder fix**: `Av1Encoder` was **139,960 bytes by value**; | ||
| 31 | + it is now **18,168**. Two lines. It is a public-API stack hazard, unrelated to the wedge. | ||
| 32 | +3. **A millisecond regression gate** for that fix, | ||
| 33 | + `the_pyramid_constructors_fit_on_a_tight_stack`: both constructors are built on a | ||
| 34 | + 1 MiB stack, which the old layout cannot survive and the new one clears with 2.7x | ||
| 35 | + margin. | ||
| 36 | + | ||
| 37 | +## Finding 1 — the cost, measured and attributed | ||
| 38 | + | ||
| 39 | +### 1.1 Where the time goes: the motion-search census | ||
| 40 | + | ||
| 41 | +`motion.rs` already keeps a census (`searches`, `evals`, `subpel evals`, | ||
| 42 | +`zero_mv`). A temporary probe (`tmp_mv_census`, since removed) read it per arm, optimized, | ||
| 43 | +48 frames of 640x384, flat path: | ||
| 44 | + | ||
| 45 | +| arm | searches | evals | **evals/search** | evals/frame | s/frame | searches/frame | | ||
| 46 | +|---|---|---|---|---|---|---| | ||
| 47 | +| 384 000 bps (`q` walks **up**) | 90,495 | 5,547,925 | **61.3** | 115,582 | 0.53 | 1,885 | | ||
| 48 | +| 1 536 000 bps (`q` → ~25) | 122,011 | 7,869,268 | **64.5** | 163,943 | 0.90 | 2,542 | | ||
| 49 | +| 2 000 000 bps (`q` lower still) | 130,163 | 8,447,516 | **64.9** | 175,990 | 1.02 | 2,712 | | ||
| 50 | + | ||
| 51 | +`evals_per_search` is **flat**. A diamond log-step search over 8 neighbours plus the | ||
| 52 | +half-pel and quarter-pel refinement stages has a designed bound right around 56–64 evals, | ||
| 53 | +and the measured 61.3 → 64.9 sits on it. **The search is not degenerating and there is no | ||
| 54 | +runaway call count to bound.** The cost is the plain product | ||
| 55 | + | ||
| 56 | +> full search x 60 superblocks (640/64 x 384/64) x 48 frames x 8 arms x ~13x debug penalty | ||
| 57 | + | ||
| 58 | +which is why the expensive arms are the **high-bitrate** ones: the controller must walk | ||
| 59 | +`q_idx` *down* from its seed 100 into the 20s to spend an 8000-byte budget, and a | ||
| 60 | +lower-`q` frame costs 1.4-1.5x more (163,943 vs 115,582 evals/frame). At 384k/768k the | ||
| 61 | +loop pushes `q` *up* and those arms are cheap. That is why the first four arms of a | ||
| 62 | +partially-completed run print and the fifth does not. | ||
| 63 | + | ||
| 64 | +### 1.2 Why the controller walks `q` down at all | ||
| 65 | + | ||
| 66 | +At its seed `base_q_idx` of 100 this clip codes **5467 bytes** for the key frame, and the | ||
| 67 | +`1_536_000 bps` target is `1536000/8/24 = 8000` bytes/frame — the seed is *already under | ||
| 68 | +budget*, so the loop must lower `q_idx` at `STEP_CLAMP`=12 per frame to spend the rest. | ||
| 69 | +Per-frame probe, one arm, optimized: | ||
| 70 | + | ||
| 71 | +``` | ||
| 72 | +TMP frame 7 at 0.0s (+0.00s) q=100 bytes_so_far=0 | ||
| 73 | +TMP frame 8 at 0.8s (+0.78s) q=75 bytes_so_far=5467 | ||
| 74 | +TMP frame 9 at 1.3s (+0.53s) q=63 bytes_so_far=9725 | ||
| 75 | +TMP frame 11 at 2.9s (+0.83s) q=39 bytes_so_far=20520 | ||
| 76 | +TMP frame 20 at 11.5s (+1.04s) q=32 bytes_so_far=91906 | ||
| 77 | +TMP frame 30 at 20.5s (+0.88s) q=23 bytes_so_far=171230 | ||
| 78 | +TMP frame 47 at 35.9s (+0.81s) q=27 bytes_so_far=308242 | ||
| 79 | +TMP done bps=1536000 pyr=false coded=372465 | ||
| 80 | +``` | ||
| 81 | + | ||
| 82 | +`q_idx` settles into a 22..36 band and **stops walking**. The same arm debug: `+10.79s, | ||
| 83 | ++8.61s, +11.24s, +12.18s` at the same `q` — the ~13x profile ratio. | ||
| 84 | + | ||
| 85 | +### 1.3 Three gdb samples prove the thread is walking, not repeating | ||
| 86 | + | ||
| 87 | +Taken 20 s apart on the `1_536_000 bps` flat arm (the arm a short run is inside when it | ||
| 88 | +looks wedged): | ||
| 89 | + | ||
| 90 | +``` | ||
| 91 | +$ for i in 1 2 3; do gdb -p <pid> -batch -ex 'thread apply all bt'; sleep 20; done | ||
| 92 | +``` | ||
| 93 | + | ||
| 94 | +Sample 1 (08:47:35) — MV-search / transform, block `x=192,y=80`, `base_q_idx=32`: | ||
| 95 | + | ||
| 96 | +``` | ||
| 97 | +#8 ec_av1::transform::permute<i32> (t=0x7f9809f91490, n=4) at crates/ec-av1/src/transform.rs:355 | ||
| 98 | +#9 ec_av1::transform::inverse_dct_n<i32, 4> (t=0x7f9809f91490, r=16) at crates/ec-av1/src/transform.rs:413 | ||
| 99 | +#11 ec_av1::transform::inverse_1d (t=0x7f9809f91490, log2=4, r=16, kind=ec_av1::transform::TxType1d::Dct) at crates/ec-av1/src/transform.rs:1103 | ||
| 100 | +#15 ec_av1::transform::inverse_transform_2d_typed_wh (dequant=..., w=16, h=16, bit_depth=8, tx_type=ec_av1::transform::TxType::DctDct) at crates/ec-av1/src/transform.rs:1171 | ||
| 101 | +#19 ec_av1::transform::dequant_and_inverse_typed_wh (levels=..., w=16, h=16, bit_depth=8, q_idx=32, dc_delta=0, ac_delta=0, tx_type=…DctDct, qm=…) at crates/ec-av1/src/transform.rs:1375 | ||
| 102 | +#20 ec_av1::encode::Plane::code_from_prediction_typed (self=0x7f9809f9c460, x=192, y=80, side=16, prediction=..., skip=false, base_q_idx=32, deadzone=0.5, set=ec_av1::cdf_state::TxbSet::Chroma16, tx_type=…DctDct) at crates/ec-av1/src/encode.rs:3109 | ||
| 103 | +#22 ec_av1::encode::mc_trial_compound (plane=0x7f9809f9c460, x=192, y=80, side=16, luma=false, ref0=..., ref1=..., base_q_idx=32, …) at crates/ec-av1/src/encode.rs:10435 | ||
| 104 | +#23 ec_av1::encode::search_inter_block (luma=0x7f9809f9c340, chroma=0x7f9809f9c3d0, search=0x7f9809f9eb28, mode_bits=0x7f9809fa6998, reference=0x7f980a01e6b0, stack=0x7f9809f9ec10, extra=..., compound=..., grid=0x7f9809f9c610, fctx=0x7f980a0403d0) at crates/ec-av1/src/encode.rs:12331 | ||
| 105 | +#24 ec_av1::encode::encode_inter_frame::{closure#19} (index=0, fctx=0x7f980a01e6b0) at crates/ec-av1/src/encode.rs:14673 | ||
| 106 | +#25 ec_av1::encode::search_tiles::{closure#0} (index=0) at crates/ec-av1/src/encode.rs:8704 | ||
| 107 | +``` | ||
| 108 | + | ||
| 109 | +Sample 2 (08:47:55) — a different function and a different block: | ||
| 110 | + | ||
| 111 | +``` | ||
| 112 | +#5 ec_av1::encode::intra_predict_u8::{closure#0} (src=..., buf=0x7f9809f90aee) at crates/ec-av1/src/encode.rs:1691 | ||
| 113 | +#6 ec_av1::encode::intra_predict_u8 (mode=2, angle_delta=0, above=..., left=..., corner=..., bw=8, bh=8, enable_edge_filter=false, smooth_neighbor=false, dst=..., fctx=0x7f980a0403d0) at crates/ec-av1/src/encode.rs:1696 | ||
| 114 | +#7 ec_av1::encode::{impl#2}::search_block::{closure#0} () at crates/ec-av1/src/encode.rs:3564 | ||
| 115 | +#18 ec_av1::encode::Plane::search_block (self=0x7f9809f9c340, at=..., search=0x7f9809f9eb28, mode_bits=0x7f9809fa6998, fctx=0x7f980a0403d0) at crates/ec-av1/src/encode.rs:3588 | ||
| 116 | +#19 ec_av1::encode::code_square (luma=0x7f9809f9c340, chroma=0x7f9809f9c3d0, side=8, search=0x7f9809f9eb28, mode_bits=0x7f9809fa6998, tx_select=true, ibc=..., census_key=false, fctx=0x7f980a0403d0) at crates/ec-av1/src/encode.rs:6271 | ||
| 117 | +#20 ec_av1::encode::code_square_inter (luma=0x7f9809f9c340, chroma=0x7f9809f9c3d0, side=8, search=0x7f9809f9eb28, mode_bits=0x7f9809fa6998, reference=0x7f980a01e6b0, stack=0x7f9809f9a550, compound=..., grid=0x7f9809f9c610, refs=0x7f9809f9c698, fctx=0x7f980a0403d0) at crates/ec-av1/src/encode.rs:7266 | ||
| 118 | +#25 ec_av1::encode::encode_inter_frame::{closure#19} (index=0, fctx=0x7f980a0403d0) at crates/ec-av1/src/encode.rs:14724 | ||
| 119 | +``` | ||
| 120 | + | ||
| 121 | +Sample 3 (08:48:16) — a third block, and a **later frame's** quantizer: | ||
| 122 | + | ||
| 123 | +``` | ||
| 124 | +#1 ec_av1::tile::base_ctx (grid=..., side=32, row=6, col=30, class=ec_av1::decode::TxClass::TwoD) at crates/ec-av1/src/tile.rs:6759 | ||
| 125 | +#14 ec_av1::tile::coeff_bits_typed (grid=..., set=ec_av1::cdf_state::TxbSet::Luma32Inter, q_ctx=1, skip_ctx=0, sign_ctx=1, tx_type=…DctDct) at crates/ec-av1/src/tile.rs:6004 | ||
| 126 | +#15 ec_av1::tile::rdoq::price (levels=..., dense=..., side=32, coded=32, set=…Luma32Inter, q_ctx=1, skip_ctx=0, sign_ctx=1, tx_type=…DctDct) at crates/ec-av1/src/tile.rs:6116 | ||
| 127 | +#16 ec_av1::tile::rdoq (levels=..., scaled=..., side=32, base_q_idx=30, set=…Luma32Inter, skip_ctx=0, sign_ctx=1, lambda=0.060500000000000005, tx_type=…DctDct) at crates/ec-av1/src/tile.rs:6176 | ||
| 128 | +#17 ec_av1::encode::Plane::code_from_prediction_typed (self=0x7f9809f9c340, x=256, y=128, side=32, prediction=..., skip=false, base_q_idx=30, deadzone=0.5, set=…Luma32Inter, tx_type=…DctDct) at crates/ec-av1/src/encode.rs:3083 | ||
| 129 | +#19 ec_av1::encode::mc_trial (plane=0x7f9809f9c340, x=256, y=128, side=32, mv=..., luma=true, reference=..., stride=640, ref_width=640, ref_height=384, skip=false, base_q_idx=30, …) at crates/ec-av1/src/encode.rs:10341 | ||
| 130 | +#20 ec_av1::encode::search_inter_block (luma=0x7f9809f9c340, chroma=0x7f9809f9c3d0, search=0x7f9809f9eb28, mode_bits=0x7f9809fa6998, reference=0x7f980a01e6b0, stack=0x7f9809f9ec10, extra=..., compound=..., grid=0x7f9809f9c610, fctx=0x7f980a0403d0) at crates/ec-av1/src/encode.rs:12407 | ||
| 131 | +``` | ||
| 132 | + | ||
| 133 | +Three samples, three functions, three blocks, and `base_q_idx` **32, 32, 30** — the `30` | ||
| 134 | +can only be a *later frame's*, because `RateLoop::update` runs once per coded frame. This | ||
| 135 | +is consistent with, and independently confirms, the coordinator's own 100%-CPU | ||
| 136 | +`search_root_128_rect -> search_skip_64 -> motion::search` reading. | ||
| 137 | + | ||
| 138 | +### 1.4 Not a regression | ||
| 139 | + | ||
| 140 | +Same test, same four bitrates, run at the older pin in a detached worktree: | ||
| 141 | + | ||
| 142 | +``` | ||
| 143 | +$ git worktree add /home/user/.cache/wt/av1pin ea8fa18f --detach | ||
| 144 | +$ cargo test -p ec-av1 --release --lib -- bitrate_target_lands_within_5_percent_over_48_frames | ||
| 145 | +bitrate 384000 bps, pyramid false: 94646 bytes over 2.00s = 378584 bps (-1.4%) | … leaf 47x1897 | ||
| 146 | +bitrate 384000 bps, pyramid true: 97738 bytes over 2.00s = 390952 bps (+1.8%) | … leaf 35x648 | ||
| 147 | +bitrate 768000 bps, pyramid false: 187877 bytes over 2.00s = 751508 bps (-2.1%) | … leaf 47x3881 | ||
| 148 | +bitrate 768000 bps, pyramid true: 191961 bytes over 2.00s = 767844 bps (-0.0%) | … leaf 35x1536 | ||
| 149 | +bitrate 1536000 bps, pyramid false: 372465 bytes over 2.00s = 1489860 bps (-3.0%) | … leaf 47x7808 | ||
| 150 | +bitrate 1536000 bps, pyramid true: 384161 bytes over 2.00s = 1536644 bps (+0.0%) | … leaf 35x3076 | ||
| 151 | +bitrate 2000000 bps, pyramid false: 491321 bytes over 2.00s = 1965284 bps (-1.7%) | … leaf 47x10337 | ||
| 152 | +bitrate 2000000 bps, pyramid true: 500299 bytes over 2.00s = 2001196 bps (+0.1%) | … leaf 35x6394 | ||
| 153 | +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 782 filtered out; finished in 275.53s | ||
| 154 | +real 4m35.622s | ||
| 155 | +``` | ||
| 156 | + | ||
| 157 | +**Byte-identical to current `main`**, arm for arm. Nothing changed; the gate has always | ||
| 158 | +been this expensive. | ||
| 159 | + | ||
| 160 | +### 1.5 Reproduce, for the record | ||
| 161 | + | ||
| 162 | +``` | ||
| 163 | +$ export CARGO_TARGET_DIR=/home/user/.cache/tgt/av1enchang2 EC_NOMEMGUARD=1 \ | ||
| 164 | + EC_FIXTURES=/home/user/Documents/Code/Rust/edith_codecs/fixtures \ | ||
| 165 | + EC_REQUIRE_FIXTURES=1 | ||
| 166 | +$ timeout 1800 cargo test -p ec-av1 --lib -- bitrate_target_lands_within_5_percent_over_48_frames \ | ||
| 167 | + --test-threads=1 --nocapture | ||
| 168 | +running 1 test | ||
| 169 | +test encoder::tests::bitrate_target_lands_within_5_percent_over_48_frames ... | ||
| 170 | +bitrate 384000 bps, pyramid false: 94646 bytes … (-1.4%) | ||
| 171 | +bitrate 384000 bps, pyramid true: 97738 bytes … (+1.8%) | ||
| 172 | +bitrate 768000 bps, pyramid false: 187877 bytes … (-2.1%) | ||
| 173 | +bitrate 768000 bps, pyramid true: 191961 bytes … (-0.0%) | ||
| 174 | +EXIT=124 <-- 4 of 8 arms in 30 minutes; the fifth is simply still running | ||
| 175 | +``` | ||
| 176 | + | ||
| 177 | +Two traps worth recording, both of which produce a false "it hung" reading: | ||
| 178 | + | ||
| 179 | +* **Without a fixture root the gate does not run and libtest still says `ok`**: | ||
| 180 | + `test … SKIP …: h264-1080p-23.976-8bit.mp4 absent at …` / `test result: ok. 1 passed … | ||
| 181 | + finished in 0.06s`. | ||
| 182 | +* **Without `--nocapture`, libtest buffers the per-arm `eprintln!` lines**, so a run that | ||
| 183 | + has done real work prints only the test name. That is what a wedge looks like in a log. | ||
| 184 | + | ||
| 185 | +## Finding 2 — the landed fix: a backstop, valued from a measured run | ||
| 186 | + | ||
| 187 | +The gate had no way to *fail*. A future non-terminating encode would wedge a suite for | ||
| 188 | +hours with no diagnostic — which is how wave3j and wave3h were lost. So each arm's encode | ||
| 189 | +now runs on a **worker thread** and the test thread watches a **per-CALL** deadline over an | ||
| 190 | +`mpsc` channel: the worker sends a progress ticket after every `encode_frames` call and | ||
| 191 | +its result after `flush` (which is itself a call that can spin, so it gets a ticket too, | ||
| 192 | +not a bare `join` that would block forever). On timeout the gate panics. | ||
| 193 | + | ||
| 194 | +* `ArmResult` (targets/coded/bytes/count) carries the tally off the worker. | ||
| 195 | +* `pictures` is an `Arc`, not an 8x 35 MB clone. | ||
| 196 | +* Worker is a plain `std::thread::spawn` — the std default 2 MiB stack. libtest spawns | ||
| 197 | + its test thread with `thread::Builder` and **no** `.stack_size()`, so the encode gets a | ||
| 198 | + byte-identical stack to before: the backstop neither introduces nor masks a stack | ||
| 199 | + problem. | ||
| 200 | + | ||
| 201 | +### The budget, and its margin | ||
| 202 | + | ||
| 203 | +**The budget is per call, not per test** — that distinction is the whole reason this shape | ||
| 204 | +is safe. An earlier 300 s value was wrong for the pyramid arms and has been raised to | ||
| 205 | +**1800 s**. | ||
| 206 | + | ||
| 207 | +| | worst single `encode_frames` call | budget | margin | | ||
| 208 | +|---|---|---|---| | ||
| 209 | +| optimized, flat arms | **1.04 s** (measured, frame 20 at `q_idx` 32) | 1800 s | **1730x** | | ||
| 210 | +| debug, flat arms | **12.2 s** (measured) | 1800 s | **148x** | | ||
| 211 | +| debug, pyramid arms | **~110 s** (derived: a pyramid call codes a whole mini-GOP, ~9 frames, at 12.2 s each) | 1800 s | **~16x** | | ||
| 212 | + | ||
| 213 | +Whole-test wall time for reference: **280.60 s optimized** for all eight arms on unmodified | ||
| 214 | +`main` (`finished in 280.60s`, `real 4m40.700s`), 275.53 s at `ea8fa18f`, 311.29 s on this | ||
| 215 | +branch. A host ~16x slower than this workstation still clears a 1800 s per-call budget, so | ||
| 216 | +the default cannot turn a correct-but-slow build red. | ||
| 217 | + | ||
| 218 | +### The red, both directions | ||
| 219 | + | ||
| 220 | +**Red 1 — the timeout path is live on the real workload** (budget forced under the honest | ||
| 221 | +cost, so it fires inside a healthy run): | ||
| 222 | + | ||
| 223 | +``` | ||
| 224 | +$ EC_AV1_ENCODE_CALL_BUDGET_SECS=1 … --nocapture | ||
| 225 | +thread 'encoder::tests::bitrate_target_lands_within_5_percent_over_48_frames' panicked at crates/ec-av1/src/encoder.rs:3551:76: | ||
| 226 | +AV1 bitrate gate SLOW, NOT HUNG: the 384000 bps pyramid false arm's encode did not return | ||
| 227 | +within 1s (arm elapsed 22s, stuck on call 49 of 49 -- the call that never came back). … | ||
| 228 | +FAILED | ||
| 229 | +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 788 filtered out; finished in 21.79s | ||
| 230 | +EXIT=101 | ||
| 231 | +``` | ||
| 232 | + | ||
| 233 | +It fails loudly and never as `ok`: the test name in the panic, the arm name, the arm's | ||
| 234 | +elapsed seconds, the stuck call index, `FAILED`, and `EXIT=101`. | ||
| 235 | + | ||
| 236 | +**Red 2 — a genuine non-terminating encode at the default budget.** A | ||
| 237 | +`loop { std::hint::spin_loop(); }` injected at the top of `Av1Encoder::encode_frames` | ||
| 238 | +(temporary; the tree now greps **0** hits for `EC_AV1_INJECTED_SPIN`): | ||
| 239 | + | ||
| 240 | +``` | ||
| 241 | +$ EC_AV1_INJECTED_SPIN=1 … --nocapture | ||
| 242 | +thread '…' panicked at crates/ec-av1/src/encoder.rs:3535:76: | ||
| 243 | +AV1 encode did not return within 300s, on call 1 of 49 (384000 bps pyramid false). … | ||
| 244 | +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 788 filtered out; finished in 300.16s | ||
| 245 | +real 5m0.249s | ||
| 246 | +user 9m59.831s | ||
| 247 | +EXIT=101 | ||
| 248 | +``` | ||
| 249 | + | ||
| 250 | +(The 300 s in that transcript is the budget value at the time of the run; the default is | ||
| 251 | +now 1800 s and the same injection still fires.) Pre-fix, that input wedges the suite | ||
| 252 | +forever; post-fix it is a bounded RED. `user 9m59s` against `real 5m0s` is the two-CPU | ||
| 253 | +burn signature the wedged hosts showed. | ||
| 254 | + | ||
| 255 | +**Green**, default budget, all eight arms, **byte-identical to the pre-fix run**: | ||
| 256 | + | ||
| 257 | +``` | ||
| 258 | +bitrate 384000 bps, pyramid false: 94646 bytes … (-1.4%) | ||
| 259 | +bitrate 384000 bps, pyramid true: 97738 bytes … (+1.8%) | ||
| 260 | +bitrate 768000 bps, pyramid false: 187877 bytes … (-2.1%) | ||
| 261 | +bitrate 768000 bps, pyramid true: 191961 bytes … (-0.0%) | ||
| 262 | +bitrate 1536000 bps, pyramid false: 372465 bytes … (-3.0%) | ||
| 263 | +bitrate 1536000 bps, pyramid true: 384161 bytes … (+0.0%) | ||
| 264 | +bitrate 2000000 bps, pyramid false: 491321 bytes … (-1.7%) | ||
| 265 | +bitrate 2000000 bps, pyramid true: 500299 bytes … (+0.1%) | ||
| 266 | +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 788 filtered out; finished in 311.29s | ||
| 267 | +EXIT=0 | ||
| 268 | +``` | ||
| 269 | + | ||
| 270 | +## Finding 3 — a 137 KB `Av1Encoder` aborts on a default-sized stack | ||
| 271 | + | ||
| 272 | +**This is a separate defect and is NOT the fix for the wedge.** It is landed on its own | ||
| 273 | +merits. Reproduced twice on the pre-fix binary built from unmodified `main`, 6m18s and | ||
| 274 | +6m35s, by invoking the test binary **directly** rather than through `cargo test`: | ||
| 275 | + | ||
| 276 | +``` | ||
| 277 | +$ /home/user/.cache/tgt/av1enchang/debug/deps/ec_av1-79bef263d07a873f \ | ||
| 278 | + bitrate_target_lands_within_5_percent_over_48_frames --test-threads=1 --nocapture | ||
| 279 | +test … bitrate 384000 bps, pyramid false: 94646 bytes … (-1.4%) | ||
| 280 | +thread 'encoder::tests::bitrate_target_lands_within_5_percent_over_48_frames' (2394233) has overflowed its stack | ||
| 281 | +fatal runtime error: stack overflow, aborting | ||
| 282 | +real 6m35.006s | ||
| 283 | +``` | ||
| 284 | + | ||
| 285 | +Not the encode — the **constructor**: | ||
| 286 | + | ||
| 287 | +``` | ||
| 288 | +$ coredumpctl debug 2394232 | ||
| 289 | +Thread 1 (Thread 0x7f00483d66c0 (LWP 2394233)): | ||
| 290 | +#6 <signal handler called> | ||
| 291 | +#8 ec_av1::encoder::Av1Encoder::new (config=...) at crates/ec-av1/src/encoder.rs:1519 | ||
| 292 | +#9 ec_av1::encoder::Av1Encoder::with_pyramid (config=..., pyramid=...) at crates/ec-av1/src/encoder.rs:1583 | ||
| 293 | +#10 ec_av1::encoder::Av1Encoder::with_pyramid_and_rate_target (config=..., pyramid=..., rate=...) at crates/ec-av1/src/encoder.rs:1615 | ||
| 294 | +#11 ec_av1::encoder::tests::bitrate_target_lands_within_5_percent_over_48_frames () at crates/ec-av1/src/encoder.rs:3427 | ||
| 295 | +``` | ||
| 296 | + | ||
| 297 | +### 3.1 The regression gate, and the measured threshold sweep | ||
| 298 | + | ||
| 299 | +Proving the old layout aborts by re-running the 48-frame gate takes 6m35s and needs a | ||
| 300 | +process that dies. A millisecond gate says the same thing: build **both** constructors on a | ||
| 301 | +thread with a deliberately tight stack. New test | ||
| 302 | +`the_pyramid_constructors_fit_on_a_tight_stack` does exactly that, and both thresholds were | ||
| 303 | +swept in an unoptimized build (the Box temporarily reverted to get the pre-fix column): | ||
| 304 | + | ||
| 305 | +| stack | pre-fix (`CdfSnapshot` by value) | post-fix (boxed) | | ||
| 306 | +|---|---|---| | ||
| 307 | +| 256 KiB | overflow | overflow | | ||
| 308 | +| 384 KiB | overflow | **ok** | | ||
| 309 | +| 512 KiB | overflow | ok | | ||
| 310 | +| **1 MiB** | **overflow** | **ok** | | ||
| 311 | +| 2 MiB (libtest's default) | **overflow** | ok | | ||
| 312 | +| 3 MiB | ok | ok | | ||
| 313 | + | ||
| 314 | +The gate runs at **1 MiB**: 2.7x what the boxed layout needs and 2x below what the old one | ||
| 315 | +did, so it is nowhere near either threshold and cannot flake. The pre-fix row at 1 MiB and | ||
| 316 | +at 2 MiB is the red. | ||
| 317 | + | ||
| 318 | +``` | ||
| 319 | +$ EC_AV1_TIGHT_STACK_BYTES=1048576 … the_pyramid_constructors_fit_on_a_tight_stack --nocapture | ||
| 320 | +TIGHTSTACK 1048576 bytes: Av1Encoder=18168 bytes, both constructors returned | ||
| 321 | +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 789 filtered out; finished in 0.00s | ||
| 322 | +``` | ||
| 323 | + | ||
| 324 | +Sizes, measured: | ||
| 325 | + | ||
| 326 | +``` | ||
| 327 | +BEFORE: SIZE Av1Encoder=139960 Result<Av1Encoder>=139960 | ||
| 328 | +AFTER: SIZE Av1Encoder=18168 Result<Av1Encoder>=18168 | ||
| 329 | +``` | ||
| 330 | + | ||
| 331 | +The 137 KB is `dpb: [Option<DpbSlot>; 8]`, each `DpbSlot` holding a 15 KB `CdfSnapshot` by | ||
| 332 | +value. `Av1Encoder` is returned by value through three nested `Result<Self>` constructors | ||
| 333 | +(`with_pyramid_and_rate_target` -> `with_pyramid` -> `new`), so an unoptimized build puts | ||
| 334 | +several 137 KB copies on the stack at once. The flat path nests one level fewer and fits. | ||
| 335 | + | ||
| 336 | +### Why `cargo test` never sees it, and why it is still real | ||
| 337 | + | ||
| 338 | +`.cargo/config.toml` already carries the mitigation, and its comment already names this | ||
| 339 | +exact failure: | ||
| 340 | + | ||
| 341 | +```toml | ||
| 342 | +[env] | ||
| 343 | +# The AV1 rate-target tests keep several frames' worth of encoder state on the | ||
| 344 | +# test thread's stack; the 2 MB default overflows in debug builds (release | ||
| 345 | +# passes). Cap lives in the repo so every checkout and worktree gets it. | ||
| 346 | +RUST_MIN_STACK = "67108864" | ||
| 347 | +``` | ||
| 348 | + | ||
| 349 | +`cargo test` hands the test thread 64 MiB, so the abort does not happen there. **This is | ||
| 350 | +also why the `cargo test` runs wedge rather than abort**, and it is the direct answer to | ||
| 351 | +the `memguard-runner.sh` question: that runner is a **cgroup `MemoryMax=10G` / | ||
| 352 | +`MemorySwapMax=2G` cap, not `RLIMIT_AS`**, and the test uses far less than 10 GB. It cannot | ||
| 353 | +turn a guard-page hit into a sustained hang. A guard-page hit aborts; it does not sit in | ||
| 354 | +`R` for three hours. | ||
| 355 | + | ||
| 356 | +The defect is still real: `RUST_MIN_STACK` is a `[env]` entry that applies only to **this | ||
| 357 | +workspace's** `cargo` invocations. Any external consumer linking `ec-av1` and calling | ||
| 358 | +`Av1Encoder::new(...)` on an ordinary 2 MiB thread stack **crashes the process**. The repo | ||
| 359 | +is hiding a public-API hazard behind a workspace-local env var. | ||
| 360 | + | ||
| 361 | +### The fix, and its evidence | ||
| 362 | + | ||
| 363 | +`DpbSlot::cdfs` becomes `Box<crate::encode::CdfSnapshot>`; the one construction site | ||
| 364 | +(`refresh()`) wraps it in `Box::new`. Two lines. | ||
| 365 | + | ||
| 366 | +``` | ||
| 367 | +$ cargo test -p ec-av1 --release --lib -- round_trip encode | ||
| 368 | +test result: ok. 108 passed; 0 failed; 40 ignored; 0 measured; 641 filtered out; finished in 503.15s | ||
| 369 | +``` | ||
| 370 | + | ||
| 371 | +**108 passed, 0 failed** — re-run *after* the change, not asserted. `size_of` before/after | ||
| 372 | +is above. `cargo check -p ec-av1 --all-targets` is clean with no warnings. Nothing in the | ||
| 373 | +suite was red for an unrelated reason. | ||
| 374 | + | ||
| 375 | +## Commands | ||
| 376 | + | ||
| 377 | +``` | ||
| 378 | +git -C /home/user/Documents/Code/Rust/edith_codecs worktree add \ | ||
| 379 | + /home/user/.cache/wt/av1enchang -b lane-av1enchang main | ||
| 380 | +git -C /home/user/Documents/Code/Rust/edith_codecs worktree add \ | ||
| 381 | + /home/user/.cache/wt/av1pin ea8fa18f --detach # the not-a-regression control | ||
| 382 | +export EC_FIXTURES=/home/user/Documents/Code/Rust/edith_codecs/fixtures | ||
| 383 | +export EC_REQUIRE_FIXTURES=1 | ||
| 384 | + | ||
| 385 | +cargo check -p ec-av1 --all-targets | ||
| 386 | +cargo test -p ec-av1 --lib -- bitrate_target_lands_within_5_percent_over_48_frames --test-threads=1 --nocapture | ||
| 387 | +cargo test -p ec-av1 --release --lib -- bitrate_target_lands_within_5_percent_over_48_frames --test-threads=1 --nocapture | ||
| 388 | +EC_AV1_ENCODE_CALL_BUDGET_SECS=1 … # red 1 | ||
| 389 | +EC_AV1_INJECTED_SPIN=1 … # red 2 (injection reverted, 0 grep hits) | ||
| 390 | +coredumpctl debug <pid> # the Finding 3 backtrace | ||
| 391 | +cargo test -p ec-av1 --release --lib -- round_trip encode | ||
| 392 | +``` | ||
| 393 | + | ||
| 394 | +## Decision wanted from the coordinator (not taken here) | ||
| 395 | + | ||
| 396 | +The honest cost is now measured and the gate is bounded, but **the ~7 hour debug suite | ||
| 397 | +remains**. That is a test-design call, and it changes what the default suite proves, so it | ||
| 398 | +is not this lane's to make: | ||
| 399 | + | ||
| 400 | +* **leave it** — the claim stays fully in the default debug suite; gate scheduling must | ||
| 401 | + budget ~7 h (measured 24341 s on the fleet). | ||
| 402 | +* **`#[ignore]` with a stated reason, run in release** — 4m40s instead of hours, at the cost | ||
| 403 | + of the claim no longer running by default. | ||
| 404 | +* **split it** — e.g. a cheap 2-bitrate/short-clip arm in the default suite plus the full | ||
| 405 | + 4x2x48 sweep behind a flag or a release-only gate. | ||
| 406 | + | ||
| 407 | +Recommendation: **split**. It keeps a rate-control regression signal in the default debug | ||
| 408 | +suite at a cost the suite can absorb, and keeps the full ±5% sweep available where it can | ||
| 409 | +be afforded. Not implemented here — it changes what the gate proves, which is the | ||
| 410 | +coordinator's call. | ||