Replay player: a play's pipeline state makes are written as they happen, on its own threads where asked
WIP: compile check pending.
This commit is contained in:
1 parent
a677cb74b3
commit
00cef89ec5
5 files changed
+671
-11
No files matched your search
@@ -3,7 +3,8 @@
|
||||
//!
|
||||
//! `command-replay play --stream FILE --out DIR --device-type cpu|gpu --shader-cache DIR
|
||||
//! [--blobs DIR] [--managed one-copy|two-copy]
|
||||
//! [--until-frame F] [--past-range yes|no] [--states-only yes|no] [--gpu-wait-timeout SECONDS]
|
||||
//! [--until-frame F] [--past-range yes|no] [--states-only yes|no] [--state-log FILE]
|
||||
//! [--state-threads N] [--state-keys KEY,...] [--gpu-wait-timeout SECONDS]
|
||||
//! [--video-handle dma-buf|opaque-fd|opaque-win32] [--check-presents F,...]` plays the stream
|
||||
//! whose first segment is `FILE` through the runtime (with `--states-only yes`, its device,
|
||||
//! library, function and pipeline state records and its presents alone, every other call passed
|
||||
@@ -49,6 +50,25 @@
|
||||
//! a harness failure (a bad command line, no device, an unreadable stream or sidecar) and 3 for
|
||||
//! `ids`.
|
||||
//!
|
||||
//! With `--state-log FILE`, each pipeline state's make is written as it happens, for a driver that
|
||||
//! ends the process inside one: `M2V-STATE begin SEQ THREAD WHAT` before its first driver call,
|
||||
//! `M2V-STATE modules SEQ THREAD` once its shader modules are made and before its `VkPipeline` is,
|
||||
//! and `M2V-STATE end SEQ THREAD made in MS ms|refused ERROR|failed ERROR` after, each line
|
||||
//! flushed to the standard output and to `FILE` as it is written, so the last `begin` with no
|
||||
//! `end` names the make a crash ended and its `modules` line, or none, which of the two calls. A
|
||||
//! render state's `WHAT` is `render #OBJECT call POSITION key KEY colors [F, ...] depth F stencil F
|
||||
//! samples N fragment true|false`: `KEY` is the hex of the translator's key of its descriptor, the
|
||||
//! name of its content's record under `renders/` in the cache directory, and `F` are raw
|
||||
//! `MTLPixelFormat` values, 0 for none; a compute state's is `compute #OBJECT call POSITION`. In a
|
||||
//! states-only play, `--state-threads N` (0 unless it says otherwise) has `N` threads of the
|
||||
//! player's own make the states, at once, through the device's one pipeline cache, as a
|
||||
//! consumer's compile threads do (their lines go to the standard output where no `--state-log`
|
||||
//! names a file), and `--state-keys KEY,...` makes only the render states of those contents and
|
||||
//! passes over every other state, each named on a `M2V-STATE pass WHAT` line. The report's
|
||||
//! `states` line counts the makes begun and how they ended, and the states passed over; pooled or
|
||||
//! passed over, a state plays as a skipped object, which a states-only play binds nowhere, so its
|
||||
//! `render states made` count leaves them out.
|
||||
//!
|
||||
//! With `--dump-command-buffers FIRST..LAST --dump-dir DIR`, the play also writes into `DIR`, once
|
||||
//! each command buffer whose stream id lies in `FIRST..=LAST` completed, every buffer its encoders
|
||||
//! named, with the ranges of it the cover rule held covered then (`docs/REPLAY-STREAM.md`, section
|
||||
@@ -89,7 +109,7 @@ use metal2vulkan_validation::replay::{
|
||||
RecordingRange, StreamError, StreamReader, Value, VideoHandle, FLAG_COMPLETION_BYTES_RECORDED,
|
||||
RECORDED_RANGES,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::io::Write as _;
|
||||
use std::ops::RangeInclusive;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -97,7 +117,8 @@ use std::path::{Path, PathBuf};
|
||||
const USAGE: &str = "usage: command-replay play --stream FILE --out DIR --device-type cpu|gpu \
|
||||
--shader-cache DIR [--blobs DIR] \
|
||||
[--managed one-copy|two-copy] [--until-frame F] [--past-range yes|no] \
|
||||
[--states-only yes|no] [--gpu-wait-timeout SECONDS] [--video-handle dma-buf|opaque-fd|opaque-win32] \
|
||||
[--states-only yes|no] [--state-log FILE] [--state-threads N] \
|
||||
[--state-keys KEY,...] [--gpu-wait-timeout SECONDS] [--video-handle dma-buf|opaque-fd|opaque-win32] \
|
||||
[--check-presents F,...] [--read-device-copies yes|no] [--prepass-width N] \
|
||||
[--dump-command-buffers FIRST..LAST --dump-dir DIR]\n \
|
||||
command-replay compare-dumps --a DIR --b DIR\n \
|
||||
@@ -409,6 +430,13 @@ fn play(options: &BTreeMap<String, String>) -> i32 {
|
||||
}
|
||||
};
|
||||
report.line(mode_line(states_only));
|
||||
let (state_log, state_threads, state_keys) = match state_options(options, states_only) {
|
||||
Ok(states) => states,
|
||||
Err(why) => {
|
||||
report.line(&format!("error {why}"));
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let mut reader = match reader(options) {
|
||||
Ok(reader) => reader,
|
||||
Err(error) => {
|
||||
@@ -582,6 +610,22 @@ fn play(options: &BTreeMap<String, String>) -> i32 {
|
||||
None => backend,
|
||||
};
|
||||
let backend = backend.with_video_handle(video);
|
||||
if state_log.is_some() || state_threads > 0 || state_keys.is_some() {
|
||||
report.line(&format!(
|
||||
"state makes on {}, {}",
|
||||
match state_threads {
|
||||
0 => "the play's thread".to_owned(),
|
||||
n => format!("{n} threads"),
|
||||
},
|
||||
state_keys
|
||||
.as_ref()
|
||||
.map_or("every state made".to_owned(), |keys| format!(
|
||||
"only the render states of {} listed keys made",
|
||||
keys.len()
|
||||
)),
|
||||
));
|
||||
}
|
||||
let backend = backend.with_states(state_log, state_threads, state_keys);
|
||||
let backend = backend.with_prepass(prepass.unwrap_or(4));
|
||||
report.line(&format!("prepass width {}", backend.prepass_width()));
|
||||
match display {
|
||||
@@ -619,6 +663,42 @@ fn play(options: &BTreeMap<String, String>) -> i32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// The play's state options: the state log `--state-log` names, made; the threads of
|
||||
/// `--state-threads`, 0 where it names none; and the keys of `--state-keys`, each 64 hex digits.
|
||||
/// The threads and the keys need a states-only play, which binds no state.
|
||||
fn state_options(
|
||||
options: &BTreeMap<String, String>,
|
||||
states_only: bool,
|
||||
) -> Result<(Option<std::fs::File>, usize, Option<HashSet<String>>), String> {
|
||||
let threads = match options.get("state-threads").map(|n| n.parse::<usize>()) {
|
||||
None => 0,
|
||||
Some(Ok(threads)) => threads,
|
||||
Some(Err(_)) => return Err("state-threads: not a count of threads".to_owned()),
|
||||
};
|
||||
let keys = match options.get("state-keys") {
|
||||
None => None,
|
||||
Some(listed) => {
|
||||
let keys: HashSet<String> = (listed.split(',')).map(str::to_ascii_lowercase).collect();
|
||||
let hex = |key: &String| key.len() == 64 && key.bytes().all(|b| b.is_ascii_hexdigit());
|
||||
if let Some(bad) = keys.iter().find(|key| !hex(key)) {
|
||||
return Err(format!("state-keys: {bad} is no key of 64 hex digits"));
|
||||
}
|
||||
Some(keys)
|
||||
}
|
||||
};
|
||||
if (threads > 0 || keys.is_some()) && !states_only {
|
||||
return Err("state-threads and state-keys: they need --states-only yes".to_owned());
|
||||
}
|
||||
let log = match options.get("state-log") {
|
||||
None => None,
|
||||
Some(path) => match std::fs::File::create(path) {
|
||||
Ok(file) => Some(file),
|
||||
Err(error) => return Err(format!("state-log: {path}: {error}")),
|
||||
},
|
||||
};
|
||||
Ok((log, threads, keys))
|
||||
}
|
||||
|
||||
/// The runtime's backend on the first physical device of `device_type` that opens (a GPU:
|
||||
/// discrete, then integrated, then virtual), its compiled kernels kept in `cache`, and its name.
|
||||
/// A GPU opens only while the hang tripwire is absent.
|
||||
|
||||
@@ -21,6 +21,7 @@ pub(super) mod places;
|
||||
mod prepass;
|
||||
mod render;
|
||||
pub(super) mod second;
|
||||
mod states;
|
||||
mod surfaces;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -630,6 +631,8 @@ pub struct NewRuntime {
|
||||
/// The runtime's stage histograms as each frame ended, read as the next frame's first call
|
||||
/// is located (`Backend::locate`): the report's `stages` lines.
|
||||
frame_stages: Vec<Stages>,
|
||||
/// The pipeline state makes' lines, their pool and the keys made alone (`with_states`).
|
||||
states: states::States,
|
||||
/// The device's `minImportedHostPointerAlignment`, where it imports host memory: the
|
||||
/// alignment of the host pages a no-copy buffer's memory is imported from (`imports`).
|
||||
host_alignment: Option<u64>,
|
||||
@@ -968,6 +971,7 @@ impl Drop for NewRuntime {
|
||||
/// runtime thread runs on into the process's `exit()`, where the driver tears itself down
|
||||
/// beside it. After [`NewRuntime::end`]'s quiesce, this one answers at once.
|
||||
fn drop(&mut self) {
|
||||
self.states.finish();
|
||||
self.prepass = None;
|
||||
self.device.quiesce(QUIESCE);
|
||||
}
|
||||
@@ -1032,9 +1036,28 @@ impl NewRuntime {
|
||||
kernels: HashSet::new(),
|
||||
makes: makes::Makes::default(),
|
||||
frame_stages: Vec::new(),
|
||||
states: states::States::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The backend whose pipeline state makes are written as they happen (`states`): a begin
|
||||
/// line before each make's first driver call, a modules line before its `VkPipeline`'s, and
|
||||
/// an end line, each flushed to the standard output and to `log`. With `threads` above 0, a
|
||||
/// states-only play's makes go to that many threads of the backend's own, which make them at
|
||||
/// once through the device's one pipeline cache; with 0 each is made on the play's thread.
|
||||
/// With `keys`, only the render states whose content's key (the hex of the translator's key of
|
||||
/// the descriptor, its record's name in the cache directory) is listed are made, and every
|
||||
/// other state is passed over, each named on a pass line.
|
||||
pub fn with_states(
|
||||
mut self,
|
||||
log: Option<std::fs::File>,
|
||||
threads: usize,
|
||||
keys: Option<HashSet<String>>,
|
||||
) -> Self {
|
||||
self.states = states::States::new(log, threads, keys);
|
||||
self
|
||||
}
|
||||
|
||||
/// The backend told how the stream's recording device kept Managed buffers.
|
||||
pub fn with_managed(mut self, copies: ManagedCopies) -> Self {
|
||||
self.managed = Some(copies);
|
||||
@@ -1104,6 +1127,7 @@ impl NewRuntime {
|
||||
/// on an event no played record signals ends unrun), drops every handle the backend holds, the
|
||||
/// device's last among them, and reads the gauges once it is torn down ([`Ended`]).
|
||||
pub fn end(mut self) -> Ended {
|
||||
self.states.finish();
|
||||
self.prepass = None;
|
||||
let counters = self.device.counters();
|
||||
let idle = self.device.quiesce(QUIESCE);
|
||||
@@ -1722,14 +1746,16 @@ impl NewRuntime {
|
||||
|
||||
/// A compute pipeline state of `kernel`, its numbered constexpr samplers at indices of their
|
||||
/// own, the same words at one index, its main pipeline then finished, as a consumer finishes
|
||||
/// it once it has answered.
|
||||
/// it once it has answered; `step` marks the shader modules made before the pipeline.
|
||||
fn compute_pipeline_state(
|
||||
&mut self,
|
||||
descriptor: &rt::ComputePipelineDescriptor,
|
||||
step: &states::Step,
|
||||
) -> Result<rt::ComputePipelineState, rt::Error> {
|
||||
let state = self.numbered(|device, ids| {
|
||||
device.new_compute_pipeline_state(descriptor, |samplers| ids(samplers))
|
||||
})?;
|
||||
step.modules();
|
||||
state.finish_pipeline()?;
|
||||
Ok(state)
|
||||
}
|
||||
@@ -1794,15 +1820,33 @@ impl NewRuntime {
|
||||
|
||||
/// A compute pipeline state of `descriptor`, of `kernel`'s, timed and counted (`creations`);
|
||||
/// skipped and counted where the runtime answers a typed gap or the translator refuses it
|
||||
/// (`compute_states`), so that the play goes on and its dispatches are skipped.
|
||||
/// (`compute_states`), so that the play goes on and its dispatches are skipped. Where the
|
||||
/// makes are pooled or a key list passes it over (`with_states`), it is not made here and
|
||||
/// plays as a skipped object: a states-only play binds no state.
|
||||
fn timed_state(
|
||||
&mut self,
|
||||
call: &Call,
|
||||
descriptor: &rt::ComputePipelineDescriptor,
|
||||
kernel: Kernel,
|
||||
) -> Result<Option<(Object, Made)>, PlayError> {
|
||||
let what = format!("compute #{} call {}", call.result, self.at.1);
|
||||
if !self.states.selects(None, &what) {
|
||||
return unaddressed(Object::Skipped);
|
||||
}
|
||||
if self.states.pooled() {
|
||||
let (device, descriptor) = (self.device.clone(), descriptor.clone());
|
||||
self.states.give(what, move |numbering, step| {
|
||||
let state = device.new_compute_pipeline_state(&descriptor, |s| numbering.ids(s))?;
|
||||
step.modules();
|
||||
state.finish_pipeline()?;
|
||||
Ok(states::Kept::Compute(state))
|
||||
});
|
||||
return unaddressed(Object::Skipped);
|
||||
}
|
||||
let mark = makes::Mark::new(&self.device, self.prepass.as_ref());
|
||||
let state = match self.compute_pipeline_state(descriptor) {
|
||||
let inline = self.states.inline();
|
||||
let made = inline.run(&what, |step| self.compute_pipeline_state(descriptor, step));
|
||||
let state = match made {
|
||||
Ok(state) => {
|
||||
self.skips.states_made[1] += 1;
|
||||
state
|
||||
@@ -3239,13 +3283,16 @@ impl Backend for NewRuntime {
|
||||
}
|
||||
|
||||
/// A `pipeline I wall_nanos=N kernel=new|again` line for each compute pipeline state made, in
|
||||
/// order: its making's wall time, and whether its kernel was new to the play.
|
||||
/// order: its making's wall time, and whether its kernel was new to the play. Where the makes
|
||||
/// were written or pooled (`with_states`), the `states` line after the pool made every state
|
||||
/// queued.
|
||||
fn lines(&self) -> Vec<String> {
|
||||
let lines = self.creations.iter().enumerate().map(|(at, made)| {
|
||||
let kernel = if made.new_kernel { "new" } else { "again" };
|
||||
format!("pipeline {at} wall_nanos={} kernel={kernel}", made.nanos)
|
||||
});
|
||||
let mut lines: Vec<String> = lines.collect();
|
||||
lines.extend(self.states.line());
|
||||
// A maximum since the device was made: it does not sum, so it is not a frame's counter.
|
||||
let metrics = self.device.counters().metrics();
|
||||
let longest = metrics.commit_lock_wait_max_nanos;
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
use super::super::args::{arg, data, index, list, metal, refuse, uint, Fields};
|
||||
use super::super::translator::{self, attachment_keys, LINKED_KEYS, PASS_KEYS};
|
||||
use super::encoders::first;
|
||||
use super::{failed, makes, unaddressed, NewRuntime, Object, Skips};
|
||||
use super::{failed, makes, states, unaddressed, NewRuntime, Object, Skips};
|
||||
use crate::replay::player::{Made, PlayError};
|
||||
use crate::replay::stream::Call;
|
||||
use crate::replay::value::Value;
|
||||
@@ -290,12 +290,33 @@ impl NewRuntime {
|
||||
function.descriptor.with_linked(linked),
|
||||
)))
|
||||
})?;
|
||||
// Where the makes are pooled or a key list passes it over (`with_states`), the state is
|
||||
// not made here and plays as a skipped object: a states-only play binds no state.
|
||||
let (key, what) = states::render_line(&self.device, &descriptor, call.result, self.at.1);
|
||||
if !self.states.selects(Some(&key), &what) {
|
||||
return unaddressed(Object::Skipped);
|
||||
}
|
||||
if self.states.pooled() {
|
||||
let device = self.device.clone();
|
||||
self.states.give(what, move |numbering, step| {
|
||||
let state = device.new_render_pipeline_state(&descriptor, |s| numbering.ids(s))?;
|
||||
step.modules();
|
||||
state.finish_pipeline()?;
|
||||
Ok(states::Kept::Render(state))
|
||||
});
|
||||
return unaddressed(Object::Skipped);
|
||||
}
|
||||
let mark = makes::Mark::new(&self.device, self.prepass.as_ref());
|
||||
// Its main pipelines finished, as a consumer finishes them once it has answered.
|
||||
let made = self.numbered(|device, ids| {
|
||||
device.new_render_pipeline_state(&descriptor, |samplers| ids(samplers))
|
||||
let inline = self.states.inline();
|
||||
let made = inline.run(&what, |step| {
|
||||
let state = self.numbered(|device, ids| {
|
||||
device.new_render_pipeline_state(&descriptor, |samplers| ids(samplers))
|
||||
})?;
|
||||
step.modules();
|
||||
state.finish_pipeline()?;
|
||||
Ok(state)
|
||||
});
|
||||
let made = made.and_then(|state| state.finish_pipeline().map(|()| state));
|
||||
match made {
|
||||
Ok(state) => {
|
||||
let (device, prepass) = (&self.device, self.prepass.as_ref());
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
//! The pipeline state makes of a play, written as they happen, for a driver that ends the process
|
||||
//! inside a make: with a state log (`NewRuntime::with_states`), each make writes a `M2V-STATE begin` line
|
||||
//! before its first driver call, a `M2V-STATE modules` line once its shader modules are made and
|
||||
//! before its `VkPipeline` is, and a `M2V-STATE end` line after, each written and flushed to the
|
||||
//! standard output and to the log as it happens. So the last `begin` with no `end` names the make
|
||||
//! a crash ended, and its `modules` line, or none, says which of the two driver calls ended it.
|
||||
//!
|
||||
//! A states-only play's makes can go to a pool of the player's own threads (`with_states`),
|
||||
//! which make them at once through the device's one pipeline cache, as a consumer's compile
|
||||
//! threads do; the runtime's reaper reads the cache between them as it does for any consumer.
|
||||
//! Without the pool each state is made on the play's thread, one after another. A list of render
|
||||
//! contents' keys (the hex of the translator's key of each descriptor, the name of its record in
|
||||
//! the cache directory) makes those states alone and passes over every other state, each named on
|
||||
//! a `M2V-STATE pass` line.
|
||||
|
||||
use super::rt;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::sync::atomic::{AtomicU64, Ordering::SeqCst};
|
||||
use std::sync::mpsc::{channel, Sender};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::Instant;
|
||||
|
||||
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
mutex.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// A state a pooled make kept, which lives until the pool ends, as a program's states live.
|
||||
pub(super) enum Kept {
|
||||
Render(rt::RenderPipelineState),
|
||||
Compute(rt::ComputePipelineState),
|
||||
}
|
||||
|
||||
/// A make the pool runs: its state's line, and the make, given the pool's sampler numbering and
|
||||
/// the make's step marks.
|
||||
type Job = (
|
||||
String,
|
||||
Box<dyn FnOnce(&Numbering, &Step) -> Result<Kept, rt::Error> + Send>,
|
||||
);
|
||||
|
||||
/// Where the lines go: the standard output and the state log, each line flushed as it is written;
|
||||
/// nowhere without a log or a pool.
|
||||
struct Log {
|
||||
on: bool,
|
||||
file: Mutex<Option<File>>,
|
||||
}
|
||||
|
||||
impl Log {
|
||||
fn line(&self, line: &str) {
|
||||
if !self.on {
|
||||
return;
|
||||
}
|
||||
let mut out = std::io::stdout().lock();
|
||||
let _ = writeln!(out, "{line}");
|
||||
let _ = out.flush();
|
||||
if let Some(file) = lock(&self.file).as_mut() {
|
||||
let _ = writeln!(file, "{line}");
|
||||
let _ = file.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The makes begun, and how those that ended ended: made, refused (the runtime's or the
|
||||
/// translator's typed answer) or failed (a Vulkan call's error).
|
||||
#[derive(Default)]
|
||||
struct Tally {
|
||||
begun: AtomicU64,
|
||||
made: AtomicU64,
|
||||
refused: AtomicU64,
|
||||
failed: AtomicU64,
|
||||
passed: AtomicU64,
|
||||
}
|
||||
|
||||
/// One make's marks: its sequence number in the play and its thread's name.
|
||||
pub(super) struct Step<'a> {
|
||||
log: &'a Log,
|
||||
seq: u64,
|
||||
thread: String,
|
||||
}
|
||||
|
||||
impl Step<'_> {
|
||||
/// The make's shader modules are made, and its `VkPipeline` is made next.
|
||||
pub(super) fn modules(&self) {
|
||||
let (seq, thread) = (self.seq, &self.thread);
|
||||
self.log.line(&format!("M2V-STATE modules {seq} {thread}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The constexpr samplers' indices of the pool's makes: one index for equal words, each new one
|
||||
/// the highest of the sampler class not taken yet. A states-only play makes no sampler state, so
|
||||
/// no other object holds one.
|
||||
pub(super) struct Numbering(Mutex<(HashMap<[u64; 2], u32>, u32)>);
|
||||
|
||||
impl Numbering {
|
||||
fn new() -> Numbering {
|
||||
let end = rt::IndexClass::Sampler.range().end;
|
||||
Numbering(Mutex::new((HashMap::new(), end)))
|
||||
}
|
||||
|
||||
/// The index of each of `samplers`, 0 for a texture read's.
|
||||
pub(super) fn ids(&self, samplers: &[rt::NumberedSampler]) -> Result<Vec<u32>, rt::Error> {
|
||||
let mut held = lock(&self.0);
|
||||
let (taken, next) = &mut *held;
|
||||
let mut ids = Vec::with_capacity(samplers.len());
|
||||
for sampler in samplers {
|
||||
let rt::NumberedSampler::Constexpr(words) = sampler else {
|
||||
ids.push(0);
|
||||
continue;
|
||||
};
|
||||
let index = match taken.get(words) {
|
||||
Some(&index) => index,
|
||||
None if *next > rt::IndexClass::Sampler.range().start => {
|
||||
*next -= 1;
|
||||
taken.insert(*words, *next);
|
||||
*next
|
||||
}
|
||||
None => {
|
||||
return Err(rt::Error::Refused(rt::Refusal::IndicesNotGranted {
|
||||
class: rt::IndexClass::Sampler,
|
||||
index: rt::IndexClass::Sampler.range().end,
|
||||
}))
|
||||
}
|
||||
};
|
||||
ids.push(index);
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines, the tally and the order of a play's makes, shared by the play's thread and the
|
||||
/// pool's.
|
||||
struct Shared {
|
||||
log: Log,
|
||||
tally: Tally,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
/// `make` of the state `what`, between its begin and its end lines, on `thread`.
|
||||
fn run<T>(
|
||||
&self,
|
||||
what: &str,
|
||||
thread: String,
|
||||
make: impl FnOnce(&Step) -> Result<T, rt::Error>,
|
||||
) -> Result<T, rt::Error> {
|
||||
let seq = self.tally.begun.fetch_add(1, SeqCst);
|
||||
self.log
|
||||
.line(&format!("M2V-STATE begin {seq} {thread} {what}"));
|
||||
let began = Instant::now();
|
||||
let step = Step {
|
||||
log: &self.log,
|
||||
seq,
|
||||
thread,
|
||||
};
|
||||
let made = make(&step);
|
||||
let ms = began.elapsed().as_secs_f64() * 1e3;
|
||||
let (count, ended) = match &made {
|
||||
Ok(_) => (&self.tally.made, format!("made in {ms:.1} ms")),
|
||||
Err(error @ rt::Error::Vulkan { .. }) => {
|
||||
(&self.tally.failed, format!("failed {error}"))
|
||||
}
|
||||
Err(error) => (&self.tally.refused, format!("refused {error}")),
|
||||
};
|
||||
count.fetch_add(1, SeqCst);
|
||||
let thread = &step.thread;
|
||||
self.log
|
||||
.line(&format!("M2V-STATE end {seq} {thread} {ended}"));
|
||||
made
|
||||
}
|
||||
}
|
||||
|
||||
/// The pool's threads and their queue; its drop makes every make queued, then ends the threads
|
||||
/// and the states they kept.
|
||||
struct Pool {
|
||||
queue: Option<Sender<Job>>,
|
||||
threads: Vec<JoinHandle<()>>,
|
||||
kept: Arc<Mutex<Vec<Kept>>>,
|
||||
}
|
||||
|
||||
impl Pool {
|
||||
fn new(width: usize, shared: &Arc<Shared>) -> Pool {
|
||||
let (queue, jobs) = channel::<Job>();
|
||||
let jobs = Arc::new(Mutex::new(jobs));
|
||||
let numbering = Arc::new(Numbering::new());
|
||||
let kept = Arc::new(Mutex::new(Vec::new()));
|
||||
let threads = (0..width)
|
||||
.filter_map(|at| {
|
||||
let (jobs, shared) = (Arc::clone(&jobs), Arc::clone(shared));
|
||||
let (numbering, kept) = (Arc::clone(&numbering), Arc::clone(&kept));
|
||||
let thread = format!("m2v-state-{at}");
|
||||
let run = {
|
||||
let thread = thread.clone();
|
||||
move || loop {
|
||||
let next = lock(&jobs).recv();
|
||||
let Ok((what, make)) = next else {
|
||||
return;
|
||||
};
|
||||
let made = shared.run(&what, thread.clone(), |step| make(&numbering, step));
|
||||
if let Ok(state) = made {
|
||||
lock(&kept).push(state);
|
||||
}
|
||||
}
|
||||
};
|
||||
std::thread::Builder::new().name(thread).spawn(run).ok()
|
||||
})
|
||||
.collect();
|
||||
Pool {
|
||||
queue: Some(queue),
|
||||
threads,
|
||||
kept,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Pool {
|
||||
fn drop(&mut self) {
|
||||
self.queue = None;
|
||||
for thread in self.threads.drain(..) {
|
||||
let _ = thread.join();
|
||||
}
|
||||
lock(&self.kept).clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// A play's state makes: their lines, their pool where it has one, and the keys it makes alone.
|
||||
pub(super) struct States {
|
||||
shared: Arc<Shared>,
|
||||
pool: Mutex<Option<Pool>>,
|
||||
/// The pool's width, 0 for none.
|
||||
width: usize,
|
||||
keys: Option<HashSet<String>>,
|
||||
}
|
||||
|
||||
impl Default for States {
|
||||
/// No lines, no pool and no key list: each state made on the play's thread, as a play
|
||||
/// without these makes them.
|
||||
fn default() -> States {
|
||||
States::new(None, 0, None)
|
||||
}
|
||||
}
|
||||
|
||||
impl States {
|
||||
/// The makes' lines written to the standard output and to `log`, where a log is given or a
|
||||
/// pool is; the makes run by `width` threads of the player's own, or on the play's thread with
|
||||
/// 0; with `keys`, only the render states of those contents made.
|
||||
pub(super) fn new(log: Option<File>, width: usize, keys: Option<HashSet<String>>) -> States {
|
||||
let shared = Arc::new(Shared {
|
||||
log: Log {
|
||||
on: log.is_some() || width > 0,
|
||||
file: Mutex::new(log),
|
||||
},
|
||||
tally: Tally::default(),
|
||||
});
|
||||
let pool = (width > 0).then(|| Pool::new(width, &shared));
|
||||
States {
|
||||
shared,
|
||||
pool: Mutex::new(pool),
|
||||
width,
|
||||
keys,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the state `what`, a render state of content `key` or a compute state (`None`), is
|
||||
/// made: every state without a key list, a render state of a listed key with one. One that
|
||||
/// is not is named on a `pass` line.
|
||||
pub(super) fn selects(&self, key: Option<&str>, what: &str) -> bool {
|
||||
let selected = match (&self.keys, key) {
|
||||
(None, _) => true,
|
||||
(Some(keys), Some(key)) => keys.contains(key),
|
||||
(Some(_), None) => false,
|
||||
};
|
||||
if !selected {
|
||||
self.shared.tally.passed.fetch_add(1, SeqCst);
|
||||
self.shared.log.line(&format!("M2V-STATE pass {what}"));
|
||||
}
|
||||
selected
|
||||
}
|
||||
|
||||
/// Whether the makes go to the pool.
|
||||
pub(super) fn pooled(&self) -> bool {
|
||||
self.width > 0
|
||||
}
|
||||
|
||||
/// Queues `make` of the state `what` for the pool's next free thread.
|
||||
pub(super) fn give(
|
||||
&self,
|
||||
what: String,
|
||||
make: impl FnOnce(&Numbering, &Step) -> Result<Kept, rt::Error> + Send + 'static,
|
||||
) {
|
||||
if let Some(queue) = lock(&self.pool)
|
||||
.as_ref()
|
||||
.and_then(|pool| pool.queue.as_ref())
|
||||
{
|
||||
let _ = queue.send((what, Box::new(make)));
|
||||
}
|
||||
}
|
||||
|
||||
/// A handle that makes a state on the play's thread between its lines ([`Inline::run`]).
|
||||
pub(super) fn inline(&self) -> Inline {
|
||||
Inline(Arc::clone(&self.shared))
|
||||
}
|
||||
|
||||
/// Ends the pool once it made every state queued, and drops the states it kept.
|
||||
pub(super) fn finish(&self) {
|
||||
drop(lock(&self.pool).take());
|
||||
}
|
||||
|
||||
/// The report's `states` line where the makes were written or pooled: the makes begun and
|
||||
/// how they ended, the states passed over, and the threads that made them. It ends the pool
|
||||
/// first ([`finish`](Self::finish)).
|
||||
pub(super) fn line(&self) -> Option<String> {
|
||||
self.finish();
|
||||
if !self.shared.log.on {
|
||||
return None;
|
||||
}
|
||||
let t = &self.shared.tally;
|
||||
let threads = match self.width {
|
||||
0 => "the play's thread".to_owned(),
|
||||
width => format!("{width} threads"),
|
||||
};
|
||||
Some(format!(
|
||||
"states begun {} made {} refused {} failed {} passed over {} on {threads}",
|
||||
t.begun.load(SeqCst),
|
||||
t.made.load(SeqCst),
|
||||
t.refused.load(SeqCst),
|
||||
t.failed.load(SeqCst),
|
||||
t.passed.load(SeqCst),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// The play's thread's handle on the makes' lines.
|
||||
pub(super) struct Inline(Arc<Shared>);
|
||||
|
||||
impl Inline {
|
||||
/// `make` of the state `what` on the play's thread, between its begin and end lines.
|
||||
pub(super) fn run<T>(
|
||||
&self,
|
||||
what: &str,
|
||||
make: impl FnOnce(&Step) -> Result<T, rt::Error>,
|
||||
) -> Result<T, rt::Error> {
|
||||
self.0.run(what, "play".to_owned(), make)
|
||||
}
|
||||
}
|
||||
|
||||
/// The line of the render state that `call` (object `object`, at stream position `at`) makes of
|
||||
/// `descriptor`, and its content's key: the hex of the translator's key of the descriptor, which
|
||||
/// names its record in the cache directory, then its colour attachments' pixel formats by index
|
||||
/// (0 for none), its depth and stencil formats and its raster sample count.
|
||||
pub(super) fn render_line(
|
||||
device: &rt::Device,
|
||||
descriptor: &rt::RenderPipelineDescriptor,
|
||||
object: u64,
|
||||
at: u64,
|
||||
) -> (String, String) {
|
||||
let key = device
|
||||
.translator()
|
||||
.queried_render_descriptor_key(descriptor);
|
||||
let key = crate::replay::hex(key.digest());
|
||||
let colors: Vec<u32> = (descriptor.color_attachments.iter())
|
||||
.map(|color| {
|
||||
color
|
||||
.as_ref()
|
||||
.map_or(0, |color| u32::from(color.pixel_format))
|
||||
})
|
||||
.collect();
|
||||
let format = |format: Option<rt::PixelFormat>| format.map_or(0, u32::from);
|
||||
let line = format!(
|
||||
"render #{object} call {at} key {key} colors {colors:?} depth {} stencil {} samples {} \
|
||||
fragment {}",
|
||||
format(descriptor.depth_format),
|
||||
format(descriptor.stencil_format),
|
||||
descriptor.raster_sample_count,
|
||||
descriptor.fragment.is_some(),
|
||||
);
|
||||
(key, line)
|
||||
}
|
||||
@@ -99,6 +99,11 @@
|
||||
//! `newTiledTextureWithDescriptor:offset:bytesPerRow:`) takes the buffer's bytes into its first
|
||||
//! level and makes its second from them at its first use: blits of both levels read the
|
||||
//! expected texels, and the take is counted once.
|
||||
//! - A states-only play writes each pipeline state's make as it happens (`with_states`): on two
|
||||
//! threads of the backend's own, each of three render states' makes writes its begin line, then
|
||||
//! its modules line, then its end line, made, and each begin's key is the name of the record
|
||||
//! its content wrote under `renders/`; with one of those keys listed, only that state is made,
|
||||
//! on the play's thread, and the other two are passed over, each on a pass line.
|
||||
//!
|
||||
//! The 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`]).
|
||||
@@ -111,6 +116,7 @@ use crate::replay::{
|
||||
use crate::ScratchDir;
|
||||
use metal2vulkan_devtools::metallib::{metallib, wrap, MtlbFunction};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
use std::fs::File;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -3411,3 +3417,131 @@ fn a_video_surface_is_waited_for_at_its_ready_point_once() {
|
||||
assert_eq!(executed["surface_waits"], in_place, "{executed:?}");
|
||||
eprintln!("REPLAY video-ready in place {in_place}");
|
||||
}
|
||||
|
||||
/// A stream of three render states of the render fixture's functions (#6, #7 and #8), colour 0 of
|
||||
/// each another pixel format: RGBA8Unorm, BGRA8Unorm and RGBA16Float.
|
||||
fn three_render_states(dir: &ScratchDir) -> PathBuf {
|
||||
written(dir, |w| {
|
||||
let library = w.blob(&render_library(dir))?;
|
||||
w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?;
|
||||
let library = [Value::Blob(library)];
|
||||
w.call("newLibraryWithData:error:", 1, 3, &library, &[])?;
|
||||
let vertex = [Value::Str("colored_vertex".into())];
|
||||
w.call("newFunctionWithName:", 3, 4, &vertex, &[])?;
|
||||
let fragment = [Value::Str("colored_fragment".into())];
|
||||
w.call("newFunctionWithName:", 3, 5, &fragment, &[])?;
|
||||
for (object, format) in [(6, 70), (7, 80), (8, 115)] {
|
||||
let pipeline = Value::Map(vec![
|
||||
("vertex".into(), Value::Object(4)),
|
||||
("fragment".into(), Value::Object(5)),
|
||||
("color0PixelFormat".into(), Value::Uint(format)),
|
||||
]);
|
||||
let made = "newRenderPipelineStateWithDescriptor:error:";
|
||||
w.call(made, 1, object, &[pipeline], &[])?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// `path` played states-only on a device of an empty cache directory, its makes written as
|
||||
/// `with_states(log, threads, keys)` writes them: the state log's lines, the backend's lines, and
|
||||
/// the names of the records the runtime wrote under `renders/` by the device's end.
|
||||
fn states_play(
|
||||
test: &str,
|
||||
path: &Path,
|
||||
threads: usize,
|
||||
keys: Option<HashSet<String>>,
|
||||
) -> (Vec<String>, Vec<String>, BTreeSet<String>) {
|
||||
let dir = ScratchDir::new(&format!("rt-replay-{test}-log")).unwrap();
|
||||
let log = dir.path().join("states.log");
|
||||
let cache = ScratchCache::new().unwrap();
|
||||
let backend = NewRuntime::new(rt_device(cache.path()), gpu::TEST_DEVICE).unwrap();
|
||||
let mut backend = backend.with_states(Some(File::create(&log).unwrap()), threads, keys);
|
||||
let mut reader = StreamReader::open(&[path.to_path_buf()], None).unwrap();
|
||||
let (report, ended) = Player::new(&mut backend).states_only().play(&mut reader);
|
||||
let lines = backend.lines();
|
||||
for line in report.lines().iter().chain(&lines) {
|
||||
eprintln!("REPLAY {test} {line}");
|
||||
}
|
||||
ended.unwrap();
|
||||
backend.end().result().unwrap();
|
||||
let logged: Vec<String> = (std::fs::read_to_string(&log).unwrap().lines())
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
let mut records = BTreeSet::new();
|
||||
for generation in std::fs::read_dir(cache.path()).unwrap() {
|
||||
let renders = generation.unwrap().path().join("renders");
|
||||
for record in std::fs::read_dir(&renders).into_iter().flatten() {
|
||||
records.insert(record.unwrap().file_name().to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
(logged, lines, records)
|
||||
}
|
||||
|
||||
/// The log's lines of `kind` (`begin`, `pass`, ...).
|
||||
fn logged<'a>(lines: &'a [String], kind: &str) -> Vec<&'a String> {
|
||||
let prefix = format!("M2V-STATE {kind} ");
|
||||
lines.iter().filter(|l| l.starts_with(&prefix)).collect()
|
||||
}
|
||||
|
||||
/// The content key a begin or pass line names.
|
||||
fn key_of(line: &str) -> String {
|
||||
let after = line.split(" key ").nth(1).expect("a key");
|
||||
after.split(' ').next().unwrap().to_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_states_only_play_on_its_threads_writes_each_make_between_its_lines() {
|
||||
let dir = ScratchDir::new("rt-replay-states-pool").unwrap();
|
||||
let path = three_render_states(&dir);
|
||||
let (lines, backend, records) = states_play("states-pool", &path, 2, None);
|
||||
let begins = logged(&lines, "begin");
|
||||
assert_eq!(begins.len(), 3, "{lines:?}");
|
||||
for begin in &begins {
|
||||
// `M2V-STATE begin SEQ THREAD ...`: the make's sequence number and its pool thread.
|
||||
let made: Vec<&str> = begin.split(' ').skip(2).take(2).collect();
|
||||
let made = made.join(" ");
|
||||
assert!(made.contains(" m2v-state-"), "{begin}");
|
||||
let at = |prefix: &str| lines.iter().position(|l| l.starts_with(prefix));
|
||||
let begun = at(begin).unwrap();
|
||||
let modules = at(&format!("M2V-STATE modules {made}")).expect("its modules line");
|
||||
let ended = at(&format!("M2V-STATE end {made} made in ")).expect("its end, made");
|
||||
assert!(begun < modules && modules < ended, "{lines:?}");
|
||||
}
|
||||
let keys: BTreeSet<String> = begins.iter().map(|l| key_of(l)).collect();
|
||||
assert_eq!(keys.len(), 3, "{lines:?}");
|
||||
assert_eq!(keys, records, "each begin's key names its content's record");
|
||||
let states = "states begun 3 made 3 refused 0 failed 0 passed over 0 on 2 threads";
|
||||
assert!(backend.iter().any(|l| l == states), "{backend:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_states_only_play_of_listed_keys_makes_those_states_alone() {
|
||||
let dir = ScratchDir::new("rt-replay-states-keys").unwrap();
|
||||
let path = three_render_states(&dir);
|
||||
let (all, ..) = states_play("states-keys-all", &path, 0, None);
|
||||
let begins = logged(&all, "begin");
|
||||
assert_eq!(begins.len(), 3, "{all:?}");
|
||||
assert!(
|
||||
begins.iter().all(|l| l.split(' ').nth(3) == Some("play")),
|
||||
"{all:?}"
|
||||
);
|
||||
// The BGRA8Unorm state's content, #7.
|
||||
let listed = (begins.iter()).find(|l| l.contains(" render #7 ")).unwrap();
|
||||
let key = key_of(listed);
|
||||
let (lines, backend, records) = states_play(
|
||||
"states-keys-one",
|
||||
&path,
|
||||
0,
|
||||
Some(HashSet::from([key.clone()])),
|
||||
);
|
||||
let made = logged(&lines, "begin");
|
||||
assert_eq!(made.len(), 1, "{lines:?}");
|
||||
assert_eq!(key_of(made[0]), key);
|
||||
let passed = logged(&lines, "pass");
|
||||
assert_eq!(passed.len(), 2, "{lines:?}");
|
||||
assert!(passed.iter().all(|l| !l.contains(&key)), "{lines:?}");
|
||||
assert_eq!(records, BTreeSet::from([key]));
|
||||
let states = "states begun 1 made 1 refused 0 failed 0 passed over 2 on the play's thread";
|
||||
assert!(backend.iter().any(|l| l == states), "{backend:?}");
|
||||
}
|
||||
Reference in new issue
Block a user