forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-rect64q': rect64 dequant reads the running qindex

Browse files at this commit

1cfbf53aa2b1685cfcaa62fb203653ef2e4b046fAhmet Kaan GümüşParent: 6b635d65361167
decode_block_rect64 dequantized all three planes with the frame-constant
base_q_idx parameter it was handed, while every sibling path --
decode_block, decode_block_rect -- reads the running per-superblock
CURRENT_Q_IDX, which decode.rs:141-145 documents as the rule. The
function reaches maybe_read_delta_q through its own read_intra_mode_rect
call, so it updated that thread-local and then dequantized with its own
stale snapshot.

Merged as a latent-trap removal, with the negative result stated rather
than hidden: NO stream in this repository currently makes the difference
observable. The existing sb_rect gate traces 105/105 dequant calls with
base_q_idx == current_q_idx == 180 (its recipe forces delta_q_present=0),
and a sibling gate that drops --deltaq-mode=0 matched 15/40 attempts with
the drift counter still 0 -- aomenc's objective delta-q never chose a
nonzero delta on that small synthetic content. That gate is committed
#[ignore]d with its negative documented, and RECT64_QIDX_DRIFT_HITS stays
in the tree so the first stream that does drift says so out loud.

Also recorded, so neither claim is trusted twice: lane-part32's seed-42
SB(0,1) mismatch does NOT reproduce here -- a hand-regenerated identical
stream gives row 0 col 91 = 81, matching ffmpeg -- and that block has
eob_nonzero=false, so no dequant change could move its pixels either way.

