diff --git a/crates/metal2vulkan-validation/src/bin/command-replay.rs b/crates/metal2vulkan-validation/src/bin/command-replay.rs index 2b67ca1a6..45a779db9 100644 --- a/crates/metal2vulkan-validation/src/bin/command-replay.rs +++ b/crates/metal2vulkan-validation/src/bin/command-replay.rs @@ -63,8 +63,8 @@ use metal2vulkan_validation::candidate::runtime_case::open_device; use metal2vulkan_validation::gpu::wait::{parse_wait_timeout, set_wait_timeout, WAIT_TIMEOUT_FLAG}; use metal2vulkan_validation::gpu::DeviceType; use metal2vulkan_validation::replay::{ - compare_dumps, display_library, judged_records, recording_range, segments, Backend, - ManagedCopies, NewRuntime, OldRuntime, PlayError, Player, RangeSource, RecordingRange, + compare_dumps, compare_plays, display_library, judged_records, recording_range, segments, + Backend, ManagedCopies, NewRuntime, OldRuntime, PlayError, Player, RangeSource, RecordingRange, StreamError, StreamReader, Value, FLAG_COMPLETION_BYTES_RECORDED, RECORDED_RANGES, }; use std::collections::BTreeMap; @@ -78,6 +78,7 @@ const USAGE: &str = "usage: command-replay play --stream FILE --out DIR --device [--gpu-wait-timeout SECONDS] \ [--dump-command-buffers FIRST..LAST --dump-dir DIR]\n \ command-replay compare-dumps --a DIR --b DIR\n \ + command-replay compare-plays --a REPORT --b REPORT [--frame F]\n \ command-replay dump \ --stream FILE\n command-replay shapes --stream FILE"; @@ -90,6 +91,7 @@ fn main() { } Some("dump") => with_options(&args[1..], &["stream"], dump), Some("compare-dumps") => with_options(&args[1..], &["a", "b"], compare), + Some("compare-plays") => with_options(&args[1..], &["a", "b"], compare_two_plays), Some("shapes") => with_options(&args[1..], &["stream"], shapes), _ => { eprintln!("{USAGE}"); @@ -153,6 +155,43 @@ fn compare(options: &BTreeMap) -> i32 { } } +/// `compare-plays`: two plays' reports (each a `report.txt` or the directory holding it) compared +/// for a timing verdict, a line each; 0 where the frame `--frame` names has a verdict (or none is +/// named), 1 where it has none, 2 where a report cannot be read. +fn compare_two_plays(options: &BTreeMap) -> i32 { + let frame = match options.get("frame").map(|f| f.parse::()) { + None => None, + Some(Ok(frame)) => Some(frame), + Some(Err(_)) => { + eprintln!("command-replay: --frame takes a frame number\n{USAGE}"); + return 2; + } + }; + let report = |name: &str| { + let path = PathBuf::from(&options[name]); + let path = match path.is_dir() { + true => path.join("report.txt"), + false => path, + }; + std::fs::read_to_string(&path).map_err(|error| format!("{}: {error}", path.display())) + }; + let (a, b) = match (report("a"), report("b")) { + (Ok(a), Ok(b)) => (a, b), + (Err(why), _) | (_, Err(why)) => { + eprintln!("command-replay: compare-plays: {why}"); + return 2; + } + }; + let (lines, verdict) = compare_plays(&a, &b, frame); + for line in lines { + println!("{line}"); + } + match verdict { + true => 0, + false => 1, + } +} + fn reader(options: &BTreeMap) -> Result { let first = PathBuf::from(&options["stream"]); StreamReader::open(&segments(&first), options.get("blobs").map(PathBuf::from)) diff --git a/crates/metal2vulkan-validation/src/replay/compare.rs b/crates/metal2vulkan-validation/src/replay/compare.rs new file mode 100644 index 000000000..609e3af8c --- /dev/null +++ b/crates/metal2vulkan-validation/src/replay/compare.rs @@ -0,0 +1,221 @@ +//! Two plays' reports compared for a timing verdict (`docs/REPLAY-STREAM.md`, section 10, two +//! plays compared): `command-replay compare-plays`. A verdict at a frame needs both plays played +//! by a player that serves every read class a stream has (its report has the `managed reads` +//! line), the frame's player-side counts equal in both (the stream's calls, draws and dispatches, +//! and the backend's skipped and refused counts), and equal digests there (the `check` lines of +//! the frame). The stale reads the line counts bar nothing: where the digests differ, they are the +//! first suspect. + +use std::collections::BTreeMap; + +/// The most lines of one kind the compare names one by one. +const NAMED: usize = 8; + +/// One frame's player-side counts: each key and its value. +type FrameCounts = BTreeMap; + +/// What a compare reads of one report. +#[derive(Default)] +struct Play { + /// The `managed reads` line's stale reads' first frame, where the line names one, and whether + /// the report has the line at all. + served: bool, + stale_from: Option, + /// Whether the backend kept the stream's Managed buffers in two copies. + two_copies: bool, + frames: BTreeMap, + /// Each frame's wall and GPU-busy nanoseconds. + ends: BTreeMap, + /// Each frame's checks: object and digest. + checks: BTreeMap>, +} + +/// Whether a frame line's `executed` key is a player-side count: a skip or a refusal. +fn player_side(key: &str) -> bool { + key.starts_with("skipped_") || key.ends_with("_refusals") +} + +/// The `key=value` words of `words` with a value that is a count. +fn pairs<'w>(words: impl Iterator) -> impl Iterator { + words.filter_map(|word| { + let (key, value) = word.split_once('=')?; + Some((key, value.parse().ok()?)) + }) +} + +fn read(report: &str) -> Play { + let mut play = Play::default(); + for line in report.lines() { + let mut words = line.split_whitespace(); + match (words.next(), words.next()) { + (Some("frame"), Some(frame)) => { + let Ok(frame) = frame.parse() else { continue }; + let mut counts = FrameCounts::new(); + let mut part = ""; + for word in words { + if !word.contains('=') { + part = word; + continue; + } + let Some((key, value)) = pairs(std::iter::once(word)).next() else { + continue; + }; + let counted = match part { + "stream" => ["calls", "draws", "dispatches"].contains(&key), + _ => player_side(key), + }; + if counted { + counts.insert(format!("{part}.{key}"), value); + } + } + play.frames.insert(frame, counts); + } + (Some("end"), Some(frame)) => { + let Ok(frame) = frame.parse() else { continue }; + let found: BTreeMap<&str, u64> = pairs(words).collect(); + let wall = found.get("wall_nanos").copied().unwrap_or(0); + let busy = found.get("gpu_busy").copied().unwrap_or(0); + play.ends.insert(frame, (wall, busy)); + } + (Some("check"), Some(object)) => { + let object = object.trim_start_matches('#').parse(); + let (Some("frame"), Some(frame), Some(sha)) = + (words.next(), words.next(), words.next()) + else { + continue; + }; + if let (Ok(object), Ok(frame)) = (object, frame.parse()) { + let checks = play.checks.entry(frame).or_default(); + checks.push((object, sha.to_owned())); + } + } + (Some("managed"), Some("reads")) => { + play.served = true; + let stale = line.split_once("; stale ").map(|(_, rest)| rest); + let from = stale.and_then(|rest| rest.split_once("first at frame ")); + let from = + from.and_then(|(_, rest)| rest.split(|c: char| !c.is_ascii_digit()).next()); + play.stale_from = from.and_then(|frame| frame.parse().ok()); + } + (Some("managed"), Some("two")) => play.two_copies = true, + _ => {} + } + } + play +} + +/// The first key whose counts differ between two frames, with both values (0 where one lacks it). +fn differs(a: &FrameCounts, b: &FrameCounts) -> Option<(String, u64, u64)> { + let keys = a.keys().chain(b.keys()); + keys.map(|key| { + let get = |counts: &FrameCounts| counts.get(key).copied().unwrap_or(0); + (key.clone(), get(a), get(b)) + }) + .find(|(_, x, y)| x != y) +} + +/// The compare's lines, and whether frame `frame`, where one is asked, has a verdict. +pub fn compare_plays(a: &str, b: &str, frame: Option) -> (Vec, bool) { + let (a, b) = (read(a), read(b)); + let mut lines = Vec::new(); + for (name, play) in [("a", &a), ("b", &b)] { + lines.push(match play.served { + true => format!("served {name}: yes"), + false => format!( + "served {name}: no: no managed reads line, so a player older than the made-with \ + and first-use rules" + ), + }); + } + let both: Vec = (a.frames.keys()) + .filter(|f| b.frames.contains_key(f)) + .copied() + .collect(); + let unequal: Vec<(u64, (String, u64, u64))> = (both.iter()) + .filter_map(|f| Some((*f, differs(&a.frames[f], &b.frames[f])?))) + .collect(); + lines.push(format!( + "frames a {} b {}; both {}; counts equal in {}, unequal in {}", + a.frames.len(), + b.frames.len(), + both.len(), + both.len() - unequal.len(), + unequal.len() + )); + for (f, (key, x, y)) in unequal.iter().take(NAMED) { + lines.push(format!("unequal frame {f}: {key} a={x} b={y}")); + } + let digested: Vec = (a.checks.keys()) + .filter(|f| b.checks.contains_key(f)) + .copied() + .collect(); + let differing: Vec = (digested.iter()) + .filter(|f| a.checks[f] != b.checks[f]) + .copied() + .collect(); + lines.push(format!( + "digests: {} frames with checks in both; equal in {}, differ in {}", + digested.len(), + digested.len() - differing.len(), + differing.len() + )); + let suspect = |f: u64| { + let from = [&a, &b] + .into_iter() + .filter(|play| play.two_copies) + .filter_map(|play| play.stale_from) + .min(); + match from { + Some(from) if from <= f => { + format!("; stale reads from frame {from}, the first suspect") + } + _ => String::new(), + } + }; + for f in differing.iter().take(NAMED) { + lines.push(format!("digests differ at frame {f}{}", suspect(*f))); + } + let Some(f) = frame else { + return (lines, true); + }; + let no = |why: String| format!("no verdict at frame {f}: {why}"); + let verdict = if !(a.served && b.served) { + Err(no( + "a play's player does not serve every read class".to_owned() + )) + } else if !both.contains(&f) { + Err(no("a play lacks the frame".to_owned())) + } else if let Some((_, (key, x, y))) = unequal.iter().find(|(g, _)| *g == f) { + Err(no(format!("counts differ ({key} a={x} b={y})"))) + } else if !digested.contains(&f) { + Err(no("no digest there in both plays".to_owned())) + } else if differing.contains(&f) { + Err(no(format!("the digests differ{}", suspect(f)))) + } else { + match (a.ends.get(&f), b.ends.get(&f)) { + (Some(&(wall_a, busy_a)), Some(&(wall_b, busy_b))) => Ok(format!( + "verdict at frame {f}: b is {} than a by GPU-busy time (a {busy_a} ns, b \ + {busy_b} ns); wall a {wall_a} ns, b {wall_b} ns", + faster(busy_a, busy_b) + )), + _ => Err(no("a play lacks the frame's end".to_owned())), + } + }; + let ok = verdict.is_ok(); + lines.push(match verdict { + Ok(line) | Err(line) => line, + }); + (lines, ok) +} + +/// How `b` compares with `a`: "N.N% faster", "N.N% slower" or "level". +fn faster(a: u64, b: u64) -> String { + if a == 0 || a == b { + return "level".to_owned(); + } + let percent = (a.abs_diff(b) as f64) * 100.0 / (a as f64); + match b < a { + true => format!("{percent:.1}% faster"), + false => format!("{percent:.1}% slower"), + } +} diff --git a/crates/metal2vulkan-validation/src/replay/mod.rs b/crates/metal2vulkan-validation/src/replay/mod.rs index 11ada9d22..7232cf9f3 100644 --- a/crates/metal2vulkan-validation/src/replay/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/mod.rs @@ -3,6 +3,7 @@ mod addresses; mod args; +mod compare; mod covers; mod dumps; mod heaps; @@ -10,11 +11,13 @@ mod new_runtime; mod old_runtime; mod player; mod range; +mod stale; mod stream; mod texwrites; mod translator; mod value; +pub use compare::compare_plays; pub use covers::SlotStage; pub use dumps::{compare_dumps, Comparison, Difference}; pub use heaps::HeapSplit; @@ -22,8 +25,8 @@ pub use new_runtime::{judged_records, Ended, 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, IdDiffers, Made, ManagedReads, PlayError, Player, + PrivateBytes, ReadClass, Relaid, Report, TextureWrites, }; pub use range::{ display_library, recording_range, sidecar, RangeRow, RangeSource, RecordingRange, diff --git a/crates/metal2vulkan-validation/src/replay/player.rs b/crates/metal2vulkan-validation/src/replay/player.rs index dc5348340..69cfc999e 100644 --- a/crates/metal2vulkan-validation/src/replay/player.rs +++ b/crates/metal2vulkan-validation/src/replay/player.rs @@ -12,6 +12,7 @@ use super::heaps::{ heap_size, placement_heap, placement_offset, places_buffer, places_texture, recorded_range, relay, HeapSplit, Layout, Overlaps, Placements, }; +use super::stale::Stale; use super::stream::{Call, StreamError, StreamReader}; use super::texwrites::TexWrites; use super::value::{Hash, Value}; @@ -283,6 +284,8 @@ impl From for PlayError { #[derive(Clone, Debug, PartialEq, Eq)] pub struct Check { pub object: u64, + /// The frame it was read in: the presents played before it. + pub frame: u64, pub sha256: Hash, /// The recording's own checksum, where the stream holds one. pub recorded: Option, @@ -406,6 +409,9 @@ pub struct Report { pub ends: Vec, /// The CPU's writes into Managed textures, and those a committed user may still be using. pub texture_writes: TextureWrites, + /// The GPU's reads of Managed bytes that no announcement took to the GPU copy, as a play that + /// keeps two copies holds them (`stale.rs`). + pub managed_reads: ManagedReads, /// The recorded devices other than the one the guest makes its objects on, whose identity /// records the play takes nothing from (`Player::guest_device`). pub other_devices: Vec, @@ -462,6 +468,71 @@ impl TextureWrites { } } +/// One kind of a play's reads of Managed bytes that no announcement took to the GPU copy: the +/// buffers read, the uses, and the frame of the first. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ReadClass { + pub objects: u64, + pub uses: u64, + pub first_frame: Option, +} + +impl ReadClass { + fn text(&self) -> String { + match self.first_frame { + None => "none".to_owned(), + Some(frame) => format!( + "{} objects, {} uses, first at frame {frame}", + self.objects, self.uses + ), + } + } +} + +/// The GPU's reads of a Managed object's bytes that no announcement took to its GPU copy, counted +/// from the stream alone as a play that keeps two copies holds them (`docs/REPLAY-STREAM.md`, +/// section 10). The made-with reads (`made_with`) are served: each runtime's GPU copy starts from +/// the bytes the buffer was made with. The stale ones (`stale`), of bytes the CPU wrote that no +/// `didModifyRange:` announced, play as recorded on both runtimes: Metal leaves what the GPU reads +/// there undefined. With no identity record (`no_identity`), a no-copy buffer's writes before its +/// first use are served and not counted. Where the guest device's identity record keeps one copy, +/// none is counted (`one_copy`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ManagedReads { + pub one_copy: bool, + pub no_identity: bool, + pub stale: ReadClass, + pub made_with: ReadClass, +} + +impl ManagedReads { + /// The report's `managed reads` line. + pub fn line(&self) -> String { + if self.one_copy { + return "managed reads on two copies: none counted: the stream's identity record \ + keeps one copy" + .to_owned(); + } + let first_use = match self.no_identity { + true => "; writes before first use served (no identity record)", + false => "", + }; + format!( + "managed reads on two copies: made-with {}, served; stale {}, played as recorded{first_use}", + self.made_with.text(), + self.stale.text() + ) + } + + /// The first frame a read of either kind falls in. + pub fn first_frame(&self) -> Option { + match (self.stale.first_frame, self.made_with.first_frame) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + } + } +} + /// A frame's end: how long the frame took to play, and what the process and the runtime held. /// None of it is fixed by the stream; it differs between plays. #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -735,7 +806,10 @@ impl Report { Some(_) => "differs", }; let sha = super::value::hex(&check.sha256); - lines.push(format!("check #{} {sha} {verdict}", check.object)); + lines.push(format!( + "check #{} frame {} {sha} {verdict}", + check.object, check.frame + )); } for id in &self.ids { let played = id @@ -822,6 +896,7 @@ impl Report { )); } lines.push(self.texture_writes.line()); + lines.push(self.managed_reads.line()); lines.push(format!("total{}", counted(&self.total))); lines } @@ -987,6 +1062,7 @@ pub struct Player<'b, B: Backend> { texwrites: TexWrites, /// What texture writes covered in placement heaps (`Report::covered`). covers: Covers, + stale: Stale, /// The live buffers a texture over a surface's plane was made on /// (`newTextureWithDescriptor:iosurface:plane:`), which stand for the surfaces' pages. A /// runtime may keep the texels apart from the buffer, as the product does: their checks and @@ -1211,6 +1287,7 @@ impl<'b, B: Backend> Player<'b, B> { frame_out: None, texwrites: TexWrites::default(), covers: Covers::default(), + stale: Stale::default(), receivers: HashSet::new(), placed_sizes: HashMap::new(), dump: None, @@ -1282,6 +1359,7 @@ impl<'b, B: Backend> Player<'b, B> { } self.report.total = Counts { stream, executed }; self.report.texture_writes = self.texwrites.counts(); + self.report.managed_reads = self.stale.counts(); self.report.covered = self.covers.covers; self.report.binding_uncovers = self.covers.binding_uncovers; (self.report, ended) @@ -1616,6 +1694,7 @@ impl<'b, B: Backend> Player<'b, B> { let guest = self.guest_device.is_none_or(|guest| guest == call.receiver); if let (Some(unified), true) = (unified, guest) { self.backend.recorded_unified_memory(unified); + self.stale.identity(unified); } Ok(()) } @@ -1675,6 +1754,7 @@ impl<'b, B: Backend> Player<'b, B> { "release" => { self.texwrites.released(call.receiver); self.covers.released(call.receiver); + self.stale.released(call.receiver); if let Some(dump) = &mut self.dump { dump.buffers.remove(&call.receiver); } @@ -1764,6 +1844,7 @@ impl<'b, B: Backend> Player<'b, B> { pending.committed = true; let (queue, signals) = (pending.queue, pending.signals.clone()); self.texwrites.committed(command_buffer, queue, &signals); + (self.stale).committed(command_buffer, self.report.frames.len() as u64); self.committed.push(command_buffer); self.run(&own_call("commit", command_buffer, 0, &[]))?; *self.fixed.entry(COMMITS).or_default() += 1; @@ -1883,6 +1964,7 @@ impl<'b, B: Backend> Player<'b, B> { let backend = &*self.backend; let writes = |pipeline, stage| backend.texture_writes(pipeline, stage); self.covers.saw(&resolved, offset, size, writes); + self.stale.saw(&resolved, self.report.frames.len() as u64); let managed = |texture| backend.managed_texture(texture); self.texwrites.saw(&resolved, self.position, managed); let object = resolved.result; @@ -2059,6 +2141,7 @@ impl<'b, B: Backend> Player<'b, B> { Value::Blob(hash) => self.blob(stream, hash)?, _ => return Err(invalid("m2v.write of no data")), }; + self.stale.wrote(target, offset, data.len() as u64); self.put(target, offset, data)?; } Ok(()) @@ -2130,6 +2213,7 @@ impl<'b, B: Backend> Player<'b, B> { let bytes = self.uncounted(left_out, |player| player.read_back(object))?; self.report.checks.push(Check { object, + frame: self.report.frames.len() as u64, sha256: Sha256::digest(&bytes).into(), recorded, covered: self.covers.covered(object), diff --git a/crates/metal2vulkan-validation/src/replay/stale.rs b/crates/metal2vulkan-validation/src/replay/stale.rs new file mode 100644 index 000000000..703d30a89 --- /dev/null +++ b/crates/metal2vulkan-validation/src/replay/stale.rs @@ -0,0 +1,484 @@ +//! The GPU's reads of a Managed object's bytes that no announcement took to its GPU copy, as a +//! play that keeps two copies would hold them (`docs/REPLAY-STREAM.md`, section 10, the +//! `managed reads` line): counted from the stream's calls alone, so the same on every runtime and +//! device. Two kinds: +//! +//! - **Stale:** bytes an `m2v.write` put into the object that no `didModifyRange:` of it +//! announced and no GPU write covered since. Where the stream has no identity record, a no-copy +//! Managed buffer's writes before its first use are not stale: its GPU copy takes them, as the +//! player plays both runtimes (section 5). +//! - **Made with:** the bytes a Managed buffer was made with (a descriptor's `contents`, to its +//! `zeroFrom` where it is a no-copy one, a no-copy buffer's pages, `newBufferWithBytes:`'s +//! bytes; bytes that are all zero left out, as the GPU copy holds zeros there anyway), before a +//! `didModifyRange:` or a GPU write covered them. Both runtimes serve them: each GPU copy +//! starts from them. +//! +//! Stale reads play as recorded on both runtimes, as Metal leaves what the GPU reads there +//! undefined: where two plays' digests differ, they are the first suspect. +//! +//! A Managed object is a buffer of any maker whose options say Managed, a Managed block and the +//! buffers in it (the block's bytes), and a texture over such a buffer or a view of it (the +//! buffer's bytes from the texture's offset). A GPU use is any command of an encoder that names the +//! object, judged when its command buffer commits: a blit's source range and a copy to the guest's +//! RAM read; a blit's, a fill's and a guest-RAM copy's destination bytes are a GPU write; every +//! other naming (a binding, `useResource:`, `synchronizeResource:`, an attachment) reads the whole +//! object, as the stream carries no buffer access. An indirect command buffer's command is judged +//! where it is encoded. A command buffer released uncommitted runs nothing. + +use super::args::option_sets; +use super::covers::named; +use super::player::{ManagedReads, ReadClass}; +use super::stream::Call; +use super::value::Value; +use std::collections::{HashMap, HashSet}; + +/// `MTLStorageModeManaged`. +const MANAGED: u64 = 1; + +/// The storage mode of resource options `options`. +fn mode(options: u64) -> u64 { + (options >> 4) & 0xf +} + +/// Where a Managed object's bytes lie: the object whose bytes they are (a block, or the buffer +/// itself), its range there, and the buffer counted for a read of it. +#[derive(Clone, Copy)] +struct Span { + base: u64, + start: u64, + end: u64, + counted: u64, +} + +/// A use of an object a command buffer's commit judges: a read or a GPU write, of a range of the +/// object's bytes from its start, or of all of them. +#[derive(Clone, Copy)] +enum Use { + Read(u64, Option<(u64, u64)>), + Write(u64, Option<(u64, u64)>), +} + +/// A kind's count: the buffers read, the uses, and the first read's frame. +#[derive(Default)] +struct Kind { + objects: HashSet, + uses: u64, + first_frame: Option, +} + +impl Kind { + fn read(&mut self, counted: u64, frame: u64) { + self.objects.insert(counted); + self.uses += 1; + self.first_frame.get_or_insert(frame); + } + + fn class(&self) -> ReadClass { + ReadClass { + objects: self.objects.len() as u64, + uses: self.uses, + first_frame: self.first_frame, + } + } +} + +#[derive(Default)] +pub(super) struct Stale { + /// The guest device's `hasUnifiedMemory`, where the stream has an identity record. + unified: Option, + spans: HashMap, + /// The no-copy Managed buffers made with no bytes that no committed command buffer named yet, + /// each with the command buffer that named it first: their writes reach the GPU copy where the + /// stream has no identity record. + fresh: HashMap>, + /// Each base's bytes the CPU wrote that nothing announced or covered. + written: HashMap>, + /// Each base's bytes it was made with that nothing announced or covered. + made: HashMap>, + /// Each open encoder's command buffer. + encoders: HashMap, + /// The indirect command buffers' commands. + commands: HashSet, + /// Each command buffer's uses, judged at its commit. + pending: HashMap>, + stale: Kind, + made_with: Kind, +} + +/// `ranges` with `[start, end)` added, merged where they meet. +fn add(ranges: &mut Vec<(u64, u64)>, start: u64, end: u64) { + if end <= start { + return; + } + let (mut start, mut end) = (start, end); + ranges.retain(|&(s, e)| { + let apart = e < start || s > end; + if !apart { + start = start.min(s); + end = end.max(e); + } + apart + }); + ranges.push((start, end)); +} + +/// `ranges` with `[start, end)` taken out. +fn remove(ranges: &mut Vec<(u64, u64)>, start: u64, end: u64) { + let mut kept = Vec::with_capacity(ranges.len() + 1); + for &(s, e) in ranges.iter() { + if e <= start || s >= end { + kept.push((s, e)); + continue; + } + if s < start { + kept.push((s, start)); + } + if e > end { + kept.push((end, e)); + } + } + *ranges = kept; +} + +fn meets(ranges: Option<&Vec<(u64, u64)>>, start: u64, end: u64) -> bool { + (ranges.into_iter().flatten()).any(|&(s, e)| s < end && start < e) +} + +/// An `NSRange`'s `{location, length}` as `(start, end)`. +fn range(value: Option<&Value>) -> Option<(u64, u64)> { + let fields = value?.as_map()?; + let field = |key: &str| fields.iter().find(|(k, _)| &**k == key)?.1.as_uint(); + let start = field("location")?; + Some((start, start.saturating_add(field("length")?))) +} + +/// The length of a piece of data: bytes (blobs are read before a call reaches the count). +fn length(value: &Value) -> Option { + value.as_bytes().map(|bytes| bytes.len() as u64) +} + +/// The bytes a buffer was made with, where they count: `None` for none, and for inline bytes that +/// are all zero. +fn made_with(value: Option<&Value>, upto: Option) -> Option { + let bytes = value?.as_bytes()?; + let length = upto.map_or(bytes.len() as u64, |upto| upto.min(bytes.len() as u64)); + (length > 0 && bytes.iter().any(|&b| b != 0)).then_some(length) +} + +impl Stale { + /// The guest device's identity record: whether its memory is unified. + pub(super) fn identity(&mut self, unified: bool) { + self.unified.get_or_insert(unified); + } + + /// The counts so far. + pub(super) fn counts(&self) -> ManagedReads { + ManagedReads { + one_copy: self.unified == Some(true), + no_identity: self.unified.is_none(), + stale: self.stale.class(), + made_with: self.made_with.class(), + } + } + + fn span(&self, object: u64) -> Option { + self.spans.get(&object).copied() + } + + /// A Managed buffer or block `object` made of `length` bytes, its own base, and the bytes it + /// was made with, where they count. + fn managed(&mut self, object: u64, length: u64, made: Option) { + let span = Span { + base: object, + start: 0, + end: length, + counted: object, + }; + self.spans.insert(object, span); + if let Some(made) = made { + add(self.made.entry(object).or_default(), 0, made.min(length)); + } + } + + /// A call played, its blobs read. + pub(super) fn saw(&mut self, call: &Call, frame: u64) { + let selector = &*call.selector; + let uint = |at: usize| call.args.get(at).and_then(Value::as_uint); + let made = call.result; + match selector { + "newBufferWithLength:options:" + | "newBufferWithLength:options:offset:" + | "m2v.newBufferOfLengthPaddingUnobserved" + | "m2v.newExportableBufferOfLength" + | "m2v.newDmaBufBufferOfLengthPaddingUnobserved" => { + if let (Some(length), Some(options), true) = (uint(0), uint(1), made != 0) { + if mode(options) == MANAGED { + self.managed(made, length, None); + } + } + return; + } + "newBufferWithBytes:length:options:" + | "newBufferWithBytesNoCopy:length:options:deallocator:" => { + if let (Some(length), Some(options), true) = (uint(1), uint(2), made != 0) { + if mode(options) == MANAGED { + let bytes = made_with(call.args.first(), None); + self.managed(made, length, bytes); + if selector.contains("NoCopy") && bytes.is_none() { + self.fresh.insert(made, None); + } + } + } + return; + } + "newBufferWithDescriptor:" => { + let Some(fields) = call.args.first().and_then(Value::as_map) else { + return; + }; + let field = |key: &str| fields.iter().find(|(k, _)| &**k == key).map(|(_, v)| v); + let sets = field("options") + .and_then(Value::as_list) + .unwrap_or_default(); + let options = option_sets(call, 0, sets).unwrap_or(0); + let length = field("length").and_then(Value::as_uint); + if let (Some(length), MANAGED, true) = (length, mode(options), made != 0) { + let no_copy = field("noCopy").and_then(Value::as_bool) == Some(true); + let upto = no_copy.then(|| field("zeroFrom").and_then(Value::as_uint)); + let bytes = made_with(field("contents"), upto.flatten()); + self.managed(made, length, bytes); + if no_copy && bytes.is_none() { + self.fresh.insert(made, None); + } + } + return; + } + "endEncoding" => { + self.encoders.remove(&call.receiver); + return; + } + "m2v.newBlockWithLength:storageMode:" => { + if let (Some(length), Some(MANAGED), true) = (uint(0), uint(1), made != 0) { + self.managed(made, length, None); + } + return; + } + "m2v.newBufferInBlock:offset:length:options:" => { + let block = call.args.first().and_then(Value::as_object); + let block = block.and_then(|block| self.span(block)); + if let (Some(block), Some(offset), Some(length), Some(options)) = + (block, uint(1), uint(2), uint(3)) + { + if mode(options) == MANAGED && made != 0 { + let start = block.start.saturating_add(offset); + let span = Span { + base: block.base, + start, + end: start.saturating_add(length), + counted: made, + }; + self.spans.insert(made, span); + } + } + return; + } + "newTextureWithDescriptor:offset:bytesPerRow:" + | "newTiledTextureWithDescriptor:offset:bytesPerRow:" + | "newLinearTextureWithDescriptor:offset:bytesPerRow:bytesPerImage:" => { + if let (Some(buffer), Some(offset)) = (self.span(call.receiver), uint(1)) { + let start = buffer.start.saturating_add(offset).min(buffer.end); + self.spans.insert(made, Span { start, ..buffer }); + } + return; + } + _ if selector.starts_with("newTextureView") => { + if let Some(texture) = self.span(call.receiver) { + self.spans.insert(made, texture); + } + return; + } + "didModifyRange:" => { + if let (Some(span), Some((start, end))) = + (self.span(call.receiver), range(call.args.first())) + { + let (start, end) = (span.start + start, span.start.saturating_add(end)); + for ranges in [&mut self.written, &mut self.made] { + if let Some(ranges) = ranges.get_mut(&span.base) { + remove(ranges, start, end); + } + } + } + return; + } + _ => {} + } + if selector.contains("CommandEncoder") && !selector.contains("Argument") && made != 0 { + let command_buffer = self.encoders.get(&call.receiver).copied(); + self.encoders + .insert(made, command_buffer.unwrap_or(call.receiver)); + } + if selector.starts_with("indirect") && selector.contains("CommandAtIndex") && made != 0 { + self.commands.insert(made); + } + let command_buffer = match self.encoders.get(&call.receiver) { + Some(&command_buffer) => Some(command_buffer), + None if self.commands.contains(&call.receiver) => None, + None if selector.contains("CommandEncoder") && !selector.contains("Argument") => { + Some(call.receiver) + } + None => return, + }; + let uses = self.uses(call); + if uses.is_empty() { + return; + } + match command_buffer { + Some(command_buffer) => { + for &one in &uses { + let (Use::Read(object, _) | Use::Write(object, _)) = one; + if let Some(user) = self.fresh.get_mut(&object) { + user.get_or_insert(command_buffer); + } + } + self.pending.entry(command_buffer).or_default().extend(uses); + } + None => { + for one in uses { + self.judge(one, frame); + } + } + } + } + + /// The uses of the Managed objects `call`, a command, names. + fn uses(&self, call: &Call) -> Vec { + let object = |at: usize| call.args.get(at).and_then(Value::as_object); + let uint = |at: usize| call.args.get(at).and_then(Value::as_uint); + let managed = |object: Option| object.filter(|o| self.spans.contains_key(o)); + let mut uses = Vec::new(); + match &*call.selector { + "copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:" => { + let size = uint(4).unwrap_or(0); + if let (Some(from), Some(at)) = (managed(object(0)), uint(1)) { + uses.push(Use::Read(from, Some((at, at.saturating_add(size))))); + } + if let (Some(to), Some(at)) = (managed(object(2)), uint(3)) { + uses.push(Use::Write(to, Some((at, at.saturating_add(size))))); + } + } + "fillBuffer:range:value:" => { + if let (Some(to), Some(bytes)) = (managed(object(0)), range(call.args.get(1))) { + uses.push(Use::Write(to, Some(bytes))); + } + } + "m2v.copyFromGuestRam" | "m2v.copyFromGuestRamAt" => { + let pieces = call + .args + .get(1) + .and_then(Value::as_list) + .unwrap_or_default(); + if let Some(to) = managed(object(0)) { + for piece in pieces { + if let Some([at, data]) = piece.as_list() { + if let (Some(at), Some(n)) = (at.as_uint(), length(data)) { + uses.push(Use::Write(to, Some((at, at.saturating_add(n))))); + } + } + } + } + } + "m2v.copyToGuestRam" => { + if let Some(from) = managed(object(0)) { + uses.push(Use::Read(from, None)); + } + } + selector + if selector.starts_with("copyFromTexture:") && selector.contains("toBuffer:") => + { + let mut objects = Vec::new(); + named(&call.args, &mut objects); + let to = objects + .into_iter() + .skip(1) + .filter(|o| self.spans.contains_key(o)); + uses.extend(to.map(|to| Use::Write(to, None))); + } + _ => { + let mut objects = Vec::new(); + named(&call.args, &mut objects); + objects.sort_unstable(); + objects.dedup(); + let read = objects.into_iter().filter(|o| self.spans.contains_key(o)); + uses.extend(read.map(|from| Use::Read(from, None))); + } + } + uses + } + + /// One use, at frame `frame`. + fn judge(&mut self, one: Use, frame: u64) { + let (Use::Read(object, bytes) | Use::Write(object, bytes)) = one; + let Some(span) = self.span(object) else { + return; + }; + let (start, end) = match bytes { + Some((start, end)) => ( + span.start.saturating_add(start), + span.start.saturating_add(end), + ), + None => (span.start, span.end), + }; + match one { + Use::Read(..) => { + if meets(self.written.get(&span.base), start, end) { + self.stale.read(span.counted, frame); + } + if meets(self.made.get(&span.base), start, end) { + self.made_with.read(span.counted, frame); + } + } + Use::Write(..) => { + for ranges in [&mut self.written, &mut self.made] { + if let Some(ranges) = ranges.get_mut(&span.base) { + remove(ranges, start, end); + } + } + } + } + } + + /// `length` bytes the CPU put at `offset` of `target` (`m2v.write`). + pub(super) fn wrote(&mut self, target: u64, offset: u64, length: u64) { + let Some(span) = self.span(target) else { + return; + }; + if self.unified.is_none() && self.fresh.contains_key(&target) { + return; + } + let start = span.start.saturating_add(offset); + add( + self.written.entry(span.base).or_default(), + start, + start.saturating_add(length), + ); + } + + /// `command_buffer` committed at frame `frame`: its uses judged, and the buffers it named + /// first fresh no more. + pub(super) fn committed(&mut self, command_buffer: u64, frame: u64) { + for one in self.pending.remove(&command_buffer).unwrap_or_default() { + self.judge(one, frame); + } + (self.fresh).retain(|_, user| *user != Some(command_buffer)); + } + + /// `object` released. + pub(super) fn released(&mut self, object: u64) { + self.spans.remove(&object); + self.fresh.remove(&object); + self.written.remove(&object); + self.made.remove(&object); + self.encoders.remove(&object); + self.commands.remove(&object); + self.pending.remove(&object); + } +} diff --git a/crates/metal2vulkan-validation/src/replay/tests.rs b/crates/metal2vulkan-validation/src/replay/tests.rs index aa9090184..41a67cc1e 100644 --- a/crates/metal2vulkan-validation/src/replay/tests.rs +++ b/crates/metal2vulkan-validation/src/replay/tests.rs @@ -2,6 +2,7 @@ //! is asked (no device). The runtime backends' tests are device tests (`runtime_lane`). use super::addresses::AddressMap; +use super::compare::compare_plays; use super::covers::SlotStage; use super::dumps::{compare_dumps, Difference}; use super::heaps::HeapSplit; @@ -3085,3 +3086,177 @@ fn the_dump_compare_agrees_on_alike_plays_and_reports_a_dump_one_play_lacks() { assert_eq!(comparison.only_one, [("cb21-obj3".to_owned(), 'a')]); assert!(!comparison.agrees()); } + +/// A Managed buffer descriptor of `length` bytes made with `contents`, a no-copy one where +/// `no_copy`. +fn managed_descriptor(length: u64, contents: Value, no_copy: bool) -> [Value; 1] { + let managed = Value::List(vec![map(&[("ResourceOptions", Value::Uint(16))])]); + let fields = [ + ("length", Value::Uint(length)), + ("options", managed), + ("contents", contents), + ("noCopy", Value::Bool(no_copy)), + ]; + [map(&fields)] +} + +/// A command buffer of queue #2, `command_buffer`, whose compute encoder `encoder` binds +/// `buffers`, committed. +fn bound( + w: &mut StreamWriter, + command_buffer: u64, + encoder: u64, + buffers: &[u64], +) -> std::io::Result<()> { + w.call("commandBuffer", 2, command_buffer, &[], &[])?; + w.call("computeCommandEncoder", command_buffer, encoder, &[], &[])?; + for (at, &buffer) in buffers.iter().enumerate() { + let args = [ + Value::Object(buffer), + Value::Uint(0), + Value::Uint(at as u64), + ]; + w.call("setBuffer:offset:atIndex:", encoder, 0, &args, &[])?; + } + w.call("endEncoding", encoder, 0, &[], &[])?; + w.call("commit", command_buffer, 0, &[], &[]) +} + +/// The GPU reads of Managed bytes no announcement took to the GPU copy, counted from the stream +/// alone, under a two-copy identity record: a copied buffer's contents read twice before any +/// announcement (made-with, served), and a no-copy buffer's write read once before its +/// `didModifyRange:` and once after (stale once). +#[test] +fn a_two_copy_stream_s_managed_reads_are_counted_by_kind() { + let mut kept = Kept::default(); + let write = [Value::Uint(0), Value::Bytes(vec![7; 4])]; + let (report, ended) = played(&mut kept, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + let identity = [("hasUnifiedMemory", Value::Bool(false))]; + w.call("m2v.deviceIdentity", 1, 0, &[], &identity)?; + w.call("newCommandQueue", 1, 2, &[], &[])?; + let copied = managed_descriptor(4, Value::Bytes(vec![9; 4]), false); + w.call("newBufferWithDescriptor:", 1, 3, &copied, &[])?; + let no_copy = managed_descriptor(4, Value::Nil, true); + w.call("newBufferWithDescriptor:", 1, 4, &no_copy, &[])?; + w.call("m2v.write", 4, 0, &write, &[])?; + bound(w, 10, 11, &[3, 4])?; + w.call("m2v.present", 0, 0, &[], &[])?; + let whole = map(&[("location", Value::Uint(0)), ("length", Value::Uint(4))]); + w.call("didModifyRange:", 4, 0, &[whole], &[])?; + bound(w, 12, 13, &[3, 4]) + }); + ended.unwrap(); + let reads = report.managed_reads; + assert_eq!((reads.made_with.objects, reads.made_with.uses), (1, 2)); + assert_eq!((reads.stale.objects, reads.stale.uses), (1, 1)); + let line = "managed reads on two copies: made-with 1 objects, 2 uses, first at frame 0, \ + served; stale 1 objects, 1 uses, first at frame 0, played as recorded"; + assert!( + report.lines().iter().any(|l| l == line), + "{:?}", + report.lines() + ); +} + +/// With no identity record, a no-copy Managed buffer's writes before the command buffer that +/// first names it commits are served, not stale; a write after that commit is stale. With a +/// one-copy identity record nothing is counted. +#[test] +fn a_no_copy_buffer_s_writes_before_first_use_are_not_stale_with_no_identity() { + let write = [Value::Uint(0), Value::Bytes(vec![7; 4])]; + let stream = |w: &mut StreamWriter, identity: Option| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + if let Some(unified) = identity { + let answers = [("hasUnifiedMemory", Value::Bool(unified))]; + w.call("m2v.deviceIdentity", 1, 0, &[], &answers)?; + } + w.call("newCommandQueue", 1, 2, &[], &[])?; + let no_copy = managed_descriptor(4, Value::Nil, true); + w.call("newBufferWithDescriptor:", 1, 4, &no_copy, &[])?; + w.call("m2v.write", 4, 0, &write, &[])?; + bound(w, 10, 11, &[4])?; + w.call("m2v.present", 0, 0, &[], &[])?; + w.call("m2v.write", 4, 0, &write, &[])?; + bound(w, 12, 13, &[4]) + }; + let mut kept = Kept::default(); + let (report, ended) = played(&mut kept, |w| stream(w, None)); + ended.unwrap(); + let reads = report.managed_reads; + assert_eq!(reads.stale.first_frame, Some(1)); + assert_eq!((reads.stale.objects, reads.stale.uses), (1, 1)); + let line = "managed reads on two copies: made-with none, served; stale 1 objects, 1 uses, \ + first at frame 1, played as recorded; writes before first use served (no identity \ + record)"; + assert!( + report.lines().iter().any(|l| l == line), + "{:?}", + report.lines() + ); + let mut kept = Kept::default(); + let (report, ended) = played(&mut kept, |w| stream(w, Some(true))); + ended.unwrap(); + let line = "managed reads on two copies: none counted: the stream's identity record keeps one \ + copy"; + assert!( + report.lines().iter().any(|l| l == line), + "{:?}", + report.lines() + ); +} + +/// Two plays' reports compared: a verdict at a frame with equal player-side counts and equal +/// digests (other executed counts may differ); none where the skips differ, where a frame has no +/// digest in both, where the digests differ (the stale reads named as the first suspect on a +/// two-copy play) or where a play's player predates the served read classes. +#[test] +fn two_plays_compare_for_a_verdict_only_where_counts_and_digests_agree() { + let report = |busy: u64, skipped: u64, sha: &str, extra: &str| { + format!( + "managed two copies (the stream's device identity): played as recorded\n\ + managed reads on two copies: made-with none, served; stale 2 objects, 3 uses, first \ + at frame 1, played as recorded\n\ + frame 0 stream calls=10 draws=1 dispatches=0 executed barriers={busy} skipped_draws=0\n\ + end 0 wall_nanos=100 times stream=1 gpu_busy={busy} live\n\ + check #7 frame 0 aa match\n\ + frame 1 stream calls=5 draws=1 dispatches=0 executed skipped_draws={skipped}\n\ + end 1 wall_nanos=90 times gpu_busy=30 live\n\ + check #7 frame 1 {sha} match\n\ + frame 2 stream calls=5 draws=1 dispatches=0 executed\n\ + end 2 wall_nanos=90 times gpu_busy=30 live\n{extra}" + ) + }; + let a = report(50, 0, "bb", ""); + let (lines, verdict) = compare_plays(&a, &report(40, 0, "bb", ""), Some(0)); + assert!(verdict, "{lines:?}"); + let line = "verdict at frame 0: b is 20.0% faster than a by GPU-busy time (a 50 ns, b 40 ns); \ + wall a 100 ns, b 100 ns"; + assert_eq!(lines.last().map(String::as_str), Some(line), "{lines:?}"); + let (lines, verdict) = compare_plays(&a, &report(50, 1, "bb", ""), Some(1)); + assert!(!verdict); + let line = "no verdict at frame 1: counts differ (executed.skipped_draws a=0 b=1)"; + assert_eq!(lines.last().map(String::as_str), Some(line), "{lines:?}"); + let (lines, verdict) = compare_plays(&a, &a, Some(2)); + assert!(!verdict); + let line = "no verdict at frame 2: no digest there in both plays"; + assert_eq!(lines.last().map(String::as_str), Some(line), "{lines:?}"); + let (lines, verdict) = compare_plays(&a, &report(50, 0, "cc", ""), Some(1)); + assert!(!verdict); + let line = "no verdict at frame 1: the digests differ; stale reads from frame 1, the first \ + suspect"; + assert_eq!(lines.last().map(String::as_str), Some(line), "{lines:?}"); + let old: String = (a.lines()) + .filter(|l| !l.starts_with("managed reads")) + .map(|l| format!("{l}\n")) + .collect(); + let (lines, verdict) = compare_plays(&old, &a, Some(0)); + assert!(!verdict); + assert!(lines.contains( + &"served a: no: no managed reads line, so a player older than the \ + made-with and first-use rules" + .to_owned() + )); + let line = "no verdict at frame 0: a play's player does not serve every read class"; + assert_eq!(lines.last().map(String::as_str), Some(line), "{lines:?}"); +} diff --git a/docs/REPLAY-STREAM.md b/docs/REPLAY-STREAM.md index 5555b47cd..45d9dc752 100644 --- a/docs/REPLAY-STREAM.md +++ b/docs/REPLAY-STREAM.md @@ -629,6 +629,27 @@ counted from 0), completes the work committed so far, reports as at the stream's running on the recording device. It counts them by the presents between the user's commit and the write (0, 1, 2, 3 or more), names the first eight (position, texture, user, presents) and counts the writes into textures whose storage the backend does not tell. It stops nothing. +- **Reads of Managed bytes on two copies:** the report's `managed reads on two copies: made-with + CLASS, served; stale CLASS, played as recorded` line (`CLASS` `N objects, U uses, first at + frame F`, or `none`) counts, from the stream's calls alone and so alike on every runtime and + device, the GPU's reads of a Managed object's bytes that no announcement took to its GPU copy, + as a play that keeps two copies holds them. A Managed object is a buffer of any maker whose + options say Managed, a Managed block and its buffers, and a texture over such a buffer or a view + of it. A GPU use is a command that names the object, judged at its command buffer's commit: a + blit's source range and a copy to the guest's RAM read; a blit's, a fill's and a guest-RAM + copy's destination bytes are a GPU write; every other naming reads the whole object, as the + stream carries no buffer access. Made-with reads are of the bytes a buffer was made with (a + descriptor's `contents`, a no-copy buffer's pages, `newBufferWithBytes:length:options:`'s bytes; + bytes that are all zero left out) before a `didModifyRange:` or a GPU write covered them. The + player serves them on both runtimes (section 5: the GPU copy starts from them), so the count + says how many reads depend on that, not that any is wrong. Stale reads are of bytes an + `m2v.write` put in that no `didModifyRange:` announced and no GPU write covered: what the GPU + reads there Metal leaves undefined, and both runtimes play it by one rule, the GPU copy's bytes + as the making and the announcements left them. Where the stream has no identity record, a + no-copy buffer's writes before its first use reach its GPU copy (section 5) and are not counted; + the line ends `; writes before first use served (no identity record)`. Where the guest device's + identity record keeps one copy, the line is `managed reads on two copies: none counted: the + stream's identity record keeps one copy`. It stops nothing. - After each commit, before each write, check and present, and where the program waited, it waits for every committed command buffer that can complete: one whose event waits are met by values the CPU set or by signals of command buffers that can complete. It never waits on a command buffer @@ -908,7 +929,7 @@ Private bytes the pool keeps, and the bytes of the blocks the backend holds for the stream by class, `shared_block_bytes` and `private_block_bytes`; the old runtime's live memory blocks, empty ones kept and dedicated ones), `devices apart from the guest's: #ID ...` where the stream recorded devices besides the one the -guest makes its objects on (section 4), `check ID SHA256 match|differs|unrecorded|covered|receiver`, `id ID RECORDED PLAYED` for each object whose runtime +guest makes its objects on (section 4), `check ID frame F SHA256 match|differs|unrecorded|covered|receiver` (`F` the frame it was read in, the presents played before it), `id ID RECORDED PLAYED` for each object whose runtime gives another `gpuResourceID` than the program saw (both in hex, `PLAYED` `none` where the runtime's getter raises), `id ID RECORDED PLAYED word WORD` on the new runtime, which lays its IDs out as [RESOURCE-ID.md](RESOURCE-ID.md) does: there the ID's low word, its index, is compared with @@ -949,7 +970,8 @@ runtime's size for each, met the recorded range of a buffer live in the same hea not a stop; section 5), `relaid HEAPS moved OFFSETS grown BYTES` where it laid placement heaps out again (the heaps, the offsets it moved in them and the bytes it added to their sizes), `texture_writes ...` (the -CPU's writes into Managed textures, below), `total COUNTS` (its `calls` the +CPU's writes into Managed textures, above), `managed reads on two copies: ...` (the reads of +Managed bytes no announcement took to the GPU copy, above), `total COUNTS` (its `calls` the calls played: where the play stopped, the stopping call is the next), the new runtime's backend's `pipeline I wall_nanos=N kernel=new|again` for each compute pipeline state it made, in order (the @@ -1015,3 +1037,30 @@ Its exit status is 0 for `agree`, 1 for `DIFFER` and 2 for a bad command line or dump. This compare says whether two plays of a range of command buffers agree; a whole-object checksum does not, as a buffer partly under a cover would differ under it and a difference outside the cover would show only as the same mismatch. + +**Two plays compared for a timing verdict.** `command-replay compare-plays --a REPORT --b REPORT +[--frame F]` reads two plays' reports (each a `report.txt` or the directory holding it), of one +stream on two runtimes or two commits, and prints `served a|b: yes`, or `no: ...` for a report +without the `managed reads` line; `frames a N b M; both B; counts equal in E, unequal in U` and +`unequal frame F: KEY a=X b=Y` for the first eight frames whose player-side counts differ (the +frame line's `stream` `calls`, `draws` and `dispatches`, and every `executed` count of a skip, +`skipped_…`, or a refusal, `…_refusals`; a count a report lacks is 0); `digests: D frames with +checks in both; equal in E, differ in X` and `digests differ at frame F` for the first eight +frames whose `check` lines differ, ending `; stale reads from frame S, the first suspect` where a +play kept two copies and its stale reads start at or before `F`. With `--frame F` it ends with +`verdict at frame F: b is P% faster|slower than a by GPU-busy time (a A ns, b B ns); wall a W ns, +b V ns` (or `level`), or `no verdict at frame F: WHY`. A timing verdict between two plays needs +all three of: + +1. both plays by a player that serves every read class the stream has, which a report shows by + its `managed reads` line: a player that prints none may not serve the made-with reads or, for + a stream with no identity record, the writes before first use; +2. the frame's player-side counts equal in both; +3. equal digests at the judged frame: its `check` lines alike in both. A frame with no check in + both plays gets no verdict until a play adds one. + +Stale reads bar no verdict: Metal leaves those bytes undefined and both runtimes play them by one +rule. Where the digests differ, they are the first suspect, as the old runtime takes a no-copy +buffer's copy in at its making later than the new runtime does. The exit status is 0 where the +frame `--frame` names has a verdict (or none is named), 1 where it has none and 2 for a bad +command line or an unreadable report.