rt: a render content's record in the cache directory names its two lowerings, so a later device makes the content with no decode or specialization of either function

A warm make, a new process on a cache directory a device before it filled, cost 1,215 ms for
glbench-3090-r4's 383 render contents on a 3090 against the old runtime's 448 ms. 1,099 ms of it
was the translator's key of each content's compile (Device::render_variant_key), which decodes and
specializes the vertex and fragment functions to learn the lowering inputs of each: per content
2.0 functions specialized, 1.0 module decode read (16,071 bytes, 1,046 instructions) and 0.4 decode
copies (24,955 bytes, 13.6 functions, 174 metadata nodes), 831 of the key's 874 ms. Only then did
the two lowerings load from the directory. The old runtime kept a record under the descriptor's
key that names the two lowerings, so a warm make there decodes nothing.

Now the same. After a content is lowered, its record goes into the lowered-function store, under
renders/, named by the translator's key of its descriptor (Device::queried_render_descriptor_key).
That key reads no function. It covers every field of the descriptor, each function by its AIR hash,
entry, constant values, linked functions and dynamic libraries, the profile's fingerprint and the
semantics version. The record holds the FunctionCompileKey digest of each lowering. A state of a
content the device does not hold reads the record first and loads the two lowerings it names. It
calls neither render_variant_key nor the specialization. The record is 122 bytes: a layout magic,
the translator's semantics and artifact format versions, the descriptor's key again, two tagged
stage digests and a checksum. A record of another version or another content, one cut short or one
changed is a miss, and the store removes it. A record whose lowering the store no longer holds is a
miss counted in the new Metrics::render_records_stale: the state takes today's path and keeps the
record again. Metrics::render_records_read counts the reads. Records go through the reaper's write
queue and the store's generations under the existing cap, as lowerings do. Only metal2vulkan-rt
changes: the translator's public API already had every item the record needs (PipelineKey::digest,
FunctionCompileKey::new, CompiledFunction::from_bytes_for_key, both versions). Device::new and every
translation are unchanged.

Compute keeps its path. A warm compute make decodes nothing: a kernel without a stage-input
descriptor is its own lowering inputs (kernel_inputs_read). gb-3090-r2's 126 compute contents and
15,299 compute states took 44.6 ms warm on ms01's Iris and 39.7 ms on the 780M, against 974.8 and
787.8 ms for its 274 render contents.

The tests:
- tests::cache: the fill-past-capacity test now fills with lowerings and records in turn, each a
  record's length. It reads a kept record back and finds a removed one gone. A new test reads a
  record only as its own content's: another content's key, a moved semantics or format version or
  layout (sealed again under the checksum), a bad stage tag, a digest beside none, one byte short or
  long, and every single bit flipped are each no record.
- tests::render, devices of the cfg's kind:
  - a second device on the directory takes the content by its record: records read 1, lowerings
    made 0 and read 2, and the stage entries count no read of either function's AIR. The negative
    control removes the record: lowerings read 2, both functions' AIR read again, and the record is
    kept again. With the fragment's lowering removed, the record is stale (1) and that function is
    lowered again.
  - each kind of input changed once misses the base content's record: the library's content (one
    constant of the fragment body, names kept), the fragment function, its constant value, and the
    colour attachment moved from index 0 to 1 (a field the fragment's specialization reads). The
    translator's keys of each compile show the change reaches a lowering key, and the base
    content's read on the same device shows the record is there to miss. The base record copied
    over the constant's content's record is no record of it. The device profile is checked where
    the host has two devices of the cfg's kind with different profiles, and skips visibly with one.

Verification: the lane's potluck jobs (clippy in three configurations, Rustdoc, the touched tests
on the host and on lavapipe), reported with their ids.
This commit is contained in:
Anees Iqbal committed 2026-11-20 04:32:47 -08:00
1 parent 090a70b6d2
commit c39f6e8350
12 files changed
+688 -79

No files matched your search

