GPU: pipelines off the render thread and cached; indirect execution on

With indirect execution the world's first frame asked for over 1,200
pipelines at once and took more than 30 s, so the title's own GPU
watchdog ended the run. Host pipelines are now made by worker threads: a
first use waits at most 0.5 s per title frame, and that pipeline's draws
are dropped until it is ready. The world presents frames again, and
indirect execution is the default (the switch is gone).

Pipelines are cached across runs:
- every host pipeline goes into a pipeline library saved under the cache
  folder (named by a hash of the translated code, our root signature and
  the state; a blob the device rejects starts an empty library);
- the pipelines drawn with are remembered and started during loading on
  the next run.
One cold and one warm run: the last pipeline was ready 38 s after the
world's first frame cold, 1.4 s warm; the first world frame took 3.2 s
cold, 0.37 s warm.

Also:
- Copy-backs of shader-written ranges return only the bytes the GPU
  changed; they used to overwrite what the title's CPU wrote meanwhile,
  which crashed the title.
- Indirect dispatch records are bounded (group counts were not), and the
  console's single-dispatch argument type runs as a dispatch.
- Per-shader counts of dropped draws in the diagnostics log; a switch
  that submits and times each list alone.

Not working yet: the world shows no geometry, and runs end on a GPU page
fault after at most about 55 s.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
MarvisandClaude Fable 5.2 committed 2026-11-24 01:02:11 +01:00
1 parent 97c78d1087
commit 35b054ec03
13 files changed
+1018 -101

No files matched your search

