From 051236c0c20fadd1ace28c1caa9726f2b909b587 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 18 Nov 2026 14:00:33 -0800 Subject: [PATCH] replay: a placement over an equal sampler state's index does not wait, and one a held commit owes stops the play u3 stopped at player frame 259: the placement of a sampler state at index 16 waited for commit 1614 (#20713), which rt held at Committed because it waits for event #35 to reach 309, which only command buffer #20439 signals, encoded 20 records later. The program had released #10401 (index 16, bound directly by #20713) and made #20822 with the same descriptor the next call; Metal gave it ID 16 again. Nothing changed for the work in flight, and the original run did not wait (it could not: #20713's signal was not yet encoded). - A sampler state whose recorded descriptor is the one placed last at its index takes the index without waiting, counted on the indices line; the index stays owed for another sampler state. - The player tells the backend, at each look for command buffers to wait for, the committed ones no record played so far lets complete (Backend::held: their unmet event waits, or a held one ahead on their queue). A placement owing its index to one of those stops with PlayError::Held naming the chain, instead of waiting for ever. - docs/REPLAY-STREAM.md says what record order does not promise (a committed buffer may wait on a later record's signal) and what the indices line and the stop say. Tests: a unit test of the equal rule in Indices; rt_replay device tests of our own sequence: an equal sampler state at an index a held commit owes plays through without a wait; another descriptor there stops with Held naming #6 and its unmet wait. Check follows. --- .../metal2vulkan-validation/src/replay/mod.rs | 4 +- .../src/replay/new_runtime/encoders.rs | 5 +- .../src/replay/new_runtime/indices.rs | 27 +++- .../src/replay/new_runtime/mod.rs | 138 ++++++++++++++---- .../src/replay/player.rs | 64 ++++++++ .../src/replay/tests.rs | 29 +++- .../src/runtime_lane/rt_replay.rs | 81 +++++++++- docs/REPLAY-STREAM.md | 15 +- 8 files changed, 325 insertions(+), 38 deletions(-) diff --git a/crates/metal2vulkan-validation/src/replay/mod.rs b/crates/metal2vulkan-validation/src/replay/mod.rs index 14fd87dcb..7e24ec48b 100644 --- a/crates/metal2vulkan-validation/src/replay/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/mod.rs @@ -15,8 +15,8 @@ pub use new_runtime::{ManagedCopies, NewRuntime}; pub use old_runtime::OldRuntime; pub use player::WAIT_COMPLETED; pub use player::{ - Backend, Check, Counters, Counts, End, IdDiffers, Made, PlayError, Player, PrivateBytes, - Relaid, Report, TextureWrites, + Backend, Check, Counters, Counts, End, HeldBuffer, IdDiffers, Made, PlayError, Player, + PrivateBytes, Relaid, Report, TextureWrites, }; pub use stream::{ segments, Call, StreamError, StreamReader, StreamWriter, FLAG_ANNOUNCED_BYTES_RECORDED, diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/encoders.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/encoders.rs index 1548048fc..38fd59a3c 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/encoders.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/encoders.rs @@ -123,7 +123,7 @@ impl NewRuntime { } } blit.end_encoding(); - self.commit(command_buffer).map_err(failed(call))?; + self.commit(command_buffer, 0).map_err(failed(call))?; for place in places { self.places.give(place, self.commits, Vec::new()); } @@ -172,7 +172,8 @@ impl NewRuntime { "parallelRenderCommandEncoderWithDescriptor:" => self.skip_encoder(), "commit" => { self.copy_named(call)?; - self.commit(command_buffer).map_err(failed(call))?; + self.commit(command_buffer, call.receiver) + .map_err(failed(call))?; // Its first use committed, a no-copy Managed buffer's GPU copy changes only by // `didModifyRange:` from here. self.fresh.retain(|_, user| *user != Some(call.receiver)); diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/indices.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/indices.rs index 460a2fefe..cb366acd4 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/indices.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/indices.rs @@ -47,6 +47,9 @@ pub(in crate::replay) struct Indices { /// The placements that waited for an index's owed commits, and the nanoseconds they waited. waits: u64, wait_nanos: u64, + /// The placements of a sampler state equal to the one placed last at its index, which took + /// the index without waiting for the commits in flight it was owed to. + equal: u64, } impl Indices { @@ -139,6 +142,24 @@ impl Indices { Some(commit) } + /// A placement at `index` of `class` of a sampler state equal to the one placed there last: + /// it displaces nothing, so it takes the index without waiting for the commits the index is + /// owed to, and is counted where one of them has not retired (`retired`, the commits that + /// have). They stay owed: a placement of another sampler state there waits for them. + pub(in crate::replay) fn equal(&mut self, class: rt::IndexClass, index: u32, retired: u64) { + let key = (slot(class), index); + match self.owed.get(&key) { + Some(&commit) if commit > retired => self.equal += 1, + Some(_) => drop(self.owed.remove(&key)), + None => {} + } + } + + /// The index `object` holds, where it holds one. + pub(in crate::replay) fn index_of(&self, object: u64) -> Option { + self.objects.get(&object).map(|&(_, index)| index) + } + /// A placement waited `nanos` for an index's owed commits, which have retired. pub(in crate::replay) fn waited(&mut self, class: rt::IndexClass, index: u32, nanos: u64) { self.owed.remove(&(slot(class), index)); @@ -235,8 +256,10 @@ impl Indices { format!( "indices named {}: objects placed at the index the stream named; {} whose named index \ the runtime refused, placed at the lowest free one; {reserved} reserved; {} placed \ - at an index whose holders' commits were in flight, after waiting for them ({} ns)", - self.named, self.refused, self.waits, self.wait_nanos + at an index whose holders' commits were in flight, after waiting for them ({} ns); {} \ + sampler states placed without waiting at an index whose last sampler state had the \ + same descriptor while its commits were in flight", + self.named, self.refused, self.waits, self.wait_nanos, self.equal ) } } diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs index 3cf4343d0..dda502ff9 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs @@ -18,7 +18,7 @@ pub(super) mod second; pub(super) mod unwritten; use super::args::{arg, data, metal, option_sets, refuse, uint, variant, Fields}; -use super::player::{Backend, Counters, Made, PlayError}; +use super::player::{Backend, Counters, HeldBuffer, Made, PlayError}; use super::stream::Call; use super::translator; use super::value::Value; @@ -218,7 +218,13 @@ pub struct NewRuntime { /// The commits so far, and the committed command buffers not yet seen retired, in order, each /// with the flag its completed handler sets ([`commit`](Self::commit)). commits: u64, - in_flight: VecDeque<(u64, rt::CommandBuffer, Arc)>, + in_flight: VecDeque<(u64, u64, rt::CommandBuffer, Arc)>, + /// The committed command buffers no record played so far lets complete, by stream id, as the + /// player last told them (`Backend::held`): a placement never waits for one. + held: HashMap, + /// The descriptor of the sampler state placed last at each sampler index, as recorded: a + /// later one of the same descriptor there displaces nothing that work in flight reads. + sampler_descriptors: HashMap, /// The commits that have completed, every earlier one with them. completed: u64, skips: Skips, @@ -499,6 +505,8 @@ impl NewRuntime { constexprs: HashMap::new(), commits: 0, in_flight: VecDeque::new(), + held: HashMap::new(), + sampler_descriptors: HashMap::new(), completed: 0, skips: Skips::default(), at: (0, 0), @@ -657,24 +665,24 @@ impl NewRuntime { Ok(()) } - /// Commits `command_buffer` as the next commit, in flight until its completed handler runs: - /// the runtime runs it once it has let go of what the command buffer held, the textures and - /// samplers it named with their indices among them, which its status alone does not say - /// (the status changes first). - fn commit(&mut self, command_buffer: rt::CommandBuffer) -> Result<(), rt::Error> { + /// Commits `command_buffer`, the stream's `id` (0 for one of the play's own), as the next + /// commit, in flight until its completed handler runs: the runtime runs it once it has let go + /// of what the command buffer held, the textures and samplers it named with their indices + /// among them, which its status alone does not say (the status changes first). + fn commit(&mut self, command_buffer: rt::CommandBuffer, id: u64) -> Result<(), rt::Error> { let retired = Arc::new(AtomicBool::new(false)); let flag = Arc::clone(&retired); command_buffer.add_completed_handler(move |_| flag.store(true, Ordering::Release))?; command_buffer.commit()?; self.commits += 1; self.in_flight - .push_back((self.commits, command_buffer, retired)); + .push_back((self.commits, id, command_buffer, retired)); Ok(()) } /// The commits that have retired ([`commit`](Self::commit)), every earlier one with them. fn completed(&mut self) -> u64 { - while let Some((at, _, retired)) = self.in_flight.front() { + while let Some((at, _, _, retired)) = self.in_flight.front() { if !retired.load(Ordering::Acquire) { break; } @@ -685,26 +693,38 @@ impl NewRuntime { } /// Waits until the commits up to `commit` have retired: `wait_until_completed` returns once the - /// command buffer's handlers have run. - fn wait_for(&mut self, commit: u64) { + /// command buffer's handlers have run. Where one of them is held (`held`), no wait can end: + /// that one's stream id, unwaited. + fn wait_for(&mut self, commit: u64) -> Result<(), u64> { + let held = (self.in_flight.iter()) + .take_while(|(at, ..)| *at <= commit) + .find(|(_, id, ..)| self.held.contains_key(id)); + if let Some(&(_, id, ..)) = held { + return Err(id); + } while self.completed() < commit { - let Some((_, front, retired)) = self.in_flight.front() else { - return; + let Some((_, _, front, retired)) = self.in_flight.front() else { + return Ok(()); }; // Refused only in a scheduled handler, where the player never runs. if front.wait_until_completed().is_err() || !retired.load(Ordering::Acquire) { - return; + return Ok(()); } } + Ok(()) } /// `make` at the index the stream names for the object `call` makes (`indices`): the call's /// resource index (`named`), else the ID the program saw of the object (`recorded`); else at - /// the lowest free index of `class`. + /// the lowest free index of `class`. `sampler` is a sampler state's recorded descriptor: where + /// the sampler state placed last at the index has the same one, the placement displaces + /// nothing work in flight reads (Metal hands an equal descriptor the same sampler and ID), and + /// it takes the index without waiting. fn place( &mut self, call: &Call, class: rt::IndexClass, + sampler: Option<&Value>, make: impl Fn(u32) -> Result, ) -> Result { let recorded = (self.recorded).filter(|&(object, _)| object == call.result); @@ -712,24 +732,81 @@ impl NewRuntime { let recorded = recorded.map(|(_, id)| id as u32); let named = self.named.or(recorded); if let Some(index) = self.indices.target(class, named) { - self.settle(class, index); + let equal = sampler.is_some() && self.sampler_descriptors.get(&index) == sampler; + match equal { + true => { + let retired = self.completed(); + self.indices.equal(class, index, retired); + } + false => self.settle(call, class, index)?, + } } - match self.indices.place(call.result, class, named, make) { - Some(made) => made.map_err(failed(call)), - None => Err(refuse(call, format!("every {class:?} index is in use"))), + let made = match self.indices.place(call.result, class, named, make) { + Some(made) => made.map_err(failed(call))?, + None => return Err(refuse(call, format!("every {class:?} index is in use"))), + }; + if let (Some(descriptor), Some(index)) = (sampler, self.indices.index_of(call.result)) { + self.sampler_descriptors.insert(index, descriptor.clone()); } + Ok(made) } - /// Before a placement at `index` of `class`: waits for the commits that named an object - /// holding it to retire, where they have not (`Indices::owed`), and counts the wait. - fn settle(&mut self, class: rt::IndexClass, index: u32) { + /// Before a placement at `index` of `class` (`call`'s): waits for the commits that named an + /// object holding it to retire, where they have not (`Indices::owed`), and counts the wait. + /// Where one of them is held on records not yet played, the play stops ([`PlayError::Held`]): + /// no wait for it can end. + fn settle(&mut self, call: &Call, class: rt::IndexClass, index: u32) -> Result<(), PlayError> { let retired = self.completed(); if let Some(commit) = self.indices.owed(class, index, retired) { let began = std::time::Instant::now(); - self.wait_for(commit); + if let Err(awaited) = self.wait_for(commit) { + return Err(self.held_error(call, class, index, awaited)); + } let nanos = u64::try_from(began.elapsed().as_nanos()).unwrap_or(u64::MAX); self.indices.waited(class, index, nanos); } + Ok(()) + } + + /// The stop of a placement at `index` of `class` (`call`'s) that owes the index to held + /// command buffer `awaited`: what holds it, following each held command buffer ahead of it on + /// its queue. + fn held_error( + &self, + call: &Call, + class: rt::IndexClass, + index: u32, + awaited: u64, + ) -> PlayError { + let mut chain = Vec::new(); + let mut at = self.held.get(&awaited); + while let Some(held) = at { + if !held.unmet.is_empty() { + let waits: Vec = (held.unmet.iter()) + .map(|(event, value)| format!("#{event} to reach {value}")) + .collect(); + chain.push(format!( + "#{} on queue #{} waits for {}, which no played record signals", + held.command_buffer, + held.queue, + waits.join(" and ") + )); + break; + } + chain.push(format!( + "#{} on queue #{} is behind a held command buffer of its queue", + held.command_buffer, held.queue + )); + at = (self.held.values()).find(|h| h.queue == held.queue && !h.unmet.is_empty()); + } + PlayError::Held { + placement: format!( + "{} (result #{}) at {class:?} index {index}", + call.selector, call.result + ), + awaited, + chain: chain.join("; "), + } } /// `make` at the highest index of `class` that no object holds and the program did not @@ -741,7 +818,7 @@ impl NewRuntime { make: impl Fn(u32) -> Result, ) -> Result { if let Some(index) = self.indices.highest(class, |_| false) { - self.settle(class, index); + self.settle(call, class, index)?; } match self.indices.top(call.result, class, make) { Some(made) => made.map_err(failed(call)), @@ -845,7 +922,7 @@ impl NewRuntime { None => device.new_texture(descriptor, index), }; match (texture_class(descriptor.usage), outside) { - (Some(class), false) => self.place(call, class, |index| make(Some(index))), + (Some(class), false) => self.place(call, class, None, |index| make(Some(index))), (Some(class), true) => self.place_outside(call, class, |index| make(Some(index))), (None, _) => make(None).map_err(failed(call)), } @@ -1226,7 +1303,8 @@ impl NewRuntime { } self.named = f.uint("resourceIndex")?.map(|index| index as u32); let device = self.device.clone(); - let state = self.place(call, rt::IndexClass::Sampler, |index| { + let recorded = arg(call, 0)?; + let state = self.place(call, rt::IndexClass::Sampler, Some(recorded), |index| { device.new_sampler_state(&descriptor, index) })?; unaddressed(Object::Sampler(state)) @@ -1344,7 +1422,7 @@ impl NewRuntime { made }; let made = match texture_class(usage) { - Some(class) => self.place(call, class, |index| noted(Some(index))), + Some(class) => self.place(call, class, None, |index| noted(Some(index))), None => noted(None).map_err(failed(call)), }; match made { @@ -1599,6 +1677,12 @@ fn write_into(buffer: &rt::Buffer, offset: u64, bytes: &[u8]) -> Result<(), Play } impl Backend for NewRuntime { + fn held(&mut self, held: &[HeldBuffer]) { + self.held = (held.iter()) + .map(|h| (h.command_buffer, h.clone())) + .collect(); + } + fn call(&mut self, call: &Call) -> Result { self.named = self.named_index(call)?; if &*call.selector == "release" { diff --git a/crates/metal2vulkan-validation/src/replay/player.rs b/crates/metal2vulkan-validation/src/replay/player.rs index 97c690a6e..cf12474e8 100644 --- a/crates/metal2vulkan-validation/src/replay/player.rs +++ b/crates/metal2vulkan-validation/src/replay/player.rs @@ -119,6 +119,12 @@ pub trait Backend { /// a backend that says where it skipped something. fn locate(&mut self, _frame: u64, _call: u64) {} + /// The committed command buffers that cannot complete with what the player has played: each + /// one's event waits that no played signal or CPU value meets, or a held one ahead of it on + /// its queue. Told whenever the player looks for command buffers to wait for, so a backend + /// that waits for a commit of its own accord does not wait for one of these. + fn held(&mut self, _held: &[HeldBuffer]) {} + /// The stream's header marks its announced bytes recorded /// ([`FLAG_ANNOUNCED_BYTES_RECORDED`](super::FLAG_ANNOUNCED_BYTES_RECORDED)), told before its /// first call: a `synchronizeResource:` of a buffer the backend plays with two copies then @@ -159,6 +165,15 @@ pub enum PlayError { }, /// The stream contradicts itself (an object it never made, a wait nothing can meet). Invalid(String), + /// A placement at an index (`placement`, its call) owes the index to command buffer + /// `awaited`, which no record played so far lets complete: `chain` says what holds it (its + /// event waits no played signal meets, or a held command buffer ahead of it on its queue). + /// The backend would wait for it for ever. + Held { + placement: String, + awaited: u64, + chain: String, + }, } impl fmt::Display for PlayError { @@ -168,6 +183,15 @@ impl fmt::Display for PlayError { PlayError::Refused { selector, why } => write!(f, "refused {selector}: {why}"), PlayError::Runtime { selector, error } => write!(f, "{selector}: {error}"), PlayError::Invalid(why) => write!(f, "invalid stream: {why}"), + PlayError::Held { + placement, + awaited, + chain, + } => write!( + f, + "{placement} waits for #{awaited}, which no record played so far lets complete: \ + {chain}" + ), } } } @@ -227,6 +251,17 @@ impl Counts { } } +/// A committed command buffer that cannot complete with the records played so far +/// ([`Backend::held`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HeldBuffer { + pub command_buffer: u64, + pub queue: u64, + /// Its event waits (event, value) that no played signal or CPU value meets; empty where it is + /// held behind a held command buffer ahead of it on its queue. + pub unmet: Vec<(u64, u64)>, +} + /// What a play did. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Report { @@ -2028,6 +2063,34 @@ impl<'b, B: Backend> Player<'b, B> { Ok(bytes?) } + /// Tells the backend the committed command buffers that cannot complete: those `ready` (the + /// ones that can) leaves out, each with its waits that neither the CPU's values nor the ready + /// ones' signals meet. + fn tell_held(&mut self, ready: &[u64]) { + let mut values = self.events.clone(); + for id in ready { + for &(event, value) in &self.pending[id].signals { + let known = values.entry(event).or_default(); + *known = (*known).max(value); + } + } + let held: Vec = (self.committed.iter()) + .filter(|id| !ready.contains(id)) + .map(|&command_buffer| { + let pending = &self.pending[&command_buffer]; + let met = |&(event, value): &(u64, u64)| { + values.get(&event).copied().unwrap_or(0) >= value + }; + HeldBuffer { + command_buffer, + queue: pending.queue, + unmet: pending.waits.iter().copied().filter(|w| !met(w)).collect(), + } + }) + .collect(); + self.backend.held(&held); + } + /// The committed command buffers that can complete, in commit order: each one whose queue's /// earlier ones can, and whose event waits the CPU's values or their signals meet. fn runnable(&self) -> Vec { @@ -2069,6 +2132,7 @@ impl<'b, B: Backend> Player<'b, B> { /// for a group that held a split (`split`), in the report's split counts instead. fn drain(&mut self) -> Result<(), PlayError> { let ready = self.runnable(); + self.tell_held(&ready); if ready.is_empty() { return Ok(()); } diff --git a/crates/metal2vulkan-validation/src/replay/tests.rs b/crates/metal2vulkan-validation/src/replay/tests.rs index 48b99e788..ec5c1e1e0 100644 --- a/crates/metal2vulkan-validation/src/replay/tests.rs +++ b/crates/metal2vulkan-validation/src/replay/tests.rs @@ -1302,7 +1302,34 @@ fn an_index_is_owed_to_the_commits_that_named_its_holders() { assert!( line.ends_with( "1 placed at an index whose holders' commits were in flight, after waiting for them \ - (7 ns)" + (7 ns); 0 sampler states placed without waiting at an index whose last sampler state \ + had the same descriptor while its commits were in flight" + ), + "{line}" + ); +} + +#[test] +fn an_equal_sampler_state_takes_an_owed_index_and_leaves_it_owed() { + let class = rt::IndexClass::Sampler; + let made = |index: u32| Ok::(index); + let mut indices = Indices::default(); + let placed = indices.place(1, class, Some(16), made); + assert_eq!(placed.expect("a free index").expect("made"), 16); + assert_eq!(indices.index_of(1), Some(16)); + indices.committed(&HashSet::from([1]), 4); + indices.give(1, 0); + // An equal sampler state at 16 while commit 4 is in flight: counted, and 16 stays owed. + indices.equal(class, 16, 3); + assert_eq!(indices.owed(class, 16, 3), Some(4), "still owed"); + // Once commit 4 retired, nothing is owed and nothing counted. + indices.equal(class, 16, 4); + assert_eq!(indices.owed(class, 16, 0), None, "owed no more"); + let line = indices.line(); + assert!( + line.ends_with( + "1 sampler states placed without waiting at an index whose last sampler state had \ + the same descriptor while its commits were in flight" ), "{line}" ); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/rt_replay.rs b/crates/metal2vulkan-validation/src/runtime_lane/rt_replay.rs index 8300be941..c39496664 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/rt_replay.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/rt_replay.rs @@ -25,6 +25,9 @@ //! - A buffer placed in a block of the stream that the runtime may take from a released block's //! bytes reads zero where nothing wrote it: the player zeroes each block and heap of the stream //! once at its making, as the live system does. +//! - A sampler state placed at an index a held commit owes (its command buffer waits for an event +//! only a later record signals) takes it without waiting where its descriptor is the one placed +//! there last, and otherwise stops the play naming what holds the commit. //! //! The new runtime's device is opened behind the hang tripwire, as every device open in this crate //! is (`gpu.rs`), its kernels kept in a cache the test owns ([`ScratchCache`]). @@ -32,7 +35,8 @@ use super::ScratchCache; use crate::gpu::{self, DeviceType}; use crate::replay::{ - Backend, NewRuntime, Player, Report, StreamReader, StreamWriter, Value, WAIT_COMPLETED, + Backend, NewRuntime, PlayError, Player, Report, StreamReader, StreamWriter, Value, + WAIT_COMPLETED, }; use crate::ScratchDir; use metal2vulkan_devtools::metallib::{metallib, wrap, MtlbFunction}; @@ -578,6 +582,81 @@ fn surface_textures_take_the_reserved_index_their_descriptor_names() { ); } +/// A stream of a placement at an index a held commit owes: command buffer #6 of queue #2 waits for +/// event #4 to reach 1, binds sampler state #5 (the default descriptor, index 16) and is +/// committed; #5 is released and sampler state #8 made at index 16 with `descriptor`; only then +/// does command buffer #10 of queue #3 signal #4 to 1, and the CPU waits for #6. +fn held_placement(dir: &ScratchDir, descriptor: Value) -> PathBuf { + written(dir, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + w.call("newCommandQueue", 1, 2, &[], &[])?; + w.call("newCommandQueue", 1, 3, &[], &[])?; + w.call("newEvent", 1, 4, &[], &[])?; + let made = "newSamplerStateWithDescriptor:"; + let id = [("gpuResourceID", Value::Uint(16))]; + w.call(made, 1, 5, &[sampler(None)], &[])?; + w.call("gpuResourceID", 5, 0, &[], &id)?; + let event = |value| [Value::Object(4), Value::Uint(value)]; + w.call("commandBuffer", 2, 6, &[], &[])?; + w.call("encodeWaitForEvent:value:", 6, 0, &event(1), &[])?; + w.call("computeCommandEncoder", 6, 7, &[], &[])?; + let bound = [ + Value::List(vec![Value::Object(5)]), + uints(&[("location", 0), ("length", 1)]), + ]; + w.call("setSamplerStates:withRange:", 7, 0, &bound, &[])?; + w.call("endEncoding", 7, 0, &[], &[])?; + w.call("commit", 6, 0, &[], &[])?; + w.call("release", 5, 0, &[], &[])?; + w.call(made, 1, 8, &[descriptor], &[])?; + w.call("gpuResourceID", 8, 0, &[], &id)?; + w.call("commandBuffer", 3, 10, &[], &[])?; + w.call("encodeSignalEvent:value:", 10, 0, &event(1), &[])?; + w.call("commit", 10, 0, &[], &[])?; + w.call(WAIT_COMPLETED, 6, 0, &[], &[]) + }) +} + +#[test] +fn an_equal_sampler_state_takes_an_index_a_held_commit_owes_without_waiting() { + let dir = ScratchDir::new("rt-replay-equal-sampler").unwrap(); + let path = held_placement(&dir, sampler(None)); + let (_, lines) = play("equal-sampler", &path); + let indices = lines.iter().find(|line| line.starts_with("indices named ")); + let indices = indices.unwrap_or_else(|| panic!("an indices line: {lines:?}")); + assert!( + indices.contains("0 placed at an index whose holders' commits were in flight") + && indices.ends_with( + "1 sampler states placed without waiting at an index whose last sampler state \ + had the same descriptor while its commits were in flight" + ), + "{indices}" + ); +} + +#[test] +fn a_placement_a_held_commit_owes_stops_the_play_naming_what_holds_it() { + let dir = ScratchDir::new("rt-replay-held-placement").unwrap(); + // A sampler state of another descriptor at index 16: #6, which reads 16, waits for a signal + // only a later record makes. + let other = uints(&[("minFilter", 1), ("magFilter", 1)]); + let path = held_placement(&dir, other); + let cache = ScratchCache::new().unwrap(); + let mut backend = NewRuntime::new(rt_device(cache.path())).unwrap(); + let mut reader = StreamReader::open(&[path], None).unwrap(); + let (_, ended) = Player::new(&mut backend).play(&mut reader); + match ended { + Err(PlayError::Held { awaited, chain, .. }) => { + assert_eq!(awaited, 6); + assert_eq!( + chain, + "#6 on queue #2 waits for #4 to reach 1, which no played record signals" + ); + } + other => panic!("a held placement's stop: {other:?}"), + } +} + #[test] fn a_sampler_state_takes_the_index_of_the_id_the_program_saw() { let dir = ScratchDir::new("rt-replay-recorded").unwrap(); diff --git a/docs/REPLAY-STREAM.md b/docs/REPLAY-STREAM.md index 5ee5e8071..79c332a03 100644 --- a/docs/REPLAY-STREAM.md +++ b/docs/REPLAY-STREAM.md @@ -286,7 +286,10 @@ and the (name id, value) answer pairs. `getBytes:...` has a nil destination and may answer `sha256`. - **Commits:** the order of `commit` records is the global commit order. A command buffer's queue is the receiver of the call that made it; each queue keeps its own order, and an event wait may hold - one queue while the others go on. + one queue while the others go on. Record order is the order of the program's calls, not of its + GPU work: a command buffer committed before a call may wait for an event that only a later + record signals, so a commit record does not promise that the work ran, or could run, before the + records after it. - **Synchronization:** `encodeSignalEvent:value:` and `encodeWaitForEvent:value:` on a command buffer; fences as encoder calls; `setSignaledValue:`; and `waitUntilCompleted` and `waitUntilSignaledValue:timeoutMS:` where the program's CPU waited. @@ -586,8 +589,14 @@ counted from 0), completes the work committed so far, reports as at the stream's the runtime back a block or heap of the stream at its release (`release_block`), and gives textures and sampler states indices from the whole of each index class (section 5): its `indices named N: ...` line counts the objects placed at the index the stream named, those - whose named index the runtime refused, the indices the program reserved, and the placements - that waited for an index's holders' commits, with the time waited. Its readback serves + whose named index the runtime refused, the indices the program reserved, the placements + that waited for an index's holders' commits, with the time waited, and the sampler states placed + without waiting at an index whose last sampler state had the same recorded descriptor while its + commits were in flight (Metal hands an equal descriptor the same sampler state and ID, so work in + flight reads nothing new there). A placement that owes its index to a command buffer no record + played so far lets complete (its event waits only later records signal, or it is behind such a + one on its queue) stops the play with an `error` line naming that chain, rather than wait for + ever. Its readback serves Shared and Managed buffers only; a check of anything else is a refusal. The runtime gives a compute or render pipeline state no `gpuResourceID`, so each one the program saw is reported on an `id` line as `none` and counted (`gap_pipeline_ids`); each skipped object's the program saw