forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-sb128b' (c124d29d): the inter writer signalled a clamped drl index while pricing against the unclamped predictor; the four writer arms take their base mv from the signalled index; symbol-trace instrument; 128 roots refuted on film B

Browse files at this commit

7d2ddc25554664a95a036fed41f31d69e3e5e84aAhmet Kaan GümüşParent: 4a23ee32301cb5
crates/ec-av1/src/decode.rsmodified+5 -0
@@ -28177,6 +28177,11 @@ fn decode_inter_block(
2817728177 };
2817828178 (mv, false)
2817928179 };
28180+ if crate::msac::symtrace::dir().is_some() {
28181+ crate::msac::symtrace::note(&format!(
28182+ " MODE mi=({mi_row},{mi_col}) dbg={dbg_mode} mv={mv:?}"
28183+ ));
28184+ }
2818028185 if crate::envflags::env_flag!("EC_TRACE_MODE") {
2818128186 for (i, e) in stack.entries.iter().enumerate() {
2818228187 eprintln!(
crates/ec-av1/src/encode.rsmodified+72 -1
@@ -13471,7 +13471,7 @@ mod tests {
1347113471 eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
1347213472 return;
1347313473 };
13474- let (width, height) = (640usize, 384usize);
13474+ let (width, height) = (1280usize, 768usize);
1347513475 let picture = clip_frame(clip, "0", width, height);
1347613476 eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
1347713477 for q in [5u8, 20, 35, 45] {
@@ -15130,6 +15130,77 @@ mod tests {
1513015130 /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
1513115131 /// the instrument the inter `TxMode::Select` hunt lacked; on failure it
1513215132 /// names the first differing frame, plane and position.
15133+ /// lane-sb128b: the writer used to price a `NEWMV` residual against
15134+ /// `stack.pred_mv` whenever the SEARCH chose a `ref_mv_idx` the
15135+ /// write-time stack could not carry, while the drl symbols signalled the
15136+ /// clamped index -- so the decoder derived a DIFFERENT motion vector with
15137+ /// the entropy stream still in sync, and the drift only surfaced frames
15138+ /// later as a drl desync (on film B, as the encoder's own trial decode
15139+ /// refusing a reference slot).
15140+ ///
15141+ /// The clamp needs a stack that shrinks between search and write, which
15142+ /// is what a 128x128 superblock's visit order does; the counter is the
15143+ /// point (class `gate-blind-to-feature`): a green round trip on a clip
15144+ /// that never clamps proves nothing.
15145+ ///
15146+ /// `#[ignore]`: [`force_sb128`] moves a process-global.
15147+ ///
15148+ /// cargo test -p ec-av1 --release --lib -- --ignored \
15149+ /// a_128_superblock_clip_whose_drl_index_the_write_time_stack --nocapture
15150+ #[test]
15151+ #[ignore = "sets the process-global superblock size: run it alone"]
15152+ fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {
15153+ let _knobs = crate::speed::knob_write();
15154+ if !have_ffmpeg() {
15155+ eprintln!("SKIP: no ffmpeg");
15156+ return;
15157+ }
15158+ force_sb128(true);
15159+ let dir = std::env::temp_dir().join(format!("ec-av1-sb128b-{}", std::process::id()));
15160+ std::fs::create_dir_all(&dir).unwrap();
15161+ let clip = dir.join("mandelbrot-1280x768.y4m");
15162+ let ok = Command::new("ffmpeg")
15163+ .args(["-v", "error", "-y", "-f", "lavfi", "-i", "mandelbrot=size=1280x768:rate=24"])
15164+ .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
15165+ .arg(&clip)
15166+ .status()
15167+ .expect("ffmpeg failed to run")
15168+ .success();
15169+ assert!(ok, "ffmpeg could not write the synthetic clip");
15170+ let path = clip.to_str().unwrap();
15171+ let (width, height) = (1280usize, 768usize);
15172+ let pictures = crate::probe::source(path, "0", "null", width, height, 12);
15173+
15174+ let _ = crate::tile::take_drl_clamp_hits();
15175+ let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
15176+ let clamps = crate::tile::take_drl_clamp_hits();
15177+ assert!(
15178+ clamps > 0,
15179+ "this clip never asked for a drl index the write-time stack could not carry, \
15180+ so it cannot witness the defect"
15181+ );
15182+ eprintln!("clamped drl indices: {clamps}");
15183+
15184+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
15185+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
15186+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
15187+ let recon = &frame.reconstruction;
15188+ for (plane, got, want) in [
15189+ ("luma", &dec.y, &recon.y),
15190+ ("U", &dec.u, &recon.u),
15191+ ("V", &dec.v, &recon.v),
15192+ ] {
15193+ let differ = got.iter().zip(want).filter(|(a, b)| a != b).count();
15194+ assert_eq!(
15195+ differ, 0,
15196+ "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
15197+ own reconstruction",
15198+ got.len()
15199+ );
15200+ }
15201+ }
15202+ }
15203+
1513315204 #[test]
1513415205 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
1513515206 let _knobs = crate::speed::knob_read();
crates/ec-av1/src/msac.rsmodified+100 -1
@@ -144,6 +144,9 @@ impl SymbolEncoder {
144144 /// shorter than a two-symbol alphabet's three entries.
145145 pub fn symbol_fixed(&mut self, symbol: usize, cdf: &[u16]) {
146146 assert!(cdf.len() >= 3, "a CDF covers at least two symbols");
147+ if !self.pricing && symtrace::dir().is_some() {
148+ symtrace::push(symbol, cdf.len() - 1, cdf[0]);
149+ }
147150 let nsyms = cdf.len() - 1;
148151 assert!(symbol < nsyms, "symbol {symbol} is outside the alphabet");
149152
@@ -201,6 +204,7 @@ impl SymbolEncoder {
201204 /// payload end on a byte boundary with no terminator.
202205 pub fn finish(mut self) -> Vec<u8> {
203206 assert!(!self.pricing, "a pricer holds no bytes to flush");
207+ symtrace::flush('w');
204208 // Round the interval's low end up to a value with 14 low zero bits,
205209 // then set bit 14: the result is inside the interval (the interval is
206210 // at least 2^15 wide before normalisation) and its tail bits are all
@@ -303,6 +307,12 @@ pub struct SymbolDecoder<'a> {
303307 max_bits: i32,
304308 }
305309
310+impl Drop for SymbolDecoder<'_> {
311+ fn drop(&mut self) {
312+ symtrace::flush('r');
313+ }
314+}
315+
306316 impl<'a> SymbolDecoder<'a> {
307317 /// `init_symbol` (spec 8.2.2).
308318 #[must_use]
@@ -397,6 +407,16 @@ impl<'a> SymbolDecoder<'a> {
397407 /// [`SymbolEncoder::symbol_fixed`].
398408 #[inline]
399409 pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize {
410+ if symtrace::dir().is_some() {
411+ let s = self.symbol_fixed_raw(cdf);
412+ symtrace::push(s, cdf.len() - 1, cdf[0]);
413+ return s;
414+ }
415+ self.symbol_fixed_raw(cdf)
416+ }
417+
418+ #[inline]
419+ fn symbol_fixed_raw(&mut self, cdf: &[u16]) -> usize {
400420 let nsyms = cdf.len() - 1;
401421 // Two-symbol alphabets are most of the stream (every flag, every bit of
402422 // a literal), and their walk has exactly one boundary: computing it
@@ -493,7 +513,11 @@ impl<'a> SymbolDecoder<'a> {
493513 // `EQUIPROBABLE`'s single boundary: `f >> EC_PROB_SHIFT` is 256, so
494514 // the range multiply is a shift.
495515 let cur = ((self.range >> 8) << 7) + EC_MIN_PROB;
496- v = (v << 1) | self.bool_cur(cur) as u32;
516+ let bit = self.bool_cur(cur);
517+ if symtrace::dir().is_some() {
518+ symtrace::push(bit, 2, EQUIPROBABLE[0]);
519+ }
520+ v = (v << 1) | bit as u32;
497521 }
498522 v
499523 }
@@ -790,3 +814,78 @@ pub(crate) mod tests {
790814 }
791815 }
792816 }
817+
818+/// Symbol-by-symbol writer/reader trace (`EC_AV1_SYMTRACE=<dir>`), the
819+/// instrument a desync between OUR writer and OUR reader is bisected with:
820+/// every non-pricing [`SymbolEncoder`] and every [`SymbolDecoder`] dumps one
821+/// line per symbol (`index value nsyms cdf0`) into `<dir>/w-<n>.txt` /
822+/// `<dir>/r-<n>.txt`, and the first line where the two differ names the
823+/// divergent symbol. `EC_AV1_SYMTRACE_AT=<index>` additionally prints a
824+/// backtrace at that index on both sides, which names the syntax element.
825+/// Off (the variable unset) this is one relaxed load per symbol.
826+pub(crate) mod symtrace {
827+ use std::cell::RefCell;
828+ use std::sync::OnceLock;
829+
830+ static DIR: OnceLock<Option<String>> = OnceLock::new();
831+ static AT: OnceLock<Option<(usize, usize)>> = OnceLock::new();
832+ static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
833+
834+ thread_local! {
835+ static BUF: RefCell<(String, usize)> = const { RefCell::new((String::new(), 0)) };
836+ }
837+
838+ pub(crate) fn dir() -> Option<&'static str> {
839+ DIR.get_or_init(|| crate::envflags::var("EC_AV1_SYMTRACE").ok().filter(|v| !v.is_empty()))
840+ .as_deref()
841+ }
842+
843+ /// `EC_AV1_SYMTRACE_AT=<i>` or `=<from>:<to>` (inclusive).
844+ fn at() -> Option<(usize, usize)> {
845+ *AT.get_or_init(|| {
846+ let v = crate::envflags::var("EC_AV1_SYMTRACE_AT").ok()?;
847+ let (a, b) = v.split_once(':').unwrap_or((v.as_str(), v.as_str()));
848+ Some((a.parse().ok()?, b.parse().ok()?))
849+ })
850+ }
851+
852+ /// A caller's own annotation, interleaved with this coder's symbol lines
853+ /// (`# ...`) so the writer/reader diff shows the state around a desync.
854+ pub(crate) fn note(line: &str) {
855+ if dir().is_none() {
856+ return;
857+ }
858+ BUF.with(|b| {
859+ let (buf, _) = &mut *b.borrow_mut();
860+ buf.push_str("# ");
861+ buf.push_str(line);
862+ buf.push('\n');
863+ });
864+ }
865+
866+ pub(crate) fn push(value: usize, nsyms: usize, cdf0: u16) {
867+ BUF.with(|b| {
868+ let (buf, n) = &mut *b.borrow_mut();
869+ if at().is_some_and(|(a, b)| (a..=b).contains(n)) {
870+ eprintln!("SYMTRACE at {n}: {}", std::backtrace::Backtrace::force_capture());
871+ }
872+ buf.push_str(&format!("{n} {value} {nsyms} {cdf0}\n"));
873+ *n += 1;
874+ });
875+ }
876+
877+ /// Flushes this coder's lines as `<dir>/<side>-<n>.txt` and starts the
878+ /// next coder's trace.
879+ pub(crate) fn flush(side: char) {
880+ let Some(dir) = dir() else { return };
881+ BUF.with(|b| {
882+ let (buf, n) = &mut *b.borrow_mut();
883+ if !buf.is_empty() {
884+ let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
885+ let _ = std::fs::write(format!("{dir}/{side}-{seq:05}.txt"), buf.as_bytes());
886+ }
887+ buf.clear();
888+ *n = 0;
889+ });
890+ }
891+}
crates/ec-av1/src/mvstack.rsmodified+18 -0
@@ -1742,6 +1742,24 @@ pub fn find_mv_stack_with_sign_bias(
17421742 .checked_sub(1)
17431743 .is_some_and(|c| grid.skip_at(mi_row, c));
17441744
1745+ // lane-sb128b: the writer/reader stack diff instrument (`EC_AV1_MVDBG=1`)
1746+ // -- one line per built stack, in build order, so the two sides' logs
1747+ // diff to the first block whose candidate list differs.
1748+ if crate::msac::symtrace::dir().is_some() {
1749+ crate::msac::symtrace::note(&format!(
1750+ "MVDBG mi=({mi_row},{mi_col}) b=({bw4}x{bh4}) ref={ref_frame} n={} mv={:?}",
1751+ candidates.len(),
1752+ candidates.iter().map(|e| (e.mv, e.weight)).collect::<Vec<_>>(),
1753+ ));
1754+ let row = mi_row.checked_sub(1).map(|r| {
1755+ (mi_col..mi_col + bw4).map(|c| grid.get(r, c).map(|m| (m.ref_frame, m.mv))).collect::<Vec<_>>()
1756+ });
1757+ let col = mi_col.checked_sub(1).map(|c| {
1758+ (mi_row..mi_row + bh4).map(|r| grid.get(r, c).map(|m| (m.ref_frame, m.mv))).collect::<Vec<_>>()
1759+ });
1760+ crate::msac::symtrace::note(&format!(" above={row:?}"));
1761+ crate::msac::symtrace::note(&format!(" left={col:?}"));
1762+ }
17451763 MvStack {
17461764 entries: candidates,
17471765 nearest_mv,
crates/ec-av1/src/tile.rsmodified+70 -15
@@ -1042,10 +1042,13 @@ fn write_compound_block(
10421042 }
10431043 walk += 1;
10441044 }
1045- stack
1046- .entries
1047- .get(idx)
1048- .map_or(stack.near_mv, |e| (e.mv0, e.mv1))
1045+ let near = |i: usize| {
1046+ stack.entries.get(i).map_or(stack.near_mv, |e| (e.mv0, e.mv1))
1047+ };
1048+ if walk != idx && near(walk) != near(idx) {
1049+ note_drl_clamp(idx, walk, stack.entries.len());
1050+ }
1051+ near(walk)
10491052 }
10501053 InterMode::NearestNewMv | InterMode::NewNearestMv => {
10511054 // Neither mode codes a DRL index (the decoder leaves `ref_mv_idx`
@@ -1074,10 +1077,13 @@ fn write_compound_block(
10741077 }
10751078 walk += 1;
10761079 }
1077- let base = stack
1078- .entries
1079- .get(idx)
1080- .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1));
1080+ let nearest = |i: usize| {
1081+ stack.entries.get(i).map_or(stack.nearest_mv, |e| (e.mv0, e.mv1))
1082+ };
1083+ if walk != idx && nearest(walk) != nearest(idx) {
1084+ note_drl_clamp(idx, walk, stack.entries.len());
1085+ }
1086+ let base = nearest(walk);
10811087 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?;
10821088 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?;
10831089 (info.mv, info.mv1)
@@ -5937,6 +5943,27 @@ pub(crate) fn take_ref_hits() -> [usize; 7] {
59375943 }
59385944
59395945 /// Bumps the two histograms for one coded inter block.
5946+/// How many blocks this process wrote whose search-chosen `ref_mv_idx` the
5947+/// write-time stack could not carry, so the writer signalled a SMALLER index
5948+/// (lane-sb128b). Every one of these used to price its residual against a
5949+/// predictor the decoder never derives.
5950+static DRL_CLAMP_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
5951+
5952+/// Counts one clamped DRL index whose predictor differs from the one the
5953+/// search asked for -- the harmful case, and the only one a witness can see.
5954+fn note_drl_clamp(target: usize, signalled: usize, entries: usize) {
5955+ DRL_CLAMP_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5956+ if crate::envflags::env_flag!("EC_AV1_TRACE") {
5957+ eprintln!("DRL_CLAMP target={target} signalled={signalled} entries={entries}");
5958+ }
5959+}
5960+
5961+/// Takes and clears [`DRL_CLAMP_HITS`], for a gate's own before/after delta.
5962+#[cfg(test)]
5963+pub(crate) fn take_drl_clamp_hits() -> usize {
5964+ DRL_CLAMP_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
5965+}
5966+
59405967 fn note_inter_mode(mode: usize, drl: usize) {
59415968 INTER_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
59425969 DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
@@ -5959,23 +5986,31 @@ pub(crate) fn take_drl_hits() -> [usize; 4] {
59595986 /// `drl_mode` bit per stack entry past `start`, `1` to advance and `0` to
59605987 /// stop, at most two bits. `drl_ctx[idx]` is the context between
59615988 /// `entries[idx]` and `entries[idx + 1]`, exactly the pair the bit chooses
5962-/// between.
5989+/// between. Returns the index the symbols actually SIGNAL, which is `target`
5990+/// clamped by the stack (`min(target, start + 2, entries.len() - 1)`): the
5991+/// decoder derives its predictor from THAT index, so every caller must take
5992+/// its own base MV from the returned value and not from `target` (lane-sb128b:
5993+/// a search-chosen `ref_mv_idx` of 2 against a two-entry write-time stack
5994+/// signalled index 1 and priced the residual against `pred_mv`, and the
5995+/// decoder's MV silently drifted a whole frame before the drl symbols
5996+/// desynced).
59635997 fn write_drl_idx(
59645998 enc: &mut SymbolEncoder,
59655999 cdfs: &mut Cdfs,
59666000 stack: &crate::mvstack::MvStack,
59676001 start: usize,
59686002 target: usize,
5969-) {
6003+) -> usize {
59706004 let mut idx = start;
59716005 while idx < start + 2 && stack.entries.len() > idx + 1 {
59726006 let advance = idx < target;
59736007 enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[idx]]);
59746008 if !advance {
5975- return;
6009+ return idx;
59766010 }
59776011 idx += 1;
59786012 }
6013+ idx
59796014 }
59806015
59816016 /// Writer-side counterpart of the decoder's single-reference
@@ -6008,8 +6043,12 @@ fn write_inter_mode(
60086043 match info.mode {
60096044 InterMode::NewMv => {
60106045 enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]);
6011- write_drl_idx(enc, cdfs, stack, 0, idx);
6012- let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
6046+ let signalled = write_drl_idx(enc, cdfs, stack, 0, idx);
6047+ let base = stack.entries.get(signalled).map_or(stack.pred_mv, |e| e.mv);
6048+ if signalled != idx && base != stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv) {
6049+ note_drl_clamp(idx, signalled, stack.entries.len());
6050+ }
6051+ let idx = signalled;
60136052 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base)?;
60146053 note_inter_mode(3, idx);
60156054 Ok((info.mv, true))
@@ -6033,8 +6072,12 @@ fn write_inter_mode(
60336072 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARMV
60346073 // `RefMvIdx` starts at 1 for NEARMV (spec 5.11.24).
60356074 let idx = idx.max(1);
6036- write_drl_idx(enc, cdfs, stack, 1, idx);
6037- let mv = stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv);
6075+ let signalled = write_drl_idx(enc, cdfs, stack, 1, idx);
6076+ let mv = stack.entries.get(signalled).map_or(stack.near_mv, |e| e.mv);
6077+ if signalled != idx && mv != stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) {
6078+ note_drl_clamp(idx, signalled, stack.entries.len());
6079+ }
6080+ let idx = signalled;
60386081 note_inter_mode(1, idx);
60396082 Ok((mv, false))
60406083 }
@@ -6327,6 +6370,12 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
63276370 mi_rows as usize,
63286371 );
63296372 let (mv, is_new_mv) = write_inter_mode(&mut enc, &mut cdfs, info, &stack)?;
6373+ if crate::msac::symtrace::dir().is_some() {
6374+ crate::msac::symtrace::note(&format!(
6375+ " MODE mi=({mi_r},{mi_c}) mode={:?} idx={} mv={mv:?} info_mv={:?}",
6376+ info.mode, info.ref_mv_idx, info.mv
6377+ ));
6378+ }
63306379 (mv, (0, 0), is_new_mv)
63316380 };
63326381 for dr in 0..SB_MI as usize {
@@ -6722,6 +6771,12 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
67226771 );
67236772
67246773 let (mv, is_new_mv) = write_inter_mode(&mut enc, &mut cdfs, info, &stack)?;
6774+ if crate::msac::symtrace::dir().is_some() {
6775+ crate::msac::symtrace::note(&format!(
6776+ " MODE mi=({mi_r},{mi_c}) mode={:?} idx={} mv={mv:?} info_mv={:?}",
6777+ info.mode, info.ref_mv_idx, info.mv
6778+ ));
6779+ }
67256780 grid.set(
67266781 mi_row,
67276782 mi_col,
lanes/sb128b.report.mdadded+123 -0
@@ -0,0 +1,123 @@
1+# lane-sb128b — the film B 128-superblock refusal, and what 128 roots cost
2+
3+Two results, independent:
4+
5+1. **A writer defect, fixed** (`daebefdc`): the inter writer priced a `NEWMV`
6+ residual against a predictor the decoder never derives whenever the SEARCH
7+ chose a DRL index the WRITE-TIME mv stack could not carry. Silent MV drift,
8+ surfacing frames later as a drl desync — on film B as the encoder's own
9+ trial decode refusing a reference slot. Not a 128-superblock bug: 128 roots
10+ only make the search/write stack drift common enough to hit.
11+2. **The 128-root lever is REFUTED on film B** (cen3's L1, ≈0.24 dB expected):
12+ every arm loses, and the loss survives the forced loop-restoration unit.
13+
14+## 1. The refusal, and the first divergent symbol
15+
16+Reproduced at `6b95562d` in 8 s:
17+
18+ EC_ENC_SS=00:40:00 EC_AV1_SB128=1 \
19+ cargo run --release -p ec-av1 --example enc_probe -- <film B> gate 0 12 150
20+ -> Unsupported { "Leaf frame at order 3 (last slot 0, self 0, altref 4,
21+ last2 None, ...): a reference frame selected with no picture at this
22+ frame's own ref_frame_idx slot for it }
23+
24+`EC_AV1_REFPROBE=1` put the refusal inside OUR decode of OUR stream
25+(`filter_search::pick_filters` -> `decode_inter_frame_tiles_lr` ->
26+`decode_inter_block`), i.e. a writer/reader desync, not a DPB bug (class
27+*refusal names a correlate*).
28+
29+**Instrument** (new, kept): `EC_AV1_SYMTRACE=<dir>` writes one line per coded
30+symbol (`index value nsyms cdf[0]`) per coder into `<dir>/w-*.txt` /
31+`<dir>/r-*.txt`, so the writer's file and the reader's file diff positionally;
32+`EC_AV1_SYMTRACE_AT=<i>` or `<from>:<to>` prints a backtrace at those indices
33+on both sides, which names the syntax element. `find_mv_stack` and the two
34+inter-mode sites annotate the same files (`# MVDBG ...`, `# MODE ...`).
35+
36+**First divergent symbol**: index **5393** of the order-3 leaf's tile.
37+
38+| | site | symbol |
39+|---|---|---|
40+| writer | `tile::write_motion_mode` (tile.rs:767) | 3-symbol `motion_mode`, value 0 |
41+| reader | `decode_inter_block` (decode.rs:28171) | 2-symbol `drl_mode`, value 0 |
42+
43+The reader read one `drl_mode` bit the writer never wrote, at mi=(32,176),
44+because its stack held 3 entries where the writer's held 2.
45+
46+**Root cause, one block earlier and silent**: at mi=(16,112) (a 64x64 block,
47+both sides' stacks IDENTICAL — `[((16,0),740), ((16,-24),736)]`):
48+
49+ W MODE mi=(16,112) mode=NewMv idx=2 mv=(16,-16) info_mv=(16,-16)
50+ R MODE mi=(16,112) dbg=16 mv=(16,-40)
51+
52+The search chose `ref_mv_idx = 2`; `write_drl_idx` can only SIGNAL index 1
53+against a two-entry stack, so the decoder derived its predictor from
54+`entries[1] = (16,-24)` while the writer priced the residual against
55+`stack.entries.get(2)` -> the `pred_mv` fallback. The two MVs differ by
56+exactly the two predictors' difference, the mi grid then differed for the rest
57+of the frame, and 60 blocks later the two stacks disagreed on size and the drl
58+symbol count desynced.
59+
60+**Fix** (`crates/ec-av1/src/tile.rs`): `write_drl_idx` returns the index it
61+actually signals, and every caller takes its base MV from THAT index — both
62+single-reference arms (`NewMv`, `NearMv`) and both compound DRL arms
63+(`NearNearMv`, `NEW_NEWMV`), where the walk variable was already the signalled
64+index but the predictor was read at the requested one. Same-shape sweep: the
65+four writer sites above are the whole class; every `entries.get(idx)` in
66+`decode.rs` derives `idx` from the symbols it just read, so the reader side
67+cannot drift. `encode.rs:8722` (the RD pricer's own base) still prices a
68+clamped candidate at the predictor the writer will NOT use — a mis-pricing,
69+not a desync; left open below.
70+
71+**Witness** (`encode::tests::a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact`,
72+`#[ignore]` because it forces the process-global superblock size):
73+
74+ cargo test -p ec-av1 --release --lib -- --ignored \
75+ a_128_superblock_clip_whose_drl_index --nocapture
76+
77+lavfi `mandelbrot=size=1280x768`, 12 frames, `force_sb128(true)`: the writer
78+clamps **7** drl indices whose predictor moves (the counter is the gate on the
79+fixture — class *gate blind to feature*), and every frame decodes sample-exact
80+against the encoder's own reconstruction. RED before the fix (frame luma
81+differs), GREEN after. `EC_AV1_SB128=0` clamps 0 on every clip probed, and
82+film B's default-path stream is byte-identical (27634 B at q=150) — the fix
83+does not move the shipped encoder.
84+
85+## 2. The 2x2 attribution — 128 roots are refuted on film B
86+
87+`bd_rate_screen_native`, `EC_AV1_NATIVE_FILM4K=1`, 12 frames, film B row,
88+BD-rate vs libaom cpu-used 6 / rav1e speed 6 (lower is better):
89+
90+| arm | vs libaom | vs rav1e | q=150 bytes |
91+|---|---|---|---|
92+| SB64, LR on (control, reproduced) | **+24.9%** | **−1.9%** | 27634 |
93+| SB64, LR off (`EC_AV1_LR=0`) | +25.4% | −1.6% | 27673 |
94+| SB128, LR on | +37.5% | +7.3% | 27753 |
95+| SB128, LR off | +33.6% | +5.8% | 27823 |
96+
97+Read it in one line: **the 128 root costs 8.2 points against libaom with the
98+loop-restoration unit held out of the comparison** (25.4 -> 33.6), and the
99+forced ≥128 LR unit adds a further 3.9 (33.6 -> 37.5). The keep rule fails on
100+both columns in every arm, so nothing ships: `EC_AV1_SB128` stays off, and
101+film A / screen / long-GOP were not run (the charter gates them on 128
102+winning).
103+
104+**Why the census's 0.24 dB never appears**: `tile::write_sb128_root` writes
105+`PARTITION_SPLIT` at every 128 root by construction — this encoder cannot code
106+a 128x128, 128x64 or 64x128 BLOCK at all. `EC_AV1_SB128=1` therefore buys zero
107+block-count saving and pays the root's partition symbols, the forced LR unit,
108+and (the new number here) whatever the 128 visit order costs: the quadrants
109+are coded TL/TR/BL/BR inside a 128 root instead of raster 64s, which moves
110+every neighbour context and strips `has_top_right` off the BR quadrant. The
111+lever cannot be measured honestly until a 128-root partition SEARCH exists;
112+cen3's L1 should be re-chartered as "search 128x128 blocks", not "set the
113+sequence bit".
114+
115+## Open
116+
117+- `open`: the RD pricer (`encode.rs:8722`) prices a `ref_mv_idx` the writer
118+ will clamp at the WRONG predictor, so those candidates' costs are wrong on
119+ both superblock sizes. Fires rarely (7 blocks per 12-frame 1280x768 clip
120+ under SB128; 0 under SB64 on every clip probed).
121+- `open`: the search-time and write-time mv stacks differ at all — that is the
122+ upstream cause of the clamp. Making the search build its stack from the
123+ writer's grid would remove the clamp instead of making it safe.