Sfoglia il codice sorgente

Writes through views picked from the heap come back (VICTORY_PICKED_WRITES)

Off by default. A shader that stores through a view it picks by an index (37
compute programs of the title, 82a2ad6d07417d36 one of them) writes buffers
nobody declared. With a submission that has one, the buffers found written
that way are declared and landed as any; of the other buffers the heap shows
unordered views of 32 MB a frame are compared on the card, in turn, and one
that changed undeclared is found. Found late is not landed late.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
local 2 giorni fa
parent
commit
b1da728148

+ 10 - 0
crates/victory-gpu/src/draw.rs

@@ -1044,6 +1044,9 @@ impl State {
         for stage in &p.stages {
             let t = stage.translated();
             STORES.set(t.stores);
+            if t.stores && crate::picked::on() && crate::picked::picks(&stage.shader, &t.picks) {
+                crate::picked::runs_in(list);
+            }
             let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute);
             STORES.set(true);
             if made.iter().any(|m| m.1 == u32::MAX) {
@@ -1469,6 +1472,7 @@ impl State {
         // it is named below.
         static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
         let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none();
+        let mut unordered = Vec::new();
         for (n, &index) in slots.iter().enumerate() {
             ranges.remove(&index);
             let Some(handle) = heap.handle(index) else {
@@ -1501,8 +1505,14 @@ impl State {
             if host.shows(index, &shadow.buffer) == Some(false) {
                 HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed);
             }
+            if crate::picked::on() && view_kind(&view) == Some(ResourceType::Uav) {
+                unordered.push((shadow.clone(), address, address + len));
+            }
             ranges.insert(index, (shadow, address, address + len));
         }
+        if crate::picked::on() {
+            crate::picked::shown(unordered, *passes % 16 == 1);
+        }
         let views = ranges.len() as u32;
         // Per host copy, the span its picked views cover.
         let mut spans: std::collections::HashMap<usize, (std::sync::Arc<crate::shadow::Shadow>, u64, u64)> =

+ 6 - 0
crates/victory-gpu/src/frame.rs

@@ -84,6 +84,12 @@ pub(crate) fn current() -> u64 {
     FRAME.load(Ordering::Relaxed)
 }
 
+/// For tests of what is done once a frame.
+#[cfg(test)]
+pub(crate) fn test_advance() {
+    FRAME.fetch_add(1, Ordering::Relaxed);
+}
+
 /// Per event kind (origin, vblank, flip and later kinds): the last tick a
 /// wait for it ended on.
 static LAST: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];

+ 67 - 9
crates/victory-gpu/src/host.rs

@@ -1670,6 +1670,22 @@ struct CardRange {
     at: u32,
     /// Whether the card compares it; else every piece is fetched.
     compared: bool,
+    /// Looked at by `crate::picked`, and not declared: what is found changed
+    /// there was written through a view nobody declared. Not landed.
+    picked: bool,
+}
+
+impl CardPlan {
+    /// `crate::picked` is told where what it looked at changed, by the
+    /// compare's results.
+    fn picked_found(&self, differs: &[u32]) {
+        for r in self.ranges.iter().filter(|r| r.picked) {
+            let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)));
+            if let Some(p) = changed {
+                crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0);
+            }
+        }
+    }
 }
 
 /// What a submission does for copies in the card's memory.
@@ -2946,6 +2962,7 @@ fn late_line(frames: f64) {
     }
     crate::land::log(frames);
     card_steps::log(frames);