Suite 266 passed / 0 failed, 20 ignored.
crates/ec-av1/src/decode.rsmodified+51 -3
@@ -724,6 +724,21 @@ pub(crate) fn sb_rect_hits() -> usize {
724724 SB_RECT_HITS.with(|c| c.get())
725725 }
726726
727+// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
728+// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
729+// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
730+// just inert-compiled. Zero forever on a passing gate means that gate's
731+// stream never carries `delta_q_present=1` through a rect64 block.
732+thread_local! {
733+ static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
734+ const { std::cell::Cell::new(0) };
735+}
736+
737+/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
738+pub(crate) fn rect64_qidx_drift_hits() -> usize {
739+ RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
740+}
741+
727742 // lane-partab r1: how many 32x32 quadrants decoded an AB partition
728743 // (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
729744 // 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
@@ -3532,12 +3547,23 @@ fn decode_block_rect64(
35323547 for row in 0..32 {
35333548 luma_levels[row * bw..][..32].copy_from_slice(&luma_corner[row * 32..][..32]);
35343549 }
3550+ {
3551+ let cur = CURRENT_Q_IDX.with(|c| c.get());
3552+ if cur != i32::from(base_q_idx) {
3553+ RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
3554+ }
3555+ if std::env::var_os("EC_AV1_TRACE").is_some() {
3556+ eprintln!(
3557+ "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
3558+ );
3559+ }
3560+ }
35353561 let luma_residual = dequant_and_inverse_typed_wh(
35363562 &luma_levels,
35373563 bw,
35383564 bh,
35393565 crate::decode::bit_depth(),
3540- i32::from(base_q_idx),
3566+ CURRENT_Q_IDX.with(|c| c.get()),
35413567 plane_q_delta(0).0,
35423568 plane_q_delta(0).1,
35433569 luma_tx_type,
@@ -3593,12 +3619,23 @@ fn decode_block_rect64(
35933619 let (rng, _) = dec.debug_state();
35943620 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
35953621 }
3622+ {
3623+ let cur = CURRENT_Q_IDX.with(|c| c.get());
3624+ if cur != i32::from(base_q_idx) {
3625+ RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
3626+ }
3627+ if std::env::var_os("EC_AV1_TRACE").is_some() {
3628+ eprintln!(
3629+ "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
3630+ );
3631+ }
3632+ }
35963633 let u_residual = dequant_and_inverse_typed_wh(
35973634 &u_levels,
35983635 chroma_w,
35993636 chroma_h,
36003637 crate::decode::bit_depth(),
3601- i32::from(base_q_idx),
3638+ CURRENT_Q_IDX.with(|c| c.get()),
36023639 plane_q_delta(1).0,
36033640 plane_q_delta(1).1,
36043641 u_tx_type,
@@ -3636,12 +3673,23 @@ fn decode_block_rect64(
36363673 let (rng, _) = dec.debug_state();
36373674 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
36383675 }
3676+ {
3677+ let cur = CURRENT_Q_IDX.with(|c| c.get());
3678+ if cur != i32::from(base_q_idx) {
3679+ RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
3680+ }
3681+ if std::env::var_os("EC_AV1_TRACE").is_some() {
3682+ eprintln!(
3683+ "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
3684+ );
3685+ }
3686+ }
36393687 let v_residual = dequant_and_inverse_typed_wh(
36403688 &v_levels,
36413689 chroma_w,
36423690 chroma_h,
36433691 crate::decode::bit_depth(),
3644- i32::from(base_q_idx),
3692+ CURRENT_Q_IDX.with(|c| c.get()),
36453693 plane_q_delta(2).0,
36463694 plane_q_delta(2).1,
36473695 v_tx_type,
crates/ec-av1/src/stream.rsmodified+163 -0
@@ -9032,6 +9032,169 @@ mod tests {
90329032 );
90339033 }
90349034
9035+ /// lane-rect64q r1: same recipe as
9036+ /// [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]
9037+ /// minus `--deltaq-mode=0` -- real aomenc's non-realtime default is
9038+ /// `DELTA_Q_OBJECTIVE` (`av1_cx_iface.c:271`), so dropping that one flag
9039+ /// is enough to make `delta_q_present=1` the norm and drive
9040+ /// [`crate::decode::decode_block_rect64`]'s running `CURRENT_Q_IDX` away
9041+ /// from the frame-constant `base_q_idx` inside a real rect64 SB --
9042+ /// exactly the bug this round's dequant fix targets. Hard-asserts
9043+ /// `rect64_qidx_drift_hits() > 0`: without that, this gate could pass
9044+ /// vacuously the same way the `--deltaq-mode=0` sibling always did.
9045+ ///
9046+ /// lane-rect64q r1: measured, does NOT fire -- 15/40 attempts matched
9047+ /// but `rect64_qidx_drift_hits()` stayed 0 every time. Real aomenc's RD
9048+ /// never chose a nonzero delta-q on this tiny synthetic gradients frame
9049+ /// even with `deltaq-mode` left at its default; `#[ignore]`d rather than
9050+ /// deleted so the recipe and the negative result both survive for the
9051+ /// next attempt (see `lanes/rect64q-r1.report.md`).
9052+ #[test]
9053+ #[ignore = "drift never observed this round -- see lanes/rect64q-r1.report.md"]
9054+ fn a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact()
9055+ {
9056+ const NAME: &str =
9057+ "a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact";
9058+ let _gate_lock = lock_gate_counters();
9059+ if !have_ffmpeg() {
9060+ eprintln!("SKIP {NAME}: no ffmpeg");
9061+ return;
9062+ }
9063+ if !have_aomenc() {
9064+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9065+ return;
9066+ }
9067+ let (width, height, frame_count) = (192usize, 128usize, 1usize);
9068+ let mut named_refusals = 0u32;
9069+ let mut matched = 0u32;
9070+ let n_attempts: u32 = std::env::var("EC_SBPART_DQ_GATE_ATTEMPTS")
9071+ .ok()
9072+ .and_then(|s| s.parse().ok())
9073+ .unwrap_or(40);
9074+ for attempt in 0..n_attempts {
9075+ let seed = 42 + attempt;
9076+ let duration = frame_count as f64 / 25.0;
9077+ let source =
9078+ gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
9079+ let y4m = Command::new("ffmpeg")
9080+ .args([
9081+ "-v",
9082+ "error",
9083+ "-f",
9084+ "lavfi",
9085+ "-i",
9086+ &source,
9087+ "-pix_fmt",
9088+ "yuv420p",
9089+ "-f",
9090+ "yuv4mpegpipe",
9091+ "-",
9092+ ])
9093+ .stdin(Stdio::null())
9094+ .stdout(Stdio::piped())
9095+ .stderr(Stdio::piped())
9096+ .output()
9097+ .expect("ffmpeg failed to run");
9098+ assert!(
9099+ y4m.status.success(),
9100+ "ffmpeg fixture: {}",
9101+ String::from_utf8_lossy(&y4m.stderr)
9102+ );
9103+ let args: Vec<&str> = vec![
9104+ "--codec=av1",
9105+ "--passes=1",
9106+ "--end-usage=q",
9107+ "--cq-level=45",
9108+ "--cpu-used=0",
9109+ "--threads=1",
9110+ "--row-mt=0",
9111+ "--sb-size=64",
9112+ "--enable-rect-partitions=1",
9113+ "--enable-ab-partitions=0",
9114+ "--enable-1to4-partitions=0",
9115+ "--min-partition-size=32",
9116+ "--max-partition-size=64",
9117+ "--enable-restoration=0",
9118+ "--enable-palette=0",
9119+ "--enable-filter-intra=0",
9120+ "--enable-cfl-intra=0",
9121+ "--enable-intrabc=0",
9122+ "--enable-tx-size-search=0",
9123+ "--obu",
9124+ "-o",
9125+ "-",
9126+ "-",
9127+ ];
9128+ let mut child = Command::new(aomenc_path())
9129+ .args(&args)
9130+ .stdin(Stdio::piped())
9131+ .stdout(Stdio::piped())
9132+ .stderr(Stdio::piped())
9133+ .spawn()
9134+ .expect("aomenc failed to start");
9135+ child
9136+ .stdin
9137+ .take()
9138+ .expect("aomenc stdin")
9139+ .write_all(&y4m.stdout)
9140+ .expect("writing y4m to aomenc");
9141+ let out = child.wait_with_output().expect("aomenc failed to run");
9142+ assert!(
9143+ out.status.success(),
9144+ "aomenc refused the fixture: {}",
9145+ String::from_utf8_lossy(&out.stderr)
9146+ );
9147+ let stream = out.stdout;
9148+ let frames = match decode_stream(&stream) {
9149+ Err(e) => {
9150+ let msg = e.to_string();
9151+ assert!(
9152+ msg.contains("unsupported"),
9153+ "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
9154+ );
9155+ named_refusals += 1;
9156+ eprintln!("seed {seed} refusal: {msg}");
9157+ continue;
9158+ }
9159+ Ok(frames) => frames,
9160+ };
9161+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
9162+ assert_eq!(frames.len(), frame_count);
9163+ let mismatched = frames
9164+ .iter()
9165+ .zip(&ffmpeg_frames)
9166+ .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
9167+ if mismatched {
9168+ if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
9169+ std::fs::write(&path, &stream).expect("writing pinned stream");
9170+ eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
9171+ }
9172+ }
9173+ for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9174+ assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
9175+ assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
9176+ assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
9177+ }
9178+ matched += 1;
9179+ }
9180+ assert!(
9181+ matched > 0,
9182+ "{NAME}: every attempt refused; the gate never decoded a stream"
9183+ );
9184+ assert!(
9185+ crate::decode::rect64_qidx_drift_hits() > 0,
9186+ "{NAME}: zero rect64 dequant calls ever observed CURRENT_Q_IDX != base_q_idx \
9187+ ({matched} matches, {named_refusals} refusals out of {n_attempts}) -- delta_q \
9188+ was never actually exercised through decode_block_rect64 this run"
9189+ );
9190+ eprintln!(
9191+ "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \
9192+ {n_attempts}, sb_rect_hits={}, rect64_qidx_drift_hits={}",
9193+ crate::decode::sb_rect_hits(),
9194+ crate::decode::rect64_qidx_drift_hits()
9195+ );
9196+ }
9197+
90359198 /// lane-sbpart r4: replays a pinned mismatch byte-for-byte off disk (no
90369199 /// aomenc/ffmpeg re-encode), same pattern as `pinned_golden3/4_stream_
90379200 /// 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.`