OCSC: optimizing command stream compiler (off by default, unmeasured) #19

Open
Fayberr wants to merge 5 commits from upstream-pr/19 into feat/vram-first
Fayberr commented 2026-12-01 05:52:06 +00:00 (Migrated from github.com)

Imported from Fayberr/Victory-United. Originally posted by Fayberr on 2026-12-01T05:52:06Z.


Adds an optimizing compiler between the recorded list calls (VICTORY_THIN) and their translation: dead and redundant state sets are left out, runs of root constants become one call, plus an adaptive sequence cache and a sharded work queue for the translation threads. All of it is off by default (VICTORY_OCSC, _CACHE, _SCHED, _PASSES, _VERIFY).

Not run in the game yet: built and tested without the test PC. The pure logic lives in the new crate victory-ocsc and is checked by unit tests, a differential fuzz test against an independent state model (mutation-checked), and queue stress tests. See docs/ocsc.md; benchmark script is scripts/benchmark-ocsc.ps1.

Does not touch memory placement or the VRAM-first code.

<!-- greyfinch-sync:Fayberr/Victory-United:issue:5579934020 --> Imported from [Fayberr/Victory-United](https://github.com/Fayberr/Victory-United/pull/19). Originally posted by [Fayberr](https://github.com/Fayberr) on 2026-12-01T05:52:06Z. --- Adds an optimizing compiler between the recorded list calls (VICTORY_THIN) and their translation: dead and redundant state sets are left out, runs of root constants become one call, plus an adaptive sequence cache and a sharded work queue for the translation threads. All of it is off by default (`VICTORY_OCSC`, `_CACHE`, `_SCHED`, `_PASSES`, `_VERIFY`). Not run in the game yet: built and tested without the test PC. The pure logic lives in the new crate `victory-ocsc` and is checked by unit tests, a differential fuzz test against an independent state model (mutation-checked), and queue stress tests. See docs/ocsc.md; benchmark script is scripts/benchmark-ocsc.ps1. Does not touch memory placement or the VRAM-first code.
chatgpt-codex-connector[bot] commented 2026-12-01 05:52:17 +00:00 (Migrated from github.com)

Imported from Fayberr/Victory-United. Originally posted by chatgpt-codex-connector[bot] on 2026-12-01T05:52:17Z.


Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-01T05:55:04.576269Z ae7332c PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

<!-- greyfinch-sync:Fayberr/Victory-United:comment:7302226735 --> Imported from [Fayberr/Victory-United](https://github.com/Fayberr/Victory-United/pull/19#issuecomment-7302226735). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/apps/chatgpt-codex-connector) on 2026-12-01T05:52:17Z. --- <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"ae7332cb7570b392919978a2e3ca38df6589eb69","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ✅ **Completed** <relative-time datetime="2026-12-01T05:55:04.576269Z">2026-12-01T05:55:04.576269Z</relative-time> | `ae7332c` | PR opened | <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review" or "@codex security review". Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. </details> </details>
chatgpt-codex-connector[bot] commented 2026-12-01 05:55:02 +00:00 (Migrated from github.com)

Imported from Fayberr/Victory-United. Originally posted by chatgpt-codex-connector[bot] on 2026-12-01T05:55:02Z.

Code review location: crates/victory-ocsc/src/compile.rs; line 761

@@ -0,0 +1,1099 @@
+//! The stream compiler: one chunk of a THIN stream in, the same calls with
+//! what never matters left out and what can share a call merged, out.
+//!
+//! What it does, and nothing else:
+//!
+//! * **Dead stores.** A binding or fixed-function setting that is set again
+//!   before anything reads it never reaches the title's draw state.
+//! * **Redundant stores.** A setting equal to what the state holds already
+//!   (the compiler follows it across chunks, from the recording's `RESET`)
+//!   is not made again.
+//! * **Coalescing.** Root constants written in several calls to one root
+//!   (`SetGraphicsRoot32BitConstant` once per value) become one call.
+//!
+//! Every op keeps its place relative to everything that reads state: a
+//! merged call stands where its last part stood, and the parts moved later
+//! only pass setters of other bindings and ops that never read bindings
+//! ([`crate::op::Effect`]). The reference model in [`crate::model`] checks
+//! this: the state each reader sees, and the state at the chunk's end, must
+//! be the same for the stream as it was and as it is made.
+
+use crate::op::{self, Effect};
+use crate::cache::{Cache, Entry, Hasher};
+use crate::stream::{self, Cmd};
+
+/// Which passes run. All of them by default; the glue lets a run turn them
+/// off one by one (`VICTORY_OCSC_PASSES`) to find which of them a problem is.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Config {
+    /// Leave out a setting that is set again before it is read.
+    pub dead: bool,
+    /// Leave out a setting equal to the one in force.
+    pub redundant: bool,
+    /// Merge root constant writes to one root.
+    pub coalesce: bool,
+    /// Apply the passes above to the fixed-function state too (topology,
+    /// viewports, scissors, blend factor, stencil reference, depth bounds,
+    /// targets); with this off they apply to bindings only.
+    pub immediate: bool,
+}
+
+impl Default for Config {
+    fn default() -> Self {
+        Config { dead: true, redundant: true, coalesce: true, immediate: true }
+    }
+}
+
+impl Config {
+    fn bits(self) -> u8 {
+        u8::from(self.dead) | u8::from(self.redundant) << 1 | u8::from(self.coalesce) << 2 | u8::from(self.immediate) << 3
+    }
+
+    /// No pass at all: the stream comes out as it went in.
+    pub const NONE: Config = Config { dead: false, redundant: false, coalesce: false, immediate: false };
+
+    /// Reads `dead,redundant,coalesce,immediate` (any of them, any order,
+    /// `all` or `none`); `None` for a word it does not know.
+    pub fn parse(list: &str) -> Option<Config> {
+        let mut config = Config::NONE;
+        for word in list.split([',', '+', ' ']).map(str::trim).filter(|w| !w.is_empty()) {
+            match word {
+                "all" => config = Config::default(),
+                "none" => config = Config::NONE,
+                "dead" => config.dead = true,
+                "redundant" => config.redundant = true,
+                "coalesce" => config.coalesce = true,
+                "immediate" => config.immediate = true,
+                _ => return None,
+            }
+        }
+        Some(config)
+    }
+}
+
+/// What the compiler did, counted.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct Stats {
+    pub chunks: u64,
+    /// Chunks that came out as they went in.
+    pub unchanged: u64,
+    /// Chunks that were not a whole stream (passed on as they are).
+    pub malformed: u64,
+    pub cmds_in: u64,
+    pub cmds_out: u64,
+    pub words_in: u64,
+    pub words_out: u64,
+    /// Set again before read.
+    pub dead: u64,
+    /// Equal to the one in force.
+    pub redundant: u64,
+    /// Calls that went into another call.
+    pub merged: u64,
+    /// Pipeline binds left out that still report to `pipeline::bound`.
+    pub bound: u64,
+    /// Chunks that were not compiled: the sequence cache had them.
+    pub cached: u64,
+}
+
+impl Stats {
+    pub fn add(&mut self, other: &Stats) {
+        self.chunks += other.chunks;
+        self.unchanged += other.unchanged;
+        self.malformed += other.malformed;
+        self.cmds_in += other.cmds_in;
+        self.cmds_out += other.cmds_out;
+        self.words_in += other.words_in;
+        self.words_out += other.words_out;
+        self.dead += other.dead;
+        self.redundant += other.redundant;
+        self.merged += other.merged;
+        self.bound += other.bound;
+        self.cached += other.cached;
+    }
+
+    /// What was counted after `before` (a copy of these counts from earlier).
+    pub fn since(&self, before: &Stats) -> Stats {
+        Stats {
+            chunks: self.chunks - before.chunks,
+            unchanged: self.unchanged - before.unchanged,
+            malformed: self.malformed - before.malformed,
+            cmds_in: self.cmds_in - before.cmds_in,
+            cmds_out: self.cmds_out - before.cmds_out,
+            words_in: self.words_in - before.words_in,
+            words_out: self.words_out - before.words_out,
+            dead: self.dead - before.dead,
+            redundant: self.redundant - before.redundant,
+            merged: self.merged - before.merged,
+            bound: self.bound - before.bound,
+            cached: self.cached - before.cached,
+        }
+    }
+
+    /// Calls the passes took out of the stream.
+    pub fn saved(&self) -> u64 {
+        self.cmds_in.saturating_sub(self.cmds_out)
+    }
+}
+
+/// What [`Compiler::compile`] made of a chunk.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Outcome {
+    /// Nothing changed: the input is the stream to translate.
+    Unchanged,
+    /// The stream to translate is in the output buffer.
+    Rewritten,
+}
+
+/// Root slots followed per root signature kind.
+pub const ROOTS: usize = 64;
+/// Vertex buffer slots (the title's state holds 32).
+pub const VERTEX_SLOTS: usize = 32;
+/// Root constants followed per root (the API allows 64 dwords in all).
+pub const TRACKED_DWORDS: usize = 256;
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+enum Imm {
+    Topology,
+    Viewports,
+    Scissors,
+    Blend,
+    Stencil,
+    Bounds,
+    Targets,
+}
+const IMMS: usize = 7;
+
+fn imm_of(op: u64) -> Option<Imm> {
+    Some(match op {
+        op::TOPOLOGY => Imm::Topology,
+        op::VIEWPORTS => Imm::Viewports,
+        op::SCISSORS => Imm::Scissors,
+        op::BLEND_FACTOR => Imm::Blend,
+        op::STENCIL_REF => Imm::Stencil,
+        op::DEPTH_BOUNDS => Imm::Bounds,
+        op::TARGETS => Imm::Targets,
+        _ => return None,
+    })
+}
+
+/// Whether the fixed-function state survives `op` as the compiler knows it.
+/// Anything that records host passes of its own (copies, clears, resolves,
+/// indirect execution, mesh dispatch, external work) may leave the host list
+/// with other settings, so what the compiler knew is forgotten there and the
+/// title's next settings are made again.
+const fn keeps_fixed_function(op: u64) -> bool {
+    matches!(
+        op,
+        op::DRAW
+            | op::DRAW_INDEXED
+            | op::DISPATCH
+            | op::DISPATCH_X
+            | op::BARRIER
+            | op::BARRIER_GROUPS
+            | op::UPLOAD
+            | op::WRITE32
+            | op::WRITE64
+            | op::WAIT_VALUE
+            | op::WAIT_VALUE64
+            | op::SYNC
+            | op::CLOSE
+    )
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+enum Root {
+    /// Could be anything.
+    #[default]
+    Unknown,
+    /// Nothing set (as after a reset).
+    Empty,
+    Table(u64),
+    View(u64),
+    Constants(Vec<u32>),
+}
+
+/// What the compiler knows the draw state holds, after the ops it has seen
+/// (not only those it let through: the ones it left out changed nothing).
+#[derive(Clone)]
+struct Known {
+    roots: [Vec<Root>; 2],
+    pipeline: Option<u64>,
+    index: Option<Vec<u64>>,
+    vertex: [Option<[u64; 2]>; VERTEX_SLOTS],
+    fixed: [Option<Vec<u64>>; IMMS],
+}
+
+impl Known {
+    fn new() -> Known {
+        Known {
+            roots: [vec![Root::Unknown; ROOTS], vec![Root::Unknown; ROOTS]],
+            pipeline: None,
+            index: None,
+            vertex: [None; VERTEX_SLOTS],
+            fixed: Default::default(),
+        }
+    }
+
+    fn forget(&mut self) {
+        for roots in &mut self.roots {
+            roots.iter_mut().for_each(|r| *r = Root::Unknown);
+        }
+        self.pipeline = None;
+        self.index = None;
+        self.vertex = [None; VERTEX_SLOTS];
+        self.forget_fixed();
+    }
+
+    fn forget_fixed(&mut self) {
+        self.fixed.fill(None);
+    }
+
+    /// 128 bits that two states share only if they are the same state (up to
+    /// the chance of a 128-bit collision).
+    fn fingerprint(&self) -> u128 {
+        let mut h = Hasher::new(0x6b_6e6f_776e);
+        for roots in &self.roots {
+            for root in roots {
+                match root {
+                    Root::Unknown => h.word(1),
+                    Root::Empty => h.word(2),
+                    Root::Table(v) => {
+                        h.word(3);
+                        h.word(*v);
+                    }
+                    Root::View(v) => {
+                        h.word(4);
+                        h.word(*v);
+                    }
+                    Root::Constants(vals) => {
+                        h.word(5 | (vals.len() as u64) << 8);
+                        for pair in vals.chunks(2) {
+                            h.word(u64::from(pair[0]) | u64::from(pair.get(1).copied().unwrap_or(0)) << 32);
+                        }
+                    }
+                }
+            }
+        }
+        h.word(self.pipeline.map_or(0, |p| p ^ 1 << 63));
+        match &self.index {
+            None => h.word(6),
+            Some(v) => {
+                h.word(7 | (v.len() as u64) << 8);
+                v.iter().for_each(|&w| h.word(w));
+            }
+        }
+        for v in &self.vertex {
+            match v {
+                None => h.word(8),
+                Some([a, b]) => {
+                    h.word(9);
+                    h.word(*a);
+                    h.word(*b);
+                }
+            }
+        }
+        for f in &self.fixed {
+            match f {
+                None => h.word(10),
+                Some(v) => {
+                    h.word(11 | (v.len() as u64) << 8);
+                    v.iter().for_each(|&w| h.word(w));
+                }
+            }
+        }
+        h.finish()
+    }
+
+    /// The state of a list just reset: all default, the given pipeline.
+    fn reset(&mut self, pipeline: u64) {
+        for roots in &mut self.roots {
+            roots.iter_mut().for_each(|r| *r = Root::Empty);
+        }
+        self.pipeline = Some(pipeline);
+        self.index = None;
+        self.vertex = [Some([0, 0]); VERTEX_SLOTS];
+        self.forget_fixed();
+    }
+}
+
+/// The state a compiler is in between chunks, to put back.
+#[derive(Clone)]
+pub struct Snapshot(Known);
+
+/// The result of a call of constants merged: the one call that stands for them.
+#[derive(Debug)]
+struct Run {
+    compute: bool,
+    slot: u32,
+    from: u32,
+    vals: Vec<u32>,
+    /// The item whose place the merged call takes: the last part.
+    head: u32,
+    parts: Vec<u32>,
+}
+
+impl Run {
+    fn to(&self) -> u32 {
+        self.from + self.vals.len() as u32
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Act {
+    Keep,
+    Drop,
+    /// Leave out, but report the pipeline (word 0 of its args) to `bound`.
+    Bound,
+    /// The call is the merged run of this number.
+    Merged(u32),
+    /// The call went into a merged call (counted when that one stands).
+    Folded,
+}
+
+#[derive(Clone, Copy, Debug)]
+struct Item {
+    at: u32,
+    len: u32,
+    act: Act,
+}
+
+#[derive(Default)]
+struct RootPend {
+    replacer: Option<u32>,
+    runs: Vec<u32>,
+}
+
+struct Pending {
+    fixed: [Option<u32>; IMMS],
+    pipeline: Option<u32>,
+    heaps: Option<u32>,
+    index: Option<u32>,
+    vertex: Vec<(u32, u32, u32)>,
+    roots: [Vec<RootPend>; 2],
+    dirty: Vec<(bool, u32)>,
+}
+
+impl Pending {
+    fn new() -> Pending {
+        Pending {
+            fixed: [None; IMMS],
+            pipeline: None,
+            heaps: None,
+            index: None,
+            vertex: Vec::new(),
+            roots: [(0..ROOTS).map(|_| RootPend::default()).collect(), (0..ROOTS).map(|_| RootPend::default()).collect()],
+            dirty: Vec::new(),
+        }
+    }
+
+    fn forget_bindings(&mut self) {
+        self.pipeline = None;
+        self.heaps = None;
+        self.index = None;
+        self.vertex.clear();
+        for (compute, slot) in self.dirty.drain(..) {
+            let root = &mut self.roots[usize::from(compute)][slot as usize];
+            root.replacer = None;
+            root.runs.clear();
+        }
+    }
+
+    fn forget_fixed(&mut self) {
+        self.fixed = [None; IMMS];
+    }
+}
+
+/// A compiler for the chunks of one recording, in order.
+pub struct Compiler {
+    config: Config,
+    known: Known,
+    pending: Pending,
+    items: Vec<Item>,
+    runs: Vec<Run>,
+    spare: Vec<Vec<u32>>,
+    stats: Stats,
+}
+
+impl Compiler {
+    pub fn new(config: Config) -> Compiler {
+        Compiler {
+            config,
+            known: Known::new(),
+            pending: Pending::new(),
+            items: Vec::new(),
+            runs: Vec::new(),
+            spare: Vec::new(),
+            stats: Stats::default(),
+        }
+    }
+
+    pub fn config(&self) -> Config {
+        self.config
+    }
+
+    /// The counts since the last call; counted afresh from here.
+    pub fn take_stats(&mut self) -> Stats {
+        std::mem::take(&mut self.stats)
+    }
+
+    /// Forgets all that was known: the next chunk is compiled as the first
+    /// of a recording that did not start at a reset.
+    pub fn forget(&mut self) {
+        self.known.forget();
+    }
+
+    /// As [`Compiler::compile`], but a chunk the cache has seen in the same
+    /// state (and with the same flag) is not compiled again: its output and
+    /// the state it leaves are taken from the cache. What is compiled is put
+    /// there. With the cache out of use for now (it did not pay) this is
+    /// `compile`.
+    pub fn compile_cached(&mut self, cache: &Cache, input: &[u64], out: &mut Vec<u64>, external: bool) -> Outcome {
+        if !cache.probing() {
+            return self.compile(input, out, external);
+        }
+        let mut h = Hasher::new(u64::from(external) | (self.config.bits() as u64) << 1);
+        h.word(input.len() as u64);
+        input.iter().for_each(|&w| h.word(w));
+        let (chunk, state) = (h.finish(), self.known.fingerprint());
+        let mut k = Hasher::new(0x6b_6579);
+        for part in [chunk, state] {
+            k.word(part as u64);
+            k.word((part >> 64) as u64);
+        }
+        let key = k.finish();
+        if let Some(hit) = cache.get(key) {
+            self.known = hit.exit.0.clone();
+            self.stats.add(&hit.delta);
+            self.stats.cached += 1;
+            return match &hit.out {
+                None => Outcome::Unchanged,
+                Some(words) => {
+                    out.clear();
+                    out.extend_from_slice(words);
+                    Outcome::Rewritten
+                }
+            };
+        }
+        let before = self.stats;
+        let outcome = self.compile(input, out, external);
+        let delta = self.stats.since(&before);
+        cache.put(
+            key,
+            Entry {
+                out: (outcome == Outcome::Rewritten).then(|| out.as_slice().into()),
+                exit: Snapshot(self.known.clone()),
+                delta,
+            },
+        );
+        outcome
+    }
+
+    /// Compiles `input`, one chunk of the recording's stream. `external` is
+    /// whether host work follows the chunk's calls (it may leave any state
+    /// as it likes, so nothing is known after it).
+    pub fn compile(&mut self, input: &[u64], out: &mut Vec<u64>, external: bool) -> Outcome {
+        self.stats.chunks += 1;
+        self.stats.words_in += input.len() as u64;
+        self.items.clear();
+        self.pending.forget_bindings();
+        self.pending.forget_fixed();
+        self.recycle_runs();
+        let config = self.config;
+        if config == Config::NONE || !stream::well_formed(input) {
+            if config != Config::NONE {
+                self.stats.malformed += 1;
+                self.known.forget();
+            }
+            if external {
+                self.known.forget();
+            }
+            self.stats.unchanged += 1;
+            let calls = stream::commands(input).count() as u64;
+            self.stats.cmds_in += calls;
+            self.stats.cmds_out += calls;
+            self.stats.words_out += input.len() as u64;
+            return Outcome::Unchanged;
+        }
+        let mut calls = 0u64;
+        for cmd in stream::commands(input) {
+            calls += 1;
+            self.items.push(Item { at: cmd.at as u32, len: cmd.words_len() as u32, act: Act::Keep });
+            self.command(self.items.len() as u32 - 1, &cmd);
+        }
+        if external {
+            self.known.forget();
+        }
+        self.stats.cmds_in += calls;
+        let changed = self.items.iter().any(|item| item.act != Act::Keep);
+        if !changed {
+            self.stats.unchanged += 1;
+            self.stats.cmds_out += calls;
+            self.stats.words_out += input.len() as u64;
+            return Outcome::Unchanged;
+        }
+        out.clear();
+        out.reserve(input.len());
+        let mut kept = 0u64;
+        for item in &self.items {
+            let words = &input[item.at as usize..(item.at + item.len) as usize];
+            match item.act {
+                Act::Keep => {
+                    out.extend_from_slice(words);
+                    kept += 1;
+                }
+                Act::Drop => {}
+                Act::Folded => self.stats.merged += 1,
+                Act::Bound => {
+                    stream::push(out, op::BOUND, &words[1..2]);
+                    kept += 1;
+                }
+                Act::Merged(run) => {
+                    let run = &self.runs[run as usize];
+                    let op = if run.compute { op::COMPUTE_CONSTANTS } else { op::GRAPHICS_CONSTANTS };
+                    out.push(op::header(op, 0));
+                    let header = out.len() - 1;
+                    out.push(u64::from(run.slot) | u64::from(run.from) << 32);
+                    out.push(run.vals.len() as u64);
+                    stream::pack_u32s(&run.vals, out);
+                    out[header] = op::header(op, out.len() - header - 1);
+                    kept += 1;
+                }
+            }
+        }
+        self.stats.cmds_out += kept;
+        self.stats.words_out += out.len() as u64;
+        Outcome::Rewritten
+    }
+
+    fn recycle_runs(&mut self) {
+        for run in self.runs.drain(..) {
+            let mut vals = run.vals;
+            vals.clear();
+            self.spare.push(vals);
+        }
+    }
+
+    fn command(&mut self, i: u32, cmd: &Cmd<'_>) {
+        let op = cmd.op;
+        if op == op::RESET {
+            self.pending.forget_bindings();
+            self.pending.forget_fixed();
+            self.known.reset(cmd.args.first().copied().unwrap_or(0));
+            return;
+        }
+        match op::effect(op) {
+            Effect::Setter => self.setter(i, cmd),
+            Effect::Consumer => {
+                self.pending.forget_bindings();
+                self.pending.forget_fixed();
+                if !keeps_fixed_function(op) {
+                    self.known.forget_fixed();
+                }
+            }
+            Effect::Transparent => {
+                self.pending.forget_fixed();
+                if !keeps_fixed_function(op) {
+                    self.known.forget_fixed();
+                }
+            }
+            Effect::Fence => {
+                self.pending.forget_bindings();
+                self.pending.forget_fixed();
+                if !keeps_fixed_function(op) {
+                    self.known.forget_fixed();
+                }
+                if op == op::EXTERNAL {
+                    self.known.forget();
+                }
+            }
+        }
+    }
+
+    fn drop_item(&mut self, i: u32, redundant: bool) {
+        if matches!(self.items[i as usize].act, Act::Drop | Act::Folded) {
+            self.items[i as usize].act = Act::Drop;
+            return;
+        }
+        self.items[i as usize].act = Act::Drop;
+        if redundant {
+            self.stats.redundant += 1;
+        } else {
+            self.stats.dead += 1;
+        }
+    }
+
+    fn setter(&mut self, i: u32, cmd: &Cmd<'_>) {
+        let a = cmd.args;
+        match cmd.op {
+            op::TOPOLOGY | op::VIEWPORTS | op::SCISSORS | op::BLEND_FACTOR | op::STENCIL_REF | op::DEPTH_BOUNDS
+            | op::TARGETS => {
+                if let Some(kind) = imm_of(cmd.op) {
+                    self.fixed(i, kind, a);
+                }
+            }
+            op::COMPUTE_TABLE | op::GRAPHICS_TABLE if a.len() >= 2 => {
+                self.replace(i, cmd.op == op::COMPUTE_TABLE, a[0], Root::Table(a[1]));
+            }
+            op::COMPUTE_VIEW | op::GRAPHICS_VIEW if a.len() >= 2 => {
+                self.replace(i, cmd.op == op::COMPUTE_VIEW, a[0], Root::View(a[1]));
+            }
+            op::COMPUTE_CONSTANT | op::GRAPHICS_CONSTANT if a.len() >= 3 => {
+                let vals = [a[1] as u32];
+                self.constants(i, cmd.op == op::COMPUTE_CONSTANT, a[0], a[2] as u32, &vals);
+            }
+            op::COMPUTE_CONSTANTS | op::GRAPHICS_CONSTANTS if a.len() >= 2 => {
+                let count = a[1] as usize;
+                match stream::u32s(&a[2..], count) {
+                    Some(vals) if a[2..].len() == count.div_ceil(2) => {
+                        let vals: Vec<u32> = vals.collect();
+                        self.constants(i, cmd.op == op::COMPUTE_CONSTANTS, a[0] & 0xffff_ffff, (a[0] >> 32) as u32, &vals);
+                    }
+                    _ => self.untracked_constants(cmd.op == op::COMPUTE_CONSTANTS, a[0] & 0xffff_ffff),
+                }
+            }
+            op::COMPUTE_TABLE | op::GRAPHICS_TABLE | op::COMPUTE_VIEW | op::GRAPHICS_VIEW | op::COMPUTE_CONSTANT
+            | op::GRAPHICS_CONSTANT | op::COMPUTE_CONSTANTS | op::GRAPHICS_CONSTANTS => {
+                // Not the shape the title's methods make: not touched.
+                self.known.forget();
+                self.pending.forget_bindings();
+            }
+            op::SET_PIPELINE if !a.is_empty() => self.pipeline(i, a[0]),
+            op::HEAPS => {
+                if self.config.dead
+                    && let Some(old) = self.pending.heaps
+                {
+                    self.drop_item(old, false);
+                }
+                self.pending.heaps = Some(i);
+            }
+            op::INDEX_BUFFER => {
+                if self.config.redundant && self.known.index.as_deref() == Some(a) {
+                    self.drop_item(i, true);
+                    return;
+                }
+                if self.config.dead
+                    && let Some(old) = self.pending.index
+                {
+                    self.drop_item(old, false);
+                }
+                self.pending.index = Some(i);
+                self.known.index = Some(a.to_vec());
+            }
+            op::VERTEX_BUFFERS => self.vertex(i, a),
+            _ => {
+                self.known.forget();
+                self.pending.forget_bindings();
+            }
+        }
+    }
+
+    fn fixed(&mut self, i: u32, kind: Imm, args: &[u64]) {
+        let slot = kind as usize;
+        if !self.config.immediate {
+            self.known.fixed[slot] = None;
+            return;
+        }
+        // An empty scissor list is the title's way to ask for the default:
+        // it is passed on every time.
+        let droppable = !(kind == Imm::Scissors && args.first() == Some(&0));
+        if self.config.redundant && droppable && self.known.fixed[slot].as_deref() == Some(args) {
+            self.drop_item(i, true);
+            return;
+        }
+        if self.config.dead
+            && let Some(old) = self.pending.fixed[slot]
+        {
+            self.drop_item(old, false);
+        }
+        self.pending.fixed[slot] = Some(i);
+        match &mut self.known.fixed[slot] {
+            Some(known) => {
+                known.clear();
+                known.extend_from_slice(args);
+            }
+            none => *none = Some(args.to_vec()),
+        }
+    }
+
+    fn pipeline(&mut self, i: u32, pipeline: u64) {
+        if self.config.redundant && self.known.pipeline == Some(pipeline) {
+            // The bind that made it current reported it.
+            self.drop_item(i, true);
+            return;
+        }
+        if self.config.dead
+            && let Some(old) = self.pending.pipeline
+        {
+            self.items[old as usize].act = Act::Bound;
+            self.stats.bound += 1;
+            self.stats.dead += 1;
+        }
+        self.pending.pipeline = Some(i);
+        self.known.pipeline = Some(pipeline);
+    }
+
+    fn vertex(&mut self, i: u32, a: &[u64]) {
+        let (Some(&first), Some(&given)) = (a.first(), a.get(1)) else {
+            self.known.vertex = [None; VERTEX_SLOTS];
+            self.pending.vertex.clear();
+            return;
+        };
+        let (start, count) = (first as u32 as usize, (first >> 32) as usize);
+        let blob = &a[2..];
+        let end = start.saturating_add(count);
+        let per_slot = if given != 0 && count != 0 { blob.len() / count } else { 2 };
+        let tracked = end <= VERTEX_SLOTS && per_slot == 2 && (given == 0 || blob.len() == count * 2);
+        if !tracked {
+            // Slots past the title's 32 are ignored by the state, and a
+            // view of another size is not the one this follows: all that is
+            // known of the slots is gone, and the call is passed on.
+            for slot in self.known.vertex.iter_mut().skip(start.min(VERTEX_SLOTS)).take(count.min(VERTEX_SLOTS)) {
+                *slot = None;
+            }
+            self.pending.vertex.clear();
+            return;
+        }
+        let views = |k: usize| -> [u64; 2] {
+            if given != 0 { [blob[k * 2], blob[k * 2 + 1]] } else { [0, 0] }
+        };
+        if self.config.redundant && (0..count).all(|k| self.known.vertex[start + k] == Some(views(k))) {
+            self.drop_item(i, true);
+            return;

P2 Badge Preserve vertex-buffer rebinds after rectangle expansion

With OCSC enabled, a rectangle draw using the CPU expansion fallback followed by a normal draw that rebinds the same vertex view can read the expanded scratch buffer instead of the title's buffer. State::rectangles in crates/victory-gpu/src/draw.rs replaces the host vertex bindings without clearing host_vb_valid; normally, the subsequent State::set_vertex_buffers clears that flag so prepare_pipeline restores the original bindings. Dropping that setter here leaves the flag valid, and if the pipeline's vertex-slot mask and list epoch are unchanged, restoration is skipped. Preserve these calls across draws that can replace host vertex bindings, or invalidate the host binding cache when expansion does so. The reference model only tracks logical vertex views, so verification does not catch this difference.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:Fayberr/Victory-United:review-comment:4749894828 --> Imported from [Fayberr/Victory-United](https://github.com/Fayberr/Victory-United/pull/19#discussion_r4749894828). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/apps/chatgpt-codex-connector) on 2026-12-01T05:55:02Z. **Code review location:** `crates/victory-ocsc/src/compile.rs`; line 761 ~~~~diff @@ -0,0 +1,1099 @@ +//! The stream compiler: one chunk of a THIN stream in, the same calls with +//! what never matters left out and what can share a call merged, out. +//! +//! What it does, and nothing else: +//! +//! * **Dead stores.** A binding or fixed-function setting that is set again +//! before anything reads it never reaches the title's draw state. +//! * **Redundant stores.** A setting equal to what the state holds already +//! (the compiler follows it across chunks, from the recording's `RESET`) +//! is not made again. +//! * **Coalescing.** Root constants written in several calls to one root +//! (`SetGraphicsRoot32BitConstant` once per value) become one call. +//! +//! Every op keeps its place relative to everything that reads state: a +//! merged call stands where its last part stood, and the parts moved later +//! only pass setters of other bindings and ops that never read bindings +//! ([`crate::op::Effect`]). The reference model in [`crate::model`] checks +//! this: the state each reader sees, and the state at the chunk's end, must +//! be the same for the stream as it was and as it is made. + +use crate::op::{self, Effect}; +use crate::cache::{Cache, Entry, Hasher}; +use crate::stream::{self, Cmd}; + +/// Which passes run. All of them by default; the glue lets a run turn them +/// off one by one (`VICTORY_OCSC_PASSES`) to find which of them a problem is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Config { + /// Leave out a setting that is set again before it is read. + pub dead: bool, + /// Leave out a setting equal to the one in force. + pub redundant: bool, + /// Merge root constant writes to one root. + pub coalesce: bool, + /// Apply the passes above to the fixed-function state too (topology, + /// viewports, scissors, blend factor, stencil reference, depth bounds, + /// targets); with this off they apply to bindings only. + pub immediate: bool, +} + +impl Default for Config { + fn default() -> Self { + Config { dead: true, redundant: true, coalesce: true, immediate: true } + } +} + +impl Config { + fn bits(self) -> u8 { + u8::from(self.dead) | u8::from(self.redundant) << 1 | u8::from(self.coalesce) << 2 | u8::from(self.immediate) << 3 + } + + /// No pass at all: the stream comes out as it went in. + pub const NONE: Config = Config { dead: false, redundant: false, coalesce: false, immediate: false }; + + /// Reads `dead,redundant,coalesce,immediate` (any of them, any order, + /// `all` or `none`); `None` for a word it does not know. + pub fn parse(list: &str) -> Option<Config> { + let mut config = Config::NONE; + for word in list.split([',', '+', ' ']).map(str::trim).filter(|w| !w.is_empty()) { + match word { + "all" => config = Config::default(), + "none" => config = Config::NONE, + "dead" => config.dead = true, + "redundant" => config.redundant = true, + "coalesce" => config.coalesce = true, + "immediate" => config.immediate = true, + _ => return None, + } + } + Some(config) + } +} + +/// What the compiler did, counted. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Stats { + pub chunks: u64, + /// Chunks that came out as they went in. + pub unchanged: u64, + /// Chunks that were not a whole stream (passed on as they are). + pub malformed: u64, + pub cmds_in: u64, + pub cmds_out: u64, + pub words_in: u64, + pub words_out: u64, + /// Set again before read. + pub dead: u64, + /// Equal to the one in force. + pub redundant: u64, + /// Calls that went into another call. + pub merged: u64, + /// Pipeline binds left out that still report to `pipeline::bound`. + pub bound: u64, + /// Chunks that were not compiled: the sequence cache had them. + pub cached: u64, +} + +impl Stats { + pub fn add(&mut self, other: &Stats) { + self.chunks += other.chunks; + self.unchanged += other.unchanged; + self.malformed += other.malformed; + self.cmds_in += other.cmds_in; + self.cmds_out += other.cmds_out; + self.words_in += other.words_in; + self.words_out += other.words_out; + self.dead += other.dead; + self.redundant += other.redundant; + self.merged += other.merged; + self.bound += other.bound; + self.cached += other.cached; + } + + /// What was counted after `before` (a copy of these counts from earlier). + pub fn since(&self, before: &Stats) -> Stats { + Stats { + chunks: self.chunks - before.chunks, + unchanged: self.unchanged - before.unchanged, + malformed: self.malformed - before.malformed, + cmds_in: self.cmds_in - before.cmds_in, + cmds_out: self.cmds_out - before.cmds_out, + words_in: self.words_in - before.words_in, + words_out: self.words_out - before.words_out, + dead: self.dead - before.dead, + redundant: self.redundant - before.redundant, + merged: self.merged - before.merged, + bound: self.bound - before.bound, + cached: self.cached - before.cached, + } + } + + /// Calls the passes took out of the stream. + pub fn saved(&self) -> u64 { + self.cmds_in.saturating_sub(self.cmds_out) + } +} + +/// What [`Compiler::compile`] made of a chunk. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Outcome { + /// Nothing changed: the input is the stream to translate. + Unchanged, + /// The stream to translate is in the output buffer. + Rewritten, +} + +/// Root slots followed per root signature kind. +pub const ROOTS: usize = 64; +/// Vertex buffer slots (the title's state holds 32). +pub const VERTEX_SLOTS: usize = 32; +/// Root constants followed per root (the API allows 64 dwords in all). +pub const TRACKED_DWORDS: usize = 256; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Imm { + Topology, + Viewports, + Scissors, + Blend, + Stencil, + Bounds, + Targets, +} +const IMMS: usize = 7; + +fn imm_of(op: u64) -> Option<Imm> { + Some(match op { + op::TOPOLOGY => Imm::Topology, + op::VIEWPORTS => Imm::Viewports, + op::SCISSORS => Imm::Scissors, + op::BLEND_FACTOR => Imm::Blend, + op::STENCIL_REF => Imm::Stencil, + op::DEPTH_BOUNDS => Imm::Bounds, + op::TARGETS => Imm::Targets, + _ => return None, + }) +} + +/// Whether the fixed-function state survives `op` as the compiler knows it. +/// Anything that records host passes of its own (copies, clears, resolves, +/// indirect execution, mesh dispatch, external work) may leave the host list +/// with other settings, so what the compiler knew is forgotten there and the +/// title's next settings are made again. +const fn keeps_fixed_function(op: u64) -> bool { + matches!( + op, + op::DRAW + | op::DRAW_INDEXED + | op::DISPATCH + | op::DISPATCH_X + | op::BARRIER + | op::BARRIER_GROUPS + | op::UPLOAD + | op::WRITE32 + | op::WRITE64 + | op::WAIT_VALUE + | op::WAIT_VALUE64 + | op::SYNC + | op::CLOSE + ) +} + +#[derive(Clone, Debug, Default, PartialEq)] +enum Root { + /// Could be anything. + #[default] + Unknown, + /// Nothing set (as after a reset). + Empty, + Table(u64), + View(u64), + Constants(Vec<u32>), +} + +/// What the compiler knows the draw state holds, after the ops it has seen +/// (not only those it let through: the ones it left out changed nothing). +#[derive(Clone)] +struct Known { + roots: [Vec<Root>; 2], + pipeline: Option<u64>, + index: Option<Vec<u64>>, + vertex: [Option<[u64; 2]>; VERTEX_SLOTS], + fixed: [Option<Vec<u64>>; IMMS], +} + +impl Known { + fn new() -> Known { + Known { + roots: [vec![Root::Unknown; ROOTS], vec![Root::Unknown; ROOTS]], + pipeline: None, + index: None, + vertex: [None; VERTEX_SLOTS], + fixed: Default::default(), + } + } + + fn forget(&mut self) { + for roots in &mut self.roots { + roots.iter_mut().for_each(|r| *r = Root::Unknown); + } + self.pipeline = None; + self.index = None; + self.vertex = [None; VERTEX_SLOTS]; + self.forget_fixed(); + } + + fn forget_fixed(&mut self) { + self.fixed.fill(None); + } + + /// 128 bits that two states share only if they are the same state (up to + /// the chance of a 128-bit collision). + fn fingerprint(&self) -> u128 { + let mut h = Hasher::new(0x6b_6e6f_776e); + for roots in &self.roots { + for root in roots { + match root { + Root::Unknown => h.word(1), + Root::Empty => h.word(2), + Root::Table(v) => { + h.word(3); + h.word(*v); + } + Root::View(v) => { + h.word(4); + h.word(*v); + } + Root::Constants(vals) => { + h.word(5 | (vals.len() as u64) << 8); + for pair in vals.chunks(2) { + h.word(u64::from(pair[0]) | u64::from(pair.get(1).copied().unwrap_or(0)) << 32); + } + } + } + } + } + h.word(self.pipeline.map_or(0, |p| p ^ 1 << 63)); + match &self.index { + None => h.word(6), + Some(v) => { + h.word(7 | (v.len() as u64) << 8); + v.iter().for_each(|&w| h.word(w)); + } + } + for v in &self.vertex { + match v { + None => h.word(8), + Some([a, b]) => { + h.word(9); + h.word(*a); + h.word(*b); + } + } + } + for f in &self.fixed { + match f { + None => h.word(10), + Some(v) => { + h.word(11 | (v.len() as u64) << 8); + v.iter().for_each(|&w| h.word(w)); + } + } + } + h.finish() + } + + /// The state of a list just reset: all default, the given pipeline. + fn reset(&mut self, pipeline: u64) { + for roots in &mut self.roots { + roots.iter_mut().for_each(|r| *r = Root::Empty); + } + self.pipeline = Some(pipeline); + self.index = None; + self.vertex = [Some([0, 0]); VERTEX_SLOTS]; + self.forget_fixed(); + } +} + +/// The state a compiler is in between chunks, to put back. +#[derive(Clone)] +pub struct Snapshot(Known); + +/// The result of a call of constants merged: the one call that stands for them. +#[derive(Debug)] +struct Run { + compute: bool, + slot: u32, + from: u32, + vals: Vec<u32>, + /// The item whose place the merged call takes: the last part. + head: u32, + parts: Vec<u32>, +} + +impl Run { + fn to(&self) -> u32 { + self.from + self.vals.len() as u32 + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Act { + Keep, + Drop, + /// Leave out, but report the pipeline (word 0 of its args) to `bound`. + Bound, + /// The call is the merged run of this number. + Merged(u32), + /// The call went into a merged call (counted when that one stands). + Folded, +} + +#[derive(Clone, Copy, Debug)] +struct Item { + at: u32, + len: u32, + act: Act, +} + +#[derive(Default)] +struct RootPend { + replacer: Option<u32>, + runs: Vec<u32>, +} + +struct Pending { + fixed: [Option<u32>; IMMS], + pipeline: Option<u32>, + heaps: Option<u32>, + index: Option<u32>, + vertex: Vec<(u32, u32, u32)>, + roots: [Vec<RootPend>; 2], + dirty: Vec<(bool, u32)>, +} + +impl Pending { + fn new() -> Pending { + Pending { + fixed: [None; IMMS], + pipeline: None, + heaps: None, + index: None, + vertex: Vec::new(), + roots: [(0..ROOTS).map(|_| RootPend::default()).collect(), (0..ROOTS).map(|_| RootPend::default()).collect()], + dirty: Vec::new(), + } + } + + fn forget_bindings(&mut self) { + self.pipeline = None; + self.heaps = None; + self.index = None; + self.vertex.clear(); + for (compute, slot) in self.dirty.drain(..) { + let root = &mut self.roots[usize::from(compute)][slot as usize]; + root.replacer = None; + root.runs.clear(); + } + } + + fn forget_fixed(&mut self) { + self.fixed = [None; IMMS]; + } +} + +/// A compiler for the chunks of one recording, in order. +pub struct Compiler { + config: Config, + known: Known, + pending: Pending, + items: Vec<Item>, + runs: Vec<Run>, + spare: Vec<Vec<u32>>, + stats: Stats, +} + +impl Compiler { + pub fn new(config: Config) -> Compiler { + Compiler { + config, + known: Known::new(), + pending: Pending::new(), + items: Vec::new(), + runs: Vec::new(), + spare: Vec::new(), + stats: Stats::default(), + } + } + + pub fn config(&self) -> Config { + self.config + } + + /// The counts since the last call; counted afresh from here. + pub fn take_stats(&mut self) -> Stats { + std::mem::take(&mut self.stats) + } + + /// Forgets all that was known: the next chunk is compiled as the first + /// of a recording that did not start at a reset. + pub fn forget(&mut self) { + self.known.forget(); + } + + /// As [`Compiler::compile`], but a chunk the cache has seen in the same + /// state (and with the same flag) is not compiled again: its output and + /// the state it leaves are taken from the cache. What is compiled is put + /// there. With the cache out of use for now (it did not pay) this is + /// `compile`. + pub fn compile_cached(&mut self, cache: &Cache, input: &[u64], out: &mut Vec<u64>, external: bool) -> Outcome { + if !cache.probing() { + return self.compile(input, out, external); + } + let mut h = Hasher::new(u64::from(external) | (self.config.bits() as u64) << 1); + h.word(input.len() as u64); + input.iter().for_each(|&w| h.word(w)); + let (chunk, state) = (h.finish(), self.known.fingerprint()); + let mut k = Hasher::new(0x6b_6579); + for part in [chunk, state] { + k.word(part as u64); + k.word((part >> 64) as u64); + } + let key = k.finish(); + if let Some(hit) = cache.get(key) { + self.known = hit.exit.0.clone(); + self.stats.add(&hit.delta); + self.stats.cached += 1; + return match &hit.out { + None => Outcome::Unchanged, + Some(words) => { + out.clear(); + out.extend_from_slice(words); + Outcome::Rewritten + } + }; + } + let before = self.stats; + let outcome = self.compile(input, out, external); + let delta = self.stats.since(&before); + cache.put( + key, + Entry { + out: (outcome == Outcome::Rewritten).then(|| out.as_slice().into()), + exit: Snapshot(self.known.clone()), + delta, + }, + ); + outcome + } + + /// Compiles `input`, one chunk of the recording's stream. `external` is + /// whether host work follows the chunk's calls (it may leave any state + /// as it likes, so nothing is known after it). + pub fn compile(&mut self, input: &[u64], out: &mut Vec<u64>, external: bool) -> Outcome { + self.stats.chunks += 1; + self.stats.words_in += input.len() as u64; + self.items.clear(); + self.pending.forget_bindings(); + self.pending.forget_fixed(); + self.recycle_runs(); + let config = self.config; + if config == Config::NONE || !stream::well_formed(input) { + if config != Config::NONE { + self.stats.malformed += 1; + self.known.forget(); + } + if external { + self.known.forget(); + } + self.stats.unchanged += 1; + let calls = stream::commands(input).count() as u64; + self.stats.cmds_in += calls; + self.stats.cmds_out += calls; + self.stats.words_out += input.len() as u64; + return Outcome::Unchanged; + } + let mut calls = 0u64; + for cmd in stream::commands(input) { + calls += 1; + self.items.push(Item { at: cmd.at as u32, len: cmd.words_len() as u32, act: Act::Keep }); + self.command(self.items.len() as u32 - 1, &cmd); + } + if external { + self.known.forget(); + } + self.stats.cmds_in += calls; + let changed = self.items.iter().any(|item| item.act != Act::Keep); + if !changed { + self.stats.unchanged += 1; + self.stats.cmds_out += calls; + self.stats.words_out += input.len() as u64; + return Outcome::Unchanged; + } + out.clear(); + out.reserve(input.len()); + let mut kept = 0u64; + for item in &self.items { + let words = &input[item.at as usize..(item.at + item.len) as usize]; + match item.act { + Act::Keep => { + out.extend_from_slice(words); + kept += 1; + } + Act::Drop => {} + Act::Folded => self.stats.merged += 1, + Act::Bound => { + stream::push(out, op::BOUND, &words[1..2]); + kept += 1; + } + Act::Merged(run) => { + let run = &self.runs[run as usize]; + let op = if run.compute { op::COMPUTE_CONSTANTS } else { op::GRAPHICS_CONSTANTS }; + out.push(op::header(op, 0)); + let header = out.len() - 1; + out.push(u64::from(run.slot) | u64::from(run.from) << 32); + out.push(run.vals.len() as u64); + stream::pack_u32s(&run.vals, out); + out[header] = op::header(op, out.len() - header - 1); + kept += 1; + } + } + } + self.stats.cmds_out += kept; + self.stats.words_out += out.len() as u64; + Outcome::Rewritten + } + + fn recycle_runs(&mut self) { + for run in self.runs.drain(..) { + let mut vals = run.vals; + vals.clear(); + self.spare.push(vals); + } + } + + fn command(&mut self, i: u32, cmd: &Cmd<'_>) { + let op = cmd.op; + if op == op::RESET { + self.pending.forget_bindings(); + self.pending.forget_fixed(); + self.known.reset(cmd.args.first().copied().unwrap_or(0)); + return; + } + match op::effect(op) { + Effect::Setter => self.setter(i, cmd), + Effect::Consumer => { + self.pending.forget_bindings(); + self.pending.forget_fixed(); + if !keeps_fixed_function(op) { + self.known.forget_fixed(); + } + } + Effect::Transparent => { + self.pending.forget_fixed(); + if !keeps_fixed_function(op) { + self.known.forget_fixed(); + } + } + Effect::Fence => { + self.pending.forget_bindings(); + self.pending.forget_fixed(); + if !keeps_fixed_function(op) { + self.known.forget_fixed(); + } + if op == op::EXTERNAL { + self.known.forget(); + } + } + } + } + + fn drop_item(&mut self, i: u32, redundant: bool) { + if matches!(self.items[i as usize].act, Act::Drop | Act::Folded) { + self.items[i as usize].act = Act::Drop; + return; + } + self.items[i as usize].act = Act::Drop; + if redundant { + self.stats.redundant += 1; + } else { + self.stats.dead += 1; + } + } + + fn setter(&mut self, i: u32, cmd: &Cmd<'_>) { + let a = cmd.args; + match cmd.op { + op::TOPOLOGY | op::VIEWPORTS | op::SCISSORS | op::BLEND_FACTOR | op::STENCIL_REF | op::DEPTH_BOUNDS + | op::TARGETS => { + if let Some(kind) = imm_of(cmd.op) { + self.fixed(i, kind, a); + } + } + op::COMPUTE_TABLE | op::GRAPHICS_TABLE if a.len() >= 2 => { + self.replace(i, cmd.op == op::COMPUTE_TABLE, a[0], Root::Table(a[1])); + } + op::COMPUTE_VIEW | op::GRAPHICS_VIEW if a.len() >= 2 => { + self.replace(i, cmd.op == op::COMPUTE_VIEW, a[0], Root::View(a[1])); + } + op::COMPUTE_CONSTANT | op::GRAPHICS_CONSTANT if a.len() >= 3 => { + let vals = [a[1] as u32]; + self.constants(i, cmd.op == op::COMPUTE_CONSTANT, a[0], a[2] as u32, &vals); + } + op::COMPUTE_CONSTANTS | op::GRAPHICS_CONSTANTS if a.len() >= 2 => { + let count = a[1] as usize; + match stream::u32s(&a[2..], count) { + Some(vals) if a[2..].len() == count.div_ceil(2) => { + let vals: Vec<u32> = vals.collect(); + self.constants(i, cmd.op == op::COMPUTE_CONSTANTS, a[0] & 0xffff_ffff, (a[0] >> 32) as u32, &vals); + } + _ => self.untracked_constants(cmd.op == op::COMPUTE_CONSTANTS, a[0] & 0xffff_ffff), + } + } + op::COMPUTE_TABLE | op::GRAPHICS_TABLE | op::COMPUTE_VIEW | op::GRAPHICS_VIEW | op::COMPUTE_CONSTANT + | op::GRAPHICS_CONSTANT | op::COMPUTE_CONSTANTS | op::GRAPHICS_CONSTANTS => { + // Not the shape the title's methods make: not touched. + self.known.forget(); + self.pending.forget_bindings(); + } + op::SET_PIPELINE if !a.is_empty() => self.pipeline(i, a[0]), + op::HEAPS => { + if self.config.dead + && let Some(old) = self.pending.heaps + { + self.drop_item(old, false); + } + self.pending.heaps = Some(i); + } + op::INDEX_BUFFER => { + if self.config.redundant && self.known.index.as_deref() == Some(a) { + self.drop_item(i, true); + return; + } + if self.config.dead + && let Some(old) = self.pending.index + { + self.drop_item(old, false); + } + self.pending.index = Some(i); + self.known.index = Some(a.to_vec()); + } + op::VERTEX_BUFFERS => self.vertex(i, a), + _ => { + self.known.forget(); + self.pending.forget_bindings(); + } + } + } + + fn fixed(&mut self, i: u32, kind: Imm, args: &[u64]) { + let slot = kind as usize; + if !self.config.immediate { + self.known.fixed[slot] = None; + return; + } + // An empty scissor list is the title's way to ask for the default: + // it is passed on every time. + let droppable = !(kind == Imm::Scissors && args.first() == Some(&0)); + if self.config.redundant && droppable && self.known.fixed[slot].as_deref() == Some(args) { + self.drop_item(i, true); + return; + } + if self.config.dead + && let Some(old) = self.pending.fixed[slot] + { + self.drop_item(old, false); + } + self.pending.fixed[slot] = Some(i); + match &mut self.known.fixed[slot] { + Some(known) => { + known.clear(); + known.extend_from_slice(args); + } + none => *none = Some(args.to_vec()), + } + } + + fn pipeline(&mut self, i: u32, pipeline: u64) { + if self.config.redundant && self.known.pipeline == Some(pipeline) { + // The bind that made it current reported it. + self.drop_item(i, true); + return; + } + if self.config.dead + && let Some(old) = self.pending.pipeline + { + self.items[old as usize].act = Act::Bound; + self.stats.bound += 1; + self.stats.dead += 1; + } + self.pending.pipeline = Some(i); + self.known.pipeline = Some(pipeline); + } + + fn vertex(&mut self, i: u32, a: &[u64]) { + let (Some(&first), Some(&given)) = (a.first(), a.get(1)) else { + self.known.vertex = [None; VERTEX_SLOTS]; + self.pending.vertex.clear(); + return; + }; + let (start, count) = (first as u32 as usize, (first >> 32) as usize); + let blob = &a[2..]; + let end = start.saturating_add(count); + let per_slot = if given != 0 && count != 0 { blob.len() / count } else { 2 }; + let tracked = end <= VERTEX_SLOTS && per_slot == 2 && (given == 0 || blob.len() == count * 2); + if !tracked { + // Slots past the title's 32 are ignored by the state, and a + // view of another size is not the one this follows: all that is + // known of the slots is gone, and the call is passed on. + for slot in self.known.vertex.iter_mut().skip(start.min(VERTEX_SLOTS)).take(count.min(VERTEX_SLOTS)) { + *slot = None; + } + self.pending.vertex.clear(); + return; + } + let views = |k: usize| -> [u64; 2] { + if given != 0 { [blob[k * 2], blob[k * 2 + 1]] } else { [0, 0] } + }; + if self.config.redundant && (0..count).all(|k| self.known.vertex[start + k] == Some(views(k))) { + self.drop_item(i, true); + return; ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Preserve vertex-buffer rebinds after rectangle expansion** With OCSC enabled, a rectangle draw using the CPU expansion fallback followed by a normal draw that rebinds the same vertex view can read the expanded scratch buffer instead of the title's buffer. `State::rectangles` in `crates/victory-gpu/src/draw.rs` replaces the host vertex bindings without clearing `host_vb_valid`; normally, the subsequent `State::set_vertex_buffers` clears that flag so `prepare_pipeline` restores the original bindings. Dropping that setter here leaves the flag valid, and if the pipeline's vertex-slot mask and list epoch are unchanged, restoration is skipped. Preserve these calls across draws that can replace host vertex bindings, or invalidate the host binding cache when expansion does so. The reference model only tracks logical vertex views, so verification does not catch this difference. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot] commented 2026-12-01 05:55:02 +00:00 (Migrated from github.com)

Imported from Fayberr/Victory-United. Originally posted by chatgpt-codex-connector[bot] on 2026-12-01T05:55:02Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ae7332cb75

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

<!-- greyfinch-sync:Fayberr/Victory-United:review:6125884783 --> Imported from [Fayberr/Victory-United](https://github.com/Fayberr/Victory-United/pull/19#pullrequestreview-6125884783). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/apps/chatgpt-codex-connector) on 2026-12-01T05:55:02Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `ae7332cb75` <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review". If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". </details>
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/19:upstream-pr/19'
git switch 'upstream-pr/19'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'feat/vram-first'
git merge --no-ff 'upstream-pr/19'
git switch 'upstream-pr/19'
git rebase 'feat/vram-first'
git switch 'feat/vram-first'
git merge --ff-only 'upstream-pr/19'
git switch 'upstream-pr/19'
git rebase 'feat/vram-first'
git switch 'feat/vram-first'
git merge --no-ff 'upstream-pr/19'
git switch 'feat/vram-first'
git merge --squash 'upstream-pr/19'
git switch 'feat/vram-first'
git merge --ff-only 'upstream-pr/19'
git switch 'feat/vram-first'
git merge 'upstream-pr/19'
git push origin 'feat/vram-first'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
Fayberr/Victory-United!19
No description provided.