+    crate::picked::log(frames);
     #[cfg(feature = "diagnostics")]
     log_blame(frames);
     if late_exact() {
@@ -3463,7 +3480,9 @@ impl Host {
     /// `flown`: the submission is sent ahead with [`relay`]. Its compare
     /// then stores the hashes it makes (see [`flagged_pieces`] and
     /// `relay`).
-    fn card_before(&self, runs: &[&HostList], flown: bool) -> Option<CardPlan> {
+    /// `picked`: ranges that may be written too, and ranges to look at
+    /// (`crate::picked`).
+    fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
         use std::sync::Arc;
         if !crate::shadow::cards() {
             return None;
@@ -3487,6 +3506,10 @@ impl Host {
                 }
             }
         }
+        let declared = crate::picked::with(declared, &picked.written);
+        // (Of a copy with a declared range here, that says it.)
+        let looked: Vec<&crate::picked::Range> =
+            picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect();
         // With the relay: the order of the queue is held from here until
         // what is taken is on the queue, and the taking is numbered.
         let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
@@ -3498,7 +3521,7 @@ impl Host {
             None => 0,
         };
         let mut dirty = crate::shadow::card_dirty(sent_as);
-        if declared.is_empty() && dirty.is_empty() {
+        if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
             return None;
         }
         let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
@@ -3506,7 +3529,7 @@ impl Host {
         // A copy whose shader writes are declared for the first time gets
         // its bytes from before, whole.
         let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
-        for (shadow, _) in &declared {
+        for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) {
             if shadow.card_make_before(|size| {
                 let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
                 name(&before, || "title buffer on the card, hashes of its pieces".into());
@@ -3631,12 +3654,30 @@ impl Host {
                     span,
                     at,
                     compared,
+                    picked: false,
                 });
                 if compared {
                     at += span.pieces;
                 }
             }
         }
+        for (shadow, from, len) in looked {
+            let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
+            if let Some(span) = shadow.card_span(*from, from + len)
+                && twin
+                && u64::from(at + span.pieces) * 4 <= work.differs.2
+            {
+                plan.ranges.push(CardRange {
+                    shadow: shadow.clone(),
+                    declared: (*from, from + len),
+                    span,
+                    at,
+                    compared: true,
+                    picked: true,
+                });
+                at += span.pieces;
+            }
+        }
         work.taken = at;
         if plan.ranges.iter().any(|r| r.compared) {
             let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
@@ -3669,7 +3710,9 @@ impl Host {
                         };
                         list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
                         list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
-                        card_pass(list, &r.span, size as u32, r.at, if flown { 2 } else { 1 });
+                        // (What is only looked at keeps its hashes: what
+                        // changed there is the next declared range's to land.)
+                        card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 });
                         CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
                     }
                     list.Close()?;
@@ -3795,9 +3838,11 @@ impl Host {
             let suspects = fetch.as_ref().map(|f| &f.suspects);
             let mut seen = std::collections::HashSet::new();
             for &(plan, behind) in plans {
+                plan.picked_found(differs);
                 let flags: Vec<(usize, u32, bool)> = plan
                     .ranges
                     .iter()
+                    .filter(|r| !r.picked)
                     .flat_map(|r| {
                         (0..r.span.pieces).map(move |p| {
                             let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d));
@@ -3807,7 +3852,7 @@ impl Host {
                     })
                     .collect();
                 let fetched = flagged_pieces(&flags);
-                for r in &plan.ranges {
+                for r in plan.ranges.iter().filter(|r| !r.picked) {
                     let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
                     if upcheck::on() {
                         upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize);
@@ -4166,7 +4211,8 @@ impl Host {
         // where the bytes come down.
         let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
         let mut total = 0u64;
-        for (i, r) in plan.ranges.iter().enumerate() {
+        plan.picked_found(differs);
+        for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) {
             for p in 0..r.span.pieces {
                 if r.compared && !torn::flagged(differs[(r.at + p) as usize]) {
                     continue;
@@ -4708,7 +4754,13 @@ impl Host {
             self.settle(&mut submitted, WHY_MOST);
             settled += settling.elapsed();
         }
-        let card = self.card_before(runs, flown);
+        // What shaders may write through views they pick: last, so that no
+        // refresh of this submission leaves it alone.
+        let picked = crate::picked::declare(runs);
+        for (shadow, at, len) in &picked.written {
+            shadow.writing(*at, *len);
+        }
+        let card = self.card_before(runs, &picked, flown);
         if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
             lists.push(Some(check));
         }
@@ -4724,7 +4776,7 @@ impl Host {
             if let Err(e) = signalled {
                 fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
             }
-            let back = declared_writes(runs);
+            let back = crate::picked::with(declared_writes(runs), &picked.written);
             let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
             SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
             submitting(0, 0);
@@ -4844,7 +4896,7 @@ impl Host {
         if let Some(card) = &card {
             self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
         }
-        let back = declared_writes(runs);
+        let back = crate::picked::with(declared_writes(runs), &picked.written);
         hand_back(&back);
         if let Some(card) = card {
             self.card_done(card);
@@ -5969,6 +6021,12 @@ impl HostList {
         self.deferred().textures.insert(key)
     }
 
+    /// Whether `key` was asked about ([`HostList::first_use`]) since the
+    /// reset.
+    pub(crate) fn used(&self, key: usize) -> bool {
+        self.deferred().textures.contains(&key)
+    }
+
     /// Runs `work` when the list is submitted, in order with its copies.
     /// `work` may write title memory (refreshes after it copy again).
     pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {

+ 1 - 1
crates/victory-gpu/src/host/torn.rs

@@ -109,7 +109,7 @@ impl Check {
             within.push(i);
         }
         // (The last flight's stands.)
-        for r in plans.flat_map(|plan| &plan.ranges).filter(|r| r.compared) {
+        for r in plans.flat_map(|plan| &plan.ranges).filter(|r| r.compared && !r.picked) {
             for p in 0..r.span.pieces {
                 if let Some(&i) = index.get(&(r.shadow.id(), r.span.first + p))
                     && let Some(&d) = differs.get((r.at + p) as usize)

+ 45 - 0
crates/victory-gpu/src/host/upcheck.rs

@@ -720,6 +720,51 @@ mod tests {
         assert_eq!((undone, found), (true, 16));
     }
 
+    /// A shader that writes through views it picks: its buffer is found when
+    /// it comes to it in turn, and what it writes from then on is landed.
+    #[test]
+    #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 VICTORY_PICKED_WRITES=1 VICTORY_PICKED_MB=1 and a process of its own"]
+    fn writes_through_picked_views_come_back() {
+        let Some(host) = host() else {
+            return;
+        };
+        assert!(crate::picked::on(), "set VICTORY_PICKED_WRITES=1");
+        let (title, start, shadow) = title(0x6666, true);
+        crate::picked::shown(vec![(shadow.clone(), start as u64, (start + LEN) as u64)], true);
+        let at = (37 << 16) + 512;
+        let mut lists = Vec::new();
+        let mut back = Vec::new();
+        for round in 0..12u8 {
+            // Turns go by frames.
+            crate::frame::test_advance();
+            title[(37 << 16) + 9000] = round + 1;
+            let list = host.new_list().unwrap();
+            shadow.refresh(&list, start as u64, LEN as u64);
+            crate::picked::runs_in(&list);
+            write(host, &list, &shadow, at, &[0x40 + round; 64]);
+            list.close();
+            host.execute_own(&list);
+            settle_now(WHY_SYNC);
+            back.push(title[at..at + 64] == [0x40 + round; 64]);
+            // The title's own write beside it is on the card, and the
+            // shader's stays, once its buffer is known.
+            let next = host.new_list().unwrap();
+            shadow.refresh(&next, start as u64, LEN as u64);
+            next.close();
+            host.execute_own(&next);
+            settle_now(WHY_SYNC);
+            if *back.last().unwrap() {
+                let holds = card(host, &shadow);
+                assert_eq!((holds[(37 << 16) + 9000], holds[at]), (round + 1, 0x40 + round));
+                assert_eq!(look(host), Some(0));
+            }
+            lists.extend([list, next]);
+        }
+        eprintln!("came back, by round: {back:?}");
+        let first = back.iter().position(|b| *b).expect("it is found");
+        assert!(first <= 6 && back[first..].iter().all(|b| *b), "{back:?}");
+    }
+
     /// Declared writes beside the title's own, in the same 64 KiB pieces and
     /// dword by dword, flights landing while later ones are in the air: in
     /// the end title memory and the card hold what each wrote last. (A byte

+ 2 - 0
crates/victory-gpu/src/lib.rs

@@ -39,6 +39,8 @@ pub mod list;
 pub mod object;
 pub mod pipeline;
 #[cfg(windows)]
+mod picked;
+#[cfg(windows)]
 mod pool;
 #[cfg(windows)]
 mod primitive;

+ 372 - 0
crates/victory-gpu/src/picked.rs

@@ -0,0 +1,372 @@
+//! Buffers shaders write through views they pick from the heap by an index
+//! they compute (`VICTORY_PICKED_WRITES=1`; off by default).
+//!
+//! Which views a draw or dispatch writes through is known from its tables
+//! and root parameters, and their ranges are declared: what is written there
+//! comes back to title memory (`Shadow::gpu_writes`). A view picked by an
+//! index out of a buffer, per lane, names any of the heap's. What was
+//! written through one stayed on the card: title memory, and the title's own
+//! copies and textures made from it, never saw it, and a refresh of its 64
+//! KiB put title memory's older bytes over it. (Captures replay1 and
+//! replay2: `[compute 82a2ad6d07417d36]` writes 4.6 MB a frame of a 24 MB
+//! buffer so.) To declare all such a shader could write would be 987 MB of
+//! 573 buffers for every list that runs one.
+//!
+//! Two things make it small. The compare on the card says what changed since
+//! the last time it looked, whoever wrote it and whenever: looking now and
+//! then misses no buffer, it only finds it later. And a buffer that was
+//! written so once is written so again. So with a submission that has a
+//! shader that stores through a picked view ([`stores_picked`])
+//!
+//! - the buffers found written that way ([`found`]) are declared: compared
+//!   and landed with the submission, as any declared write;
+//! - of the others that the heap shows unordered views of the next [`slice`]
+//!   in turn, once a frame, is compared, and nothing else: at 32 MB all of
+//!   them in some 30 frames. Where something changed that nobody declared,
+//!   the buffer is one of the first kind from then on.
+//!
+//! What is found late is not landed late: the title may have other things in
+//! that memory by then. It goes to title memory with the next declared write
+//! to its 64 KiB. So what is written once, into a buffer not found yet, stays
+//! on the card as before.
+//!
+//! The declarations are the submission's, made when its refreshes are done
+//! (`Host::submit`): no refresh of it finds a range closed on their account.
+//!
+//! Only copies in the card's memory: for those in the PC's, a declared range
+//! is a snapshot and a compare on the CPU. (They hold 55 MB of the 987.)
+//!
+//! What it costs: the hashing of the slice and of the buffers found, and
+//! what changed of the latter coming back. What else changes: a step on the
+//! CPU that reads a buffer found waits for the flight, as it should always
+//! have done.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed};
+use std::sync::{Arc, Mutex, OnceLock, Weak};
+
+use crate::host::HostList;
+use crate::shadow::Shadow;
+
+pub(crate) fn on() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| std::env::var_os("VICTORY_PICKED_WRITES").is_some_and(|v| v == "1"))
+}
+
+/// Bytes looked at in turn per frame (`VICTORY_PICKED_MB`).
+fn slice() -> u64 {
+    static SLICE: OnceLock<u64> = OnceLock::new();
+    *SLICE.get_or_init(|| {
+        let mb = std::env::var("VICTORY_PICKED_MB").ok().and_then(|v| v.trim().parse::<u64>().ok());
+        mb.unwrap_or(32) << 20
+    })
+}
+
+/// A list's key for [`HostList::first_use`]: it runs such a shader (no title
+/// resource is there).
+const KEY: usize = usize::MAX - 0x7a;
+
+/// `list` runs a shader that stores through a picked view.
+pub(crate) fn runs_in(list: &HostList) {
+    list.first_use(KEY);
+}
+
+/// [`crate::pipeline::Translated::picks`]: not asked yet, asked, the answers.
+const UNKNOWN: u8 = 0;
+const ASKED: u8 = 1;
+const NO: u8 = 2;
+const YES: u8 = 3;
+
+/// Whether `shader`, which stores to buffers, does so through a view it
+/// picks. Tracing its descriptors takes some 50 ms, so a thread of ours does
+/// it when the shader is first bound, and it is "no" until then: what it
+/// writes is found some frames later in any case. (Of the 25,904 programs of
+/// the title 2,923 store and have the view heap among their parameters; 37
+/// compute programs store through views they pick.)
+pub(crate) fn picks(shader: &Arc<crate::pipeline::Shader>, known: &AtomicU8) -> bool {
+    match known.load(Relaxed) {
+        YES => true,
+        UNKNOWN => {
+            if known.compare_exchange(UNKNOWN, ASKED, Relaxed, Relaxed).is_ok() {
+                ask(shader.clone());
+            }
+            false
+        }
+        _ => false,
+    }
+}
+
+fn ask(shader: Arc<crate::pipeline::Shader>) {
+    use std::sync::mpsc::{Sender, channel};
+    static ASKS: OnceLock<Mutex<Sender<Arc<crate::pipeline::Shader>>>> = OnceLock::new();
+    let asks = ASKS.get_or_init(|| {
+        let (send, asks) = channel::<Arc<crate::pipeline::Shader>>();
+        let _ = std::thread::Builder::new().name("victory-picked".into()).spawn(move || {
+            use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL};
+            // SAFETY: this thread's own.
+            unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL) };
+            for shader in asks {
+                let yes = shader.programs().is_none_or(|all| all.iter().any(stores_picked));
+                if yes {
+                    tracing::info!(hash = %shader.hash, "a shader stores through views it picks from the heap (VICTORY_PICKED_WRITES=1)");
+                }
+                if let Some(t) = shader.translated() {
+                    t.picks.store(if yes { YES } else { NO }, Relaxed);
+                }
+            }
+        });
+        Mutex::new(send)
+    });
+    let _ = asks.lock().unwrap_or_else(|e| e.into_inner()).send(shader);
+}
+
+/// Whether the code of `program` stores to a buffer through a descriptor
+/// that its tables do not name: loaded from the view heap, or from a table at
+/// an offset it computes (programs with the view heap among their parameters). Yes where that cannot be told.
+fn stores_picked(program: &victory_shader::NativeProgram) -> bool {
+    use victory_shader::HwStage;
+    use victory_shader::gfx10::Fields;
+    use victory_shader::native::RootType;
+    use victory_shader::resource::{Role, Source};
+    // (The programs that are translated.)
+    if !matches!(program.stage, HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms) {
+        return false;
+    }
+    let heap = |param: usize| program.layout.get(param).is_some_and(|p| p.root == RootType::ResourceHeap);
+    if !(0..program.layout.len()).any(heap) {
+        return false;
+    }
+    let Ok(p) = victory_shader::spill::build(program) else {
+        return true;
+    };
+    // The structure is what takes time, and only per-lane descriptors need
+    // it.
+    let plain = victory_shader::resource::track(&p, &program.layout, program.stage, None);
+    let res = plain.or_else(|_| {
+        let st = victory_shader::structure::structure(&p);
+        victory_shader::resource::track(&p, &program.layout, program.stage, st.as_ref().ok())
+    });
+    let Ok(res) = res else {
+        return true;
+    };
+    res.descriptors.iter().filter(|d| d.role == Role::Resource).any(|d| {
+        let inst = &p.blocks[d.site.0].insts[d.site.1];
+        let stores = matches!(inst.fields, Fields::Buffer { .. }) && (inst.name().contains("store") || inst.name().contains("atomic"));
+        stores
+            && d.source.leaves().into_iter().any(|s| match s {
+                Source::Loaded { load, .. } | Source::Fetched { load, .. } => res
+                    .scalar
+                    .iter()
+                    .find(|(site, _)| site == load)
+                    .is_some_and(|(_, a)| heap(a.param) || a.dynamic.is_some()),
+                _ => false,
+            })
+    })
+}
+
+/// A buffer the heap shows unordered views of: title addresses, from the
+/// first to the last.
+struct Shown {
+    copy: Weak<Shadow>,
+    from: u64,
+    to: u64,
+}
+
+#[derive(Default)]
+struct State {
+    shown: BTreeMap<u64, Shown>,
+    /// The copies (by number) found written through picked views.
+    found: BTreeSet<u64>,
+    /// Where the next slice begins: copy, offset from its first address.
+    next: (u64, u64),
+    /// The frame of the last slice.
+    frame: u64,
+}
+
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+
+impl State {
+    /// The ranges of the next `most` bytes in turn, at most all once.
+    fn turn(&mut self, most: u64) -> Vec<(u64, u64, u64)> {
+        let mut out: Vec<(u64, u64, u64)> = Vec::new();
+        let mut left = most;
+        // (The one it begins in may come twice: its end first.)
+        for _ in 0..=self.shown.len() {
+            let (copy, offset) = self.next;
+            let Some((&id, s)) = self.shown.range(copy..).next().or_else(|| self.shown.iter().next()) else {
+                break;
+            };
+            let offset = if id == copy { offset } else { 0 };
+            let len = s.to - s.from;
+            let n = len.saturating_sub(offset).min(left);
+            if n > 0 && !self.found.contains(&id) {
+                if out.iter().any(|r| r.0 == id) {
+                    break;
+                }
+                out.push((id, s.from + offset, n));
+                left -= n;
+                if offset + n < len {
+                    self.next = (id, offset + n);
+                    break;
+                }
+            }
+            self.next = (id + 1, 0);
+            if left == 0 {
+                break;
+            }
+        }
+        out
+    }
+}
+
+/// The pass over the heap's buffer views (`crate::draw`): the unordered ones
+/// it looked at (copy, from, to); `all` if those are all there are.
+pub(crate) fn shown(views: Vec<(Arc<Shadow>, u64, u64)>, all: bool) {
+    let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    let state = state.get_or_insert_with(State::default);
+    if all {
+        state.shown.clear();
+    }
+    for (copy, from, to) in views.into_iter().filter(|v| v.0.carded() && v.1 < v.2) {
+        let e = state.shown.entry(copy.id()).or_insert_with(|| Shown {
+            copy: Arc::downgrade(&copy),
+            from,
+            to,
+        });
+        (e.from, e.to) = (e.from.min(from), e.to.max(to));
+    }
+}
+
+/// A range of a copy: title address and bytes.
+pub(crate) type Range = (Arc<Shadow>, usize, usize);
+
+/// What is done with a submission.
+#[derive(Default)]
+pub(crate) struct Ranges {
+    /// To be declared.
+    pub(crate) written: Vec<Range>,
+    /// To be compared only.
+    pub(crate) looked: Vec<Range>,
+}
+
+/// Of a submission that is about to go to the card, its refreshes done: what
+/// is to be declared and looked at, if one of its lists runs a shader that
+/// stores through a picked view.
+pub(crate) fn declare(runs: &[&HostList]) -> Ranges {
+    if !on() || !runs.iter().any(|list| list.used(KEY)) {
+        return Ranges::default();
+    }
+    let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    let Some(state) = state.as_mut() else {
+        return Ranges::default();
+    };
+    let frame = crate::frame::current();
+    let written: Vec<(u64, u64, u64)> =
+        state.found.iter().filter_map(|id| state.shown.get(id).map(|s| (*id, s.from, s.to - s.from))).collect();
+    let mut looked = Vec::new();
+    if state.frame != frame {
+        state.frame = frame;
+        looked = state.turn(slice());
+    }
+    let of = |ranges: Vec<(u64, u64, u64)>, count: usize| -> Vec<Range> {
+        COUNTS[count].fetch_add(ranges.iter().map(|r| r.2).sum(), Relaxed);
+        ranges
+            .into_iter()
+            .filter_map(|(id, at, len)| Some((state.shown.get(&id)?.copy.upgrade()?, at as usize, len as usize)))
+            .collect()
+    };
+    Ranges { written: of(written, 0), looked: of(looked, 1) }
+}
+
+/// The compare found a piece changed (it begins at offset `at` of `copy`)
+/// where it only looked: something wrote it through a view nobody declared.
+pub(crate) fn found(copy: &Arc<Shadow>, at: usize) {
+    let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    if state.get_or_insert_with(State::default).found.insert(copy.id()) {
+        let (start, len) = copy.span();
+        tracing::info!(
+            "a buffer is written through views picked from the heap: {start:#x}+{len:#x} (first seen at +{at:#x}; VICTORY_PICKED_WRITES=1): \
+             declared with every submission that may write it from here on"
+        );
+    }
+}
+
+/// Since the last frame-rate line: bytes declared, and bytes looked at.
+static COUNTS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
+
+/// For the frame-rate line.
+pub(crate) fn log(frames: f64) {
+    if !on() {
+        return;
+    }
+    let [declared, looked] = [0, 1].map(|i| COUNTS[i].swap(0, Relaxed) as f64 / frames / (1 << 20) as f64);
+    let state = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    let (shown, found) = state.as_ref().map_or((0, 0), |s| (s.shown.len(), s.found.len()));
+    tracing::info!(
+        "views picked from the heap, per frame (VICTORY_PICKED_WRITES=1): {declared:.1} MB declared for them, {looked:.1} MB \
+         looked at in turn; unordered views of {shown} buffers on the card, {found} of them found written"
+    );
+}
+
+/// Declared writes, per copy, and those of `picked`.
+pub(crate) fn with(mut back: Vec<(Arc<Shadow>, Vec<(usize, usize)>)>, picked: &[Range]) -> Vec<(Arc<Shadow>, Vec<(usize, usize)>)> {
+    for (copy, at, len) in picked {
+        let range = (*at, *at + *len);
+        match back.iter_mut().find(|b| Arc::ptr_eq(&b.0, copy)) {
+            Some((_, ranges)) if ranges.contains(&range) => {}
+            Some((_, ranges)) => ranges.push(range),
+            None => back.push((copy.clone(), vec![range])),
+        }
+    }
+    back
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn state(sizes: &[u64]) -> State {
+        let mut state = State::default();
+        for (i, &n) in sizes.iter().enumerate() {
+            let from = (i as u64 + 1) << 32;
+            state.shown.insert(i as u64 * 3 + 2, Shown { copy: Weak::new(), from, to: from + n });
+        }
+        state
+    }
+
+    /// Every byte in turn, none left out, whatever the slice.
+    #[test]
+    fn all_buffers_are_looked_at_in_turn() {
+        let sizes = [100u64, 7, 1000, 1, 350];
+        let total: u64 = sizes.iter().sum();
+        for most in [1u64, 10, 99, 350, 1000, 5000] {
+            let mut s = state(&sizes);
+            let mut seen = std::collections::BTreeMap::<u64, u64>::new();
+            // (A turn ends with the list: it may take one more.)
+            let turns = total.div_ceil(most) + sizes.len() as u64 + 1;
+            for _ in 0..turns {
+                let turn = s.turn(most);
+                assert!(turn.iter().map(|r| r.2).sum::<u64>() <= most);
+                for (id, at, n) in turn {
+                    let from = s.shown[&id].from;
+                    for b in at - from..at - from + n.min(2000) {
+                        *seen.entry(id << 32 | b).or_default() += 1;
+                    }
+                }
+            }
+            assert_eq!(seen.len() as u64, total, "slices of {most}");
+        }
+    }
+
+    #[test]
+    fn what_was_found_has_no_turn() {
+        let mut s = state(&[64, 64, 64]);
+        s.found.insert(5);
+        let turn = s.turn(1000);
+        assert_eq!(turn.iter().map(|r| r.0).collect::<Vec<_>>(), [2, 8]);
+        assert!(state(&[]).turn(10).is_empty());
+        let mut all = state(&[64]);
+        all.found.insert(2);
+        assert!(all.turn(10).is_empty());
+    }
+}

+ 20 - 1
crates/victory-gpu/src/pipeline.rs

@@ -126,6 +126,9 @@ pub(crate) struct Translated {
     /// Whether the shader's code can store to buffer memory ([`stores`]);
     /// true when its code is not known.
     pub(crate) stores: bool,
+    /// Whether it stores through a view it picks from the heap by an index,
+    /// once asked (`crate::picked`).
+    pub(crate) picks: std::sync::atomic::AtomicU8,
 }
 
 #[cfg(windows)]
@@ -172,6 +175,17 @@ impl Shader {
     }
 }
 
+#[cfg(windows)]
+impl Shader {
+    /// The console programs of the container; `None` if they are not known.
+    pub(crate) fn programs(&self) -> Option<Vec<victory_shader::NativeProgram>> {
+        use victory_shader::{Container, FourCC};
+        let c = Container::parse(&self.container).ok()?;
+        let part = c.part(FourCC::DXIL).or(c.part(FourCC::ACCC))?;
+        victory_shader::native_programs(part.data).ok()
+    }
+}
+
 #[cfg(windows)]
 fn translate(container: &[u8]) -> Result<Translated, String> {
     use victory_shader::{Container, FourCC, HwStage};
@@ -194,7 +208,12 @@ fn translate(container: &[u8]) -> Result<Translated, String> {
         })
         .map(|p| p.used)
         .unwrap_or_default();
-    Ok(Translated { host, used, stores })
+    Ok(Translated {
+        host,
+        used,
+        stores,
+        picks: Default::default(),
+    })
 }
 
 /// The compute pipelines of the console's ray-tracing structure builder