🐛 Leave out of later warm passes a record whose making stood 60 s

A host's warm pass hands every record in the file to the runtime at every
start, so a record whose driver compile never ends is made again at each one.
On ms01's Iris Xe (ANV, Xe-LP), since Blender's Cycles kernels joined its
records on 11-12, one of them (cycles_metal_integrator_intersect_closest,
spirv c8908289da74fa86) holds every start's pass: glibc in-use goes from 22 MB
to 4.57 GB once the pass reaches it, boot peaks went from 9.6 to 18-20 GiB,
and every exit waits up to 60 s for the making.

Once the pass has stood on one record for RECORD_BOUND (60 s, the bound the
runtime's exit gives a driver making), the warm thread appends a tombstone
frame of it to the records file. It does so while the making still runs, so a
killed process leaves it too. The read that hands the pass its records then
leaves that record out and says how many it left out. A tombstone is a frame
of the existing format whose payload is a fixed prefix plus the record's
bytes. An earlier build hands the runtime its bytes, which it reads as no
record and drops, so files stay readable both ways. A tombstone is appended
past CAPACITY too, since a left-out record is never made by a pass again.

Nothing the guest sees changes: only the warm pass leaves the record out.
The guest's own creation of its state is made as ever, and the hook keeps
records as before.

Interim flaw: the runtime names no record in making, so the record is
inferred from the pass's counts (one call's records go in order, and the sum
of the six record counts is the place of the one being made). Its time is the
warm thread's own clock from the poll where the counts last moved. That clock
also counts the pass's waits behind the process's other makings (the
runtime's Urgency::Warm never ages), so a record the guest's makings starve
for 60 s is left out as well. It is then only warmed no more. A recovery
resets the per-generation counts, which device_recoveries guards. metal2vulkan
is adding WarmStatistics::record_in_making and record_in_making_nanos (turn
waits left out). The inference gives way to them once the pin carries them.
This commit is contained in:
Anees Iqbal committed 2026-11-13 02:48:08 -08:00
1 parent 788d82edd3
commit 73a583264f
1 file changed
+240 -22
+240 -22
View File
@@ -18,11 +18,23 @@
//! guest's first creations of the states an earlier process made find them made, after a host
//! restart, and after an update of the runtime, whose translations of the earlier build's the
//! shader cache keeps apart (a record holds a descriptor, never a translation).
//! - **The file's format**: frames, each [`MAGIC`], the record's length and the FNV-1a hash of its
//! bytes (each a little-endian `u32`), then its bytes. A reader skips a frame whose length runs
//! past the file or whose hash does not match (a process that died mid-write, or two writing at
//! once), and goes on at the next [`MAGIC`] after its start; a record of another format the
//! runtime reads as none (`PipelineRecord::from_bytes`) and the pass drops.
//! - **Left out once it stood.** A record whose warm making stood [`RECORD_BOUND`] without ending
//! (a driver compile that never ends, or runs for minutes) is left out of every later pass: the
//! warm thread appends a tombstone of it ([`leave_out`]) as the bound passes, so a process
//! killed meanwhile leaves it too, and [`read`] hands no pass a record the file holds a
//! tombstone of. A host then pays for such a making in the start whose pass stands on it the
//! bound, not at every start: its driver memory, the records behind it the pass does not reach,
//! and the exit's wait for it. Only the pass leaves it out: the guest's own creation of its
//! state is made as ever, and the hook keeps its record as before. The record in making is read
//! from the pass's counts ([`Watch`]), and its time from this thread's polls.
//! - **The file's format**: frames, each [`MAGIC`], the payload's length and the FNV-1a hash of
//! its bytes (each a little-endian `u32`), then its bytes: a record's, or a tombstone's,
//! [`UNFINISHED`] followed by the bytes of the record it leaves out. A reader skips a frame
//! whose length runs past the file or whose hash does not match (a process that died
//! mid-write, or two writing at once), and goes on at the next [`MAGIC`] after its start; a
//! record of another format the runtime reads as none (`PipelineRecord::from_bytes`) and the
//! pass drops, and an earlier build, which knows no tombstone, hands the runtime a tombstone's
//! bytes, which it reads so.
//!
//! A test build's devices keep and warm no records ([`KEPT`]): this crate's unit tests', and every
//! crate's tests', which turn on its `testkit` feature (only dev-dependencies do, `cargo xtask
@@ -83,9 +95,28 @@ pub(crate) const WARM_BUDGET: u64 = crate::platform::SHADER_CACHE_CAPACITY / 2;
/// How often the warm thread looks whether the runtime's pass has ended.
const WARM_POLL: std::time::Duration = std::time::Duration::from_millis(250);
/// How long the warm pass may stand on one record before later passes leave it out (the module
/// docs, [`Watch`]): the bound the runtime's exit gives a pipeline making in the driver (its exit
/// waits at most 60 s for one). **Measured** 2026-11-12 on homelab-ms01-1's Iris Xe (ANV, Xe-LP),
/// macOS 26.7.2 guests' boots over 2,983 records: the making of one, a compute kernel whose
/// driver compile does not end, held the pass at every start, the process's glibc heap in use going
/// from 22 MB to 4.57 GB once the pass reached it and the boot's peak from 9.6 to 18-20 GiB, and
/// each exit waited the bound for it; the log of such a boot (job m3-max-25012) names 1,520
/// makings, and each of the 1,519 others took under 10 ms.
///
/// The time is this thread's, from the poll where the pass's counts last moved: it counts the
/// pass's waits behind the process's other makings (the runtime ranks the pass's makings below
/// all of them), so a record the guest's makings starve that long is left out as well, and only
/// warmed no more: the guest's creation of its state makes it as ever.
pub(crate) const RECORD_BOUND: std::time::Duration = std::time::Duration::from_secs(60);
/// The start of each frame of the records file.
pub(crate) const MAGIC: u32 = u32::from_le_bytes(*b"RVGR");
/// The start of a tombstone's payload, the bytes of the record it leaves out following (the
/// module docs): never a record's start, which is the runtime's format name (`M2VPREC`).
pub(crate) const UNFINISHED: &[u8] = b"reims-vgpu: unfinished warm making\0";
/// The bytes of a frame before its record's.
const FRAME_HEAD: usize = 12;
@@ -228,13 +259,90 @@ pub(crate) fn hook(path: PathBuf) -> Option<Arc<dyn Fn(rt::PipelineRecord) + Sen
}))
}
/// The records of the file at `path`, in its order.
pub(crate) fn read(path: &Path) -> Vec<rt::PipelineRecord> {
/// The records of `frames`, a records file's ([`split`]), that a warm pass is handed, in their
/// order: every one but those a tombstone leaves out (the module docs), and how many those are.
fn warmable<'a>(frames: &[&'a [u8]]) -> (Vec<&'a [u8]>, usize) {
let unfinished: HashSet<&[u8]> = frames
.iter()
.filter_map(|frame| frame.strip_prefix(UNFINISHED))
.collect();
let records = frames.iter().filter(|frame| !frame.starts_with(UNFINISHED));
let (left_out, handed): (Vec<&[u8]>, Vec<&[u8]>) =
records.partition(|record| unfinished.contains(*record));
(handed, left_out.len())
}
/// The records of the file at `path` a warm pass is handed, in its order ([`warmable`]), and how
/// many its tombstones leave out.
pub(crate) fn read(path: &Path) -> (Vec<rt::PipelineRecord>, usize) {
let bytes = std::fs::read(path).unwrap_or_default();
split(&bytes)
let (records, left_out) = warmable(&split(&bytes));
let records = records
.into_iter()
.filter_map(rt::PipelineRecord::from_bytes)
.collect()
.collect();
(records, left_out)
}
/// Appends to the file at `path` the tombstone of `record` (the module docs): one write of its
/// frame, as the keeper's ([`Keeper::keep`]), past [`CAPACITY`] too, since no later pass makes a
/// record with a tombstone, so tombstones stay as few as the records whose makings stood.
pub(crate) fn leave_out(path: &Path, record: &[u8]) -> std::io::Result<()> {
let mut tombstone = UNFINISHED.to_vec();
tombstone.extend_from_slice(record);
OpenOptions::new()
.append(true)
.open(path)?
.write_all(&frame(&tombstone))
}
/// The warm thread's watch over the record the pass makes (the module docs): the pass makes its
/// records one at a time, in the order handed, and counts each as it ends, so while it runs the
/// sum of its record counts is the place of the record it makes, among the records handed.
struct Watch {
/// The records handed.
handed: u64,
/// The sum of the counts at the last poll that moved it.
at: u64,
/// When that poll was, on the monotonic clock in nanoseconds.
since: u64,
/// Whether the record at `at` overran already.
overran: bool,
}
impl Watch {
/// The watch over a pass of `handed` records, as it starts at `now`.
fn new(handed: u64, now: u64) -> Watch {
Watch {
handed,
at: 0,
since: now,
overran: false,
}
}
/// The place of the record the pass has stood on for [`RECORD_BOUND`] by `now`, by its counts
/// then (`statistics`), once a record; `None` while none has.
fn overran(&mut self, statistics: &rt::WarmStatistics, now: u64) -> Option<u64> {
let at = counted(statistics);
if at != self.at {
(self.at, self.since, self.overran) = (at, now, false);
return None;
}
let stood = now.saturating_sub(self.since) >= RECORD_BOUND.as_nanos() as u64;
(stood && at < self.handed && !std::mem::replace(&mut self.overran, true)).then_some(at)
}
}
/// The records a warm pass's counts say ended, each warmed, translated only, failed, unread, not
/// warmable or not run.
fn counted(s: &rt::WarmStatistics) -> u64 {
s.records_warmed
+ s.records_translated
+ s.records_failed
+ s.records_unread
+ s.records_not_warmable
+ s.records_not_run
}
/// Hands `device` the records of the file at `path`, from a thread of its own that reads the
@@ -249,22 +357,28 @@ pub(crate) fn warm(
let spawned = std::thread::Builder::new()
.name("reims-vgpu-warm".into())
.spawn(move || {
let records = read(&path);
let (records, left_out) = read(&path);
if records.is_empty() || stop.stopped() {
return;
}
log::info!(
target: "reims_vgpu_vulkan::records",
"warming {} pipeline records from {}",
"warming {} pipeline records from {} ({left_out} left out: their warm making \
stood {} s in an earlier pass)",
records.len(),
path.display()
path.display(),
RECORD_BOUND.as_secs()
);
let handed = records.len() as u64;
device.warm(records, WARM_BUDGET);
// A recovery starts the counts of the new generation's passes from none, and ends this
// one: past it, the counts name no record of this pass.
let recoveries = device.work_counts().device_recoveries;
device.warm(records.clone(), WARM_BUDGET);
// The pass runs on the runtime's thread and says nothing when it ends: its counts
// reach the records handed then. The device's end stops the polls, which hold its
// runtime device.
let clock = crate::os::OsClock::new();
let mut watch = Watch::new(handed, clock.now_mono().as_nanos());
let mut polls = 0u64;
loop {
let statistics = device.warm_statistics();
@@ -276,6 +390,22 @@ pub(crate) fn warm(
);
return;
}
if let Some(at) = watch.overran(&statistics, clock.now_mono().as_nanos())
&& device.work_counts().device_recoveries == recoveries
&& let Some(record) = records.get(at as usize)
{
let left = leave_out(&path, &record.to_bytes());
log::warn!(
target: "reims_vgpu_vulkan::records",
"the warm pass's making of pipeline record {at} of {handed} stood {} s \
without ending: {}; the guest's own creation of its state still makes it",
RECORD_BOUND.as_secs(),
match left {
Ok(()) => "later passes leave it out".to_owned(),
Err(e) => format!("its tombstone was not appended ({e})"),
}
);
}
polls += 1;
if stop.wait_until(clock.now_mono().saturating_add(WARM_POLL)) {
return;
@@ -290,13 +420,7 @@ pub(crate) fn warm(
/// while the pass runs.
pub(crate) fn summary(statistics: &rt::WarmStatistics, handed: u64) -> Option<String> {
let s = statistics;
let ended = s.records_warmed
+ s.records_translated
+ s.records_failed
+ s.records_unread
+ s.records_not_warmable
+ s.records_not_run;
(ended >= handed).then(|| {
(counted(s) >= handed).then(|| {
format!(
"warmed {handed} pipeline records: {} made, {} translated only, {} failed, {} unread, \
{} not warmable, {} not run (the budget spent or the process ending); {} bytes of \
@@ -396,6 +520,100 @@ mod tests {
assert!(split(&frame(&a)[..FRAME_HEAD]).is_empty());
}
/// The time [`RECORD_BOUND`] past `start`, in nanoseconds.
fn bound_past(start: u64) -> u64 {
start + RECORD_BOUND.as_nanos() as u64
}
/// The counts of a pass whose first `ended` records ended, each made.
fn ended(ended: u64) -> rt::WarmStatistics {
let mut s = rt::WarmStatistics::default();
s.records_warmed = ended;
s
}
/// A record whose warm making stands the bound is named once, its tombstone appended, and the
/// next pass is handed every record but it
#[test]
fn an_unfinished_record_is_not_handed_to_the_next_pass() {
let dir = Scratch::new("unfinished");
let path = dir.0.join("records");
let records = [b"one".as_slice(), b"two", b"three"];
let mut keeper = Keeper::open(path.clone());
for record in records {
keeper.keep(record);
}
let mut watch = Watch::new(3, 1_000);
assert_eq!(watch.overran(&ended(0), 2_000), None);
assert_eq!(watch.overran(&ended(1), 3_000), None);
assert_eq!(watch.overran(&ended(1), bound_past(3_000) - 1), None);
assert_eq!(watch.overran(&ended(1), bound_past(3_000)), Some(1));
assert_eq!(
watch.overran(&ended(1), bound_past(9_000)),
None,
"named once"
);
leave_out(&path, records[1]).unwrap();
let bytes = std::fs::read(&path).unwrap();
assert_eq!(warmable(&split(&bytes)), (vec![records[0], records[2]], 1));
// The keeper, the guest's creations' end of the file, still holds it, and keeps it once.
let mut keeper = Keeper::open(path.clone());
keeper.keep(records[1]);
assert_eq!(std::fs::read(&path).unwrap(), bytes);
}
/// A record whose making ends within the bound is named by no poll, and the next pass is
/// handed it; the next record's time runs from the poll that saw its making start, and the
/// counts' end (the records handed) names none
#[test]
fn a_finished_record_is_still_handed_to_the_next_pass() {
let dir = Scratch::new("finished");
let path = dir.0.join("records");
let mut keeper = Keeper::open(path.clone());
keeper.keep(b"one");
keeper.keep(b"two");
let mut watch = Watch::new(2, 0);
assert_eq!(watch.overran(&ended(0), bound_past(0) - 1), None);
assert_eq!(watch.overran(&ended(1), bound_past(0)), None);
assert_eq!(
watch.overran(&ended(1), bound_past(bound_past(0)) - 1),
None
);
assert_eq!(watch.overran(&ended(2), bound_past(bound_past(0))), None);
assert_eq!(
watch.overran(&ended(2), bound_past(bound_past(bound_past(0)))),
None
);
let bytes = std::fs::read(&path).unwrap();
assert_eq!(
warmable(&split(&bytes)),
(vec![b"one".as_slice(), b"two"], 0)
);
}
/// A file of records alone, as every earlier build wrote it, hands a pass all of them in its
/// order; a tombstone of a record the file does not hold leaves out none; and a tombstone's
/// bytes, which an earlier build hands the runtime, are no record to it
#[test]
fn the_file_s_existing_frames_still_read() {
let (a, b) = (b"first".to_vec(), vec![7u8; 300]);
let mut file = frame(&a);
file.extend_from_slice(&frame(&b));
assert_eq!(
warmable(&split(&file)),
(vec![a.as_slice(), b.as_slice()], 0)
);
let mut tombstone = UNFINISHED.to_vec();
tombstone.extend_from_slice(b"absent");
file.extend_from_slice(&frame(&tombstone));
assert_eq!(split(&file).len(), 3);
assert_eq!(
warmable(&split(&file)),
(vec![a.as_slice(), b.as_slice()], 0)
);
assert!(rt::PipelineRecord::from_bytes(&tombstone).is_none());
}
/// The keeper appends each record once, across reopenings of the file, and nothing past its
/// capacity
#[test]
@@ -450,12 +668,12 @@ mod tests {
}
// The writer appends on its own thread, within 30 s.
for _ in 0..3000 {
if !read(&path).is_empty() {
if !read(&path).0.is_empty() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert_eq!(read(&path).len(), 1);
assert_eq!(read(&path).0.len(), 1);
let device = rt::Device::system_default_with(&options()).unwrap();
let stop = Arc::new(crate::let_go::Stop::default());
let _polls = warm(&device, path, &stop);