player: a two-copy stream's Managed buffers start their GPU copy from the bytes they were made with

docs/REPLAY-STREAM.md says a Managed buffer that plays with two copies has
a GPU copy that starts from the bytes it was made with: a copied buffer's
contents, or a no-copy one's bytes at its making. Neither backend did so.
The player stripped every newBufferWithDescriptor: descriptor's contents
before the backend's making and wrote them afterwards as a CPU write. So
the new runtime's new_buffer, written to take them, never got them, and the
old backend made every such buffer zeroed. Under two copies neither GPU
copy held the bytes, and a draw reading the buffer before any
didModifyRange: read zeros where the recording's GPU read the bytes.

This changes the new runtime's plays too, not only the old runtime's. The
player now passes the descriptor to the backend with its contents and still
writes them once the buffer is made. The new runtime's backend takes them
as it was written to. The old backend's making takes them, both a
descriptor's contents and newBufferWithBytesNoCopy's pages. Where the buffer
plays as the runtime's Managed buffer, it writes them and announces them
(didModifyRange: over them).

Found by synthetic streams of our own on the RX 550 (m3-max-53813): under
a two-copy identity record, a no-copy and a copied Managed buffer made with
7s read zeros through a blit on both backends. The GPU-free count has the
recordings this touches: glbench-3090-r2, r3 and r4, gb-3090-r3, r4 and r5,
web3d-3090-r2 and r3, nvdec-3090 and nvdec-3090-wd.

Tests: a_two_copy_stream_s_managed_buffers_start_from_the_bytes_they_were_
made_with, in rt_replay (new runtime) and replay_streams (old runtime). Both
play one stream, rt_replay::made_with. They fail without the fix on a
device that keeps two copies.
This commit is contained in:
Anees Iqbal committed 2026-11-19 12:31:16 -08:00
1 parent 54d43118a9
commit d88af7befe
6 files changed
+188 -52

No files matched your search

