Record none of a pending dispatch's commands once a rebind freed what they name

The steps this packet landed as, in order:
- Pin the published crates' public surface by signature

Content: the tree of `development` at e46d17fe41, unchanged.
This commit is contained in:
Anees Iqbal committed 2026-10-26 13:19:17 +02:00
1 parent b2bbffa5d7
commit 2bd6f6fcf8
11 files changed
+15571 -2

No files matched your search

+6
View File
@@ -141,6 +141,12 @@ Edit the source, then regenerate:
| `crates/metal2vulkan/src/spv.rs`, `crates/metal2vulkan/src/spirv_binary/table.rs` | `scripts/regen-spirv-grammar/regen-spirv-grammar.sh` | Khronos SPIRV-Headers' grammar JSON, and `items.txt` beside the script |
| `crates/metal2vulkan-validation/profiles/*.json` | `scripts/regen-device-profiles/` | gpuinfo reports and local captures |
`crates/metal2vulkan/tests/api_signatures.tsv` is written the same way: the signature-level public
surface of the three published crates, by `python3 scripts/api-signatures/signatures.py --bless`
(`--check` to verify, `--selftest` for the derivation's own tests), from those crates' sources
alone. `crates/metal2vulkan/tests/api_signatures.rs` says what it pins, what it cannot see, and
what blessing it asserts; a removed or changed line is a breaking change of a published crate.
Three docs are checked by tests: `docs/FAST-PATHS.md` must name every `DevicePolicy` accuracy
choice and the notes it records (`tests::fast_paths`); `docs/API.md` must list every degrade code
with its category and quote `examples/api_preview.rs` verbatim in its `rust` blocks; and
@@ -1860,6 +1860,26 @@ impl CommandBuffer {
lock(&self.0.state)
}
/// Whether a buffer over host pages a command of its ended encoder at `encoder` named lies
/// elsewhere now than the command took it (`Rebinds::rebound_now`): a rebind since its commit
/// that no encoding again reached. The submission holding that encoder runs nothing and the
/// command buffer fails `CommandBufferError::EncodedUseRebound` (`first_submission.rs`), so
/// work of the encoder a host step records resolved as it was encoded records nothing
/// (`pending_dispatch.rs`): the descriptors it would record name a `VkBuffer` the rebind
/// freed. Read without the state's lock held, as the lock each submission reads it under is
/// taken inside this one.
pub(super) fn encoder_rebound(&self, encoder: usize) -> bool {
let rebinds = &self.0.device.shared().rebinds;
if !rebinds.any() {
return false;
}
let state = self.state();
let Some(record) = state.ended.get(encoder) else {
return false;
};
rebinds.rebound_now(&record.taken)
}
/// This command buffer as the device's commits that wait hold it ([`Waiting`]).
pub(crate) fn waiting(self) -> Arc<dyn Waiting> {
self.0
@@ -2209,6 +2209,28 @@ impl EncoderCore {
}
impl EncoderCore {
/// A segment that records nothing and takes no `VkCommandBuffer`, for work of an encoder
/// whose submission runs nothing: dead as one whose command named a detached buffer is
/// ([`skips`](Self::skips), `Taken::die`), so the submission never places it
/// (`State::place`) and no part of it reaches a `VkQueue`
/// (`State::runs_nothing_unrunnable`). Its caller has read that the encoder's submission
/// fails (`CommandBuffer::encoder_rebound`), which no later judging unreads: pages a
/// command took are compared by identity, and a buffer never lies in the pages it left.
pub(super) fn unrecorded_segment() -> RecordedSegment {
let mut taken = Taken::default();
taken.die();
RecordedSegment {
raws: Vec::new(),
summary: EncoderUses::new(false).finish(),
retained: Retained::default(),
executions: Vec::new(),
keys: BTreeSet::new(),
taken,
resident_misses: 0,
faults: ReplayFaults::default(),
}
}
/// A segment of `command_buffer` that `record` records alone into a new `VkCommandBuffer` of
/// its pool, retaining `retained`: no barrier around it and nothing tracked, its encoder
/// having tracked its commands where it left them ([`command_later`](Self::command_later)),
@@ -233,11 +233,27 @@ impl PendingDispatch {
/// Its segment of `command_buffer`, recorded once its pipelines are made: its barrier, then
/// its commands.
///
/// Nothing is recorded where a buffer over host pages one of its encoder's commands named
/// lies elsewhere now than the command took it (`CommandBuffer::encoder_rebound`): a rebind
/// since the commit that no encoding again reached, so the submission holding the dispatch
/// runs nothing and the command buffer fails `CommandBufferError::EncodedUseRebound`
/// (`command_buffer/first_submission.rs`). What it would record resolved as it was encoded,
/// its set 0 among it, and the rebind freed the `VkBuffer` those descriptors name: a
/// descriptor a command names must be valid as it is recorded, where its binding is not
/// `UPDATE_AFTER_BIND` (the Vulkan specification, Descriptor Set Binding: such contents
/// "may be consumed ... during host execution of the command, or during shader execution of
/// the resulting draws and dispatches, or any time in between"), and a driver that reads one
/// as it encodes reads freed memory. Its pipelines are made all the same, so a making that
/// failed fails the command buffer as it does where the dispatch records.
pub(super) fn record(&self, command_buffer: &CommandBuffer) -> Result<RecordedSegment, Error> {
let pipelines = self.made(command_buffer)?;
if let Some(creation) = &self.creation {
creation.get_or_init(|| pipelines.iter().map(|made| made.created_in).collect());
}
if command_buffer.encoder_rebound(self.encoder) {
return Ok(EncoderCore::unrecorded_segment());
}
let (barrier, recording, made) = (self.barrier, &self.recording, &pipelines);
let record = |raw: &Vk, cb: vk::CommandBuffer| {
// SAFETY: the segment's command buffer is recording outside a render pass, by this
@@ -391,6 +391,14 @@ impl Rebinds {
.is_some_and(|entry| entry.submitted > 0)
}
/// Whether a buffer a command of `taken` named lies elsewhere now than the command took it,
/// not detached ([`Submitting::rebound`]), taking nothing: what a command buffer's submission
/// of such a command finds, read before the submission by work of its that records later
/// (`pending_dispatch.rs`). One load while the device has no buffer over host pages.
pub(super) fn rebound_now(&self, taken: &Taken) -> bool {
self.any() && self.submitting().rebound(taken)
}
/// The buffers over host pages as a command buffer's batch is submitted, locked: what its
/// commands took is judged and held at once (`Submitting`), so no detach falls between.
pub(super) fn submitting(&self) -> Submitting<'_> {
@@ -168,6 +168,8 @@ mod own;
mod owned_kernel_builds;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod owned_pushes;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod pending_rebind;
mod pipeline;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod pipeline_wait_order;
@@ -0,0 +1,138 @@
//! A dispatch whose `VkPipeline`s are still being made (`pending_dispatch.rs`) and a rebind of a
//! no-copy buffer it named, made after its command buffer's commit and before the command
//! buffer's first submission (`rebind.rs`).
//!
//! Such a dispatch's commands are recorded later -- by the scheduler's host step once the makings
//! are done -- and they are the commands its encoding resolved: its set 0 names the `VkBuffer`
//! the buffer lay in as the dispatch was encoded. A rebind meanwhile frees that `VkBuffer`, since
//! a command buffer committed and not yet submitted holds the pages its commands took only weakly
//! (`first_submission.rs`), and the submission that holds the dispatch then runs nothing:
//! `CommandBufferError::EncodedUseRebound`, the encoder having kept no log a rebind encodes it
//! again from (`Unlogged::NoCalls`: the encoder opened while the device had no buffer over host
//! pages). So the host step records none of its commands.
//!
//! Recording them named a freed `VkBuffer` in a bound descriptor, which the validation layer
//! reports (`VUID-vkCmdDispatch-None-08114`) and a driver that reads a descriptor as it encodes
//! reads freed memory for: the Vulkan specification's Descriptor Set Binding has the contents a
//! binding without `VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT` is bound with consumed "during
//! host execution of the command, or during shader execution of the resulting draws and
//! dispatches, or any time in between", so a descriptor must be valid as its command is recorded.
//!
//! The device's pool's test hold (`pool::held`) keeps the makings waiting until the rebind is
//! made, so the host step records after it in every run, not only under load.
//!
//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. The kernel is `scale_and_offset` of the
//! owned fixture `validation/fixtures/public/examples/runtime_examples.ll`, as
//! `tests/dispatch_pending.rs` runs it.
use super::blit_holds::{over_host, Host, Scratch, WAIT};
use super::dispatch_pending::state;
use super::layer_claim::Watched;
use crate::pipeline::pool::held;
use crate::{
CommandBufferError, CommandBufferStatus, Device, DeviceKind, DeviceOptions, ResourceOptions,
ShaderCacheOptions, Size,
};
use std::path::Path;
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
/// The threads the dispatch runs, in threadgroups of this many: a `dispatchThreads` of a size the
/// state's creation predicts none of, so its making goes to the device's pool.
const COUNT: u64 = 1000;
const PER_GROUP: u64 = 64;
/// The scale the kernel multiplies by.
const SCALE: f32 = 2.0;
/// The device the cfg selects, its shader cache in `cache`, asking for the validation layer and
/// reporting to `watched`.
fn device(watched: &Watched, cache: &Path) -> Device {
let options = DeviceOptions {
kinds: match cfg!(m2v_cpu_icd) {
true => vec![DeviceKind::Cpu],
false => vec![
DeviceKind::Discrete,
DeviceKind::Integrated,
DeviceKind::Virtual,
],
},
shader_cache: ShaderCacheOptions {
directory: Some(cache.to_owned()),
..ShaderCacheOptions::default()
},
layers: watched.layers(),
messages: Some(watched.sink(|_| {})),
..DeviceOptions::default()
};
Device::system_default_with(&options).unwrap()
}
/// A dispatch of a kernel writing into a no-copy buffer, its `VkPipeline` held from being made,
/// and the buffer rebound after the commit: the command buffer fails `EncodedUseRebound`, writing
/// nothing into either range of pages, and the host step that records the dispatch once its
/// making is done records nothing of it -- the validation layer reports no descriptor naming the
/// `VkBuffer` the rebind freed.
#[test]
fn a_pending_dispatch_records_nothing_where_a_rebind_freed_what_its_descriptors_name() {
// Declared before the device, so dropped after it.
let hosts = [Host::new(), Host::new()];
let watched = Watched::default();
let scratch = Scratch::new("pending-rebind");
let device = device(&watched, &scratch.0);
let state = state(&device);
let queue = device.new_command_queue().unwrap();
let input: Vec<u8> = (0..COUNT).flat_map(|i| (i as f32).to_le_bytes()).collect();
let input = device
.new_buffer_with_bytes(&input, ResourceOptions::shared())
.unwrap();
let scale = device
.new_buffer_with_bytes(&SCALE.to_le_bytes(), ResourceOptions::shared())
.unwrap();
// Every making the pool starts waits from here: only a host step records the dispatch, and
// only once this hold is gone.
let hold = held::hold();
let command_buffer = queue.command_buffer().unwrap();
// Opened while the device has no buffer over host pages, so the encoder logs no call and no
// rebind encodes it again (`Unlogged::NoCalls`).
let mut encoder = command_buffer.compute_command_encoder().unwrap();
let runs = Arc::new(AtomicUsize::new(0));
let Some(output) = over_host(&device, &hosts[0], &runs) else {
return;
};
encoder.set_compute_pipeline_state(&state).unwrap();
encoder.set_buffer(Some(&input), 0, 0).unwrap();
encoder.set_buffer(Some(&output), 0, 1).unwrap();
encoder.set_buffer(Some(&scale), 0, 2).unwrap();
let pooled = device.work_counts().dispatch_pipelines_pooled;
encoder
.dispatch_threads(Size::new(COUNT, 1, 1), Size::new(PER_GROUP, 1, 1))
.unwrap();
assert!(
device.work_counts().dispatch_pipelines_pooled > pooled,
"the dispatch handed a making to the pool, so a host step records it"
);
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
// The buffer lies elsewhere from here, and the pages it lay in go: nothing submitted holds
// them, and the committed command buffer holds them weakly.
//
// SAFETY: the pages outlive every buffer over them, and only its commands use them while it
// lives.
unsafe { output.rebind_bytes_no_copy(hosts[1].memory(), None, None) }.unwrap();
// The makings may finish now, so the host step records the dispatch after the rebind.
drop(hold);
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Error);
assert_eq!(
command_buffer.error(),
Some(CommandBufferError::EncodedUseRebound),
"the submission holding the dispatch ran nothing"
);
assert!(hosts[0].holds(0), "the pages the dispatch took");
assert!(hosts[1].holds(0), "the pages the buffer lies in now");
watched.layer_reported_nothing(
"a dispatch recorded after a rebind of a buffer it named bound no freed VkBuffer",
);
}
+196
View File
@@ -0,0 +1,196 @@
//! The public surface of the three published crates, signature by signature.
//!
//! `api_surface` pins the **names** `metal2vulkan` exports and the construction class of each
//! public type; `metal2vulkan-air`'s own `api_surface` pins its names. Neither pins a method's
//! parameters or its return type, neither covers `metal2vulkan-runtime` at all, and neither sees a
//! method or an enum variant disappear — so a parameter added to a public method, a return type
//! widened to an `Option`, a unit variant that became a struct variant, and a `pub fn` that
//! stopped being public are all breaking changes those tables pass. This test is what makes them
//! fail.
//!
//! `scripts/api-signatures/signatures.py` derives the surface from the sources and
//! `tests/api_signatures.tsv` is what it must derive. The derivation reads source text only: no
//! build, no toolchain, and no rustdoc, whose JSON surface is nightly-only while this workspace
//! is pinned to stable. So it gives the same answer under any feature set, and the run is seconds.
//!
//! A record is `kind<TAB>key<TAB>signature`. The kinds are the declaration itself (`struct`,
//! `enum`, `fn`, `trait`, `type`, `const`, `static`), a public field or an enum variant (`field`,
//! `variant`), the `pub fn`, `pub const` and `pub type` of an inherent impl wherever in the crate
//! it lives (`method`, `assoc-const`, `assoc-type`), the header of each trait impl
//! (`trait-impl`), a public trait's own items (`trait-item`), a declaring macro's template
//! (`macro-template`) and the items one of its calls states (`macro-decl`, `macro-member`). A
//! constant's declaration and its value are two records (`const` and `const-value`, `assoc-const`
//! and `assoc-const-value`), so a value that moves is a different line from a type that moves, in
//! its own section of the report.
//!
//! # What blessing it asserts
//!
//! `python3 scripts/api-signatures/signatures.py --bless` rewrites the table and prints every
//! record that moved, with both sides of a change. Running it asserts that each of those moves is
//! **intended**, and that a removed or changed line — which is a breaking change of a published
//! crate — is one the commit means to make and says so in its message. It is not a way to make a
//! red test green: a line here is what a consumer's source is written against.
//!
//! # What it cannot see
//!
//! - A trait impl past its header. `impl Display for X` is a record; its `fmt` is not.
//! - A derived or a blanket impl, which no source states. The `#[derive(..)]` on the type is part
//! of its record, so a derive that is dropped does show.
//! - A method a macro expands. The declaring macro's template stands for every type it declares,
//! so a change to the generated methods shows once, against the template, not once per type.
//! - A value the build computes. `cache::SOURCE_DIGEST` is `env!("M2V_SOURCE_DIGEST")`: its type
//! is a record and its value is that call, never the digest.
//! - The values of `cache::SEMANTICS_VERSION`, `cache::ARTIFACT_FORMAT_VERSION` and
//! `cache::RUNTIME_VERSION`. Their declarations are pinned like any other constant; their
//! values are not recorded, because this repository bumps them whenever behaviour, an encoding
//! or a run changes — several times a day — and a table that holds them is blessed by reflex
//! within a day. Every other public constant's value is a record. `--check` holds each of the
//! three to a constant the surface still has, so the exception cannot outlive its constant.
//! - A generic bound past the declaration's own text, and whitespace: two spellings of one
//! signature read as a change. Bracket spacing and the comma the formatter leaves before a
//! closing bracket are put in one form first, so a signature that merely crossed the line width
//! does not read as a change in each of its arguments.
//! - `#[cfg]`: a gated item is read as present, with its gate kept in the signature, so a gate
//! that moves reads as a changed signature rather than as an item that came and went.
//! - A name two types share. Where a surface name's spelling also names a private type in the
//! same crate, or a type of another published crate whose items this one re-exports, their
//! records merge: twenty-one keys carry two. That over-reports — a change to the namesake shows
//! against the surface name — and never under-reports.
//! - `#[doc(hidden)]`, which `api_surface` calls public but not API: the runtime's
//! `generated_commands`, `Execution` and `CommandsReplayed` are not pinned here.
//! - `Send`, `Sync` and anything else the type system implies. `api_surface` and the runtime's
//! `consumer_auto_traits` own those.
//!
//! The derivation's own parse is held to the sources three ways, because a check over text fails
//! quietly: `--check` reproduces `api_surface`'s module-root table exactly on the real tree, the
//! table itself is the pin so a parse that went blind reads as thousands of removals, and
//! `--selftest` runs the derivation over little trees whose answer is known by construction, each
//! case asserting both a record that must be there and one that must not.
//!
//! `python3 scripts/api-signatures/signatures.py --check` prints the per-crate record counts and
//! the diff; `--print` prints the derived records.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;
/// The repository root.
fn root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
}
/// The table's own path.
fn table_path() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/api_signatures.tsv")
}
/// The derivation run with `verb`, as its own words and its exit status.
fn derivation(verb: &str) -> (bool, String) {
let script = root().join("scripts/api-signatures/signatures.py");
// `-B` so the run leaves no `__pycache__` beside the script: a test writes nothing into the
// tree it is checking.
let run = Command::new("python3")
.arg("-I")
.arg("-B")
.arg(&script)
.arg(verb)
.current_dir(root())
.output()
.unwrap_or_else(|error| panic!("python3 {} {verb}: {error}", script.display()));
let out = format!(
"{}{}",
String::from_utf8_lossy(&run.stdout),
String::from_utf8_lossy(&run.stderr)
);
(run.status.success(), out)
}
/// The table is the surface the sources state, record for record.
///
/// The failure names every record that moved and both sides of every change. A line here is a
/// published crate's API: see the module documentation for what blessing it asserts.
#[test]
fn the_public_signatures_are_the_committed_table() {
let (ok, out) = derivation("--check");
assert!(ok, "{out}");
}
/// The derivation records what it claims and refuses what it must.
///
/// The table catches a derivation that went **stale**. It cannot catch one that went **vacuous**:
/// a shape the parse stops recognising takes records out and a smaller surface then reads like the
/// truth, which is how `#[doc(hidden)]` and `#[cfg(test)]` items leaked into an earlier draft of
/// this derivation as if they were API. `--selftest` runs it over trees it writes itself, where
/// the answer follows from the sources, and every case asserts both directions.
#[test]
fn the_derivation_still_sees_what_it_claims() {
let (ok, out) = derivation("--selftest");
assert!(ok, "{out}");
}
/// The table is a table of the whole surface, not of a corner of it.
///
/// `--check` holds the table to the derivation, and holds the derivation to a floor. Neither
/// notices a table that was truncated and blessed while the derivation was truncated the same
/// way, so the committed file is read here on its own terms: every published crate is in it, in
/// quantity, and each kind of record it claims to carry is present. The floor is far under the
/// real counts and says only that a table of a few items is wrong rather than quiet.
#[test]
fn the_table_covers_all_three_published_crates() {
let path = table_path();
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{path:?}: {e}"));
let mut per_crate: BTreeMap<&str, usize> = BTreeMap::new();
let mut per_kind: BTreeMap<&str, usize> = BTreeMap::new();
for line in text.lines() {
if line.is_empty() || line.starts_with('#') {
continue;
}
let mut parts = line.splitn(3, '\t');
let kind = parts.next().unwrap_or_default();
let key = parts.next().unwrap_or_default();
assert!(
parts.next().is_some() && !kind.is_empty() && !key.is_empty(),
"{path:?}: not a `kind<TAB>key<TAB>signature` record: {line:?}"
);
*per_kind.entry(kind).or_default() += 1;
*per_crate
.entry(key.split("::").next().unwrap_or_default())
.or_default() += 1;
}
for name in ["metal2vulkan", "metal2vulkan-runtime", "metal2vulkan-air"] {
let got = per_crate.get(name).copied().unwrap_or_default();
assert!(
got >= 1000,
"{path:?} holds {got} record(s) for {name}, which is not that crate's public \
surface: the table was truncated, not derived. Counts: {per_crate:?}"
);
}
// The kinds the module documentation says a record may be. One that no longer appears is a
// parse that stopped seeing a whole class of item, which the per-crate counts would not move
// enough to catch.
for kind in [
"struct",
"enum",
"trait",
"type",
"fn",
"const",
"const-value",
"field",
"variant",
"method",
"assoc-const",
"assoc-const-value",
"trait-impl",
"trait-item",
"macro-template",
"macro-decl",
"macro-member",
] {
assert!(
per_kind.contains_key(kind),
"{path:?} holds no `{kind}` record, so the derivation no longer sees that kind of \
public item. Kinds: {per_kind:?}"
);
}
}
File diff suppressed because it is too large. Load diff
+6 -2
View File
@@ -23,8 +23,12 @@
//! breaking change whatever the attribute, or an enum every consumer must interpret completely, so
//! a new variant is a compile error there.
//!
//! Method signatures are not pinned here; `compiled_functions_round_trip_through_the_public_api`
//! and `compiled_render_stages_round_trip_through_the_public_api` drive the main consumer flow
//! Method signatures are not pinned here, and neither are fields, variants or the other two
//! published crates: `api_signatures` pins all of those, record by record, against
//! `tests/api_signatures.tsv`. A change this table cannot see — a method's parameters or return
//! type, a method or a variant removed, anything in `metal2vulkan-runtime` — fails there.
//! `compiled_functions_round_trip_through_the_public_api` and
//! `compiled_render_stages_round_trip_through_the_public_api` drive the main consumer flow
//! (compile, cache, link, plan, instantiate) through the public paths.
//!
//! The consumer reference (`scripts/api-docs`) renders exactly this table:
File diff suppressed because it is too large. Load diff