+14
View File
@@ -2184,6 +2184,20 @@ the lowerings from one device to the next:
place of lowering (`Metrics::translations_loaded`, beside `Metrics::translations`); a kernel
variant the translator refused is kept too, and so is its answer that a kernel observes its
threadgroup partition, which a state on the directory reads in place of asking it again.
- `renders/`: each render content's record, 122 bytes, named by the hex of the translator's key of
its descriptor (`Device::queried_render_descriptor_key`), which reads no function: the
`FunctionCompileKey` of its vertex and fragment functions' lowerings. A state of a content the
device does not hold reads its record and the two lowerings it names
(`Metrics::render_records_read`), so neither function is decoded or specialized. The name covers
everything that changes either lowering: every field of the descriptor, the fields the functions'
specialization reads among them; each function by its library's AIR hash (its content), its entry,
its constant values as supplied, its linked functions and dynamic libraries; the device profile's
fingerprint; and the translator's semantics version. The record holds the translator's semantics
and artifact format versions and the descriptor's key again under a checksum, so one of another
version or another content is a miss and is removed. A record naming a lowering the directory no
longer holds is a miss too, counted (`Metrics::render_records_stale`): the state decodes,
specializes and lowers as with no record, and keeps the record again. Records are written and
counted as lowerings are, within the cap below.
**The pipeline cache.** The reaper makes an empty cache first when it starts, which a creation that
comes before it waits for (microseconds). Then, off every guest thread, it reads the blob, makes a
+117 -3
View File
@@ -52,6 +52,23 @@
//! so is the translator's answer that a kernel observes its threadgroup partition, under its
//! variant's key, until that variant's lowering replaces it.
//!
//! **The records.** A render content whose functions a device lowered keeps a record under
//! `renders/`, named by the hex of the translator's key of its descriptor
//! (`Device::queried_render_descriptor_key`), which reads no function: the `FunctionCompileKey` of
//! each of its functions' lowerings ([`Lowerings`]). A state of a content the device does not hold
//! reads its record in place of the translator's key of its compile (`Device::render_variant_key`),
//! which decodes and specializes both functions, and then reads the lowerings the record names. The
//! record's name covers everything that can change either lowering: every field of the descriptor,
//! the fields the specialization reads among them; each function by its library's AIR hash (the
//! library's content), its entry, its constant values as supplied, its linked functions and its
//! dynamic libraries; the device profile's fingerprint; and the translator's semantics version. Its
//! bytes ([`record_bytes`]) hold the translator's semantics and artifact format versions and the
//! descriptor's key again, under a checksum, so a record of another version or of another content,
//! or one cut short, is a miss, and is removed. A record whose lowering the store no longer holds
//! is a miss too, counted (`Metrics::render_records_stale`): the state takes the path of a content
//! with no record, and keeps the record again. A record is [`RECORD_LEN`] bytes, written and
//! counted as a lowering is, within the store's cap.
//!
//! The files live in two generations, `g<N>/` (young) and `g<N-1>/` (old), which the consumer's cap
//! ([`DeviceOptions::pipeline_cache_cap`]) bounds at half of it each. A lookup tries young, then
//! old; a hit in old is renamed into young, which is its mark of use. Generations start at 1, and
@@ -88,6 +105,7 @@ use crate::counters::{Counters, Gauge, Metric};
use crate::device::{lock, Core};
use crate::times::host_time;
use ash::vk;
use metal2vulkan::cache::{Hash256, ARTIFACT_FORMAT_VERSION, SEMANTICS_VERSION};
use std::collections::VecDeque;
use std::fs::{self, File};
use std::io::{self, ErrorKind, Read, Write};
@@ -132,6 +150,13 @@ const REFUSED: &[u8] = b"m2v-refused";
const OBSERVES: &[u8] = b"m2v-observes";
/// The translations' directory, under a generation.
const TRANSLATIONS: &str = "translations";
/// The render contents' records' directory, under a generation.
const RENDERS: &str = "renders";
/// The first bytes of a render content's record: its layout's name and version.
const RECORD: &[u8; 8] = b"m2vrndr1";
/// The length of a render content's record ([`record_bytes`]): its first bytes, two versions, the
/// descriptor's key, two stages of a tag and a digest each, and the checksum.
pub(crate) const RECORD_LEN: usize = 8 + 4 + 4 + 32 + 2 * 33 + 8;
/// The directory, under a generation, an earlier version kept a file of pipeline data per
/// `VkPipeline` in: removed where it is found.
const PIPELINES: &str = "pipelines";
@@ -705,6 +730,66 @@ pub(crate) fn frame(data: &[u8]) -> [u8; 24] {
head
}
/// What a render content's record holds: the `FunctionCompileKey` digest of each of its
/// functions' lowerings, `None` for a stage the descriptor gives compiled, or has not.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Lowerings {
pub(crate) vertex: Option<Hash256>,
pub(crate) fragment: Option<Hash256>,
}
/// The record of the render content of descriptor key digest `content` (the module's doc):
/// [`RECORD`], the translator's semantics and artifact format versions, `content`, each stage's
/// tag (1 for a lowering, 0 for none) and digest (zeros for none), and the [`checksum`] of all of
/// them, [`RECORD_LEN`] bytes.
pub(crate) fn record_bytes(content: &Hash256, lowerings: &Lowerings) -> Vec<u8> {
let mut bytes = Vec::with_capacity(RECORD_LEN);
bytes.extend_from_slice(RECORD);
bytes.extend_from_slice(&SEMANTICS_VERSION.to_le_bytes());
bytes.extend_from_slice(&ARTIFACT_FORMAT_VERSION.to_le_bytes());
bytes.extend_from_slice(content);
for stage in [lowerings.vertex, lowerings.fragment] {
bytes.push(u8::from(stage.is_some()));
bytes.extend_from_slice(&stage.unwrap_or_default());
}
let sum = checksum(&bytes);
bytes.extend_from_slice(&sum.to_le_bytes());
bytes
}
/// The lowerings `bytes` record for the render content of descriptor key digest `content`, where
/// they are the record [`record_bytes`] writes for it under this build's versions; none for
/// another content's record, another layout or version, or bytes cut short or changed.
pub(crate) fn read_record(bytes: &[u8], content: &Hash256) -> Option<Lowerings> {
let (body, sum) = bytes.split_last_chunk::<8>()?;
let (magic, rest) = body.split_first_chunk::<8>()?;
let (semantics, rest) = rest.split_first_chunk::<4>()?;
let (format, rest) = rest.split_first_chunk::<4>()?;
let (key, rest) = rest.split_first_chunk::<32>()?;
let (vertex, rest) = recorded_stage(rest)?;
let (fragment, rest) = recorded_stage(rest)?;
(rest.is_empty()
&& magic == RECORD
&& u32::from_le_bytes(*semantics) == SEMANTICS_VERSION
&& u32::from_le_bytes(*format) == ARTIFACT_FORMAT_VERSION
&& key == content
&& u64::from_le_bytes(*sum) == checksum(body))
.then_some(Lowerings { vertex, fragment })
}
/// A stage of a record, its tag and digest, and the bytes after it; none for another tag, or a
/// digest that is not zeros beside tag 0.
fn recorded_stage(bytes: &[u8]) -> Option<(Option<Hash256>, &[u8])> {
let (&tag, rest) = bytes.split_first()?;
let (digest, rest) = rest.split_first_chunk::<32>()?;
let stage = match tag {
1 => Some(*digest),
0 if *digest == [0; 32] => None,
_ => return None,
};
Some((stage, rest))
}
/// A device's caches: the lowerings in the store, and the `VkPipelineCache` every `VkPipeline`
/// is made through, with its blob.
pub(crate) struct Caches {
@@ -729,7 +814,7 @@ pub(crate) struct Caches {
grown: AtomicBool,
/// [`PIPELINE_CACHE_BOUND`], lower in a test.
bound: AtomicU64,
/// The lowerings and refusals waiting for the reaper to write them.
/// The lowerings, refusals and records waiting for the reaper to write them.
pending: Mutex<Pending>,
/// Whether the reaper's writes wait, for a test.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
@@ -841,10 +926,25 @@ pub(crate) struct PipelineCache(vk::PipelineCache);
/// already, they are dropped and counted (`Metrics::cache_writes_dropped`), never waited for: a
/// lowering is only a cache, and a later state lowers it again.
pub(crate) fn keep_translation(core: &Core, key: &[u8], bytes: Vec<u8>) {
keep(core, Caches::translation_file(key), bytes);
}
/// Hands the record of the render content of descriptor key digest `content`, the keys of its
/// functions' lowerings, to the reaper, as [`keep_translation`] does a lowering.
pub(crate) fn keep_record(core: &Core, content: &Hash256, lowerings: &Lowerings) {
keep(
core,
Caches::record_file(content),
record_bytes(content, lowerings),
);
}
/// Hands `bytes` to the reaper, to write as `file` in the store ([`keep_translation`]).
fn keep(core: &Core, file: String, bytes: Vec<u8>) {
if core.caches.store.is_none() {
return;
}
let queued = lock(&core.caches.pending).push(Caches::translation_file(key), bytes);
let queued = lock(&core.caches.pending).push(file, bytes);
match queued {
true => core.reaper.poke(),
false => core.counters.count(Metric::CacheWritesDropped),
@@ -1151,6 +1251,20 @@ impl Caches {
format!("{TRANSLATIONS}/{}", hex(key))
}
/// The file, under a generation, of the record of the render content of descriptor key digest
/// `content`.
pub(crate) fn record_file(content: &Hash256) -> String {
format!("{RENDERS}/{}", hex(content))
}
/// The lowerings the record of the render content of descriptor key digest `content` names,
/// where the store holds one that reads as its record ([`read_record`]); bytes that do not are
/// removed, a miss.
pub(crate) fn record(&self, content: &Hash256) -> Option<Lowerings> {
let file = Caches::record_file(content);
(self.store.as_ref()?).get(&file, |bytes| read_record(bytes, content))
}
/// What `decode` makes of the bytes kept for a lowered kernel of key digest `key`, where they
/// decode. A file that holds the translator's refusal, or its answer that the kernel observes
/// its partition, is no lowering, and stays.
@@ -1167,7 +1281,7 @@ impl Caches {
kept.flatten()
}
/// The next lowering or refusal waiting for the reaper to write it.
/// The next lowering, refusal or record waiting for the reaper to write it.
pub(crate) fn next_write(&self) -> Option<(String, Vec<u8>)> {
lock(&self.pending).pop()
}
+28 -3
View File
@@ -100,6 +100,10 @@ pub(crate) enum Metric {
Translations,
/// [`Metrics::translations_loaded`].
TranslationsLoaded,
/// [`Metrics::render_records_read`].
RenderRecordsRead,
/// [`Metrics::render_records_stale`].
RenderRecordsStale,
/// [`Metrics::creations_before_seed`].
CreationsBeforeSeed,
/// [`Metrics::cache_writes_dropped`].
@@ -159,6 +163,8 @@ const METRIC_ORDER: [Metric; METRICS] = [
Metric::DispatchesWithoutEffects,
Metric::Translations,
Metric::TranslationsLoaded,
Metric::RenderRecordsRead,
Metric::RenderRecordsStale,
Metric::CreationsBeforeSeed,
Metric::CacheWritesDropped,
Metric::RingWrites,
@@ -395,6 +401,8 @@ struct Atomics {
allocation_map_refusals: AtomicU64,
translations: AtomicU64,
translations_loaded: AtomicU64,
render_records_read: AtomicU64,
render_records_stale: AtomicU64,
creations_before_seed: AtomicU64,
pipeline_cache_looks_skipped: AtomicU64,
pipeline_cache_lock_waits: AtomicU64,
@@ -543,6 +551,8 @@ impl Counters {
Metric::DispatchesWithoutEffects => &a.dispatches_without_effects,
Metric::Translations => &a.translations,
Metric::TranslationsLoaded => &a.translations_loaded,
Metric::RenderRecordsRead => &a.render_records_read,
Metric::RenderRecordsStale => &a.render_records_stale,
Metric::CreationsBeforeSeed => &a.creations_before_seed,
Metric::CacheWritesDropped => &a.cache_writes_dropped,
Metric::RingWrites => &a.ring_writes,
@@ -1108,6 +1118,8 @@ impl Counters {
dispatches_without_effects: a.dispatches_without_effects.load(Relaxed),
translations: a.translations.load(Relaxed),
translations_loaded: a.translations_loaded.load(Relaxed),
render_records_read: a.render_records_read.load(Relaxed),
render_records_stale: a.render_records_stale.load(Relaxed),
creations_before_seed: a.creations_before_seed.load(Relaxed),
pipeline_cache_looks_skipped: a.pipeline_cache_looks_skipped.load(Relaxed),
pipeline_cache_lock_waits: a.pipeline_cache_lock_waits.load(Relaxed),
@@ -1459,6 +1471,19 @@ pub struct Metrics {
pub translations: u64,
/// Lowered kernels a pipeline state took from the cache directory in place of a lowering.
pub translations_loaded: u64,
/// Render contents a state took by their record in the cache directory
/// ([`DeviceOptions::pipeline_cache_dir`]): the keys of the content's lowerings, kept under the
/// translator's key of its descriptor, which reads no function, so the state read the
/// lowerings with no decode or specialization of either function. Each lowering it read is in
/// [`translations_loaded`](Self::translations_loaded) too.
///
/// [`DeviceOptions::pipeline_cache_dir`]: crate::DeviceOptions::pipeline_cache_dir
pub render_records_read: u64,
/// Render contents whose record in the cache directory named a lowering the directory no
/// longer held (a removed generation took it, or it was not written): each took the path of
/// a content with no record, decoding and specializing its functions, and kept the record
/// again.
pub render_records_stale: u64,
/// `VkPipeline` creations that went through the device's empty pipeline cache while the
/// reaper read and took in the device's blob ([`DeviceOptions::pipeline_cache_dir`]): each
/// compiled without the blob's data, and those pipelines are not in this run's blob, so a
@@ -1483,9 +1508,9 @@ pub struct Metrics {
/// The longest such wait, in nanoseconds; a maximum since the device was made, so the
/// difference of two reads does not apply to it.
pub pipeline_cache_lock_wait_max_nanos: u64,
/// Lowerings and refusals not kept in the cache directory: each was handed to the reaper,
/// which writes them off every guest thread, while the ones waiting for it held 8 MiB, and was
/// dropped rather than waited for. A later device lowers it again.
/// Lowerings, refusals and render contents' records not kept in the cache directory: each was
/// handed to the reaper, which writes them off every guest thread, while the ones waiting for
/// it held 8 MiB, and was dropped rather than waited for. A later device lowers it again.
pub cache_writes_dropped: u64,
/// Bytes written to the cache directory ([`DeviceOptions::pipeline_cache_dir`]): lowered
/// kernels, and the device's pipeline cache blob each time it is written: once creation is
+4 -4
View File
@@ -409,10 +409,10 @@ pub struct DeviceOptions {
/// Vulkan features the consumer needs for its own raw Vulkan work, each enabled where the
/// device reports it ([`Device::features`]).
pub features: Vec<ConsumerFeature>,
/// The directory the device keeps the compute and render functions it lowered and its
/// pipeline cache in, made where it is missing, so a later device on it, in this process or
/// another, takes them in place of lowering and compiling again
/// ([`Metrics::translations_loaded`]). The lowerings take at most
/// The directory the device keeps the compute and render functions it lowered, each render
/// content's record of its lowerings and its pipeline cache in, made where it is missing, so a
/// later device on it, in this process or another, takes them in place of lowering and
/// 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
+14 -6
View File
@@ -53,8 +53,9 @@ use crate::ring::CHUNK;
use crate::sampler::{canonical, constexpr_notes, hold_constexpr, release_constexpr};
use crate::times::host_time;
use ash::vk;
use metal2vulkan::cache::Hash256;
use metal2vulkan::error::{Error as TranslationError, Feature};
use metal2vulkan::library::CompiledFunction;
use metal2vulkan::library::{CompiledFunction, FunctionCompileKey};
use metal2vulkan::metal::{BindingAccess, BindingType};
use metal2vulkan::pipeline::{
arena_bytes, AccessSet, Axis, BindingSource, BufferKind, CombinedSampler, ComputePipeline,
@@ -951,17 +952,24 @@ fn kept(
function: &FunctionDescriptor,
inputs: &LoweringInputs,
) -> Option<CompiledFunction> {
let translator = &core.translator;
let key = translator.function_compile_key(function, inputs);
let kept = (core.caches).translation(key.digest(), |bytes| {
CompiledFunction::from_bytes_for_key(bytes, &key, translator).ok()
});
let key = core.translator.function_compile_key(function, inputs);
let kept = loaded(core, key.digest());
if kept.is_some() {
core.counters.count(Metric::TranslationsLoaded);
}
kept
}
/// The lowering of `FunctionCompileKey` digest `key` a device kept in the cache directory, where
/// its bytes decode for that key; not counted.
pub(crate) fn loaded(core: &Core, key: &Hash256) -> Option<CompiledFunction> {
let translator = &core.translator;
let key = FunctionCompileKey::new(*key);
(core.caches).translation(key.digest(), |bytes| {
CompiledFunction::from_bytes_for_key(bytes, &key, translator).ok()
})
}
/// The kernel `function` lowered under `inputs`: the lowering a device kept in the cache directory
/// ([`kept`]), or one made now and kept.
pub(crate) fn lower(
+1 -1
View File
@@ -274,7 +274,7 @@ enum Next {
Lower(Weak<Compiled>, Which),
/// Look at the pipeline cache, creation being quiet.
Look,
/// Write a lowering or refusal to the store.
/// Write a lowering, refusal or record to the store.
Write(String, Vec<u8>),
/// End, after telling the contents whose lowering is left that it will not run.
End(VecDeque<(Weak<Compiled>, Which)>),
+114 -45
View File
@@ -9,9 +9,11 @@
//! modules and their `VkPipeline`s. The device's one map of contents (`kernel_map`), which compute
//! states use too, holds each content's, so a state of a content the map holds costs the key and a
//! lookup. A content the map does not hold is decoded, keyed for its compile
//! (`Device::render_variant_key`) and lowered. The cost of keying on the descriptor: two
//! descriptors that differ only in a field their compile does not read are two contents, each
//! compiled.
//! (`Device::render_variant_key`) and lowered, and its record, the keys of its two lowerings, is
//! kept in the cache directory under the descriptor's key (`crate::cache`): a device after it on
//! the directory reads the record and the two lowerings in place of decoding, keying and lowering
//! the content. The cost of keying on the descriptor: two descriptors that differ only in a field
//! their compile does not read are two contents, each compiled.
//!
//! What a `VkPipeline` bakes is what Vulkan 1.3 cannot leave dynamic: the content, and the
//! topology class (point, line or triangle) of the draws it serves. Everything Metal sets on the
@@ -45,22 +47,23 @@
//! ([`FieldValue::Word`]). A per-instance factor step function and an enabled factor scale, which
//! the replay streams' states never use, are refused ([`RenderPipelineKind::Tessellation`]).
use crate::counters::Gauge;
use crate::cache::{self, Lowerings};
use crate::counters::{Gauge, Metric};
use crate::device::{lock, Core};
use crate::error::{Error, Gap, RenderPipelineKind};
use crate::hazard::Access;
use crate::kernel_map::KernelKey;
use crate::pass::Pass;
use crate::pipeline::{
access, lower, made_through_cache, number_samplers, of_the_device, texture_access, FieldValue,
Numbered, PUSH_BYTES,
access, loaded, lower, made_through_cache, number_samplers, of_the_device, texture_access,
FieldValue, Numbered, PUSH_BYTES,
};
use crate::reaper::{Free, Job};
use crate::ring::CHUNK;
use crate::sampler::constexpr_notes;
use crate::times::host_time;
use ash::vk;
use metal2vulkan::cache::VariantKey;
use metal2vulkan::cache::{Hash256, VariantKey};
use metal2vulkan::device::EnabledCaps;
use metal2vulkan::metal::BindingAccess;
use metal2vulkan::pipeline::{
@@ -249,8 +252,12 @@ impl crate::Device {
/// triangle-class `VkPipeline` is made here. Where the device has a cache directory
/// ([`DeviceOptions::pipeline_cache_dir`]), a lowering a device made before is read from it in
/// place of lowering again, and each `VkPipeline` is made through the pipeline data kept for
/// it there. A point or line class's `VkPipeline` comes with the draws. The
/// `completionHandler:` forms are not built (no replay stream calls them).
/// it there; a content a device made before is read by its record there, kept under the
/// translator's key of the descriptor, which names its two lowerings, so its functions are
/// neither decoded nor specialized
/// ([`Metrics::render_records_read`](crate::Metrics::render_records_read)). A point or line
/// class's `VkPipeline` comes with the draws. The `completionHandler:` forms are not built (no
/// replay stream calls them).
///
/// [`DeviceOptions::pipeline_cache_dir`]: crate::DeviceOptions::pipeline_cache_dir
///
@@ -291,13 +298,22 @@ impl crate::Device {
Some(compiled) => compiled,
None => {
let budget = Budget::standard();
let entries = &core.entries;
let keys = (core.translator)
.render_variant_key(descriptor, &VariantKey::new(), &budget, entries)
.map_err(Error::Translation)?;
let compiled = RenderCompiled::of(core, descriptor, &keys, &budget, entries);
core.note_entries();
let compiled = compiled?;
let content = key.pipeline.digest();
let lowered = match recorded(core, descriptor, content) {
Some(lowered) => lowered,
None => {
let entries = &core.entries;
let keys = (core.translator)
.render_variant_key(descriptor, &VariantKey::new(), &budget, entries)
.map_err(Error::Translation)?;
let lowered = lower_stages(core, descriptor, &keys, &budget, entries);
core.note_entries();
let (lowered, lowerings) = lowered?;
cache::keep_record(core, content, &lowerings);
lowered
}
};
let compiled = RenderCompiled::of(core, &lowered, &budget)?;
(core.kernels).keep_render(key, Arc::new(compiled), &core.counters)
}
};
@@ -719,40 +735,93 @@ impl Fixed {
}
}
/// `descriptor` with each `Function` stage lowered under `keys` through the cache directory
/// ([`lower`]), and the keys of the lowerings, which the content's record keeps
/// ([`cache::keep_record`]).
fn lower_stages(
core: &Core,
descriptor: &RenderPipelineDescriptor,
keys: &RenderPipelineKeys,
budget: &Budget,
entries: &StageEntries,
) -> Result<(RenderPipelineDescriptor, Lowerings), Error> {
let mut lowered = descriptor.clone();
let mut lowerings = Lowerings {
vertex: None,
fragment: None,
};
if let (StageSource::Function(function), Some(inputs)) =
(&descriptor.vertex, &keys.vertex_inputs)
{
let function = lower(core, function, inputs, budget, entries);
let function = function.map_err(Error::Translation)?;
lowerings.vertex = Some(*function.key().digest());
lowered.vertex = StageSource::Compiled(function);
}
// The fragment function's push fields follow the vertex function's in the floor's one
// range, from the vertex function's end.
let base = match &lowered.vertex {
StageSource::Compiled(vertex) => vertex.fragment_push_base(),
StageSource::Function(_) => 0,
};
if let (Some(StageSource::Function(function)), Some(inputs)) =
(&descriptor.fragment, &keys.fragment_inputs)
{
let mut inputs = inputs.clone();
inputs.push_base = base;
let function = lower(core, function, &inputs, budget, entries);
let function = function.map_err(Error::Translation)?;
lowerings.fragment = Some(*function.key().digest());
lowered.fragment = Some(StageSource::Compiled(function));
}
Ok((lowered, lowerings))
}
/// `descriptor` with each `Function` stage the lowering its content's record names, where the
/// cache directory holds the record of `content`, the descriptor's key, and every lowering it
/// names (the key holds each stage's kind, so the record names a lowering for each `Function`
/// stage the compile lowered, as [`lower_stages`] kept them): read with no decode or
/// specialization of a function, counted
/// ([`Metrics::render_records_read`](crate::Metrics::render_records_read), each lowering in
/// `translations_loaded`). None where it holds no record, and the content takes the path of a
/// content with no record; a record that names a lowering the directory no longer holds is
/// counted ([`Metrics::render_records_stale`](crate::Metrics::render_records_stale)).
fn recorded(
core: &Core,
descriptor: &RenderPipelineDescriptor,
content: &Hash256,
) -> Option<RenderPipelineDescriptor> {
let lowerings = core.caches.record(content)?;
let read = |key: Option<Hash256>| key.map(|key| loaded(core, &key));
let (vertex, fragment) = (read(lowerings.vertex), read(lowerings.fragment));
if matches!(vertex, Some(None)) || matches!(fragment, Some(None)) {
core.counters.count(Metric::RenderRecordsStale);
return None;
}
let mut lowered = descriptor.clone();
if let Some(Some(vertex)) = vertex {
lowered.vertex = StageSource::Compiled(vertex);
core.counters.count(Metric::TranslationsLoaded);
}
if let Some(Some(fragment)) = fragment {
lowered.fragment = Some(StageSource::Compiled(fragment));
core.counters.count(Metric::TranslationsLoaded);
}
core.counters.count(Metric::RenderRecordsRead);
Some(lowered)
}
impl RenderCompiled {
/// The translation of `descriptor` under `keys`, its stages lowered through the cache
/// directory, with its triangle-class `VkPipeline`.
/// The translation of `lowered`, a descriptor whose `Function` stages are lowered
/// ([`lower_stages`], [`recorded`]), with its triangle-class `VkPipeline`.
fn of(
core: &Arc<Core>,
descriptor: &RenderPipelineDescriptor,
keys: &RenderPipelineKeys,
lowered: &RenderPipelineDescriptor,
budget: &Budget,
entries: &StageEntries,
) -> Result<RenderCompiled, Error> {
let translator = &core.translator;
let mut lowered = descriptor.clone();
if let (StageSource::Function(function), Some(inputs)) =
(&descriptor.vertex, &keys.vertex_inputs)
{
let function = lower(core, function, inputs, budget, entries);
lowered.vertex = StageSource::Compiled(function.map_err(Error::Translation)?);
}
// The fragment function's push fields follow the vertex function's in the floor's one
// range, from the vertex function's end.
let base = match &lowered.vertex {
StageSource::Compiled(vertex) => vertex.fragment_push_base(),
StageSource::Function(_) => 0,
};
if let (Some(StageSource::Function(function)), Some(inputs)) =
(&descriptor.fragment, &keys.fragment_inputs)
{
let mut inputs = inputs.clone();
inputs.push_base = base;
let function = lower(core, function, &inputs, budget, entries);
lowered.fragment = Some(StageSource::Compiled(function.map_err(Error::Translation)?));
}
let pipeline =
(translator.compile_render_pipeline(&lowered, budget)).map_err(Error::Translation)?;
(translator.compile_render_pipeline(lowered, budget)).map_err(Error::Translation)?;
if let Some(kind) = unbuilt(&pipeline, translator.profile().enabled()) {
return Err(Error::Unsupported(Gap::RenderPipeline { kind }));
}
@@ -761,7 +830,7 @@ impl RenderCompiled {
.limits()
.supports_non_zero_first_instance;
let (draws, (numbered, constexprs)) = draws(&pipeline, nonzero_first_instance)?;
let samples = descriptor.raster_sample_count;
let samples = lowered.raster_sample_count;
let mut stages = Vec::new();
let mut notes: Vec<_> = constexpr_notes(translator.profile(), &constexprs).collect();
for stage in &pipeline.stages {
@@ -823,7 +892,7 @@ impl RenderCompiled {
core.counters.rise(Gauge::RenderContents);
// A state whose fragment function reaches an imageblock is not made (`unbuilt`), so its
// sample is its colors alone.
let colors = (descriptor.color_attachments).map(|color| color.map(|c| c.pixel_format));
let colors = (lowered.color_attachments).map(|color| color.map(|c| c.pixel_format));
let imageblock_sample = metal2vulkan::metal::format::imageblock_sample_length(&colors);
let mut compiled = RenderCompiled {
core: Arc::clone(core),
+103 -11
View File
@@ -1,4 +1,5 @@
//! The cache directory on the host: two generations under one cap, a hit in old moved into young,
//! The cache directory on the host: two generations under one cap, lowerings and render contents'
//! 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
@@ -8,8 +9,8 @@
//! or reading a file another was writing.
use crate::cache::{
blob_name, checksum, frame, prune_blobs, unframe, usable_header, Pending, State, Store,
BLOBS_KEPT,
blob_name, checksum, frame, prune_blobs, read_record, record_bytes, unframe, usable_header,
Caches, Lowerings, Pending, State, Store, BLOBS_KEPT, RECORD_LEN,
};
use crate::counters::Counters;
use std::fs;
@@ -66,6 +67,25 @@ fn name(n: u32) -> String {
format!("translations/{n:064x}")
}
/// A digest of `n`'s.
fn digest(n: u32) -> [u8; 32] {
let mut digest = [0; 32];
digest[..4].copy_from_slice(&n.to_le_bytes());
digest
}
/// The record of a render content of descriptor key `n`'s, as its file and its bytes.
fn record_of(n: u32) -> (String, Vec<u8>) {
let lowerings = Lowerings {
vertex: Some(digest(n + 1_000)),
fragment: Some(digest(n + 2_000)),
};
(
Caches::record_file(&digest(n)),
record_bytes(&digest(n), &lowerings),
)
}
/// `data` as its blob holds it, after its magic, length and checksum.
fn framed(data: &[u8]) -> Vec<u8> {
[&frame(data)[..], data].concat()
@@ -80,34 +100,44 @@ fn state(store: &Store) -> State {
store.current().expect("the state")
}
/// Filled past its cap with lowerings and render contents' records in turn, each a record's
/// length, the store keeps them within it, moving on a generation at each half, and keeps the last
/// ten whatever their kind.
#[test]
fn a_store_filled_past_its_cap_stays_within_it_and_moves_on() {
let len = RECORD_LEN as u64;
let file = |n: u32| match n % 2 {
0 => (name(n), vec![n as u8; RECORD_LEN]),
_ => record_of(n),
};
let scratch = Scratch::new("store-cap");
let store = Store::open(scratch.0.clone(), 1000, Counters::new());
let store = Store::open(scratch.0.clone(), 10 * len, Counters::new());
assert_eq!(state(&store), State { young: 1, bytes: 0 });
for n in 0..40 {
assert!(store.put(&name(n), &[n as u8; 100]), "file {n} written");
let (name, bytes) = file(n);
assert_eq!(bytes.len(), RECORD_LEN, "file {n}'s length");
assert!(store.put(&name, &bytes), "file {n} written");
// While a removal runs, the dead generation is on disk beside old and young.
assert!(
scratch.bytes() <= 1500,
scratch.bytes() <= 15 * len,
"{} bytes after {n}",
scratch.bytes()
);
store.settle();
let now = state(&store);
assert!(now.bytes <= 500, "{now:?} after {n}");
assert!(now.bytes <= 5 * len, "{now:?} after {n}");
assert_eq!(
bytes_under(&store.generation(now.young)),
now.bytes,
"young after {n}"
);
assert!(
scratch.bytes() <= 1000,
scratch.bytes() <= 10 * len,
"{} bytes after {n}",
scratch.bytes()
);
}
// Five files of 100 bytes a generation: the fortieth file is in the eighth.
// Five files a generation: the fortieth file is in the eighth.
assert_eq!(state(&store).young, 8);
// The last ten files are kept, in old and young, and none before them. (A lookup would move
// a file of old into young, and young is full.)
@@ -115,15 +145,77 @@ fn a_store_filled_past_its_cap_stays_within_it_and_moves_on() {
.map(|n| {
[7, 8]
.iter()
.any(|&g| store.generation(g).join(name(n)).exists())
.any(|&g| store.generation(g).join(file(n).0).exists())
})
.collect();
assert_eq!(kept, (0..40).map(|n| n >= 30).collect::<Vec<_>>());
// A kept record reads as its content's; a removed one is a miss.
let read = |n: u32| store.get(&file(n).0, |bytes| read_record(bytes, &digest(n)));
assert_eq!(
read(39).map(|lowerings| lowerings.fragment),
Some(Some(digest(2_039)))
);
assert_eq!(read(29), None, "a removed record");
// A file of more than half the cap is not kept.
assert!(!store.put(&name(40), &[0; 501]));
assert!(!store.put(&name(40), &vec![0; 5 * RECORD_LEN + 1]));
assert_eq!(store.get(&name(40), whole), None);
}
/// A render content's record reads back as what was kept, under its own content's key alone:
/// under another content's key, of another semantics or format version or layout (each sealed
/// again under its checksum, so the version is what refuses it), with a stage tag that is neither
/// a lowering nor none, cut short or longer, or with any one bit changed, it is no record.
#[test]
fn a_record_reads_only_as_its_own_content_s() {
let content = digest(7);
let lowerings = Lowerings {
vertex: Some(digest(8)),
fragment: None,
};
let bytes = record_bytes(&content, &lowerings);
assert_eq!(bytes.len(), RECORD_LEN);
assert_eq!(read_record(&bytes, &content), Some(lowerings));
assert_eq!(read_record(&bytes, &digest(9)), None, "another content's");
let sealed = |at: usize, value: u8| {
let mut moved = bytes.clone();
moved[at] = value;
let end = RECORD_LEN - 8;
let sum = checksum(&moved[..end]).to_le_bytes();
moved[end..].copy_from_slice(&sum);
moved
};
for (at, what) in [
(0, "another layout"),
(8, "another semantics version"),
(12, "another format version"),
] {
let moved = sealed(at, bytes[at] ^ 1);
assert_eq!(read_record(&moved, &content), None, "{what}");
}
// The vertex stage's tag is at 48, the fragment's at 81.
assert_eq!(read_record(&sealed(48, 2), &content), None, "a tag of 2");
assert_eq!(
read_record(&sealed(81, 1), &content),
Some(Lowerings {
vertex: Some(digest(8)),
fragment: Some([0; 32]),
}),
"the fragment's tag at 81"
);
assert_eq!(
read_record(&sealed(82, 1), &content),
None,
"a digest beside none"
);
assert_eq!(read_record(&bytes[..RECORD_LEN - 1], &content), None);
assert_eq!(read_record(&[&bytes[..], &[0]].concat(), &content), None);
for bit in 0..RECORD_LEN * 8 {
let mut flipped = bytes.clone();
flipped[bit / 8] ^= 1 << (bit % 8);
assert_eq!(read_record(&flipped, &content), None, "bit {bit} flipped");
}
}
#[test]
fn a_hit_in_old_moves_into_young_and_outlives_the_next_generation() {
let scratch = Scratch::new("store-old");
+1 -1
View File
@@ -1408,7 +1408,7 @@ pub(crate) mod on_device {
/// A fragment function that reads the texture `t`, which the boolean constant 0 gates, at
/// (0, 0) on its one path, and returns the texel plus (0, 1, 0, 0).
const ABSENT_READ: &str = r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"
pub(crate) const ABSENT_READ: &str = r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"
target triple = "air64_v28-apple-macosx26.0.0"
@has_t.MTL_FC_INIT_0_b = linkonce_odr hidden local_unnamed_addr addrspace(2) externally_initialized constant i8 undef, section "air.fc_initializer", align 1
+288 -5
View File
@@ -16,21 +16,36 @@
//! lowerings are read from the directory, and the triangle class's `VkPipeline` is made from
//! its file; the first device writes one pipeline file for each `VkPipeline` it made, and the
//! second writes nothing.
//! - A device on a cache directory a device before it made a render content in takes the content
//! by its record, reading the two lowerings it names and specializing neither function; with
//! the record removed it specializes both, and a record whose lowering was removed is stale,
//! counted. Each kind of input that changes a lowering (the library's content, the function, its
//! constant values, a field its specialization reads, and the device profile where the host has
//! two devices of the cfg's kind), changed once, misses the record, and a record of another
//! content under a content's name is no record of it.
//!
//! `llvm-as` assembles the fixtures; without it a test skips visibly.
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod on_device {
use crate::cache::{hex, read_record};
use crate::tests::command::on_device::{each_device, within};
use crate::tests::draw::on_device::ABSENT_READ;
use crate::tests::{devices_of_the_cfgs_kind, keeps_a_blob};
use crate::{
ColorAttachmentDescriptor, Device, DeviceOptions, Error, FunctionDescriptor, Gap, Gauges,
Library, Metrics, PixelFormat, RenderPipelineDescriptor, RenderPipelineKind,
RenderPipelineState, StageSource,
Library, Metrics, PhysicalDevice, PixelFormat, RenderPipelineDescriptor,
RenderPipelineKind, RenderPipelineState, StageSource,
};
use metal2vulkan::metal::BlendFactor;
use metal2vulkan_devtools::{fixtures_dir, llvm_assemble, AssembleError};
use std::path::Path;
use metal2vulkan::cache::{Hash256, VariantKey};
use metal2vulkan::library::{
FunctionCompileKey, FunctionConstantValue, FunctionConstantValues,
};
use metal2vulkan::metal::{BlendFactor, DataType};
use metal2vulkan::pipeline::StageEntries;
use metal2vulkan::Budget;
use metal2vulkan_devtools::{fixtures_dir, llvm_assemble, llvm_assemble_text, AssembleError};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::SystemTime;
@@ -360,4 +375,272 @@ mod on_device {
println!("{name}: a second device lowers nothing and writes nothing");
}
}
/// The files of kind `kind` (`renders`, the records, or `translations`, the lowerings) under
/// the generations of the cache directory `dir`, by path.
fn kept_files(dir: &Path, kind: &str) -> Vec<PathBuf> {
let mut files = Vec::new();
for generation in std::fs::read_dir(dir).into_iter().flatten().flatten() {
if generation.file_name().to_string_lossy().starts_with('g') {
let kept = std::fs::read_dir(generation.path().join(kind));
files.extend(kept.into_iter().flatten().flatten().map(|file| file.path()));
}
}
files.sort();
files
}
/// A device of `physical` on the cache directory `dir`.
fn on_directory(name: &str, physical: &PhysicalDevice, dir: &Path) -> Device {
let options = DeviceOptions {
pipeline_cache_dir: Some(dir.to_owned()),
..DeviceOptions::default()
};
Device::new(physical, options).unwrap_or_else(|error| panic!("{name}: {error}"))
}
/// The translator's key of `d`'s descriptor on `device`, which names its record.
fn content(device: &Device, d: &RenderPipelineDescriptor) -> Hash256 {
*device
.core()
.translator
.queried_render_descriptor_key(d)
.digest()
}
/// Drops `device` and waits for its teardown, which ends once the reaper wrote what it was
/// given.
fn torn_down(device: Device) {
let counters = device.counters();
drop(device);
within("the teardown", || counters.gauges() == Gauges::default());
}
/// A device on a cache directory a device before it made a render content in takes the
/// content by its record: it reads the two lowerings the record names, and reads neither
/// function's AIR (the translator's stage entries count no read of a stage, to specialize it
/// or for a plain answer). The negative control: with the record removed, a device reads the
/// same two lowerings but reads both functions' AIR again, and keeps the record again. A record
/// whose fragment lowering was removed is stale, counted, and the device lowers that function
/// again and reads the vertex function's lowering.
#[test]
fn every_device_takes_a_render_content_by_its_record_without_specializing() {
let Some(library) = library() else {
return;
};
let d = descriptor(&library, "colored_fragment", PixelFormat::BGRA8Unorm);
let instance = crate::tests::validation::instance(&[]);
let devices = devices_of_the_cfgs_kind(&instance);
assert!(!devices.is_empty(), "no device of this cfg's kind");
for (name, physical) in &devices {
let dir = std::env::temp_dir().join(format!("m2v-rt-record-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut key = None;
for round in 0..4 {
if round == 2 {
for record in kept_files(&dir, "renders") {
std::fs::remove_file(record).expect("the record removed");
}
}
if round == 3 {
let records = kept_files(&dir, "renders");
assert_eq!(records.len(), 1, "{name}: the record kept again");
let bytes = std::fs::read(&records[0]).expect("the record");
let key = key.expect("the content's key");
let lowerings = read_record(&bytes, &key).expect("a record of the content");
let fragment = hex(&lowerings.fragment.expect("the fragment's lowering"));
let lowered = kept_files(&dir, "translations");
let file = lowered.iter().find(|file| file.ends_with(&fragment));
std::fs::remove_file(file.expect("the fragment's lowering"))
.expect("the fragment's lowering removed");
}
let device = on_directory(name, physical, &dir);
key = Some(content(&device, &d));
let counters = device.counters();
let (read_before, _) = device.core().entries.counts();
let made = state(name, &device, &d);
let (read_after, _) = device.core().entries.counts();
let m = counters.metrics();
let counted = (
m.render_records_read,
m.render_records_stale,
m.translations,
m.translations_loaded,
);
let want = [(0, 0, 2, 0), (1, 0, 0, 2), (0, 0, 0, 2), (0, 1, 1, 1)][round];
assert_eq!(
counted, want,
"{name}: device {round}'s records read and stale, lowerings made and read"
);
let reads = read_after - read_before;
assert_eq!(
reads > 0,
round != 1,
"{name}: device {round} read a stage's AIR {reads} times"
);
drop(made);
torn_down(device);
let records = kept_files(&dir, "renders").len();
assert_eq!(records, 1, "{name}: device {round} leaves one record");
}
let _ = std::fs::remove_dir_all(&dir);
println!("{name}: a record takes the content with no read of a function's AIR");
}
}
/// Each kind of input that changes a render content's lowerings, changed once from a content a
/// device made on a cache directory, misses that content's record on a device after it, and
/// never reads another content's record: the library's content (one constant of its fragment
/// function's body, every name kept), the fragment function, its constant values, and a field
/// of the descriptor its specialization reads (the colour attachment moved from index 0 to 1,
/// so the colour the function writes has none). The translator's keys of each changed
/// content's compile show the change reaches a lowering's key, and the base content, made
/// first on the second device, reads its record, so the record is there to miss. The base
/// content's record copied over the record of the constant's content is no record of it. The
/// device profile is the fifth kind: where the host has two devices of the cfg's kind whose
/// profiles differ, the second misses the first's record of the base descriptor; with one, that
/// part skips visibly. The translator's semantics and format versions are in every record,
/// which `a_record_reads_only_as_its_own_content_s` reads, and the semantics version in every
/// key of the translator's.
#[test]
fn every_device_misses_a_record_for_each_kind_of_input_that_changes_a_lowering() {
let Some(examples) = library() else {
return;
};
let assemble = |text: &str| match llvm_assemble_text(text) {
Ok(bitcode) => Some(Library::from_air(&bitcode).expect("the library")),
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
None
}
Err(error) => panic!("the fragment: {error:?}"),
};
let Some(gated) = assemble(ABSENT_READ) else {
return;
};
let added =
"<float 0.000000e+00, float 1.000000e+00, float 0.000000e+00, float 0.000000e+00>";
let moved = added.replace("float 1.000000e+00", "float 2.000000e+00");
assert_eq!(
ABSENT_READ.matches(added).count(),
1,
"the constant the fragment adds"
);
let Some(moved) = assemble(&ABSENT_READ.replace(added, &moved)) else {
return;
};
let fragment = |library: &Library, has_t: u8| {
let function = library.function("absent_read_fragment");
let mut f = FunctionDescriptor::new(function.expect("the function"));
f.constants = FunctionConstantValues::defaults()
.with_index(0, FunctionConstantValue::new(DataType::Bool, [has_t]));
f.specialized = true;
StageSource::Function(f)
};
let with = |fragment: StageSource| {
let vertex = examples.function("colored_vertex").expect("the function");
let mut d = RenderPipelineDescriptor::new(StageSource::Function(
FunctionDescriptor::new(vertex),
));
d.fragment = Some(fragment);
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm));
d
};
let base = with(fragment(&gated, 0));
let mut field = base.clone();
field.color_attachments[0] = None;
field.color_attachments[1] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm));
let changes = [
("the library's content", with(fragment(&moved, 0))),
(
"the fragment function",
descriptor(&examples, "colored_fragment", PixelFormat::RGBA8Unorm),
),
("its constant values", with(fragment(&gated, 1))),
("a field its specialization reads", field),
];
// The keys of each stage's lowering, as the translator keys the compile.
let keys = |device: &Device, d: &RenderPipelineDescriptor| {
let keys = (device.core().translator).render_variant_key(
d,
&VariantKey::new(),
&Budget::standard(),
&StageEntries::new(),
);
let keys = keys.unwrap_or_else(|error| panic!("the keys: {error}"));
(keys.vertex, keys.fragment)
};
let instance = crate::tests::validation::instance(&[]);
let devices = devices_of_the_cfgs_kind(&instance);
assert!(!devices.is_empty(), "no device of this cfg's kind");
let dir_of = |n: usize| {
let dir = format!("m2v-rt-records-{}-{n}", std::process::id());
std::env::temp_dir().join(dir)
};
let mut contents = Vec::new();
for (n, (name, physical)) in devices.iter().enumerate() {
let dir = dir_of(n);
let _ = std::fs::remove_dir_all(&dir);
let first = on_directory(name, physical, &dir);
contents.push(content(&first, &base));
drop(state(name, &first, &base));
let base_keys: (FunctionCompileKey, Option<FunctionCompileKey>) = keys(&first, &base);
torn_down(first);
let device = on_directory(name, physical, &dir);
// The base content's record, copied over the constant's content's.
let records = kept_files(&dir, "renders");
assert_eq!(records.len(), 1, "{name}: the base content's record");
let over = records[0].with_file_name(hex(&content(&device, &changes[2].1)));
std::fs::copy(&records[0], &over).expect("the record copied");
let counters = device.counters();
drop(state(name, &device, &base));
let m = counters.metrics();
assert_eq!(
m.render_records_read, 1,
"{name}: the base content's record read"
);
for (what, d) in &changes {
assert_ne!(keys(&device, d), base_keys, "{name}: {what} changes a key");
let before = counters.metrics();
drop(state(name, &device, d));
let after = counters.metrics();
let counted = |m: &Metrics| (m.render_records_read, m.render_records_stale);
assert_eq!(
counted(&after),
counted(&before),
"{name}: {what}: no record"
);
assert!(
after.translations > before.translations,
"{name}: {what}: a lowering made"
);
}
torn_down(device);
println!("{name}: each kind of input changed once misses the record");
}
// The device profile: each other device of the cfg's kind on the first's directory, which
// holds the first's record of the base content.
let first_name = &devices[0].0;
let mut others = 0;
for ((name, physical), content) in devices.iter().zip(&contents).skip(1) {
if *content == contents[0] {
println!("{name}: the profile of {first_name}");
continue;
}
let device = on_directory(name, physical, &dir_of(0));
let counters = device.counters();
drop(state(name, &device, &base));
let m = counters.metrics();
let counted = (m.render_records_read, m.render_records_stale);
assert_eq!(counted, (0, 0), "{name}: no record of {first_name}'s");
torn_down(device);
others += 1;
}
if others == 0 {
println!("SKIPPED: the device profile: one profile among this cfg's devices");
}
for n in 0..devices.len() {
let _ = std::fs::remove_dir_all(dir_of(n));
}
}
}
@@ -2817,6 +2817,8 @@ impl Backend for NewRuntime {
),
("translations", metrics.translations),
("translations_loaded", metrics.translations_loaded),
("render_records_read", metrics.render_records_read),
("render_records_stale", metrics.render_records_stale),
("ring_writes", metrics.ring_writes),
("upload_waits", metrics.upload_waits),
("staging_sleeps", metrics.staging_sleeps),
@@ -2451,6 +2451,8 @@ field metal2vulkan-rt::Metrics.private_long_reuses pub private_long_reuses: u64
field metal2vulkan-rt::Metrics.private_take_allocations pub private_take_allocations: SiteAllocations
field metal2vulkan-rt::Metrics.pushes pub pushes: u64
field metal2vulkan-rt::Metrics.pushes_held pub pushes_held: u64
field metal2vulkan-rt::Metrics.render_records_read pub render_records_read: u64
field metal2vulkan-rt::Metrics.render_records_stale pub render_records_stale: u64
field metal2vulkan-rt::Metrics.resolves pub resolves: u64
field metal2vulkan-rt::Metrics.ring_block_allocations pub ring_block_allocations: SiteAllocations
field metal2vulkan-rt::Metrics.ring_writes pub ring_writes: u64
Can't render this file because it is too large.