forge
Explore
Log in

Don't you dare go Hollow

Instrument rect64 qindex drift, and record that nothing fires it

Browse files at this commit

5361167f88aa7642b1f2312e830c29de97bf1ca9Ahmet Kaan GümüşParent: 528531a
  • test
    • instrument rect64 qindex drift, and record that nothing fires it
Show full message
test(av1): instrument rect64 qindex drift, and record that nothing fires it

Adds RECT64_QIDX_DRIFT_HITS plus an EC_AV1_TRACE-gated `TRACE
rect64_dequant` line at each of decode_block_rect64's three dequant
sites, and an #[ignore]d sibling gate that drops --deltaq-mode=0 in the
hope aomenc's objective delta-q would vary q inside a rect64
superblock.

It does not, on this content: the existing sb_rect gate traced 105/105
dequant calls with base_q_idx == current_q_idx == 180, and the
delta-q-permitting gate matched 15/40 attempts with the drift counter
still 0. So the fix in 1d2c3bb is correct by construction -- every
sibling path reads CURRENT_Q_IDX, and decode.rs:141-145 documents that
as the rule -- but no stream in this repository currently makes it
observable. The counter is the instrument that will say so the moment
one does.

Committed by the orchestrator at the agent's turn cap.
crates/ec-av1/src/decode.rsmodified+48 -0
@@ -719,6 +719,21 @@ pub(crate) fn sb_rect_hits() -> usize {
719719 SB_RECT_HITS.with(|c| c.get())
720720 }
721721
722+// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
723+// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
724+// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
725+// just inert-compiled. Zero forever on a passing gate means that gate's
726+// stream never carries `delta_q_present=1` through a rect64 block.
727+thread_local! {
728+ static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
729+ const { std::cell::Cell::new(0) };
730+}
731+
732+/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
733+pub(crate) fn rect64_qidx_drift_hits() -> usize {
734+ RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
735+}
736+
722737 // lane-partab r1: how many 32x32 quadrants decoded an AB partition
723738 // (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
724739 // 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
@@ -3527,6 +3542,17 @@ fn decode_block_rect64(
35273542 for row in 0..32 {
35283543 luma_levels[row * bw..][..32].copy_from_slice(&luma_corner[row * 32..][..32]);
35293544 }
3545+ {
3546+ let cur = CURRENT_Q_IDX.with(|c| c.get());
3547+ if cur != i32::from(base_q_idx) {
3548+ RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
3549+ }
3550+ if std::env::var_os("EC_AV1_TRACE").is_some() {
3551+ eprintln!(
3552+ "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
3553+ );
3554+ }
3555+ }
35303556 let luma_residual = dequant_and_inverse_typed_wh(
35313557 &luma_levels,
35323558 bw,
@@ -3588,6 +3614,17 @@ fn decode_block_rect64(
35883614 let (rng, _) = dec.debug_state();
35893615 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
35903616 }
3617+ {
3618+ let cur = CURRENT_Q_IDX.with(|c| c.get());
3619+ if cur != i32::from(base_q_idx) {
3620+ RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
3621+ }
3622+ if std::env::var_os("EC_AV1_TRACE").is_some() {
3623+ eprintln!(
3624+ "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
3625+ );
3626+ }
3627+ }
35913628 let u_residual = dequant_and_inverse_typed_wh(
35923629 &u_levels,
35933630 chroma_w,
@@ -3631,6 +3668,17 @@ fn decode_block_rect64(
36313668 let (rng, _) = dec.debug_state();
36323669 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
36333670 }
3671+ {
3672+ let cur = CURRENT_Q_IDX.with(|c| c.get());
3673+ if cur != i32::from(base_q_idx) {
3674+ RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
3675+ }
3676+ if std::env::var_os("EC_AV1_TRACE").is_some() {
3677+ eprintln!(
3678+ "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
3679+ );
3680+ }
3681+ }
36343682 let v_residual = dequant_and_inverse_typed_wh(
36353683 &v_levels,
36363684 chroma_w,
crates/ec-av1/src/stream.rsmodified+163 -0
@@ -8831,6 +8831,169 @@ mod tests {
88318831 );
88328832 }
88338833
8834+ /// lane-rect64q r1: same recipe as
8835+ /// [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]
8836+ /// minus `--deltaq-mode=0` -- real aomenc's non-realtime default is
8837+ /// `DELTA_Q_OBJECTIVE` (`av1_cx_iface.c:271`), so dropping that one flag
8838+ /// is enough to make `delta_q_present=1` the norm and drive
8839+ /// [`crate::decode::decode_block_rect64`]'s running `CURRENT_Q_IDX` away
8840+ /// from the frame-constant `base_q_idx` inside a real rect64 SB --
8841+ /// exactly the bug this round's dequant fix targets. Hard-asserts
8842+ /// `rect64_qidx_drift_hits() > 0`: without that, this gate could pass
8843+ /// vacuously the same way the `--deltaq-mode=0` sibling always did.
8844+ ///
8845+ /// lane-rect64q r1: measured, does NOT fire -- 15/40 attempts matched
8846+ /// but `rect64_qidx_drift_hits()` stayed 0 every time. Real aomenc's RD
8847+ /// never chose a nonzero delta-q on this tiny synthetic gradients frame
8848+ /// even with `deltaq-mode` left at its default; `#[ignore]`d rather than
8849+ /// deleted so the recipe and the negative result both survive for the
8850+ /// next attempt (see `lanes/rect64q-r1.report.md`).
8851+ #[test]
8852+ #[ignore = "drift never observed this round -- see lanes/rect64q-r1.report.md"]
8853+ fn a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact()
8854+ {
8855+ const NAME: &str =
8856+ "a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact";
8857+ let _gate_lock = lock_gate_counters();
8858+ if !have_ffmpeg() {
8859+ eprintln!("SKIP {NAME}: no ffmpeg");
8860+ return;
8861+ }
8862+ if !have_aomenc() {
8863+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8864+ return;
8865+ }
8866+ let (width, height, frame_count) = (192usize, 128usize, 1usize);
8867+ let mut named_refusals = 0u32;
8868+ let mut matched = 0u32;
8869+ let n_attempts: u32 = std::env::var("EC_SBPART_DQ_GATE_ATTEMPTS")
8870+ .ok()
8871+ .and_then(|s| s.parse().ok())
8872+ .unwrap_or(40);
8873+ for attempt in 0..n_attempts {
8874+ let seed = 42 + attempt;
8875+ let duration = frame_count as f64 / 25.0;
8876+ let source =
8877+ gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
8878+ let y4m = Command::new("ffmpeg")
8879+ .args([
8880+ "-v",
8881+ "error",
8882+ "-f",
8883+ "lavfi",
8884+ "-i",
8885+ &source,
8886+ "-pix_fmt",
8887+ "yuv420p",
8888+ "-f",
8889+ "yuv4mpegpipe",
8890+ "-",
8891+ ])
8892+ .stdin(Stdio::null())
8893+ .stdout(Stdio::piped())
8894+ .stderr(Stdio::piped())
8895+ .output()
8896+ .expect("ffmpeg failed to run");
8897+ assert!(
8898+ y4m.status.success(),
8899+ "ffmpeg fixture: {}",
8900+ String::from_utf8_lossy(&y4m.stderr)
8901+ );
8902+ let args: Vec<&str> = vec![
8903+ "--codec=av1",
8904+ "--passes=1",
8905+ "--end-usage=q",
8906+ "--cq-level=45",
8907+ "--cpu-used=0",
8908+ "--threads=1",
8909+ "--row-mt=0",
8910+ "--sb-size=64",
8911+ "--enable-rect-partitions=1",
8912+ "--enable-ab-partitions=0",
8913+ "--enable-1to4-partitions=0",
8914+ "--min-partition-size=32",
8915+ "--max-partition-size=64",
8916+ "--enable-restoration=0",
8917+ "--enable-palette=0",
8918+ "--enable-filter-intra=0",
8919+ "--enable-cfl-intra=0",
8920+ "--enable-intrabc=0",
8921+ "--enable-tx-size-search=0",
8922+ "--obu",
8923+ "-o",
8924+ "-",
8925+ "-",
8926+ ];
8927+ let mut child = Command::new(aomenc_path())
8928+ .args(&args)
8929+ .stdin(Stdio::piped())
8930+ .stdout(Stdio::piped())
8931+ .stderr(Stdio::piped())
8932+ .spawn()
8933+ .expect("aomenc failed to start");
8934+ child
8935+ .stdin
8936+ .take()
8937+ .expect("aomenc stdin")
8938+ .write_all(&y4m.stdout)
8939+ .expect("writing y4m to aomenc");
8940+ let out = child.wait_with_output().expect("aomenc failed to run");
8941+ assert!(
8942+ out.status.success(),
8943+ "aomenc refused the fixture: {}",
8944+ String::from_utf8_lossy(&out.stderr)
8945+ );
8946+ let stream = out.stdout;
8947+ let frames = match decode_stream(&stream) {
8948+ Err(e) => {
8949+ let msg = e.to_string();
8950+ assert!(
8951+ msg.contains("unsupported"),
8952+ "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
8953+ );
8954+ named_refusals += 1;
8955+ eprintln!("seed {seed} refusal: {msg}");
8956+ continue;
8957+ }
8958+ Ok(frames) => frames,
8959+ };
8960+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
8961+ assert_eq!(frames.len(), frame_count);
8962+ let mismatched = frames
8963+ .iter()
8964+ .zip(&ffmpeg_frames)
8965+ .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
8966+ if mismatched {
8967+ if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
8968+ std::fs::write(&path, &stream).expect("writing pinned stream");
8969+ eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
8970+ }
8971+ }
8972+ for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8973+ assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
8974+ assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
8975+ assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
8976+ }
8977+ matched += 1;
8978+ }
8979+ assert!(
8980+ matched > 0,
8981+ "{NAME}: every attempt refused; the gate never decoded a stream"
8982+ );
8983+ assert!(
8984+ crate::decode::rect64_qidx_drift_hits() > 0,
8985+ "{NAME}: zero rect64 dequant calls ever observed CURRENT_Q_IDX != base_q_idx \
8986+ ({matched} matches, {named_refusals} refusals out of {n_attempts}) -- delta_q \
8987+ was never actually exercised through decode_block_rect64 this run"
8988+ );
8989+ eprintln!(
8990+ "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \
8991+ {n_attempts}, sb_rect_hits={}, rect64_qidx_drift_hits={}",
8992+ crate::decode::sb_rect_hits(),
8993+ crate::decode::rect64_qidx_drift_hits()
8994+ );
8995+ }
8996+
88348997 /// lane-sbpart r4: replays a pinned mismatch byte-for-byte off disk (no
88358998 /// aomenc/ffmpeg re-encode), same pattern as `pinned_golden3/4_stream_
88368999 /// decodes_pixel_exact` -- fast red/green loop for the bisect, and lets
lanes/rect64q-r1.report.mdadded+145 -0
@@ -0,0 +1,145 @@
1+# lane-rect64q r1 report
2+
3+## What was already there / applied
4+
5+Hunter's fix (three `decode_block_rect64` dequant call sites use
6+`CURRENT_Q_IDX.with(|c| c.get())` instead of the stale `base_q_idx`
7+parameter) was already applied uncommitted in this worktree. Committed
8+first, as instructed: `1d2c3bb`.
9+
10+## Instrumentation (charter step 1)
11+
12+Added `RECT64_QIDX_DRIFT_HITS` thread-local counter (`decode.rs:719-733`)
13+and, at each of the three dequant sites inside `decode_block_rect64`
14+(luma, U, V — `decode.rs` ~3560, 3623, 3684), a check comparing
15+`CURRENT_Q_IDX` against `base_q_idx`, incrementing the counter on any
16+mismatch and printing `TRACE rect64_dequant plane=<p> base_q_idx=<b>
17+current_q_idx=<c>` under the existing `EC_AV1_TRACE` gate.
18+
19+**Measured on the only existing gate that reaches `decode_block_rect64`**
20+(`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`,
21+40 attempts, `--deltaq-mode=0`): 105 dequant calls traced, every single one
22+`base_q_idx=180 current_q_idx=180`. `rect64_qidx_drift_hits()` stayed 0.
23+This gate forces `delta_q_present=0` by its own recipe (`--deltaq-mode=0`),
24+so this result is exactly as expected — it proves the instrumentation
25+works, not that the fix is inert in general.
26+
27+EVIDENCE: `EC_AV1_TRACE=1 EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib
28+a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact
29+-- --nocapture --test-threads=1` | `/tmp/rect64q-trace1.log` | 105/105
30+`TRACE rect64_dequant` lines all `180 180`, `sb_rect_hits=36`.
31+
32+## Gate attempt 2: drop `--deltaq-mode=0` (charter step 2)
33+
34+Wrote
35+`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact`
36+(`stream.rs`, right after the sibling gate): identical recipe minus the
37+one flag, since real aomenc's non-realtime default is `DELTA_Q_OBJECTIVE`
38+(hunter's own finding, `av1_cx_iface.c:271`). Hard-asserts
39+`rect64_qidx_drift_hits() > 0`.
40+
41+**Result: does not fire.** 40 attempts, 15 matched, 25 named refusals
42+(same refusal shapes as the sibling gate — AB-at-64, 32x32 AB, Golomb
43+tail, screen-content strip), but `rect64_qidx_drift_hits()` stayed 0
44+across all 15 matched attempts. Real aomenc's objective delta-q RD never
45+chose a nonzero delta on this tiny (192x128, 1 frame, cq=45) synthetic
46+gradients content, even with the flag left at its default. Marked
47+`#[ignore]` with the negative result recorded in its own doc comment
48+rather than deleted, so the recipe survives for whoever picks this up
49+next; it does NOT run in the default `--lib` suite, so it does not block
50+green.
51+
52+I did **not** port lane-palette2's gate. Two reasons found live, in order:
53+1. My worktree's `read_intra_mode_rect` (used by both `decode_block_rect`
54+ and `decode_block_rect64`) still carries the blanket refusal *"a
55+ HORZ/VERT intra strip in a screen-content frame"* for any
56+ `allow_screen_content_tools` frame — I do not have lane-palette2's
57+ rect-generalised palette wiring (`palette_bsize_ctx_wh` is defined at
58+ `decode.rs:2553` but never called). Porting palette2's gate as-is would
59+ mostly just hit this refusal (confirmed live: seed 59 in my own
60+ modified gate's run hit exactly this string).
61+2. The coordinator's mid-task message pointed at a cheaper, *already-real*
62+ repro (below) before I sank more budget into that path.
63+
64+## The coordinator's SB(0,1) lead — investigated, does not reproduce here
65+
66+lane-part32 (`64ccb9f`, read-only) reported seed 42, same
67+`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
68+recipe, SB(0,1)'s VERT-64 left arm, `row=0 col=91`, DC_PRED,
69+`all_zero=1`, "got=80 want=81".
70+
71+Regenerated that exact stream by hand (same `gradients_source` seed-42
72+hash, same aomenc args) and decoded it in **this** worktree with
73+`EC_SBPART_DUMP64=1`:
74+
75+```
76+DUMP64 mi_r=0 mi_c=16 px=64 py=0 bw=32 bh=64 mode=0 skip=false eob_nonzero=false
77+ row0=[81,81,...,81] (32 values, all 81)
78+```
79+
80+Independently decoded the same `.obu` with real ffmpeg
81+(`ffmpeg -i seed42.obu -f rawvideo -pix_fmt yuv420p`) and read row 0,
82+cols 60-99 of luma: all `81`. **My worktree and ffmpeg agree at col 91
83+(value 81) — no mismatch.** This is also exactly the outcome the
84+coordinator's own reasoning predicts: `eob_nonzero=false` means zero
85+residual, so a dequant qindex bug (drift or not) cannot move this
86+specific block's pixels either way — consistent with `rect64_qidx_drift_hits()`
87+staying 0 on this exact stream too (checked: `deltaq-mode=0` in this
88+recipe, no drift possible by construction).
89+
90+I cannot explain the discrepancy with part32's reported "got=80" from the
91+evidence available in this round (my byte-for-byte reproduction matches
92+ffmpeg, not their reported mismatch) — possibly a difference in tree
93+state between their fork point and mine, or an artifact of the exact
94+attempt-loop state (`lock_gate_counters`/thread-local counters carried
95+across earlier attempts in the same test process) rather than this one
96+block in isolation. Did not chase further given budget; this is now open
97+for whoever picks up either lane next, with the reproduction recipe above
98+(exact aomenc/ffmpeg commands in scratchpad) ready to hand.
99+
100+**lane-palette2's defect status: still open, not touched this round.**
101+**lane-part32's SB(0,1) defect: investigated, does NOT reproduce
102+byte-for-byte in this worktree against real ffmpeg; open.**
103+
104+## Dead parameter (charter step 3)
105+
106+**Not removed.** My own instrumentation (comparing `CURRENT_Q_IDX` against
107+`base_q_idx` to increment the drift counter) now legitimately *uses*
108+`base_q_idx` inside `decode_block_rect64` — it is no longer a parsed-and-
109+discarded value, so `cargo check` no longer warns about it there
110+(confirmed: the only two remaining `unused variable: base_q_idx` warnings
111+are at `decode.rs:3053` (`decode_block_rect`) and `decode.rs:7259`
112+(`read_inter_plane`), both pre-existing and out of this charter's scope —
113+`decode_block_rect64` itself is clean). This is a deviation from the
114+charter's literal step 3 instruction ("remove the parameter"): the
115+premise (dead parameter) stopped being true once the drift-proof
116+instrumentation was added, since that instrumentation is exactly the
117+"permanently non-inert" proof charter step 2 asked for and it needs
118+`base_q_idx` as its ground truth. Flagging this explicitly rather than
119+silently keeping the param.
120+
121+## Suite / check
122+
123+- `cargo check -p ec-av1 --lib`: clean, no new warnings beyond pre-existing
124+ 108 doc/lint warnings.
125+- `cargo test -p ec-av1 --lib` (default set, `#[ignore]`d test excluded):
126+ running full run at report time — appending numbers below once done.
127+
128+## HEAD
129+
130+Will update after final commit.
131+
132+## Open (disposition)
133+
134+- `rect64_qidx_drift_hits()` has never been observed nonzero anywhere in
135+ this repo. The dequant fix (`1d2c3bb`) is **still unproven live** —
136+ correct by code inspection and by matching every sibling path
137+ (`decode_block`, `decode_block_rect`), but no gate in this repo (old or
138+ new) has yet exercised a rect64 block with `delta_q_present=1` AND a
139+ nonzero coded residual. `deferred: a firing gate for this fix —
140+ needs either bigger/noisier real content (more SB rows so aomenc's
141+ objective delta-q actually varies q) or a hand-crafted/pinned stream —
142+ next lane round.`
143+- lane-part32's SB(0,1) "got=80 want=81" report does not reproduce here;
144+ `deferred: reconcile the two worktrees' byte streams for seed 42 — next
145+ round, needs comparing actual stream bytes, not just recipe text.`