+80 -10
View File
@@ -169,6 +169,34 @@ impl GraphicsState {
}
}
/// Everything the state holds, as text: part of a pipeline's name in
/// the library and of the key a title pipeline is started early by.
pub(crate) fn describe(&self) -> String {
let inputs: Vec<String> = self
.inputs
.iter()
.zip(&self.names)
.map(|(e, name)| {
format!(
"{name:?} {} {} {} {} {} {}",
e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0, e.InstanceDataStepRate
)
})
.collect();
format!(
"{:?} {} {:?} {:?} {inputs:?} {} {} {:?} {} {:?}",
self.blend,
self.sample_mask,
self.rasterizer,
self.depth,
self.strip_cut.0,
self.topology.0,
self.targets,
self.depth_format.0,
self.samples
)
}
/// The vertex buffer slots the input layout reads.
fn slots(&self) -> u32 {
self.inputs
@@ -373,7 +401,7 @@ impl HostPipeline {
}
bound.push(stage);
}
let root = match root_signature(&host.device, &params, &samplers, compute.is_some()) {
let (root, root_blob) = match root_signature(&host.device, &params, &samplers, compute.is_some()) {
Ok(root) => root,
Err(e) => {
tracing::warn!(error = %e, ?shaders, "host root signature refused");
@@ -396,8 +424,15 @@ impl HostPipeline {
CS: code(0),
..Default::default()
};
// SAFETY: the description points at live data.
let pso = match unsafe { host.device.CreateComputePipelineState(&desc) } {
let name = super::library::name("compute", &root_blob, &[&code_bytes(&code(0))], "");
let made = super::library::pipeline(
&name,
// SAFETY: the description points at live data.
|library, name| unsafe { library.LoadComputePipeline(name, &desc) },
// SAFETY: as above.
|| unsafe { host.device.CreateComputePipelineState(&desc) },
);
let pso = match made {
Ok(pso) => pso,
Err(e) => {
tracing::warn!(error = %e, ?shaders, "host pipeline refused");
@@ -421,8 +456,15 @@ impl HostPipeline {
let Some(g) = g else {
return refuse("graphics state not kept (plain description)", shaders);
};
let state = g.describe();
if mesh.is_some() {
let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g) {
let name = super::library::name(
"mesh",
&root_blob,
&[&code_bytes(&code(0)), &code_bytes(&code(1))],
&state,
);
let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g, &name) {
Ok(pso) => pso,
Err(e) => {
tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused");
@@ -470,8 +512,20 @@ impl HostPipeline {
SampleDesc: g.samples,
..Default::default()
};
// SAFETY: the description points at live data.
let pso = match unsafe { host.device.CreateGraphicsPipelineState(&desc) } {
let name = super::library::name(
"graphics",
&root_blob,
&[&code_bytes(&code(0)), &code_bytes(&code(1))],
&state,
);
let made = super::library::pipeline(
&name,
// SAFETY: the description points at live data.
|library, name| unsafe { library.LoadGraphicsPipeline(name, &desc) },
// SAFETY: as above.
|| unsafe { host.device.CreateGraphicsPipelineState(&desc) },
);
let pso = match made {
Ok(pso) => pso,
Err(e) => {
tracing::warn!(error = %e, ?shaders, "host pipeline refused");
@@ -511,6 +565,7 @@ fn mesh_pipeline(
ms: D3D12_SHADER_BYTECODE,
ps: D3D12_SHADER_BYTECODE,
g: &GraphicsState,
name: &str,
) -> windows::core::Result<ID3D12PipelineState> {
use windows::core::Interface;
/// A stream subobject: its type, then its description, pointer-aligned.
@@ -545,8 +600,23 @@ fn mesh_pipeline(
SizeInBytes: size_of::<Stream>(),
pPipelineStateSubobjectStream: (&raw mut stream).cast(),
};
// SAFETY: the stream holds whole subobjects pointing at live data.
unsafe { device.cast::<ID3D12Device2>()?.CreatePipelineState(&desc) }
let device = device.cast::<ID3D12Device2>()?;
super::library::pipeline(
name,
// SAFETY: the stream holds whole subobjects pointing at live data.
|library, name| unsafe { library.LoadPipeline(name, &desc) },
// SAFETY: as above.
|| unsafe { device.CreatePipelineState(&desc) },
)
}
/// The bytes of shader code (none for an absent stage).
fn code_bytes(code: &D3D12_SHADER_BYTECODE) -> Vec<u8> {
if code.pShaderBytecode.is_null() {
return Vec::new();
}
// SAFETY: a translation's own bytes, alive while its shader is.
unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::<u8>(), code.BytecodeLength) }.to_vec()
}
fn root_signature(
@@ -554,7 +624,7 @@ fn root_signature(
params: &[D3D12_ROOT_PARAMETER1],
samplers: &[D3D12_STATIC_SAMPLER_DESC],
compute: bool,
) -> windows::core::Result<ID3D12RootSignature> {
) -> windows::core::Result<(ID3D12RootSignature, Vec<u8>)> {
let input = if compute {
D3D12_ROOT_SIGNATURE_FLAG_NONE
} else {
@@ -592,6 +662,6 @@ fn root_signature(
let blob = blob.ok_or_else(windows::core::Error::empty)?;
let bytes =
std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize());
device.CreateRootSignature(0, bytes)
Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec()))
}
}
+254
View File
@@ -0,0 +1,254 @@
//! Compiled host pipelines kept on disk, and the title pipelines worth
//! starting early (decision 0007, "Pipeline cache").
//!
//! 1. Every host pipeline goes into the host's pipeline library, named by
//! a hash of all that its host description holds (the translated
//! shaders' code, which changes when a translation does, our root
//! signature, the graphics state). The library is saved under the cache
//! folder; the host refuses a library of another adapter or driver, and
//! an entry whose description differs, so neither is ever used.
//! 2. The title pipelines a run drew or dispatched with are listed by a key
//! known when the title creates them (their shader containers and
//! graphics state); the next run hands those to the workers at
//! creation, during loading.
//!
//! All library calls are serialised: the interface does not promise that
//! stores, loads and serialising may overlap.
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
use windows::Win32::Graphics::Direct3D12::*;
use windows::core::{HSTRING, Interface, PCWSTR};
static DIR: OnceLock<PathBuf> = OnceLock::new();
/// Keeps the pipeline library and the early list in `dir` from now on.
pub fn use_pipeline_cache(dir: PathBuf) {
let _ = DIR.set(dir);
}
/// Host pipelines created, loaded from the library, and title pipelines
/// started at creation, since the start.
pub(crate) static MADE: AtomicU64 = AtomicU64::new(0);
pub(crate) static LOADED: AtomicU64 = AtomicU64::new(0);
pub(crate) static EARLY: AtomicU64 = AtomicU64::new(0);
struct Library {
library: ID3D12PipelineLibrary1,
/// The blob the library was made from: it must outlive the library.
_blob: Vec<u8>,
/// Pipelines stored since the last save.
added: u64,
}
// SAFETY: D3D12 objects are free-threaded; every call is made under the
// mutex that holds the library.
unsafe impl Send for Library {}
const LIBRARY_FILE: &str = "host-pipelines.bin";
const EARLY_FILE: &str = "early-pipelines.txt";
/// Title pipelines listed for an early start, at most.
const EARLY_MAX: usize = 8192;
fn library() -> Option<&'static Mutex<Library>> {
static LIBRARY: OnceLock<Option<Mutex<Library>>> = OnceLock::new();
LIBRARY
.get_or_init(|| {
let device = crate::host::host()?.device.cast::<ID3D12Device1>().ok()?;
let blob = DIR
.get()
.and_then(|d| std::fs::read(d.join(LIBRARY_FILE)).ok())
.unwrap_or_default();
let library = open(&device, blob);
if library.is_none() {
tracing::warn!("no host pipeline library: pipelines are not kept");
}
library.map(Mutex::new)
})
.as_ref()
}
/// The library in `blob`, or an empty one if the host rejects the blob (an
/// adapter or driver change, damage).
fn open(device: &ID3D12Device1, blob: Vec<u8>) -> Option<Library> {
let make = |bytes: &[u8]| -> windows::core::Result<ID3D12PipelineLibrary1> {
// SAFETY: the bytes outlive the library (kept beside it).
unsafe {
device.CreatePipelineLibrary::<ID3D12PipelineLibrary>(bytes)?.cast()
}
};
if !blob.is_empty() {
match make(&blob) {
Ok(library) => {
tracing::info!(bytes = blob.len(), "host pipeline library loaded");
return Some(Library { library, _blob: blob, added: 0 });
}
Err(e) => tracing::info!(error = %e, "host pipeline library rejected; starting an empty one"),
}
} else {
tracing::info!("no host pipeline library yet; starting an empty one");
}
let library = make(&[]).ok()?;
Some(Library { library, _blob: Vec::new(), added: 0 })
}
/// A pipeline's name in the library: the hash of what its host
/// description holds.
pub(crate) fn name(kind: &str, root: &[u8], code: &[&[u8]], state: &str) -> String {
let mut h = blake3::Hasher::new();
for part in [kind.as_bytes(), root].into_iter().chain(code.iter().copied()).chain([state.as_bytes()]) {
h.update(&(part.len() as u64).to_le_bytes());
h.update(part);
}
h.finalize().to_hex()[..32].to_owned()
}
/// The pipeline named `name`: loaded from the library by `load` if it is
/// there with the same description, else made by `create` and stored.
pub(crate) fn pipeline(
name: &str,
load: impl FnOnce(&ID3D12PipelineLibrary1, PCWSTR) -> windows::core::Result<ID3D12PipelineState>,
create: impl FnOnce() -> windows::core::Result<ID3D12PipelineState>,
) -> windows::core::Result<ID3D12PipelineState> {
let wide = HSTRING::from(name);
let Some(library) = library() else {
MADE.fetch_add(1, Ordering::Relaxed);
return create();
};
if let Ok(pso) = load(&library.lock().unwrap_or_else(|e| e.into_inner()).library, PCWSTR(wide.as_ptr())) {
LOADED.fetch_add(1, Ordering::Relaxed);
return Ok(pso);
}
// Compiled outside the lock: compiles take up to seconds.
let pso = create()?;
MADE.fetch_add(1, Ordering::Relaxed);
let mut l = library.lock().unwrap_or_else(|e| e.into_inner());
// SAFETY: a live pipeline; a name already stored (a description that
// differs) is refused, which leaves the library as it was.
if unsafe { l.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() {
l.added += 1;
}
Ok(pso)
}
/// Writes the library and the early list if pipelines were added since the
/// last save and `SAVE_EVERY` has passed (or `now`).
pub(crate) fn save(now: bool) {
static LAST: Mutex<Option<std::time::Instant>> = Mutex::new(None);
const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20);
let (Some(dir), Some(library)) = (DIR.get(), library()) else { return };
{
let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner());
if !now && last.is_some_and(|t| t.elapsed() < SAVE_EVERY) {
return;
}
*last = Some(std::time::Instant::now());
}
let blob = {
let mut l = library.lock().unwrap_or_else(|e| e.into_inner());
if l.added == 0 && !USED_CHANGED.swap(false, Ordering::Relaxed) {
return;
}
// SAFETY: a buffer of the size the library asks for.
let bytes = unsafe {
let mut bytes = vec![0u8; l.library.GetSerializedSize()];
l.library.Serialize(&mut bytes).map(|()| bytes)
};
match bytes {
Ok(bytes) => {
l.added = 0;
bytes
}
Err(e) => {
tracing::warn!(error = %e, "host pipeline library not serialised");
return;
}
}
};
let used: Vec<String> = USED.lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().cloned().collect();
let written = std::fs::create_dir_all(dir)
.and_then(|()| write_atomically(&dir.join(LIBRARY_FILE), &blob))
.and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes()));
match written {
Ok(()) => tracing::info!(
bytes = blob.len(),
early = used.len(),
made = MADE.load(Ordering::Relaxed),
loaded = LOADED.load(Ordering::Relaxed),
started_early = EARLY.load(Ordering::Relaxed),
"host pipeline library saved"
),
Err(e) => tracing::warn!(error = %e, "host pipeline library not saved"),
}
}
/// Writes `bytes` to a temporary file beside `path`, then renames it over
/// `path`: a reader never sees a part.
fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, bytes)?;
std::fs::rename(&tmp, path)
}
/// Title pipeline keys drawn or dispatched with (this run and the last).
static USED: Mutex<Option<HashSet<String>>> = Mutex::new(None);
static USED_CHANGED: AtomicBool = AtomicBool::new(false);
fn used() -> std::sync::MutexGuard<'static, Option<HashSet<String>>> {
let mut used = USED.lock().unwrap_or_else(|e| e.into_inner());
if used.is_none() {
let listed = DIR
.get()
.and_then(|d| std::fs::read_to_string(d.join(EARLY_FILE)).ok())
.unwrap_or_default();
let set: HashSet<String> = listed.lines().filter(|l| !l.is_empty()).map(str::to_owned).collect();
tracing::info!(pipelines = set.len(), "title pipelines to start early");
*used = Some(set);
}
used
}
/// Whether the title pipeline with `key` was drawn with in an earlier run.
pub(crate) fn wanted_early(key: &str) -> bool {
used().as_ref().is_some_and(|s| s.contains(key))
}
/// The title pipeline with `key` was drawn or dispatched with.
pub(crate) fn note_used(key: &str) {
let mut used = used();
let set = used.get_or_insert_with(HashSet::new);
if set.len() < EARLY_MAX && set.insert(key.to_owned()) {
USED_CHANGED.store(true, Ordering::Relaxed);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_change_with_what_goes_into_the_pipeline() {
let a = name("graphics", b"root", &[b"vs", b"ps"], "state");
assert_eq!(a, name("graphics", b"root", &[b"vs", b"ps"], "state"));
assert_ne!(a, name("graphics", b"root", &[b"vs", b"ps2"], "state"));
assert_ne!(a, name("graphics", b"root", &[b"vs", b"ps"], "state2"));
assert_ne!(a, name("graphics", b"root2", &[b"vs", b"ps"], "state"));
assert_ne!(a, name("mesh", b"root", &[b"vs", b"ps"], "state"));
// Parts do not run into each other.
assert_ne!(a, name("graphics", b"root", &[b"vsp", b"s"], "state"));
}
#[test]
fn a_rejected_blob_gives_an_empty_library() {
let Some(device) = crate::host::host().and_then(|h| h.device.cast::<ID3D12Device1>().ok()) else {
return; // no host GPU here
};
let library = open(&device, b"not a pipeline library".repeat(16)).expect("an empty library");
// SAFETY: a plain query on a live library.
assert!(unsafe { library.library.GetSerializedSize() } > 0);
assert!(library._blob.is_empty());
}
}
+238
View File
@@ -0,0 +1,238 @@
//! Host pipelines are made by workers, not by the title thread that first
//! records a draw with them. Translating a shader and the host driver's
//! compile take from milliseconds to seconds each (structurisation of the
//! biggest compute programs ~0.4 s, some driver compiles 3.4 s), and Grand
//! Theft Auto VI's first world frame wants over 1,200 new pipelines: made
//! on its recording threads, that frame took more than 30 s and the
//! title's GPU watchdog ended the run (decision 0007, "Pipelines made off
//! the title's threads").
//!
//! A first use queues the pipeline and waits for it within a budget per
//! frame, so the cheap ones (menus, one-off passes such as a colour-grading
//! bake) are there at once as before; past the budget a draw or dispatch
//! whose pipeline is not ready is dropped, as an untranslated one is.
//!
//! shortcut: the budget (half a second of waiting per title frame) is a
//! guess; a pass the title runs only once and whose pipeline takes longer
//! is lost.
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};
use super::Shader;
use super::host::{GraphicsState, HostPipeline};
/// What a host pipeline is made from, and the host pipeline once made.
pub(crate) struct Pending {
shaders: Vec<Arc<Shader>>,
pub(crate) graphics: Option<Box<GraphicsState>>,
queued: AtomicBool,
made: OnceLock<Option<HostPipeline>>,
/// What identifies it across runs (shader containers and state), and
/// whether a draw has used it yet.
key: String,
used: AtomicBool,
}
// SAFETY: D3D12 objects are free-threaded; the graphics state (whose input
// elements point into its own names) is only read after creation.
unsafe impl Send for Pending {}
// SAFETY: as above.
unsafe impl Sync for Pending {}
impl Pending {
pub(crate) fn new(shaders: Vec<Arc<Shader>>, graphics: Option<Box<GraphicsState>>) -> Pending {
let mut key = blake3::Hasher::new();
for s in &shaders {
key.update(s.stage.as_bytes());
key.update(s.hash.as_bytes());
}
key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes());
Pending {
shaders,
graphics,
queued: AtomicBool::new(false),
made: OnceLock::new(),
key: key.finalize().to_hex()[..32].to_owned(),
used: AtomicBool::new(false),
}
}
fn make(&self) {
self.made
.get_or_init(|| HostPipeline::new(&self.shaders, self.graphics.as_deref()));
let (lock, done) = &DONE;
let _held = lock.lock().unwrap_or_else(|e| e.into_inner());
done.notify_all();
}
}
/// Why a pipeline has no host pipeline (diagnostics): its shaders that do
/// not translate, else "refused" or "being made"; `None` if it has one.
#[cfg(feature = "diagnostics")]
pub(crate) fn missing(p: &Pending) -> Option<String> {
match p.made.get() {
Some(Some(_)) => None,
None => Some("being made".into()),
Some(None) => {
let failed: Vec<String> = p
.shaders
.iter()
.filter(|s| matches!(s.translated.get(), Some(None)))
.map(|s| format!("{} {}", s.stage, s.hash))
.collect();
Some(if failed.is_empty() {
format!("refused {:?}", p.shaders)
} else {
failed.join(" + ")
})
}
}
}
/// Signalled whenever a worker has made a pipeline.
static DONE: (Mutex<()>, Condvar) = (Mutex::new(()), Condvar::new());
/// Waiting allowed per title frame, over all threads.
const BUDGET: Duration = Duration::from_millis(500);
/// Pipelines queued and not made yet.
static WAITING: AtomicU64 = AtomicU64::new(0);
/// Pipelines queued and not made yet (for the frame line).
pub(crate) fn waiting() -> u64 {
WAITING.load(Ordering::Relaxed)
}
/// The host pipeline if it is made (or is made within the frame's budget);
/// queues it on first use.
pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> {
if p.made.get().is_none() {
start(p);
wait(p, crate::frame::current());
}
let made = p.made.get()?.as_ref();
if made.is_some() && !p.used.swap(true, Ordering::Relaxed) {
super::library::note_used(&p.key);
}
made
}
/// Queues `p` for the workers, once.
fn start(p: &Arc<Pending>) {
if !p.queued.swap(true, Ordering::Relaxed) {
PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed);
queue(p.clone());
}
}
/// At the title's creation of a pipeline: starts it at once if an earlier
/// run drew with it (during loading, so the world's first frames find it).
pub(crate) fn early(p: &Arc<Pending>) {
if !p.shaders.is_empty() && super::library::wanted_early(&p.key) {
super::library::EARLY.fetch_add(1, Ordering::Relaxed);
start(p);
}
}
/// Waits for `p` while frame `frame` has budget left.
fn wait(p: &Pending, frame: u64) {
static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
static WAITED_US: AtomicU64 = AtomicU64::new(0);
if FRAME.swap(frame, Ordering::Relaxed) != frame {
WAITED_US.store(0, Ordering::Relaxed);
}
let left = BUDGET.saturating_sub(Duration::from_micros(WAITED_US.load(Ordering::Relaxed)));
let started = Instant::now();
let (lock, done) = &DONE;
let mut held = lock.lock().unwrap_or_else(|e| e.into_inner());
while p.made.get().is_none() {
let rest = left.saturating_sub(started.elapsed());
if rest.is_zero() {
break;
}
held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0;
}
WAITED_US.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
}
/// Hands `p` to the workers (half the logical processors, 2 to 8), started
/// on first use.
fn queue(p: Arc<Pending>) {
static SENDER: OnceLock<std::sync::mpsc::Sender<Arc<Pending>>> = OnceLock::new();
let sender = SENDER.get_or_init(|| {
let (sender, receiver) = std::sync::mpsc::channel::<Arc<Pending>>();
let receiver = Arc::new(Mutex::new(receiver));
let workers = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8));
for i in 0..workers {
let receiver = receiver.clone();
let spawned = std::thread::Builder::new()
.name(format!("victory-pipelines-{i}"))
.spawn(move || {
// Below the title's own threads (loading, recording).
// SAFETY: a plain call on our own thread.
unsafe {
use windows::Win32::System::Threading::*;
let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
}
loop {
let next = receiver.lock().unwrap_or_else(|e| e.into_inner()).recv();
let Ok(p) = next else { return };
p.make();
if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 {
drained();
} else {
super::library::save(false);
}
}
});
if let Err(e) = spawned {
tracing::warn!(error = %e, "no pipeline worker");
}
}
sender
});
if let Err(e) = sender.send(p) {
// No worker: made here instead.
e.0.make();
WAITING.fetch_sub(1, Ordering::Relaxed);
}
}
/// The most pipelines waiting at once since the workers last ran out.
static PEAK: AtomicU64 = AtomicU64::new(0);
/// The workers ran out of work: logged after a batch of 10 or more, and
/// the cache saved (at most every 20 s).
fn drained() {
use super::library::{EARLY, LOADED, MADE};
if PEAK.swap(0, Ordering::Relaxed) >= 10 {
tracing::info!(
made = MADE.load(Ordering::Relaxed),
loaded = LOADED.load(Ordering::Relaxed),
started_early = EARLY.load(Ordering::Relaxed),
"host pipelines all made"
);
}
super::library::save(false);
}
#[cfg(test)]
mod tests {
use super::*;
/// A first use queues the pipeline and, within the budget, gets the
/// worker's answer (here: no host pipeline for no shaders).
#[test]
fn first_use_is_made_by_a_worker() {
let p = Arc::new(Pending::new(Vec::new(), None));
assert!(ready(&p).is_none());
assert!(p.queued.load(Ordering::Relaxed));
let started = Instant::now();
while p.made.get().is_none() && started.elapsed() < Duration::from_secs(10) {
std::thread::yield_now();
}
assert!(matches!(p.made.get(), Some(None)));
}
}