From 3d2b846caa9588abe6fdcf877a3f1098dea1eefb Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 21 Nov 2026 17:43:08 -0800 Subject: [PATCH] Runtime cache directory: a newer translator's open retires both generations Every lowering's and record's name under translations/ and renders/ holds the translator's SEMANTICS_VERSION, and a lowering decodes under its own ARTIFACT_FORMAT_VERSION alone. So after a version change no file of the old version is looked up again, yet it stayed counted until young filled, and the one rotation then only moved it from young to old. A consumer's directory held 97.6 MB of translations, of which 92.7 MB were of older versions. The state file now records, after young's number, its bytes and their checksum (bytes 0..24, unchanged), the newest SEMANTICS_VERSION and ARTIFACT_FORMAT_VERSION a store opened the directory under, each at its highest, with a checksum (bytes 24..40). At its open, under the state's lock (Store::meet), a store whose translator is newer than the record in either version moves young two generations on, counted empty, so the young and old it found are both below old and the existing removal thread removes them, and it records the higher of each version. A store at the recorded versions or older ones retires nothing and records nothing: product builds of every version share one directory in the consumer's layout, so two builds alternating on it, or one running beside the other, keep each other's files after the newer one's first open, and the older one's writes go into young. A state whose versions are missing or do not check after a young's record that does (an earlier version's 24-byte state file) reads as older than every translator, so the first open after this change retires once; an earlier version writes only bytes 0..24 at the start of a file it opens without truncation, so the record stays. A state that does not check at all (a new directory's, or a torn one) is rebuilt from the generations' names as before and retires nothing. Read-only directories retire nothing. The removal now takes the dead generations lowest first, so a removal cut short while two are dead (the retire's case) leaves the one just below old, which the next open looks for. Store::open takes the store's Versions; Caches::new passes Versions::BUILT (the translator's constants). No SEMANTICS bump: the translator's output and keys are unchanged. The cache.rs module doc, the runtime README's cache-directory section and DeviceOptions::pipeline_cache_dir's doc say so. Tests (host, each on a directory of its own, in src/tests/cache.rs): - a_newer_translators_open_retires_both_generations_once: filled under (S, F), four stores open at once under (S+1, F), then under (S, F+1): young 3 -> 5 once, generations 2 and 3 gone, no older file left, writes and hits work, a reopen retires nothing. - an_older_translators_open_retires_nothing_of_a_newer_ones: after the newer one's open, the older one's open removes nothing and records nothing, its write and the newer one's file are both read by the newer one's reopen; a translator newer in format alone retires and the record keeps the higher of each, so neither earlier one retires after it. - a_state_with_no_versions_reads_as_older_once: the record cut to 24 bytes, or its checksum broken, retires once; then an earlier version's 24-byte write at offset 0 leaves the record, and the next open reads that write and retires nothing. - the_dead_generations_are_removed_lowest_first: dead generations 30, 9, 1, 10, 2 listed as 1, 2, 9, 10, 30. Verified: compile job m3-max-65330 (fmt, the signatures table, clippy plain, --cfg m2v_gpu and --cfg m2v_cpu_icd, workspace Rustdoc -D warnings, the store's host tests 23/23, and metal2vulkan-runtime's suite on lavapipe 629 passed, the four new tests among them). --- crates/metal2vulkan-runtime/README.md | 16 +- crates/metal2vulkan-runtime/src/cache.rs | 207 +++++++++--- crates/metal2vulkan-runtime/src/device.rs | 5 +- .../metal2vulkan-runtime/src/tests/cache.rs | 308 ++++++++++++++++-- .../metal2vulkan-runtime/src/tests/device.rs | 4 +- 5 files changed, 472 insertions(+), 68 deletions(-) diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index d7d1ef2aa..c525b2487 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2700,16 +2700,28 @@ the lowerings waiting for the reaper past 8 MiB it is dropped and counted larger than 8 MiB by itself is queued where none waits, so the heaviest kernels are kept too. The write that takes young past half the cap starts the next generation: young becomes old, and the old one is removed whole, by a thread the store starts for it. So a file stays for at least half the cap, and at most the whole cap, of files -written or moved after its last use. Half the cap is what the store is sure to keep: a set of +written or moved after its last use, until a device of a newer translator opens the directory +(below). Half the cap is what the store is sure to keep: a set of functions used over and over that is larger than half the cap is partly removed at each new generation and lowered again. On disk the lowerings take at most the cap, and while a removal runs, also what is left of the generation it removes; the blobs are beside them. A file larger than half the cap is not kept. `Metrics::cache_bytes_written` counts the bytes the device wrote there, lowerings and blobs. -The bytes young holds are counted in `state`, a file of 24 bytes beside the generations, read and +The bytes young holds are counted in `state`, a file of 40 bytes beside the generations, read and written under its lock, so devices open on one directory, in one process or several, share its files and one count; they should pass one cap, since each starts a generation at half its own. +After the count, `state` records the newest translator semantics and artifact format versions a +device opened the directory under. Every file's name holds the semantics version, and a lowering +decodes under its own format version alone, so a device under a newer translator reads no file +an older one wrote. So a device whose translator is newer than the recorded one, in either +version, retires both generations at its open: young moves two generations on, counted empty, the +store's thread removes the two it found, and `state` records the higher of each version. A device +at the recorded versions or older ones retires nothing and records nothing. So two builds of +different versions on one directory, at once or in turn, keep each other's files after the newer +one's first open. A `state` of 24 bytes, as an earlier version of the runtime wrote it, reads as +older than every translator: its first open retires both generations once. An earlier version +writes only those 24 bytes and leaves the recorded versions as they are. Opening the directory reads `state` and checks for a generation a removal left unfinished, and for the `pipelines/` directories under young and old in which an earlier version kept one file of pipeline data per `VkPipeline`, which the store's thread then removes; it lists no directory and diff --git a/crates/metal2vulkan-runtime/src/cache.rs b/crates/metal2vulkan-runtime/src/cache.rs index 10dae941e..ab49b06d2 100644 --- a/crates/metal2vulkan-runtime/src/cache.rs +++ b/crates/metal2vulkan-runtime/src/cache.rs @@ -76,18 +76,36 @@ //! reaper: a state hands its lowering over ([`keep_translation`]) and returns, and a lowering that //! would take the ones waiting past [`PENDING_BYTES`] is dropped and counted, never waited for, //! except that one larger than that by itself is queued where nothing else waits. The -//! bytes young holds are counted in `state`, 24 bytes beside the generations: young's number, its -//! bytes and a checksum of both, read and written under a lock on the file, which every store on -//! the directory, in this process or another, holds open for its life. The write that takes young -//! past half the cap makes the next generation young: young becomes old, and the old one is dead. A -//! store keeps young's number as it last read or wrote the state, so a lookup reads no state: a -//! move another store made is seen at this store's next write, and until then its lookups try the -//! generations it knew, a miss at worst. A thread of the store's own removes the dead generation -//! and ends, so no thread that submits, waits for or completes work removes files. So a file stays -//! at least half the cap and at most the cap of other writes and moves after its last use, opening -//! reads one file whatever the store holds, and nothing per file is kept in memory. The same thread -//! removes the `pipelines/` directories under young and old in which an earlier version kept one -//! file of pipeline data per `VkPipeline`; their bytes stay counted in young until it moves on. +//! bytes young holds are counted in `state`, 40 bytes beside the generations: young's number, its +//! bytes and a checksum of both, then the newest translator versions a store opened the directory +//! under ([`Versions`]) and a checksum of them, read and written under a lock on the file, which +//! every store on the directory, in this process or another, holds open for its life. The write +//! that takes young past half the cap makes the next generation young: young becomes old, and the +//! old one is dead. A store keeps young's number as it last read or wrote the state, so a lookup +//! reads no state: a move another store made is seen at this store's next write, and until then +//! its lookups try the generations it knew, a miss at worst. A thread of the store's own removes +//! the dead generation and ends, so no thread that submits, waits for or completes work removes +//! files. So a file stays at least half the cap and at most the cap of other writes and moves +//! after its last use, until a newer translator's open (below), opening reads one file whatever +//! the store holds, and nothing per file is kept in memory. The same thread removes the +//! `pipelines/` directories under young and old in which an earlier version kept one file of +//! pipeline data per `VkPipeline`; their bytes stay counted in young until it moves on. +//! +//! **A newer translator.** Every lowering's and record's name holds the translator's semantics +//! version, and a lowering decodes under its own artifact format version alone, so a store under +//! a newer translator reads no file an older one wrote: in both generations they are dead. So a +//! store whose translator is newer, in either version, than the newest the state records retires +//! both at its open: under the lock, young moves two generations on, counted empty, so the young +//! and old it found are both below old and the removal thread takes them, and the state records +//! the higher of each version. A store at the versions the state records, or older ones, retires +//! nothing and records nothing. So builds of two versions that share a directory, at once or in +//! turn, keep each other's files after the newer one's first open: the older one's go into young +//! and stay by use, as every store's do. Versions that are missing or do not check after young's +//! number and bytes that do, as in an earlier version's state file, read as older than every +//! translator's, so the first open of a store that records them retires both generations once. +//! An earlier version writes only the first 24 bytes, at the file's start, and leaves the versions +//! as they are. A store that is still open under an older translator when a newer one retires its +//! generations misses in them until its next write reads the new young. //! //! Every write is a temporary file renamed over its name, counted before it is written and given //! back where it fails, so the count is never below what young holds. Every file checks itself @@ -164,6 +182,9 @@ pub(crate) const RECORD_LEN: usize = 8 + 4 + 4 + 32 + 2 * 33 + 8; const PIPELINES: &str = "pipelines"; /// The state file, under the cache directory. const STATE: &str = "state"; +/// Where the newest versions the state file records start in it, after young's number, its +/// bytes and their checksum. +const NEWEST_AT: u64 = 24; /// Young's number and the bytes counted in it. #[derive(Clone, Copy, Debug, PartialEq)] @@ -172,12 +193,44 @@ pub(crate) struct State { pub(crate) bytes: u64, } +/// The translator's versions a store writes its files under: its semantics version, which every +/// lowering's and record's name holds, and its artifact format version, under which alone a +/// lowering decodes. So a store under newer versions reads no file of older ones. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Versions { + pub(crate) semantics: u32, + pub(crate) format: u32, +} + +impl Versions { + /// This build's translator's. + pub(crate) const BUILT: Versions = Versions { + semantics: SEMANTICS_VERSION, + format: ARTIFACT_FORMAT_VERSION, + }; + + /// Whether either version is above `other`'s. + fn newer_than(self, other: Versions) -> bool { + self.semantics > other.semantics || self.format > other.format + } + + /// The higher of each version. + fn newest(self, other: Versions) -> Versions { + Versions { + semantics: self.semantics.max(other.semantics), + format: self.format.max(other.format), + } + } +} + /// The lowerings of a cache directory, `translations/` under two generations of at most /// half of `cap` bytes each (the module's doc). pub(crate) struct Store { root: PathBuf, /// Half the cap: the most bytes young counts. half: u64, + /// The translator's versions the store writes its files under. + versions: Versions, /// The state file, open for the store's life; none where it could not be opened, and every /// lookup misses. state: Option, @@ -203,9 +256,16 @@ pub(crate) struct Store { } impl Store { - /// The store in `root`, made where it is missing; it starts the removal of a generation a - /// removal before left, and of an earlier version's pipeline data. - pub(crate) fn open(root: PathBuf, cap: u64, counters: Counters) -> Arc { + /// The store in `root` under the translator's `versions`, made where it is missing. It + /// retires both generations where the directory records older versions ([`Store::meet`]), + /// and starts the removal of the generations that leaves dead, of a generation a removal + /// before left, and of an earlier version's pipeline data. + pub(crate) fn open( + root: PathBuf, + cap: u64, + counters: Counters, + versions: Versions, + ) -> Arc { let _ = fs::create_dir_all(&root); let path = root.join(STATE); let opened = File::options() @@ -221,6 +281,7 @@ impl Store { let store = Arc::new(Store { root, half: cap / 2, + versions, state, writable, writer: Mutex::new(()), @@ -233,6 +294,7 @@ impl Store { #[cfg(test)] state_reads: AtomicUsize::new(0), }); + store.meet(); if let Some(state) = store.current() { store.young.fetch_max(state.young, Relaxed); let young = state.young; @@ -249,6 +311,37 @@ impl Store { self.writable } + /// At the open, under the state file's lock: where the state records versions older than + /// the store's in either, makes young two generations on, counted empty, so the young and old + /// it found are both dead (no lookup of the store's reads their files), and records the + /// higher of each version. A state that records the store's versions or newer ones keeps its + /// generations and its record: a store of an older build on the directory empties nothing of + /// a newer one's. Versions that are missing or do not check after a state that does (an + /// earlier version's state file) read as older than every translator's; a state that does not + /// check at all, a new directory's among them, is rebuilt (the module's doc) and retires + /// nothing. + fn meet(&self) { + self.locked(|file| { + let recorded = read_newest(file); + if recorded.is_some_and(|recorded| !self.versions.newer_than(recorded)) { + return Some(()); + } + if recorded.is_some() || read_state(file).is_some() { + self.change(file, |state| { + let next = state.young + 2; + make_dir(&self.generation(next)).ok()?; + *state = State { + young: next, + bytes: 0, + }; + Some(()) + })?; + } + let newest = recorded.map_or(self.versions, |recorded| recorded.newest(self.versions)); + write_newest(file, newest).ok() + }); + } + /// The directories of an earlier version's pipeline data under young, `young`, and old. fn pipeline_dirs(&self, young: u64) -> Vec { (young.saturating_sub(1)..=young) @@ -406,18 +499,27 @@ impl Store { /// Runs `change` on the state under the lock, and writes the state back where it answers. fn update(&self, change: impl FnOnce(&mut State) -> Option) -> Option { + self.locked(|file| self.change(file, change)) + } + + /// Runs `op` on the state file under its lock, where the file is open for writing. + fn locked(&self, op: impl FnOnce(&File) -> Option) -> Option { let file = self.state.as_ref().filter(|_| self.writable)?; let _writer = lock(&self.writer); file.lock().ok()?; - let changed = (|| { - let mut state = read_state(file).or_else(|| self.rebuild(file))?; - let answer = change(&mut state)?; - write_state(file, state).ok()?; - self.young.fetch_max(state.young, Relaxed); - Some(answer) - })(); + let done = op(file); let _ = file.unlock(); - changed + done + } + + /// Under the lock: runs `change` on the state `file` holds, rebuilt where it does not check, + /// and writes the state back where it answers. + fn change(&self, file: &File, change: impl FnOnce(&mut State) -> Option) -> Option { + let mut state = read_state(file).or_else(|| self.rebuild(file))?; + let answer = change(&mut state)?; + write_state(file, state).ok()?; + self.young.fetch_max(state.young, Relaxed); + Some(answer) } /// Under the lock, a state for a state file that is missing or does not check: young is the @@ -518,12 +620,16 @@ impl Store { } } - /// The generations below old, and an earlier version's pipeline data under young and old. - fn dead(&self) -> Vec { + /// The generations below old, lowest first, so a removal cut short leaves the one just below + /// old, which the next open looks for; and an earlier version's pipeline data under young and + /// old. + pub(crate) fn dead(&self) -> Vec { let Some(young) = self.current().map(|state| state.young) else { return Vec::new(); }; - let mut dead: Vec = (generations(&self.root).into_iter()) + let mut numbers = generations(&self.root); + numbers.sort_unstable(); + let mut dead: Vec = (numbers.into_iter()) .filter(|&number| number + 1 < young) .map(|number| self.generation(number)) .collect(); @@ -565,8 +671,8 @@ fn generations(root: &Path) -> Vec { /// The state `file` holds, where it checks. fn read_state(file: &File) -> Option { - let mut record = [0; 24]; - read_at(file, &mut record).ok()?; + let mut record = [0; NEWEST_AT as usize]; + read_at(file, &mut record, 0).ok()?; let word = |at: usize| u64::from_le_bytes(record[at..at + 8].try_into().expect("8 bytes")); let state = State { young: word(0), @@ -577,35 +683,57 @@ fn read_state(file: &File) -> Option { /// Writes `state` to `file`, with its checksum. fn write_state(file: &File, state: State) -> io::Result<()> { - let mut record = [0; 24]; + let mut record = [0; NEWEST_AT as usize]; record[..8].copy_from_slice(&state.young.to_le_bytes()); record[8..16].copy_from_slice(&state.bytes.to_le_bytes()); let sum = checksum(&record[..16]); record[16..].copy_from_slice(&sum.to_le_bytes()); - write_at(file, &record) + write_at(file, &record, 0) +} + +/// The newest versions `file` records after the state, where they check. +fn read_newest(file: &File) -> Option { + let mut record = [0; 16]; + read_at(file, &mut record, NEWEST_AT).ok()?; + let word = |at: usize| u32::from_le_bytes(record[at..at + 4].try_into().expect("4 bytes")); + let sum = u64::from_le_bytes(record[8..].try_into().expect("8 bytes")); + (sum == checksum(&record[..8])).then(|| Versions { + semantics: word(0), + format: word(4), + }) +} + +/// Writes `versions` to `file` after the state, with their checksum. +fn write_newest(file: &File, versions: Versions) -> io::Result<()> { + let mut record = [0; 16]; + record[..4].copy_from_slice(&versions.semantics.to_le_bytes()); + record[4..8].copy_from_slice(&versions.format.to_le_bytes()); + let sum = checksum(&record[..8]); + record[8..].copy_from_slice(&sum.to_le_bytes()); + write_at(file, &record, NEWEST_AT) } #[cfg(unix)] -fn read_at(file: &File, buf: &mut [u8]) -> io::Result<()> { - std::os::unix::fs::FileExt::read_exact_at(file, buf, 0) +fn read_at(file: &File, buf: &mut [u8], at: u64) -> io::Result<()> { + std::os::unix::fs::FileExt::read_exact_at(file, buf, at) } #[cfg(unix)] -fn write_at(file: &File, buf: &[u8]) -> io::Result<()> { - std::os::unix::fs::FileExt::write_all_at(file, buf, 0) +fn write_at(file: &File, buf: &[u8], at: u64) -> io::Result<()> { + std::os::unix::fs::FileExt::write_all_at(file, buf, at) } #[cfg(windows)] -fn read_at(file: &File, buf: &mut [u8]) -> io::Result<()> { - match std::os::windows::fs::FileExt::seek_read(file, buf, 0)? { +fn read_at(file: &File, buf: &mut [u8], at: u64) -> io::Result<()> { + match std::os::windows::fs::FileExt::seek_read(file, buf, at)? { read if read == buf.len() => Ok(()), _ => Err(ErrorKind::UnexpectedEof.into()), } } #[cfg(windows)] -fn write_at(file: &File, buf: &[u8]) -> io::Result<()> { - match std::os::windows::fs::FileExt::seek_write(file, buf, 0)? { +fn write_at(file: &File, buf: &[u8], at: u64) -> io::Result<()> { + match std::os::windows::fs::FileExt::seek_write(file, buf, at)? { written if written == buf.len() => Ok(()), _ => Err(ErrorKind::WriteZero.into()), } @@ -1107,7 +1235,8 @@ impl Caches { /// removal thread counts in `counters`' thread gauge. pub(crate) fn new(dir: Option<&Path>, cap: u64, counters: &Counters) -> Caches { Caches { - store: dir.map(|dir| Store::open(dir.to_owned(), cap, counters.clone())), + store: dir + .map(|dir| Store::open(dir.to_owned(), cap, counters.clone(), Versions::BUILT)), dir: dir.map(Path::to_owned), blob: OnceLock::new(), header: OnceLock::new(), diff --git a/crates/metal2vulkan-runtime/src/device.rs b/crates/metal2vulkan-runtime/src/device.rs index 55f5b07c0..8d4b9fe26 100644 --- a/crates/metal2vulkan-runtime/src/device.rs +++ b/crates/metal2vulkan-runtime/src/device.rs @@ -430,7 +430,10 @@ pub struct DeviceOptions { /// compiling again ([`Metrics::translations_loaded`]). The lowerings take at most /// [`pipeline_cache_cap`](Self::pipeline_cache_cap) bytes, in two generations of half of it /// each: a file used again moves into the young one, and the old one is removed whole when - /// the young one fills. Beside them, one file per pipeline cache header (a kind of device and + /// the young one fills. Both are removed at the open of a device whose translator is newer, in + /// its semantics or artifact format version, than every one before it on the directory, + /// since none of its lookups reads their files; a device of an older one removes nothing of + /// a newer one's. Beside them, one file per pipeline cache header (a kind of device and /// driver version; at most four such files, the oldest by last write removed) holds the data /// of the `VkPipelineCache` every `VkPipeline` of the device is made through, at most 32 MiB: /// the device's cache takes it in off every guest thread, and it is diff --git a/crates/metal2vulkan-runtime/src/tests/cache.rs b/crates/metal2vulkan-runtime/src/tests/cache.rs index 80ef3920a..600052271 100644 --- a/crates/metal2vulkan-runtime/src/tests/cache.rs +++ b/crates/metal2vulkan-runtime/src/tests/cache.rs @@ -2,15 +2,17 @@ //! records alike, a record read only as its own content's, a hit in old moved into young, //! a lookup that reads no state, the state file read at open with no listing and rebuilt where it //! is torn or missing, a settled store's removal thread ended with its last look, a removal cut -//! short (a process's exit in it included) finished by the next -//! open, an earlier version's pipeline data removed at open, torn files removed, a blob that does +//! short (a process's exit in it included) finished by the next open, the dead generations removed +//! lowest first, a newer translator's open retiring both generations once and an older one's +//! retiring nothing, a state with no versions read as older once, an earlier version's pipeline +//! data removed at open, torn files removed, a blob that does //! not check refused, a blob named by its device's whole pipeline cache header, at most four //! blobs kept, and stores in threads and processes sharing one directory without losing a count //! or reading a file another was writing. use crate::cache::{ blob_name, checksum, frame, prune_blobs, read_record, record_bytes, unframe, usable_header, - Caches, Lowerings, Pending, State, Store, BLOBS_KEPT, RECORD_LEN, + Caches, Lowerings, Pending, State, Store, Versions, BLOBS_KEPT, RECORD_LEN, }; use crate::counters::Counters; use std::fs; @@ -111,7 +113,12 @@ fn a_store_filled_past_its_cap_stays_within_it_and_moves_on() { _ => record_of(n), }; let scratch = Scratch::new("store-cap"); - let store = Store::open(scratch.0.clone(), 10 * len, Counters::new()); + let store = Store::open( + scratch.0.clone(), + 10 * len, + Counters::new(), + Versions::BUILT, + ); assert_eq!(state(&store), State { young: 1, bytes: 0 }); for n in 0..40 { let (name, bytes) = file(n); @@ -219,7 +226,7 @@ fn a_record_reads_only_as_its_own_content_s() { #[test] fn a_hit_in_old_moves_into_young_and_outlives_the_next_generation() { let scratch = Scratch::new("store-old"); - let store = Store::open(scratch.0.clone(), 1000, Counters::new()); + let store = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); for n in 0..6 { assert!(store.put(&name(n), &[n as u8; 100])); } @@ -247,8 +254,8 @@ fn a_hit_in_old_moves_into_young_and_outlives_the_next_generation() { #[test] fn a_lookup_reads_no_state_and_sees_another_stores_move_at_its_next_write() { let scratch = Scratch::new("store-young"); - let first = Store::open(scratch.0.clone(), 1000, Counters::new()); - let second = Store::open(scratch.0.clone(), 1000, Counters::new()); + let first = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); + let second = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); assert!(first.put(&name(0), &[0; 100])); let reads = first.state_reads.load(Relaxed); for _ in 0..10 { @@ -284,7 +291,7 @@ fn a_lookup_reads_no_state_and_sees_another_stores_move_at_its_next_write() { #[test] fn a_reopened_store_reads_its_state_and_lists_no_directory() { let scratch = Scratch::new("store-reopen"); - let store = Store::open(scratch.0.clone(), 1000, Counters::new()); + let store = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); assert_eq!( store.listings.load(Relaxed), 1, @@ -296,7 +303,7 @@ fn a_reopened_store_reads_its_state_and_lists_no_directory() { store.settle(); let before = state(&store); drop(store); - let reopened = Store::open(scratch.0.clone(), 1000, Counters::new()); + let reopened = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); assert_eq!(state(&reopened), before); // Files 20 to 22 in young, file 15 in old. for n in [20, 21, 22, 15] { @@ -313,7 +320,7 @@ fn a_reopened_store_reads_its_state_and_lists_no_directory() { #[test] fn a_removal_cut_short_is_finished_by_the_next_open() { let scratch = Scratch::new("store-cut"); - let store = Store::open(scratch.0.clone(), 1000, Counters::new()); + let store = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); for n in 0..16 { assert!(store.put(&name(n), &[n as u8; 100])); } @@ -327,7 +334,7 @@ fn a_removal_cut_short_is_finished_by_the_next_open() { fs::create_dir_all(path.parent().expect("a parent")).expect("the directory"); fs::write(&path, [0; 100]).expect("the file"); } - let reopened = Store::open(scratch.0.clone(), 1000, Counters::new()); + let reopened = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); reopened.settle(); assert!(!reopened.generation(2).exists() && !reopened.generation(1).exists()); assert!(reopened.generation(3).exists() && reopened.generation(4).exists()); @@ -354,7 +361,12 @@ fn store_exit_child() { let Some(dir) = std::env::var_os(EXIT_DIR) else { return; }; - let store = Store::open(PathBuf::from(dir), EXIT_CAP, Counters::new()); + let store = Store::open( + PathBuf::from(dir), + EXIT_CAP, + Counters::new(), + Versions::BUILT, + ); for n in 0..=2 * EXIT_FILES { assert!(store.put(&name(n), &[1; 10])); } @@ -385,7 +397,12 @@ fn a_process_that_exits_in_a_removal_leaves_it_to_the_next_open() { assert!(status.success(), "the child wrote every file"); let dead = scratch.0.join("g1"); assert!(dead.exists(), "the child exited before its removal ended"); - let reopened = Store::open(scratch.0.clone(), EXIT_CAP, Counters::new()); + let reopened = Store::open( + scratch.0.clone(), + EXIT_CAP, + Counters::new(), + Versions::BUILT, + ); reopened.settle(); assert!(!dead.exists(), "the next open finished the removal"); assert_eq!( @@ -411,7 +428,7 @@ fn a_settled_stores_removal_reads_the_state_no_more() { use crate::cache::LAST_LOOK_PAUSE; let scratch = Scratch::new("store-settled"); LAST_LOOK_PAUSE.store(200, Relaxed); - let store = Store::open(scratch.0.clone(), 1000, Counters::new()); + let store = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); // The move to generation 3 leaves generation 1 dead, and starts the removal. for n in 0..13 { assert!(store.put(&name(n), &[n as u8; 100])); @@ -440,7 +457,7 @@ fn a_settled_stores_removal_reads_the_state_no_more() { #[test] fn a_torn_or_missing_state_is_rebuilt_from_the_generations() { let scratch = Scratch::new("store-state"); - let store = Store::open(scratch.0.clone(), 1000, Counters::new()); + let store = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); for n in 0..13 { assert!(store.put(&name(n), &[n as u8; 100])); } @@ -449,7 +466,7 @@ fn a_torn_or_missing_state_is_rebuilt_from_the_generations() { drop(store); for torn in [&b"cut short"[..], &[7; 24][..], &[][..]] { fs::write(scratch.0.join("state"), torn).expect("the state torn"); - let reopened = Store::open(scratch.0.clone(), 1000, Counters::new()); + let reopened = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); assert_eq!( reopened.listings.load(Relaxed), 1, @@ -466,7 +483,7 @@ fn a_torn_or_missing_state_is_rebuilt_from_the_generations() { assert_eq!(reopened.get(&name(12), whole), Some(vec![12; 100])); } fs::remove_file(scratch.0.join("state")).expect("the state removed"); - let reopened = Store::open(scratch.0.clone(), 1000, Counters::new()); + let reopened = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); assert_eq!( state(&reopened), State { @@ -488,10 +505,241 @@ fn a_torn_or_missing_state_is_rebuilt_from_the_generations() { assert!(scratch.bytes() <= 1000); } +/// Translator versions below this build's, for a store of an older build. +const OLDER: Versions = Versions { + semantics: 10, + format: 20, +}; + +/// Fills the directory under `versions` with files 0 to 12 of 100 bytes in a cap of 1000: young +/// is generation 3, holding files 10 to 12, and old is generation 2, holding files 5 to 9. +fn filled(scratch: &Scratch, versions: Versions) { + let store = Store::open(scratch.0.clone(), 1000, Counters::new(), versions); + for n in 0..13 { + assert!(store.put(&name(n), &[n as u8; 100])); + } + store.settle(); + assert_eq!( + state(&store), + State { + young: 3, + bytes: 300 + } + ); +} + +/// A store under a translator newer in its semantics or its artifact format version retires +/// young and old at its open, both dead to it: young moves two generations on, counted empty, the +/// removal takes both, and the directory then holds only what the store writes. Four stores +/// opening at once retire them once, and a reopen under the same versions retires nothing. +#[test] +fn a_newer_translators_open_retires_both_generations_once() { + let newer = [ + Versions { + semantics: OLDER.semantics + 1, + ..OLDER + }, + Versions { + format: OLDER.format + 1, + ..OLDER + }, + ]; + for (case, newer) in newer.into_iter().enumerate() { + let scratch = Scratch::new(&format!("store-newer-{case}")); + filled(&scratch, OLDER); + let barrier = std::sync::Barrier::new(4); + let stores: Vec> = std::thread::scope(|scope| { + let opens: Vec<_> = (0..4) + .map(|_| { + scope.spawn(|| { + barrier.wait(); + Store::open(scratch.0.clone(), 1000, Counters::new(), newer) + }) + }) + .collect(); + (opens.into_iter()) + .map(|open| open.join().expect("an open")) + .collect() + }); + for store in &stores { + store.settle(); + } + assert_eq!( + state(&stores[0]), + State { young: 5, bytes: 0 }, + "case {case}: young moved on twice, once" + ); + assert!(!stores[0].generation(3).exists() && !stores[0].generation(2).exists()); + assert_eq!( + scratch.bytes(), + 0, + "case {case}: an older translator's file left" + ); + for n in [12, 5] { + assert_eq!( + stores[1].get(&name(n), whole), + None, + "case {case}: file {n}" + ); + } + assert!(stores[2].put(&name(13), &[13; 100])); + assert_eq!(stores[3].get(&name(13), whole), Some(vec![13; 100])); + drop(stores); + let reopened = Store::open(scratch.0.clone(), 1000, Counters::new(), newer); + reopened.settle(); + assert_eq!( + state(&reopened), + State { + young: 5, + bytes: 100 + }, + "case {case}: the reopen retired nothing" + ); + } +} + +/// Builds of two translators on one directory, in turn, keep each other's files after the newer +/// one's first open: the older one's open retires nothing and records nothing, and what it writes +/// goes into young beside the newer one's. A translator newer in one version and older in the +/// other retires them, and the directory records the higher of each, so neither earlier one +/// retires anything after it. +#[test] +fn an_older_translators_open_retires_nothing_of_a_newer_ones() { + let newer = Versions { + semantics: OLDER.semantics + 1, + ..OLDER + }; + let scratch = Scratch::new("store-older"); + filled(&scratch, OLDER); + let store = Store::open(scratch.0.clone(), 1000, Counters::new(), newer); + assert!(store.put(&name(100), &[100; 100])); + store.settle(); + drop(store); + let older = Store::open(scratch.0.clone(), 1000, Counters::new(), OLDER); + older.settle(); + assert_eq!( + state(&older), + State { + young: 5, + bytes: 100 + } + ); + assert_eq!( + older.get(&name(100), whole), + Some(vec![100; 100]), + "the newer one's file" + ); + assert!(older.put(&name(101), &[101; 100])); + drop(older); + let store = Store::open(scratch.0.clone(), 1000, Counters::new(), newer); + store.settle(); + assert_eq!(state(&store).young, 5, "the older one recorded nothing"); + for n in [100, 101] { + assert_eq!( + store.get(&name(n), whole), + Some(vec![n as u8; 100]), + "file {n}" + ); + } + drop(store); + let format = Versions { + format: OLDER.format + 1, + ..OLDER + }; + let store = Store::open(scratch.0.clone(), 1000, Counters::new(), format); + store.settle(); + assert_eq!(state(&store), State { young: 7, bytes: 0 }); + assert_eq!(scratch.bytes(), 0); + drop(store); + for versions in [newer, format, OLDER] { + let store = Store::open(scratch.0.clone(), 1000, Counters::new(), versions); + store.settle(); + assert_eq!(state(&store).young, 7, "{versions:?} retired nothing"); + } +} + +/// A state with no versions after young's number and bytes, as an earlier version of the store +/// wrote it, or whose versions do not check, reads as older than every translator: the open +/// retires both generations, once, and records its versions. An earlier version's write of the +/// state, its 24 bytes at the file's start through a file opened without truncation, keeps the +/// versions after them, so the next open retires nothing. (A state that does not check at all is +/// rebuilt and retires nothing: `a_torn_or_missing_state_is_rebuilt_from_the_generations`.) +#[test] +fn a_state_with_no_versions_reads_as_older_once() { + for case in ["cut", "flipped"] { + let scratch = Scratch::new(&format!("store-unversioned-{case}")); + filled(&scratch, Versions::BUILT); + let path = scratch.0.join("state"); + let mut held = fs::read(&path).expect("the state"); + assert_eq!( + held.len(), + 40, + "young, its bytes, the versions and two checksums" + ); + match case { + "cut" => held.truncate(24), + _ => held[30] ^= 1, + } + fs::write(&path, &held).expect("the state rewritten"); + let store = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); + store.settle(); + assert_eq!(state(&store), State { young: 5, bytes: 0 }, "{case}"); + assert_eq!(scratch.bytes(), 0, "{case}: a file left"); + assert_eq!( + store.listings.load(Relaxed), + 0, + "{case}: young's record was whole" + ); + assert!(store.put(&name(13), &[13; 100])); + drop(store); + let mut head = [0; 24]; + head[..8].copy_from_slice(&5_u64.to_le_bytes()); + head[8..16].copy_from_slice(&200_u64.to_le_bytes()); + let sum = checksum(&head[..16]); + head[16..].copy_from_slice(&sum.to_le_bytes()); + let mut earlier = fs::File::options() + .write(true) + .open(&path) + .expect("the state"); + std::io::Write::write_all(&mut earlier, &head).expect("an earlier version's write"); + drop(earlier); + assert_eq!(fs::metadata(&path).expect("the state").len(), 40); + let store = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); + store.settle(); + assert_eq!( + state(&store), + State { + young: 5, + bytes: 200 + }, + "{case}: the earlier version's write read, its versions kept" + ); + assert_eq!(store.get(&name(13), whole), Some(vec![13; 100]), "{case}"); + } +} + +/// The removal takes the dead generations lowest first, by number, so one cut short leaves the +/// generation just below old, which the next open looks for. +#[test] +fn the_dead_generations_are_removed_lowest_first() { + let scratch = Scratch::new("store-dead-order"); + let store = Store::open(scratch.0.clone(), 2, Counters::new(), Versions::BUILT); + for n in 0..32 { + assert!(store.put(&name(n), &[1])); + } + store.settle(); + assert_eq!(state(&store).young, 32); + for number in [30, 9, 1, 10, 2] { + fs::create_dir(store.generation(number)).expect("a dead generation"); + } + let dead = Vec::from([1, 2, 9, 10, 30].map(|number| store.generation(number))); + assert_eq!(store.dead(), dead); +} + #[test] fn a_torn_file_is_a_miss_and_is_removed() { let scratch = Scratch::new("store-torn"); - let store = Store::open(scratch.0.clone(), 1000, Counters::new()); + let store = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); let data: Vec = (0..=255).collect(); assert!(store.put(&name(1), &framed(&data))); let path = store.generation(1).join(name(1)); @@ -510,8 +758,8 @@ fn a_torn_file_is_a_miss_and_is_removed() { #[test] fn stores_on_one_directory_share_its_files_and_its_count() { let scratch = Scratch::new("store-share"); - let first = Store::open(scratch.0.clone(), 1000, Counters::new()); - let second = Store::open(scratch.0.clone(), 1000, Counters::new()); + let first = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); + let second = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); assert!(first.put(&name(1), b"compiled")); assert_eq!(second.get(&name(1), whole), Some(b"compiled".to_vec())); assert_eq!(state(&second).bytes, 8); @@ -690,7 +938,7 @@ fn the_write_queue_refuses_a_file_past_its_bound() { #[test] fn an_earlier_versions_pipeline_data_is_removed_at_open() { let scratch = Scratch::new("store-earlier"); - let store = Store::open(scratch.0.clone(), 1000, Counters::new()); + let store = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); for n in 0..6 { assert!(store.put(&name(n), &[n as u8; 100])); } @@ -704,7 +952,7 @@ fn an_earlier_versions_pipeline_data_is_removed_at_open() { fs::create_dir_all(dir).expect("an earlier version's directory"); fs::write(dir.join(format!("{:064x}", 1)), [1; 50]).expect("its file"); } - let reopened = Store::open(scratch.0.clone(), 1000, Counters::new()); + let reopened = Store::open(scratch.0.clone(), 1000, Counters::new(), Versions::BUILT); reopened.settle(); for g in [1, 2] { let dir = scratch.0.join(format!("g{g}/pipelines")); @@ -761,7 +1009,12 @@ fn store_stress_child() { let Some(dir) = std::env::var_os(STRESS_DIR) else { return; }; - let store = Store::open(PathBuf::from(dir), STRESS_CAP, Counters::new()); + let store = Store::open( + PathBuf::from(dir), + STRESS_CAP, + Counters::new(), + Versions::BUILT, + ); assert_eq!(stress(&store, u64::from(std::process::id()), 4000), 0); store.settle(); } @@ -781,7 +1034,14 @@ fn stores_in_threads_and_processes_racing_writes_moves_and_flips_corrupt_nothing }) .collect(); let stores: Vec> = (0..3) - .map(|_| Store::open(scratch.0.clone(), STRESS_CAP, Counters::new())) + .map(|_| { + Store::open( + scratch.0.clone(), + STRESS_CAP, + Counters::new(), + Versions::BUILT, + ) + }) .collect(); std::thread::scope(|scope| { let workers: Vec<_> = (0..6) diff --git a/crates/metal2vulkan-runtime/src/tests/device.rs b/crates/metal2vulkan-runtime/src/tests/device.rs index e59ff7a55..b669dd8ce 100644 --- a/crates/metal2vulkan-runtime/src/tests/device.rs +++ b/crates/metal2vulkan-runtime/src/tests/device.rs @@ -207,7 +207,7 @@ fn every_device_of_the_cfgs_kind_opens_presents_and_tears_down_to_zero() { #[cfg(any(m2v_gpu, m2v_cpu_icd))] #[test] fn every_device_joins_its_cache_directory_s_removal_at_teardown() { - use crate::cache::{Store, REMOVAL_PAUSE}; + use crate::cache::{Store, Versions, REMOVAL_PAUSE}; use std::sync::atomic::Ordering::Relaxed; REMOVAL_PAUSE.store(200, Relaxed); @@ -221,7 +221,7 @@ fn every_device_joins_its_cache_directory_s_removal_at_teardown() { let _ = std::fs::remove_dir_all(&dir); // Generations 1 to 4 made through a store of its own, 4 young; then 1 and 2, dead, refilled // as a run cut short in their removal leaves them. - let store = Store::open(dir.clone(), 1000, Counters::new()); + let store = Store::open(dir.clone(), 1000, Counters::new(), Versions::BUILT); for n in 0..16_u32 { assert!(store.put(&format!("translations/{n:064x}"), &[1; 100])); }