@@ -117,14 +117,14 @@ pub(super) fn texture(call: &Call, f: &Fields, d: &mut TextureDescriptor) -> Res
Ok(())
}
/// `newBufferWithDescriptor:`: the buffer's length and options. Its host memory reaches it nil: a
/// copied buffer's `contents` the player writes once the buffer is made, a no-copy buffer's bytes
/// arrive as `m2v.write`, and the pinned address is the recorded one the call answers, where the
/// backend makes the buffer (`address_placement`). A
/// `newBufferWithDescriptor:`: the buffer's length, options and the bytes it was made with (its
/// `contents`, empty where the stream gives none), which the player also writes once the buffer
/// is made; a no-copy buffer's later bytes arrive as `m2v.write`, and the pinned address is the
/// recorded one the call answers, where the backend makes the buffer (`address_placement`). A
/// no-copy buffer is played as a buffer of its length, so one of the read-only option
/// (`ResourceOptions::PRIVATE_BIT`) is made without it: its GPU writes, which Metal drops, are
/// kept.
pub(super) fn buffer(call: &Call) -> Result<(u64, ResourceOptions), PlayError> {
pub(super) fn buffer(call: &Call) -> Result<(u64, ResourceOptions, &[u8]), PlayError> {
let f = Fields::arg(
call,
0,
@@ -138,15 +138,23 @@ pub(super) fn buffer(call: &Call) -> Result<(u64, ResourceOptions), PlayError> {
"zeroFrom",
],
)?;
if f.get("contents").is_some() {
return Err(refuse(call, "contents that are no bytes"));
}
// The bytes it was made with, where the stream gives them (`docs/REPLAY-STREAM.md`, section 5).
let contents = match f.get("contents") {
None => &[][..],
Some(value) => {
(value.as_bytes()).ok_or_else(|| refuse(call, "contents that are no bytes"))?
}
};
let sets = f.list("options")?.unwrap_or_default();
let mut raw = option_sets(call, 0, sets)?;
if f.bool("noCopy")? == Some(true) {
raw &= !ResourceOptions::PRIVATE_BIT;
}
Ok((f.required("length", Fields::uint)?, options(call, raw)?))
Ok((
f.required("length", Fields::uint)?,
options(call, raw)?,
contents,
))
}
/// `newHeapWithDescriptor:`: Metal's new heap descriptor holds `Private` storage.
@@ -157,6 +157,47 @@ fn placed(
Ok(addressed(buffer.map_err(unplaced(call, at))?))
}
/// `made`, a buffer of `options` that `call` made, holding `bytes` from its first byte, the bytes
/// the stream says it was made with (a descriptor's `contents`, a no-copy buffer's pages): where it
/// plays as the runtime's Managed buffer, its GPU copy starts from them too, as Metal makes it
/// where the device keeps two copies (`docs/REPLAY-STREAM.md`, Managed buffers). The player writes
/// them again once the buffer is made, which changes nothing.
fn made_with(
call: &Call,
made: (Object, Made),
options: ResourceOptions,
bytes: &[u8],
) -> Result<(Object, Made), PlayError> {
let (Object::Buffer(buffer), _) = &made else {
unreachable!("a buffer maker's object");
};
if bytes.is_empty() || options.storage_mode() != Ok(StorageMode::Managed) {
return Ok(made);
}
write_into(buffer, 0, bytes).map_err(|why| refuse(call, why))?;
let end = bytes.len() as u64;
buffer.did_modify_range(0..end).map_err(failed(call))?;
Ok(made)
}
/// `bytes` into `buffer`'s CPU-visible bytes at `offset`; why not, where they do not fit.
fn write_into(buffer: &Buffer, offset: u64, bytes: &[u8]) -> Result<(), String> {
let fits = offset
.checked_add(bytes.len() as u64)
.is_some_and(|end| end <= buffer.length());
let contents = (buffer.contents().filter(|_| fits)).ok_or("bytes past its CPU-visible ones")?;
// SAFETY: `[offset, offset + len)` lies in the buffer's mapped bytes, and the player waited
// for every command buffer that can complete before writing.
unsafe {
std::ptr::copy_nonoverlapping(
bytes.as_ptr(),
contents.as_ptr().add(offset as usize),
bytes.len(),
);
}
Ok(())
}
/// A buffer of the player's own (a staging copy, a read-back), `length` bytes of `contents`:
/// outside the space, so that no recorded address can meet it.
pub(super) fn own_buffer(
@@ -385,7 +426,10 @@ impl OldRuntime {
// Played as a buffer of its length: without the read-only option (`buffer`).
let options = options(call, uint(call, 2)? & !ResourceOptions::PRIVATE_BIT)?;
let options = self.played(call, options)?;
placed(device, call, uint(call, 1)?, options, BufferContents::Zero)?
let made = placed(device, call, uint(call, 1)?, options, BufferContents::Zero)?;
// The pages' bytes at its making, where the stream gives them.
let bytes = arg(call, 0)?.as_bytes().unwrap_or_default();
made_with(call, made, options, bytes)?
}
"newBufferWithBytes:length:options:" => {
let bytes = data(call, 0)?;
@@ -398,9 +442,10 @@ impl OldRuntime {
placed(device, call, length, options, BufferContents::Copy(bytes))?
}
"newBufferWithDescriptor:" => {
let (length, options) = descriptors::buffer(call)?;
let (length, options, contents) = descriptors::buffer(call)?;
let options = self.played(call, options)?;
placed(device, call, length, options, BufferContents::Zero)?
let made = placed(device, call, length, options, BufferContents::Zero)?;
made_with(call, made, options, contents)?
}
"m2v.newBlockWithLength:storageMode:" => {
let length = uint(call, 0)?;
@@ -991,22 +1036,11 @@ impl Backend for OldRuntime {
)))
}
};
let fits = offset
.checked_add(bytes.len() as u64)
.is_some_and(|end| end <= buffer.length());
let contents = buffer.contents().filter(|_| fits).ok_or_else(|| {
PlayError::Invalid(format!("m2v.write past #{target}'s CPU-visible bytes"))
})?;
// SAFETY: `[offset, offset + len)` lies in the buffer's mapped bytes, and the player waited
// for every command buffer that can complete before writing.
unsafe {
std::ptr::copy_nonoverlapping(
bytes.as_ptr(),
contents.as_ptr().add(offset as usize),
bytes.len(),
);
}
Ok(())
write_into(buffer, offset, bytes).map_err(|why| {
PlayError::Invalid(format!(
"m2v.write past #{target}'s CPU-visible bytes: {why}"
))
})
}
fn wait(&mut self, command_buffer: u64) -> Result<(), PlayError> {
@@ -1135,23 +1135,14 @@ fn cut(call: &Call) -> Result<bool, PlayError> {
}
}
/// `descriptor`, a `newBufferWithDescriptor:` map, with its `contents` nil, and the bytes they
/// held: what a buffer made as a copy of host memory starts with, which the player writes once the
/// buffer is made (`docs/REPLAY-STREAM.md`, section 5).
fn copied(descriptor: Value) -> (Value, Option<Vec<u8>>) {
let Value::Map(fields) = descriptor else {
return (descriptor, None);
};
let mut contents = None;
let fields = fields.into_iter().map(|(key, value)| match value {
Value::Bytes(bytes) if &*key == "contents" => {
contents = Some(bytes);
(key, Value::Nil)
}
value => (key, value),
});
let fields = fields.collect();
(Value::Map(fields), contents)
/// The bytes `descriptor`, a `newBufferWithDescriptor:` map, says the buffer was made with (its
/// `contents`): a copied buffer's, or a no-copy one's at its making. The backend's making takes
/// them with the descriptor, so a buffer that plays with two copies starts its GPU copy from them,
/// and the player writes them once the buffer is made (`docs/REPLAY-STREAM.md`, section 5).
fn copied(descriptor: &Value) -> Option<Vec<u8>> {
let fields = descriptor.as_map()?;
let (_, contents) = fields.iter().find(|(key, _)| &**key == "contents")?;
contents.as_bytes().map(<[u8]>::to_vec)
}
/// Whether a blob of `around` holds as many bytes as its range.
@@ -1857,9 +1848,8 @@ impl<'b, B: Backend> Player<'b, B> {
let arg = self.resolve(stream, arg, &mut relocated)?;
let arg = match (at, &*call.selector) {
(0, "newBufferWithDescriptor:") => {
let (descriptor, bytes) = copied(arg);
contents = bytes;
descriptor
contents = copied(&arg);
arg
}
_ => arg,
};
@@ -23,6 +23,9 @@
//! - A one-copy stream's Managed buffer plays as Shared: a CPU write with no `didModifyRange:`
//! reaches a blit's read of it, on a device that keeps Managed buffers in two copies as on one
//! that keeps one.
//! - A two-copy stream's Managed buffers start their GPU copies from the bytes they were made with
//! (`rt_replay::made_with`): a no-copy descriptor buffer and a copied one read through a blit as
//! the bytes each was made with, on a device that keeps two copies as on one that keeps one.
//! - A buffer made as a copy of host memory starts with its contents, and the IDs the program saw
//! are compared with the runtime's.
//! - A texture its descriptor marks `outside` takes none of the program's IDs.
@@ -43,7 +46,7 @@
//! their own beside the stream's.
use super::host_memory::on_device_with;
use super::rt_replay::library_of;
use super::rt_replay::{library_of, made_with};
use super::{at_plan, public_case};
use crate::replay::{
Backend, OldRuntime, PlayError, Player, Report, StreamReader, StreamWriter, Value,
@@ -1726,3 +1729,28 @@ fn a_one_copy_stream_s_managed_buffer_plays_as_shared() {
assert!(lines.iter().any(|l| l == managed), "{lines:?}");
});
}
/// `rt_replay::made_with`'s stream on the old runtime: both Managed buffers' GPU copies start from
/// the bytes they were made with, and the report says two copies, from the stream's identity.
#[test]
fn a_two_copy_stream_s_managed_buffers_start_from_the_bytes_they_were_made_with() {
let dir = ScratchDir::new("replay-made-with").unwrap();
let path = written(&dir, made_with);
on_device_with(at_plan, |device| {
let mut backend = OldRuntime::new(device.clone(), crate::gpu::TEST_DEVICE);
let mut reader = StreamReader::open(std::slice::from_ref(&path), None).unwrap();
let (report, ended) = Player::new(&mut backend).play(&mut reader);
let lines = backend.lines();
for line in report.lines().iter().chain(&lines) {
eprintln!("REPLAY made-with {} {line}", device.name());
}
ended.unwrap();
assert_eq!(report.checks.len(), 2);
for check in &report.checks {
let object = check.object;
assert_eq!(Some(check.sha256), check.recorded, "#{object}'s GPU copy");
}
let managed = "managed two copies (the stream's device identity): played as recorded";
assert!(lines.iter().any(|l| l == managed), "{lines:?}");
});
}
@@ -27,6 +27,10 @@
//! own second copy where the device has one): a blit's fill reaches the GPU's copy and not the
//! CPU's, an announcement with no write puts the CPU's bytes back into the GPU's copy at the next
//! commit, and a synchronize brings the GPU's bytes into the CPU's copy.
//! - A two-copy stream's Managed buffers start their GPU copies from the bytes they were made with:
//! a no-copy descriptor buffer and a copied one, each made with 7s and written 7s before its
//! first use with no `didModifyRange:`, read as 7s through a blit (on the old runtime too,
//! `replay_streams`).
//! - A Private buffer, which has no CPU mapping, reads back through a copy into a Shared buffer of
//! the play's own: a blit's fill of it reads as the fill's bytes.
//! - In a stream whose header marks its announced bytes recorded, an announcement after a
@@ -2344,3 +2348,71 @@ fn a_copy_from_the_guest_s_ram_plays_as_a_cpu_gather_then_one_copy() {
assert_eq!(executed["guest_ram_fill_copies"], 1 + 2);
assert_eq!(executed["guest_ram_fill_bytes"], 16 + 4 + 8);
}
/// A stream recorded with two copies (`hasUnifiedMemory` false), with Managed #3, a no-copy
/// descriptor buffer, and Managed #5, a copied one, 4 bytes each, made with `[7; 4]` and
/// `[9; 4]` (their descriptors' `contents`) and written so before their first use with no
/// `didModifyRange:`, as a recorder writes every buffer's bytes before its first use; a blit
/// copies each into Shared #4 and #6, which a check reads as the bytes each was made with: the
/// recording device's GPU copy started from them.
pub(super) fn made_with(w: &mut StreamWriter<File>) -> std::io::Result<()> {
w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?;
let identity = [("hasUnifiedMemory", Value::Bool(false))];
w.call("m2v.deviceIdentity", 1, 0, &[], &identity)?;
w.call("newCommandQueue", 1, 2, &[], &[])?;
let managed = Value::List(vec![Value::Map(vec![(
"ResourceOptions".into(),
Value::Uint(16),
)])]);
let copy_from = "copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:";
let mut sums = Vec::new();
w.call("commandBuffer", 2, 10, &[], &[])?;
for (id, no_copy, byte) in [(3, true, 7u8), (5, false, 9)] {
let bytes = vec![byte; 4];
let descriptor = Value::Map(vec![
("length".into(), Value::Uint(4)),
("options".into(), managed.clone()),
("contents".into(), Value::Bytes(bytes.clone())),
("noCopy".into(), Value::Bool(no_copy)),
]);
w.call("newBufferWithDescriptor:", 1, id, &[descriptor], &[])?;
let shared = [Value::Uint(4), Value::Uint(0)];
w.call("newBufferWithLength:options:", 1, id + 1, &shared, &[])?;
let pairs = [Value::Uint(0), Value::Bytes(bytes.clone())];
w.call("m2v.write", id, 0, &pairs, &[])?;
let encoder = 10 + id;
w.call("blitCommandEncoder", 10, encoder, &[], &[])?;
let (zero, four) = (Value::Uint(0), Value::Uint(4));
let copy = [
Value::Object(id),
zero.clone(),
Value::Object(id + 1),
zero,
four,
];
w.call(copy_from, encoder, 0, &copy, &[])?;
w.call("endEncoding", encoder, 0, &[], &[])?;
sums.push(Value::Bytes(Sha256::digest(&bytes).to_vec()));
}
w.call("commit", 10, 0, &[], &[])?;
w.call(WAIT_COMPLETED, 10, 0, &[], &[])?;
let answer = [("sha256", Value::List(sums))];
let checked = [Value::Object(4), Value::Object(6)];
w.call("m2v.check", 0, 0, &checked, &answer)
}
#[test]
fn a_two_copy_stream_s_managed_buffers_start_from_the_bytes_they_were_made_with() {
let dir = ScratchDir::new("rt-replay-made-with").unwrap();
let path = written(&dir, made_with);
let (report, lines) = play("made-with", &path);
assert_eq!(report.checks.len(), 2);
for check in &report.checks {
let object = check.object;
assert_eq!(Some(check.sha256), check.recorded, "#{object}'s GPU copy");
}
let managed = "managed two copies (the stream's device identity): 2 Managed buffers; 0 \
no-copy ones with contents from first use, not from create";
// A device with unified memory adds that it played the two copies as its one.
assert!(lines.iter().any(|l| l.starts_with(managed)), "{lines:?}");
}
+7 -3
View File
@@ -542,7 +542,9 @@ counted from 0), completes the work committed so far, reports as at the stream's
the play with an error that says so. One copy: every Managed buffer plays as a Shared buffer, on
every device. Two copies: it plays as the runtime's Managed buffer, whose GPU copy starts from
the bytes it was made with: a copied buffer's bytes, or a no-copy one's bytes at its making
(section 5). A stream with no identity record gives a no-copy buffer none, so its GPU copy takes
(section 5), which the backend's making takes from the call (a descriptor's `contents`, the
pages `newBufferWithBytesNoCopy:length:options:deallocator:` holds) and the player writes again
once the buffer is made. A stream with no identity record gives a no-copy buffer none, so its GPU copy takes
the writes recorded before its first use (a commit of a command buffer one of whose encoders
names it), the nearest record the stream has of its bytes at its making. Where the device keeps
a GPU copy, the player places it as it places a Private buffer of the buffer's length (below), a
@@ -554,8 +556,10 @@ counted from 0), completes the work committed so far, reports as at the stream's
record (or `--managed one-copy`), every Managed buffer and block plays as a Shared one, so a CPU
write reaches the GPU as it reached the recording device's, with or without a
`didModifyRange:`. Otherwise a Managed buffer plays as the old runtime's, which keeps a GPU copy
on a device without unified memory. Its report's `managed` line says which form played, from
what, and counts the buffers and blocks played as Shared.
on a device without unified memory, and that copy starts from the bytes the buffer was made
with, as on the new runtime: the backend's making takes them from the call and announces them
(`didModifyRange:` over them). Its report's `managed` line says which form played, from what,
and counts the buffers and blocks played as Shared.
- **No-copy buffers** (the new runtime) play as the product makes them, by creator:
- A `newBufferWithDescriptor:` with `noCopy` is a pool buffer in the product: a guest buffer's
storage in one of the host's blocks. Where its recorded address and length lie inside a live