From bbbbe720a5dcb958eb7e9d0d7382d9b697a0d1da Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Fri, 23 Oct 2026 11:12:14 +0300 Subject: [PATCH] Count the allowances a run never needed The steps this packet landed as, in order: - Run the two-plane blits on Metal: the fill is private, the format is not - Say the call, not the format, wherever the suite explains a carried row - A verdict for "Metal did not return" - Count the answers that came from another chip Content: the tree of `development` at cfff72226b, unchanged. --- .../two-plane-announced-row-blits.json | 14 +- .../recordings/two-plane-heap-blits.json | 20 +- crates/metal2vulkan-conformance/src/case.rs | 43 +- crates/metal2vulkan-conformance/src/cases.rs | 5 +- .../src/cases/two_plane_copies.rs | 70 +- .../src/cases/two_plane_heap_blits.rs | 95 +-- .../metal2vulkan-conformance/src/compare.rs | 128 +++- crates/metal2vulkan-conformance/src/diff.rs | 12 + crates/metal2vulkan-conformance/src/lib.rs | 3 + .../src/metal_side.rs | 13 +- .../src/metal_work.rs | 692 ++++++++++++++++++ crates/metal2vulkan-conformance/src/record.rs | 29 + .../metal2vulkan-conformance/src/recording.rs | 22 + crates/metal2vulkan-conformance/src/replay.rs | 95 ++- crates/metal2vulkan-conformance/src/report.rs | 217 +++++- crates/metal2vulkan-conformance/src/run.rs | 11 + crates/metal2vulkan-conformance/src/tests.rs | 444 ++++++++++- .../metal2vulkan-conformance/src/verdict.rs | 82 ++- crates/metal2vulkan-conformance/src/work.rs | 15 +- 19 files changed, 1863 insertions(+), 147 deletions(-) create mode 100644 crates/metal2vulkan-conformance/src/metal_work.rs diff --git a/crates/metal2vulkan-conformance/recordings/two-plane-announced-row-blits.json b/crates/metal2vulkan-conformance/recordings/two-plane-announced-row-blits.json index 278af32b0..078507fd1 100644 --- a/crates/metal2vulkan-conformance/recordings/two-plane-announced-row-blits.json +++ b/crates/metal2vulkan-conformance/recordings/two-plane-announced-row-blits.json @@ -10,16 +10,12 @@ "os_build": "26A434", "metal_level": "27.0.1" }, - "provenance": { - "carried": { - "from": "runtime_lane::two_plane_copies, from the probes bp.m and pad.m (an Apple M3 Max, macOS 27.0.1)" - } - }, - "device": "apple-m3-max", - "runs": 1, + "provenance": "metal_run", + "device": "Apple M3 Max", + "runs": 3, "outcomes": [ { - "runs": 1, + "runs": 3, "transcript": { "root": { "name": "case", @@ -865,7 +861,7 @@ } } ], - "validated": "not_run" + "validated": "ran" } ] } diff --git a/crates/metal2vulkan-conformance/recordings/two-plane-heap-blits.json b/crates/metal2vulkan-conformance/recordings/two-plane-heap-blits.json index b5ecc52d7..56127905d 100644 --- a/crates/metal2vulkan-conformance/recordings/two-plane-heap-blits.json +++ b/crates/metal2vulkan-conformance/recordings/two-plane-heap-blits.json @@ -10,17 +10,12 @@ "os_build": "26A434", "metal_level": "27.0.1" }, - "provenance": { - "carried": { - "from": "runtime_lane::two_plane_heap_blits, from the probe tph: the heap digests on an Apple M4 under macOS 27.0.1 and an Apple M3 Max under macOS 26.7 alike, and the run shape recovered on an Apple M3 Max under MoltenVK", - "measured_on": "apple-m4" - } - }, - "device": "apple-m3-max", - "runs": 6, + "provenance": "metal_run", + "device": "Apple M3 Max", + "runs": 3, "outcomes": [ { - "runs": 6, + "runs": 3, "transcript": { "root": { "name": "case", @@ -21465,7 +21460,12 @@ } } ], - "validated": "not_run" + "validated": { + "stopped": { + "call": "work", + "message": "Copy From Texture Validation\n[sourceTexture pixelFormat](MTLPixelFormatRGB10A8_2P_XR10) must equal [destinationTexture pixelFormat](MTLPixelFormatRGB10A8_2P_XR10_sRGB)" + } + } } ] } diff --git a/crates/metal2vulkan-conformance/src/case.rs b/crates/metal2vulkan-conformance/src/case.rs index 259947858..5417c1257 100644 --- a/crates/metal2vulkan-conformance/src/case.rs +++ b/crates/metal2vulkan-conformance/src/case.rs @@ -516,9 +516,12 @@ pub trait Side { /// Run a copy-and-fill program ([`crate::work`]) and answer what it read. /// - /// Metal fills a texture through private API and its two-plane extended-range formats are - /// private too, so the Metal side has no public call for this and answers - /// [`Failure::unavailable`]; a case built on it carries its Metal answer. + /// The Metal side runs a program through public `objc2-metal` calls and refuses the two fills + /// alone, because `fillTexture:` and `fillTextureColor:` are Apple SPI. The pixel format a + /// case names is never the reason: it is a raw value, and Metal handles Apple's two-plane + /// extended-range formats publicly. So a program that fills carries its Metal answer; a + /// program of copies records on Metal. A side that runs no program at all answers + /// [`Failure::unavailable`], which is this default. fn work(&mut self, work: &crate::work::Work) -> Answer { let _ = work; Err(Failure::unavailable("work")) @@ -1004,6 +1007,26 @@ pub enum MetalSource { /// says otherwise ([`MetalSource::measured_on`]). measured_on: &'static str, }, + /// **Metal did not return from the call.** There is nothing to carry and nothing to run. + /// + /// A row of this shape has no value and no behaviour on Metal's side: the probe that found it + /// out ended Metal's process, so the lane it came from holds no line for it either — it is not + /// recorded-only material, it simply has no answer. What the case pins is the one fact there + /// is, that Metal never came back from the call, against our typed refusal at that site + /// ([`Verdict::MetalNeverReturned`](crate::verdict::Verdict::MetalNeverReturned)). + /// + /// **It is never produced by running the shape.** The transcript is stated by the case + /// ([`Case::carried_transcript`]) from a probe that already died, and record mode refuses the + /// row outright rather than taking an answer from it: this is the one source whose Metal leg + /// would end the process, and the suite's standing rule is that no case may do that. + DidNotReturn { + /// Where the probe that died is written down. + from: &'static str, + /// The call Metal did not return from, as the case names the site. + call: &'static str, + /// What happened, in the probe's own words: how Metal went away. + says: &'static str, + }, } impl MetalSource { @@ -1042,9 +1065,20 @@ impl MetalSource { measured_on: chip, }, Self::Run => Self::Run, + source @ Self::DidNotReturn { .. } => source, } } + /// A row whose Metal leg does not come back: `call` is the call, `says` is how Metal went + /// away, and `from` is where the probe that found that out is written down. + pub const fn did_not_return( + from: &'static str, + call: &'static str, + says: &'static str, + ) -> Self { + Self::DidNotReturn { from, call, says } + } + /// Why record mode must not run the case on Metal, where it must not. pub const fn forbidden(&self) -> Option<&'static str> { match self { @@ -1052,6 +1086,9 @@ impl MetalSource { re_record: ReRecord::Forbidden { reason }, .. } => Some(reason), + // Record mode must never run this one: the call it would make is the call Metal does + // not come back from. The case's own words are the reason a refusal prints. + MetalSource::DidNotReturn { says, .. } => Some(says), MetalSource::Run | MetalSource::Carried { .. } => None, } } diff --git a/crates/metal2vulkan-conformance/src/cases.rs b/crates/metal2vulkan-conformance/src/cases.rs index cba45c992..3751cb398 100644 --- a/crates/metal2vulkan-conformance/src/cases.rs +++ b/crates/metal2vulkan-conformance/src/cases.rs @@ -8,8 +8,9 @@ //! Metal probe's printed lines, which is what made them the first batch. Where Metal's whole path //! is public, record mode **runs** the probe rather than copying it: the mesh draws, the mesh draws //! behind a barrier, and the mesh draws of an indirect command buffer's own-state commands. Where -//! it is not, the case carries our own measurement and forbids re-recording: the private texture -//! fills, and an indirect command's read-back through private getters. +//! it is not, the case carries our own measurement and forbids re-recording: the texture fills, +//! whose `fillTexture:` is Apple SPI, and an indirect command's read-back through private getters. +//! The reason is always the *call*, never the pixel format a case names. //! //! [`rate_maps`] is the family where Metal's own API validation layer and plain Metal disagree, //! and it is what exercises the recording's second oracle ([`crate::validated`]). diff --git a/crates/metal2vulkan-conformance/src/cases/two_plane_copies.rs b/crates/metal2vulkan-conformance/src/cases/two_plane_copies.rs index be5c0b4f5..c339dc588 100644 --- a/crates/metal2vulkan-conformance/src/cases/two_plane_copies.rs +++ b/crates/metal2vulkan-conformance/src/cases/two_plane_copies.rs @@ -16,9 +16,14 @@ //! kept of its printed lines, so the site is **digest-only** and says so: the bytes between the //! rows are inside the digest, and nobody wrote them out. //! -//! Metal's answer is **carried** and re-recording is **forbidden**: the two-plane formats are -//! Apple's private ones and the fills go through private API, so the Metal side has no public call -//! to record either from. +//! **`two-plane-announced-row-blits` records on Metal; the other two carry their answer, and only +//! because of the fill.** The stated reason used to be that the two-plane formats are Apple's +//! private ones. That is wrong: the *format* is not private — `MTLTextureDescriptor`'s pixel format +//! is a raw value, and Metal makes, writes, blits and reads back 550 and 551 through entirely +//! public `objc2-metal` calls ([`crate::metal_work`]). What is private is `fillTexture:`. So the +//! announced blits, which fill nothing, run on Metal; `two-plane-row-blits` still carries its +//! answer because two of its twenty-two blits fill first, and `two-plane-pad-fills` because every +//! case of it is a fill. //! //! **Not ported, and why.** The lane's other three families stay the lane's: //! @@ -44,10 +49,14 @@ const MEASURED_IN: &str = "runtime_lane::two_plane_copies, from the probes bp.m and pad.m (an Apple M3 Max, \ macOS 27.0.1)"; -/// Why record mode must not run these cases on Metal. -const NO_PUBLIC_CALL: &str = - "the two-plane extended-range formats are Apple's private ones and their fills go through \ - private API, so no public call exists to record them from"; +/// Why record mode must not run a case that fills on Metal. +/// +/// The call, not the format: `fillTexture:` and `fillTextureColor:` are Apple SPI, and a case that +/// runs neither records on Metal whatever pixel format it names. +const PRIVATE_FILL: &str = + "the fill goes through fillTexture:/fillTextureColor:, which are Apple SPI, so no public call \ + exists to record it from; the two-plane extended-range formats themselves are public, and \ + the cases here that run no fill do record on Metal"; /// The runs the row-blit table stands on: the probe ran each blit once, and the announced ones /// three times alike. @@ -329,6 +338,27 @@ pub fn announced_row_blits() -> RowBlits { } impl RowBlits { + /// The transcript the probe's own printed words state: every word of every blit, as `bp.m` + /// printed it. + /// + /// For `two-plane-row-blits` this is the case's answer, because two of its blits fill. For + /// `two-plane-announced-row-blits`, which record mode runs on Metal, it is the cross-check: a + /// test holds the committed recording to it, so the probe's words and Metal's live answer must + /// agree. + pub fn printed_by_the_probe(&self) -> Result { + let mut sites = Sites::new(); + sites.push(crate::case::inputs_node(&self.inputs()?)); + for (at, blit) in self.blits().iter().enumerate() { + sites.leaf(format!("work/{at}"), answered()); + sites.push(Node::leaf( + row_site(at, blit), + Observed::value(words_value(&printed_words(blit.metal)?)), + )); + } + sites.notices(NOTICES_SITE, &[] as &[&str]); + Ok(sites.finish()) + } + /// The case's blits. fn blits(&self) -> &'static [RowBlit] { if self.announced { @@ -352,7 +382,12 @@ impl Case for RowBlits { } fn metal_source(&self) -> MetalSource { - MetalSource::carried_only(MEASURED_IN, NO_PUBLIC_CALL) + // The announced blits fill nothing, so every call they make is public and record mode + // takes Metal's own answer. The other twenty-two include two that fill first. + if self.announced { + return MetalSource::Run; + } + MetalSource::carried_only(MEASURED_IN, PRIVATE_FILL) } fn inputs(&self) -> Result, String> { @@ -406,17 +441,14 @@ impl Case for RowBlits { } fn carried_transcript(&self) -> Result, String> { - let mut sites = Sites::new(); - sites.push(crate::case::inputs_node(&self.inputs()?)); - for (at, blit) in self.blits().iter().enumerate() { - sites.leaf(format!("work/{at}"), answered()); - sites.push(Node::leaf( - row_site(at, blit), - Observed::value(words_value(&printed_words(blit.metal)?)), - )); + if self.announced { + // Record mode runs this one on Metal. Its probe's table stays as the cross-check + // ([`RowBlits::printed_by_the_probe`]), held against the committed recording by a + // test, so the words the probe printed still have to agree with what Metal answers + // here. + return Ok(None); } - sites.notices(NOTICES_SITE, &[] as &[&str]); - Ok(Some((ROW_BLIT_RUNS, sites.finish()))) + Ok(Some((ROW_BLIT_RUNS, self.printed_by_the_probe()?))) } fn run(&self, side: &mut dyn Side, sites: &mut Sites) -> Result<(), Abort> { @@ -626,7 +658,7 @@ impl Case for PadFills { } fn metal_source(&self) -> MetalSource { - MetalSource::carried_only(MEASURED_IN, NO_PUBLIC_CALL) + MetalSource::carried_only(MEASURED_IN, PRIVATE_FILL) } fn allowances(&self) -> Vec { diff --git a/crates/metal2vulkan-conformance/src/cases/two_plane_heap_blits.rs b/crates/metal2vulkan-conformance/src/cases/two_plane_heap_blits.rs index 34cc081d6..1e5d1f649 100644 --- a/crates/metal2vulkan-conformance/src/cases/two_plane_heap_blits.rs +++ b/crates/metal2vulkan-conformance/src/cases/two_plane_heap_blits.rs @@ -22,13 +22,22 @@ //! Upgrading the site to raw bytes later needs no rewrite: the same site gains a value beside its //! digest. //! -//! Metal's answer is **carried**: the two-plane extended-range formats are Apple's private ones -//! and Metal fills and places them through private API, so the Metal side has no public call to -//! record them from. The digests are the probe's, on an Apple M4 under macOS 27.0.1 (each blit -//! three times on the same bytes and every case twice, alike) and on an Apple M3 Max under macOS -//! 26.7, the same; the run shape was recovered on this M3 Max under MoltenVK, where every case's -//! recorded digest held. **The digests were not measured on this chip under this release**, which -//! the recording's provenance says in words. +//! **Record mode runs this case on Metal.** It used to carry its answer, on the stated reason that +//! the two-plane extended-range formats are Apple's private ones and so Metal has no public call +//! for them. That reason was wrong: the *format* is not private — `MTLTextureDescriptor`'s pixel +//! format is a raw value — and nothing this case does is Apple SPI. The heap, the placed textures, +//! the buffer over the heap, the texture-to-texture blit and the read-back are all public +//! `objc2-metal` calls, which is what the probe used to take the table in the first place +//! ([`crate::metal_work`]). +//! +//! The carried table stays, as a cross-check rather than as the answer +//! ([`HeapBlits::carried_from_the_m4`]): the digests the probe printed on an Apple M4 under macOS +//! 27.0.1 (each blit three times on the same bytes and every case twice, alike) and on an Apple M3 +//! Max under macOS 26.7, with the run shape recovered on this M3 Max under MoltenVK. A test holds +//! the committed recording to it, so "this M3 Max agrees with the M4, run shape and digest, in all +//! 25 cases" is a checked fact instead of a sentence. Note what the run shape's provenance was: +//! recovered under MoltenVK, which is *our* answer, not Metal's — so until record mode ran, that +//! site's expectation was never tied to Metal at all. use crate::allowance::Allowance; use crate::case::{call, Abort, Case, Input, MetalSource, Side}; @@ -37,19 +46,8 @@ use crate::replay::{notice_allowance, NOTICES_SITE}; use crate::transcript::{Digest, DigestKind, Node, Observed, Sites, Transcript, Value}; use crate::work::{Resource, Step, TextureSpec, Work}; -/// Where the carried values were measured. -const MEASURED_IN: &str = - "runtime_lane::two_plane_heap_blits, from the probe tph: the heap digests on an Apple M4 \ - under macOS 27.0.1 and an Apple M3 Max under macOS 26.7 alike, and the run shape recovered \ - on an Apple M3 Max under MoltenVK"; - -/// Why record mode must not run the case on Metal. -const NO_PUBLIC_CALL: &str = - "the two-plane extended-range formats are Apple's private ones, placed and blitted through \ - private API, so no public call exists to record them from"; - -/// The runs the carried table stands on: the probe ran each blit three times on the same bytes and -/// every case twice, alike. +/// The runs the carried cross-check table stands on: the probe ran each blit three times on the +/// same bytes and every case twice, alike. const MEASURED_RUNS: u32 = 6; /// The committed runs of bytes each case's blit changed, as `+` each, a line a @@ -364,6 +362,38 @@ pub fn heap_blits() -> HeapBlits { HeapBlits { name: HEAP_BLITS } } +impl HeapBlits { + /// The transcript the probe's own table states: the run shape it printed and the digest of + /// each case's heap, over the runs behind them. + /// + /// This was the case's answer while it was carried, and it is kept as the **cross-check** now + /// that record mode runs the case on Metal. A test holds the committed recording to it, so the + /// agreement between this M3 Max under macOS 27.0.1 and the probe's Apple M4 is a checked fact + /// rather than a claim in a comment — and the day Apple changes one of these blits, the + /// re-record and this table disagree where a reader can see it. + pub fn carried_from_the_m4(&self) -> Result<(u32, Transcript), String> { + let runs = public_fixture(METAL_RUNS)?; + let mut sites = Sites::new(); + sites.push(crate::case::inputs_node(&self.inputs()?)); + for case in &CASES { + sites.leaf(format!("work/{}", case.name), crate::case::answered()); + let shape = metal_runs(&runs, case.name)?; + for node in case_nodes( + case.name, + runs_value(&shape), + Digest { + kind: DigestKind::Sha256Prefix16, + hex: case.metal.to_owned(), + }, + ) { + sites.push(node); + } + } + sites.notices(NOTICES_SITE, &[] as &[&str]); + Ok((MEASURED_RUNS, sites.finish())) + } +} + /// The program one case runs: the heap, its two textures, the seed's bytes written through a /// buffer over the whole heap, one blit, and the heap's bytes read back. fn case_work(work: &mut Work, case: &Case2P) { @@ -504,8 +534,7 @@ impl Case for HeapBlits { } fn metal_source(&self) -> MetalSource { - MetalSource::carried_only(MEASURED_IN, NO_PUBLIC_CALL) - .measured_on(crate::recording::APPLE_M4) + MetalSource::Run } fn inputs(&self) -> Result, String> { @@ -543,28 +572,6 @@ impl Case for HeapBlits { )] } - fn carried_transcript(&self) -> Result, String> { - let runs = public_fixture(METAL_RUNS)?; - let mut sites = Sites::new(); - sites.push(crate::case::inputs_node(&self.inputs()?)); - for case in &CASES { - sites.leaf(format!("work/{}", case.name), crate::case::answered()); - let shape = metal_runs(&runs, case.name)?; - for node in case_nodes( - case.name, - runs_value(&shape), - Digest { - kind: DigestKind::Sha256Prefix16, - hex: case.metal.to_owned(), - }, - ) { - sites.push(node); - } - } - sites.notices(NOTICES_SITE, &[] as &[&str]); - Ok(Some((MEASURED_RUNS, sites.finish()))) - } - fn run(&self, side: &mut dyn Side, sites: &mut Sites) -> Result<(), Abort> { for (at, case) in CASES.iter().enumerate() { let mut work = Work::new(); diff --git a/crates/metal2vulkan-conformance/src/compare.rs b/crates/metal2vulkan-conformance/src/compare.rs index 41f51f1af..ae87e00c6 100644 --- a/crates/metal2vulkan-conformance/src/compare.rs +++ b/crates/metal2vulkan-conformance/src/compare.rs @@ -12,6 +12,10 @@ //! A case may name what *documents* its refusal — Metal's own API validation refusing the same //! call is the one thing that can — and the justification is still checked, but it buys an //! explanation in the report and not a pass. See [`crate::validated`]. +//! +//! The walk also counts the allowances it **did not** use ([`Unfired`]). A tolerance no site needed +//! is not a failure — it may be venue-specific — but it is a claim no run has checked, and until it +//! was counted a case could name one indefinitely without anybody noticing. use crate::allowance::{Allowance, Loosening, Offered, Unjustified}; use crate::diff::{Divergence, DivergenceKind, Side}; @@ -51,6 +55,24 @@ pub struct Refusal { pub documented_by: Option, } +/// A site where Metal did not return from the call and we gave a typed error. +/// +/// Its own outcome, because it is neither of the two it would otherwise be squeezed into. It is not +/// exact: there is no value on Metal's side to match. It is not divergent: there is no behaviour of +/// Metal's to differ from — the call ended Metal's process. And it is not a refusal, which is +/// reserved for a call plain Metal **answered**. +/// +/// **No allowance is consulted here**, in either direction. A case cannot loosen its way into this +/// outcome, and it cannot loosen its way out of the divergence it becomes when we answer where +/// Metal did not ([`crate::diff::DivergenceKind::AnsweredWhereMetalDidNotReturn`]). +#[derive(Clone, Debug, PartialEq)] +pub struct NeverReturned { + /// The site, as node names from the root. + pub path: String, + /// Our typed error, as the report prints it. + pub ours: String, +} + /// An allowance that does not hold: the case names it, and why it cannot be used. #[derive(Clone, Debug, PartialEq)] pub struct BadAllowance { @@ -59,15 +81,60 @@ pub struct BadAllowance { pub why: Unjustified, } +/// An allowance nothing on the run needed: the case names a tolerance and every site it covers +/// matched exactly. +/// +/// This is counted because an allowance that never fires is otherwise **invisible**. The up-front +/// check over a case's allowances exempts a degrade notice that was not announced — it has to, +/// since a notice is announced once per device per kind and the run's own notices are checked +/// where the allowance fires — so a case may name a tolerance no venue ever justifies and no run +/// says a word. The day some venue does fire it, the row reads "announced, justified" with nobody +/// ever having looked at whether the tolerance was the right one. Two such speculative allowances +/// were written and deleted by hand in this round; the suite now says so itself. +/// +/// It is **reported, not failed**: an allowance may be legitimately venue-specific, firing on +/// lavapipe where MoltenVK is exact. What the report says instead is how many fired nowhere at +/// all ([`crate::report::Report::unfired_everywhere`]), which is the suspicious shape. +#[derive(Clone, Debug, PartialEq)] +pub struct Unfired { + /// The allowance's path, as the case wrote it. + pub path: String, + /// What the case loosened there. + pub how: Loosening, + /// What the case named to justify it, in words. + pub justified_by: String, + /// Why that justification does not hold on this run, where it does not. An unfired allowance + /// whose justification is also missing is the speculative shape at its plainest: the case + /// names a notice the run never announced *and* no site needed the tolerance, so nothing + /// anywhere connects the two. + pub why: Option, +} + +impl std::fmt::Display for Unfired { + fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(out, "{} ({})", self.path, self.justified_by)?; + match &self.why { + Some(why) => write!(out, ", and {why}"), + None => Ok(()), + } + } +} + /// What comparing one run against its recording found. #[derive(Clone, Debug, Default, PartialEq)] pub struct Comparison { pub announced: Vec, pub divergences: Vec, pub refusals: Vec, + /// Sites where Metal did not return from the call and we gave a typed error. + pub never_returned: Vec, /// Allowances whose justification is gone. Each of these fails the case on its own: a /// difference nobody is accounting for. pub bad_allowances: Vec, + /// Allowances nothing on this run needed ([`Unfired`]). Reported, never fatal. + pub unfired: Vec, + /// How many allowances the case named, so a report can say "none of 2" rather than only "2". + pub named: usize, } impl Comparison { @@ -95,6 +162,7 @@ impl Comparison { self.announced.is_empty() && self.divergences.is_empty() && self.refusals.is_empty() + && self.never_returned.is_empty() && self.bad_allowances.is_empty() } } @@ -143,13 +211,34 @@ pub fn compare_run( found.note_bad(&allowance.path, why); } } + let mut fired = vec![false; allowances.len()]; let mut walk = Walk { allowances, offered, stopped, + fired: &mut fired, found: &mut found, }; walk.node("", &metal.root, &ours.root); + // An allowance no site needed is the case naming a tolerance this run cannot vouch for. It is + // counted rather than failed, and the justification is re-read here without the exemption the + // up-front check gives a notice, because "the tolerance fired nowhere and the notice was never + // announced" is the one shape nothing else in the suite can say. + found.named = allowances.len(); + for (allowance, fired) in allowances.iter().zip(&fired) { + if *fired { + continue; + } + found.unfired.push(Unfired { + path: allowance.path.clone(), + how: allowance.loosening.clone(), + justified_by: allowance.justified_by.describe(), + why: allowance + .justified_by + .unjustified(&offered) + .map(|why| why.to_string()), + }); + } found } @@ -171,6 +260,9 @@ struct Walk<'a> { offered: Offered<'a>, /// Whether the run stopped before the end: a site only Metal reached is then no divergence. stopped: bool, + /// One flag per allowance: whether the walk used it to justify a difference, or named it as + /// what documents a refusal. What stays false is an allowance this run never needed. + fired: &'a mut [bool], found: &'a mut Comparison, } @@ -342,6 +434,26 @@ impl Walk<'_> { if metal == ours { return; } + // Metal not coming back from the call is settled first, and without consulting an + // allowance at all. There is no value here to be within a tolerance of, and the one fact + // the row holds -- that we refuse where Metal went away -- must not be loosenable. + if let Value::Nothing(crate::transcript::Negative::NeverReturned) = metal { + match ours { + Value::Variant { name, .. } if name == "Err" => { + self.found.never_returned.push(NeverReturned { + path: path.to_owned(), + ours: crate::diff::print(ours), + }); + } + _ => self.found.divergences.push(Divergence::new( + path, + DivergenceKind::AnsweredWhereMetalDidNotReturn { + ours: crate::diff::print(ours), + }, + )), + } + return; + } // A refusal is settled before any allowance is consulted, because no allowance may turn // one into a pass: Metal answered the call and we did not. if refused(metal, ours) { @@ -480,13 +592,15 @@ impl Walk<'_> { fn refusal(&mut self, path: &str, ours: &Value) { let mut documented_by = None; let mut first_unjustified = None; - for allowance in self + for (at, allowance) in self .allowances .iter() - .filter(|allowance| allowance.covers(path)) + .enumerate() + .filter(|(_, allowance)| allowance.covers(path)) { match allowance.justified_by.unjustified(&self.offered) { None => { + self.fired[at] = true; documented_by = Some(allowance.justified_by.describe()); break; } @@ -529,17 +643,18 @@ impl Walk<'_> { let mut covering = self .allowances .iter() - .filter(|allowance| allowance.covers(path) && allowance.within(metal, ours)) + .enumerate() + .filter(|(_, allowance)| allowance.covers(path) && allowance.within(metal, ours)) .peekable(); if covering.peek().is_none() { return false; } let mut first_unjustified = None; let mut held = None; - for allowance in covering { + for (at, allowance) in covering { match allowance.justified_by.unjustified(&self.offered) { None => { - held = Some(allowance); + held = Some((at, allowance)); break; } Some(why) => { @@ -547,12 +662,13 @@ impl Walk<'_> { } } } - let Some(allowance) = held else { + let Some((at, allowance)) = held else { let (allowance, why) = first_unjustified.expect("a covering allowance"); let path = allowance.path.clone(); self.found.note_bad(&path, why); return false; }; + self.fired[at] = true; let difference = crate::allowance::difference(metal, ours); match self.found.announced.iter_mut().find(|held| { held.path == path && held.justified_by == allowance.justified_by.describe() diff --git a/crates/metal2vulkan-conformance/src/diff.rs b/crates/metal2vulkan-conformance/src/diff.rs index f1b2203e0..c5e547241 100644 --- a/crates/metal2vulkan-conformance/src/diff.rs +++ b/crates/metal2vulkan-conformance/src/diff.rs @@ -89,6 +89,14 @@ pub enum DivergenceKind { Unjustified { why: String }, /// The site's fields differ in which fields they hold. Field { name: String, held_by: Side }, + /// Metal did not return from the call, and we answered it. + /// + /// The case's recording says Metal never came back from this call: the probe that found that + /// out ended Metal's process, so there is no value and no behaviour to compare. What the case + /// pins is that *we* refuse there. Answering instead is a divergence from the one fact the row + /// holds, and it is the shape that keeps + /// [`Verdict::MetalNeverReturned`](crate::verdict::Verdict::MetalNeverReturned) able to fail. + AnsweredWhereMetalDidNotReturn { ours: String }, } /// Which side holds something the other does not. @@ -182,6 +190,10 @@ impl std::fmt::Display for DivergenceKind { DivergenceKind::Field { name, held_by } => { write!(out, "only {held_by} holds the field {name}") } + DivergenceKind::AnsweredWhereMetalDidNotReturn { ours } => write!( + out, + "Metal did not return from this call, and we answered it: {ours}" + ), } } } diff --git a/crates/metal2vulkan-conformance/src/lib.rs b/crates/metal2vulkan-conformance/src/lib.rs index db4e52a9b..5073d159f 100644 --- a/crates/metal2vulkan-conformance/src/lib.rs +++ b/crates/metal2vulkan-conformance/src/lib.rs @@ -61,6 +61,9 @@ pub mod work; #[cfg(target_os = "macos")] pub mod metal_side; +#[cfg(target_os = "macos")] +pub mod metal_work; + #[cfg(test)] mod tests; diff --git a/crates/metal2vulkan-conformance/src/metal_side.rs b/crates/metal2vulkan-conformance/src/metal_side.rs index a912fc7cd..c61c25693 100644 --- a/crates/metal2vulkan-conformance/src/metal_side.rs +++ b/crates/metal2vulkan-conformance/src/metal_side.rs @@ -678,6 +678,17 @@ impl Side for MetalSide { Ok(bytes.to_vec()) } + /// A copy-and-fill program, through public Metal alone ([`crate::metal_work`]). + /// + /// The fills (`fillTexture:` and `fillTextureColor:`) are Apple SPI and the interpreter refuses + /// those two steps, so a case built on a fill still carries its Metal answer. Everything else a + /// program states -- heaps, placed textures, textures over a buffer, views, every blit, + /// `replaceRegion:` and `getBytes:` -- is public Metal whatever pixel format the case names, + /// including Apple's two-plane extended-range 550 and 551. + fn work(&mut self, work: &crate::work::Work) -> Answer { + crate::metal_work::run(&self.device, &self.queue, work) + } + fn announced(&mut self) -> Vec { Vec::new() } @@ -1207,7 +1218,7 @@ impl MetalSide { /// The word a command buffer's status records as, in the runtime's spelling so the two sides' /// transcripts hold one vocabulary. -fn status_word(status: MTLCommandBufferStatus) -> &'static str { +pub(crate) fn status_word(status: MTLCommandBufferStatus) -> &'static str { match status { MTLCommandBufferStatus::NotEnqueued => "NotEnqueued", MTLCommandBufferStatus::Enqueued => "Enqueued", diff --git a/crates/metal2vulkan-conformance/src/metal_work.rs b/crates/metal2vulkan-conformance/src/metal_work.rs new file mode 100644 index 000000000..792e323ce --- /dev/null +++ b/crates/metal2vulkan-conformance/src/metal_work.rs @@ -0,0 +1,692 @@ +//! Running a [`Work`] program on native Metal, through public `objc2-metal` calls alone. +//! +//! This exists because a carried-only row's stated reason was wrong. `two_plane_copies` and +//! `two_plane_heap_blits` said the two-plane extended-range formats are Apple's private ones and so +//! Metal has no public call for them. **The format is not private.** `MTLTextureDescriptor`'s pixel +//! format is a raw value and Metal makes, writes, blits and reads back 550 and 551 through entirely +//! public calls; what is private is `fillTexture:`, the *fill*. Two lanes lost their Metal leg to +//! that confusion, and a case can only run on Metal if something runs the program. +//! +//! So the interpreter mirrors [`crate::runtime_work`] call for call, in the same order, with one +//! blit encoder at a time, and refuses exactly the steps Metal really has no public call for: +//! `fillTexture:` and `fillTextureColor:`, which are Apple SPI. A case built on those still carries +//! its Metal answer; a case built on copies does not. +//! +//! Nothing here is unsafe for the GPU that the probes these cases came from were not: the same +//! shapes, through the same public calls, are what produced the tables in the first place. + +use crate::case::{Answer, Failure}; +use crate::work::{Done, Plane, Rect, Resource, Step, TextureKind, TextureSpec, Work}; +use objc2::rc::Retained; +use objc2::runtime::ProtocolObject; +use objc2_metal::{ + MTLBlitCommandEncoder, MTLBlitOption, MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, + MTLCommandQueue, MTLDevice, MTLHeap, MTLHeapDescriptor, MTLHeapType, MTLOrigin, MTLPixelFormat, + MTLRegion, MTLResourceOptions, MTLSize, MTLStorageMode, MTLTexture, MTLTextureDescriptor, + MTLTextureType, MTLTextureUsage, +}; + +/// A resource the program made on Metal. +enum Made { + Buffer(Retained>), + Heap(Retained>), + Texture(Retained>), +} + +/// Run `work` on `device` through `queue`, answering what it read. +pub fn run( + device: &ProtocolObject, + queue: &ProtocolObject, + work: &Work, +) -> Answer { + let mut made: Vec = Vec::with_capacity(work.resources.len()); + for (at, resource) in work.resources.iter().enumerate() { + let one = make(device, &made, resource).map_err(|failure| at_resource(at, failure))?; + made.push(one); + } + let mut state = Run { + queue, + made, + command_buffer: None, + encoder: None, + reads: vec![None; work.reads()], + next_read: 0, + statuses: Vec::new(), + }; + for (at, step) in work.steps.iter().enumerate() { + state.step(step).map_err(|failure| at_step(at, failure))?; + } + state.close()?; + let reads = state + .reads + .into_iter() + .enumerate() + .map(|(slot, bytes)| { + bytes.ok_or_else(|| Failure::named("UnansweredRead", format!("read {slot}"))) + }) + .collect::>>>()?; + Ok(Done { + reads, + statuses: state.statuses, + }) +} + +/// The failure a resource's refusal is, naming which resource. The shape is +/// [`crate::runtime_work`]'s, so a refusal reads the same whichever side gave it. +fn at_resource(at: usize, failure: Failure) -> Failure { + Failure { + value: crate::transcript::Value::fields([ + ("resource", crate::transcript::Value::Uint(at as u64)), + ("refused", failure.value), + ]), + lacks: failure.lacks, + } +} + +/// The failure a step's refusal is, naming which step. +fn at_step(at: usize, failure: Failure) -> Failure { + Failure { + value: crate::transcript::Value::fields([ + ("step", crate::transcript::Value::Uint(at as u64)), + ("refused", failure.value), + ]), + lacks: failure.lacks, + } +} + +/// The storage mode and resource options a private or shared resource takes. +fn options(private: bool) -> (MTLStorageMode, MTLResourceOptions) { + if private { + ( + MTLStorageMode::Private, + MTLResourceOptions::StorageModePrivate, + ) + } else { + ( + MTLStorageMode::Shared, + MTLResourceOptions::StorageModeShared, + ) + } +} + +/// The descriptor `spec` names, field for field as [`crate::runtime_work`] builds it: the same +/// usage, the same array length, levels, samples and storage, so neither side can read a shape the +/// other does not. +fn descriptor(spec: &TextureSpec) -> Answer> { + let format = MTLPixelFormat(spec.format as usize); + let mut usage = MTLTextureUsage::ShaderRead; + if spec.render_target { + usage |= MTLTextureUsage::RenderTarget | MTLTextureUsage::PixelFormatView; + } + let (storage, resource_options) = options(spec.private); + if spec.kind == TextureKind::TextureBuffer { + // SAFETY: the constructor reads only the format, the width, the options and the usage it + // is given. + let descriptor = unsafe { + MTLTextureDescriptor::textureBufferDescriptorWithPixelFormat_width_resourceOptions_usage( + format, + spec.width as usize, + resource_options, + usage, + ) + }; + return Ok(descriptor); + } + // SAFETY: the constructor reads only the format and the size it is given. + let descriptor = unsafe { + MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped( + format, + spec.width as usize, + spec.height as usize, + false, + ) + }; + descriptor.setTextureType(match spec.kind { + TextureKind::Type2D => MTLTextureType::Type2D, + TextureKind::Type2DArray => MTLTextureType::Type2DArray, + TextureKind::Type2DMultisample => MTLTextureType::Type2DMultisample, + TextureKind::Type2DMultisampleArray => MTLTextureType::Type2DMultisampleArray, + TextureKind::TextureBuffer => MTLTextureType::TypeTextureBuffer, + }); + // SAFETY: each setter writes one field of a descriptor this call owns; nothing reads it until + // the texture is made. + unsafe { + descriptor.setArrayLength(spec.slices.max(1) as usize); + descriptor.setMipmapLevelCount(spec.levels.max(1) as usize); + descriptor.setSampleCount(spec.samples.max(1) as usize); + } + descriptor.setUsage(usage); + descriptor.setStorageMode(storage); + Ok(descriptor) +} + +/// Make one resource. +fn make( + device: &ProtocolObject, + made: &[Made], + resource: &Resource, +) -> Answer { + let heap_at = |at: usize| match made.get(at) { + Some(Made::Heap(heap)) => Ok(heap), + _ => Err(Failure::named("NoSuchResource", format!("heap {at}"))), + }; + let buffer_at = |at: usize| match made.get(at) { + Some(Made::Buffer(buffer)) => Ok(buffer), + _ => Err(Failure::named("NoSuchResource", format!("buffer {at}"))), + }; + let texture_at = |at: usize| match made.get(at) { + Some(Made::Texture(texture)) => Ok(texture), + _ => Err(Failure::named("NoSuchResource", format!("texture {at}"))), + }; + let heap_of = |size: u64, private: bool| -> Answer { + let (_, resource_options) = options(private); + let descriptor = MTLHeapDescriptor::new(); + descriptor.setType(MTLHeapType::Placement); + descriptor.setSize(size as usize); + descriptor.setResourceOptions(resource_options); + let heap = device.newHeapWithDescriptor(&descriptor).ok_or_else(|| { + Failure::named("NewHeapWithDescriptor", format!("{size} returned nil")) + })?; + Ok(Made::Heap(heap)) + }; + match resource { + Resource::Buffer { bytes } => { + let buffer = device + .newBufferWithLength_options( + bytes.len().max(1), + MTLResourceOptions::StorageModeShared, + ) + .ok_or_else(|| { + Failure::named( + "NewBufferWithLength", + format!("{} bytes returned nil", bytes.len()), + ) + })?; + let contents = buffer.contents(); + // SAFETY: the buffer was just made with at least `bytes.len()` bytes of shared + // storage, which the host reaches, and no command uses it yet. + unsafe { + std::ptr::copy_nonoverlapping( + bytes.as_ptr(), + contents.as_ptr().cast(), + bytes.len(), + ); + } + Ok(Made::Buffer(buffer)) + } + Resource::Heap { size, private } => heap_of(*size, *private), + Resource::HeapForTexture { spec, private } => { + let descriptor = descriptor(spec)?; + let sized = device.heapTextureSizeAndAlignWithDescriptor(&descriptor); + heap_of(sized.size as u64, *private) + } + Resource::HeapBuffer { + heap, + length, + offset, + } => { + let held = heap_at(*heap)?; + let resource_options = held.resourceOptions(); + // SAFETY: the heap is a placement heap whose bytes `[offset, offset + length)` are + // inside it, which the case states, and no resource of this program overlaps the + // range before its own steps run. + let buffer = unsafe { + held.newBufferWithLength_options_offset( + *length as usize, + resource_options, + *offset as usize, + ) + } + .ok_or_else(|| { + Failure::named( + "NewBufferWithLengthOffset", + format!("{length} bytes at {offset} returned nil"), + ) + })?; + Ok(Made::Buffer(buffer)) + } + Resource::Texture { spec } => { + let texture = device + .newTextureWithDescriptor(&descriptor(spec)?.clone()) + .ok_or_else(|| { + Failure::named("NewTextureWithDescriptor", format!("{spec:?} returned nil")) + })?; + Ok(Made::Texture(texture)) + } + Resource::HeapTexture { heap, spec, offset } => { + let held = heap_at(*heap)?; + let descriptor = descriptor(spec)?; + // SAFETY: the heap is a placement heap large enough for the texture at `offset`, + // which the case states as the probe's own placement. + let texture = + unsafe { held.newTextureWithDescriptor_offset(&descriptor, *offset as usize) } + .ok_or_else(|| { + Failure::named( + "NewTextureWithDescriptorOffset", + format!("{spec:?} at {offset} returned nil"), + ) + })?; + Ok(Made::Texture(texture)) + } + Resource::TextureOverBuffer { + buffer, + spec, + offset, + bytes_per_row, + } => { + let held = buffer_at(*buffer)?; + let texture = held + .newTextureWithDescriptor_offset_bytesPerRow( + &descriptor(spec)?.clone(), + *offset as usize, + *bytes_per_row as usize, + ) + .ok_or_else(|| { + Failure::named( + "NewTextureOverBuffer", + format!("{spec:?} at {offset} by {bytes_per_row} returned nil"), + ) + })?; + Ok(Made::Texture(texture)) + } + Resource::View { + texture, + format, + slice, + flatten, + } => { + let held = texture_at(*texture)?; + let kind = if *flatten { + MTLTextureType::Type2DMultisample + } else { + held.textureType() + }; + let levels = objc2_foundation::NSRange::new(0, 1); + let slices = objc2_foundation::NSRange::new(*slice as usize, 1); + // SAFETY: the view's format is of the texture's own size class, which the case states, + // and the level and slice ranges are inside the texture. + let view = unsafe { + held.newTextureViewWithPixelFormat_textureType_levels_slices( + MTLPixelFormat(*format as usize), + kind, + levels, + slices, + ) + } + .ok_or_else(|| { + Failure::named( + "NewTextureView", + format!("format {format} slice {slice} returned nil"), + ) + })?; + Ok(Made::Texture(view)) + } + } +} + +/// The interpreter's state as it runs a program. +struct Run<'a> { + queue: &'a ProtocolObject, + made: Vec, + command_buffer: Option>>, + encoder: Option>>, + reads: Vec>>, + next_read: usize, + statuses: Vec, +} + +impl Run<'_> { + /// The buffer resource `at`. + fn buffer(&self, at: usize) -> Answer>> { + match self.made.get(at) { + Some(Made::Buffer(buffer)) => Ok(buffer.clone()), + _ => Err(Failure::named("NoSuchResource", format!("buffer {at}"))), + } + } + + /// The texture resource `at`. + fn texture(&self, at: usize) -> Answer>> { + match self.made.get(at) { + Some(Made::Texture(texture)) => Ok(texture.clone()), + _ => Err(Failure::named("NoSuchResource", format!("texture {at}"))), + } + } + + /// The command buffer the steps encode into, made on first use. + fn command_buffer(&mut self) -> Answer>> { + if self.command_buffer.is_none() { + self.command_buffer = Some( + self.queue + .commandBuffer() + .ok_or_else(|| Failure::named("CommandBuffer", "returned nil"))?, + ); + } + Ok(self + .command_buffer + .clone() + .expect("the command buffer was just made")) + } + + /// The blit encoder the copies go into, opened on first use. + fn encoder(&mut self) -> Answer>> { + if self.encoder.is_none() { + let command_buffer = self.command_buffer()?; + self.encoder = Some( + command_buffer + .blitCommandEncoder() + .ok_or_else(|| Failure::named("BlitCommandEncoder", "returned nil"))?, + ); + } + Ok(self.encoder.clone().expect("the encoder was just opened")) + } + + /// The slot the next read answers. + fn slot(&mut self) -> usize { + let slot = self.next_read; + self.next_read += 1; + slot + } + + /// Run one step. + fn step(&mut self, step: &Step) -> Answer<()> { + match step { + // The two fills are Apple SPI: `fillTexture:` and `fillTextureColor:` are the calls + // that have no public form, and they are the only reason a copy-and-fill case has to + // carry its Metal answer. The format a case names is not the reason. + Step::FillTexture { .. } => Err(Failure::unavailable( + "fillTexture:level:slice:region:pattern: (Apple SPI)", + )), + Step::FillTextureColor { .. } => Err(Failure::unavailable( + "fillTextureColor:level:slice:region:color:packedInFormat: (Apple SPI)", + )), + Step::CopyBufferToTexture { + buffer, + offset, + bytes_per_row, + bytes_per_image, + size, + texture, + slice, + level, + origin, + plane, + } => { + let buffer = self.buffer(*buffer)?; + let texture = self.texture(*texture)?; + let encoder = self.encoder()?; + // SAFETY: the buffer holds `bytes_per_image` bytes from `offset` for the depth the + // size names, and the region is inside the texture's level and slice; both are the + // case's own statement of what the probe encoded. + unsafe { + encoder.copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_options( + &buffer, + *offset as usize, + *bytes_per_row as usize, + *bytes_per_image as usize, + size_of(size), + &texture, + *slice as usize, + *level as usize, + origin_of(origin), + option_of(*plane), + ); + } + Ok(()) + } + Step::CopyTextureToBuffer { + texture, + slice, + level, + origin, + size, + buffer, + offset, + bytes_per_row, + bytes_per_image, + plane, + } => { + let buffer = self.buffer(*buffer)?; + let texture = self.texture(*texture)?; + let encoder = self.encoder()?; + // SAFETY: the region is inside the texture's level and slice and the buffer holds + // the bytes the pitches name from `offset`, as the case states. + unsafe { + encoder.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage_options( + &texture, + *slice as usize, + *level as usize, + origin_of(origin), + size_of(size), + &buffer, + *offset as usize, + *bytes_per_row as usize, + *bytes_per_image as usize, + option_of(*plane), + ); + } + Ok(()) + } + Step::CopyTextureToTexture { + from, + from_slice, + from_level, + from_origin, + size, + to, + to_slice, + to_level, + to_origin, + } => { + let source = self.texture(*from)?; + let destination = self.texture(*to)?; + let encoder = self.encoder()?; + // SAFETY: both regions are inside their texture's level and slice, as the case + // states. + unsafe { + encoder.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin( + &source, + *from_slice as usize, + *from_level as usize, + origin_of(from_origin), + size_of(size), + &destination, + *to_slice as usize, + *to_level as usize, + origin_of(to_origin), + ); + } + Ok(()) + } + Step::CopyBufferToBuffer { + from, + from_offset, + to, + to_offset, + length, + } => { + let source = self.buffer(*from)?; + let destination = self.buffer(*to)?; + let encoder = self.encoder()?; + // SAFETY: both ranges are inside their buffer, as the case states. + unsafe { + encoder.copyFromBuffer_sourceOffset_toBuffer_destinationOffset_size( + &source, + *from_offset as usize, + &destination, + *to_offset as usize, + *length as usize, + ); + } + Ok(()) + } + // A render pass that clears one slice, and a per-sample read-back by a dispatch, are + // both public Metal. Neither is built here, because every case that needs one also + // needs a private fill and so carries its answer anyway; a case that needs one without + // a fill is where to build it. + Step::ClearPass { .. } => Err(Failure::unavailable( + "a clearing render pass on the Metal side of a Work program (not built)", + )), + Step::ReadSamples { .. } => Err(Failure::unavailable( + "a per-sample read-back on the Metal side of a Work program (not built)", + )), + Step::ReplaceRegion { + texture, + level, + slice, + region, + bytes, + bytes_per_row, + bytes_per_image, + } => { + let texture = self.texture(*texture)?; + let wanted = (*bytes_per_image as usize) + .max(*bytes_per_row as usize * region.size[1].max(1) as usize); + if bytes.len() < wanted { + return Err(Failure::named( + "TooFewBytes", + format!("{} bytes for a region needing {wanted}", bytes.len()), + )); + } + // SAFETY: `bytes` holds at least the rows and images the pitches name for the + // region, checked just above, and the region is inside the texture's level and + // slice as the case states. + unsafe { + texture.replaceRegion_mipmapLevel_slice_withBytes_bytesPerRow_bytesPerImage( + region_of(region), + *level as usize, + *slice as usize, + std::ptr::NonNull::from(bytes.as_slice()).cast(), + *bytes_per_row as usize, + *bytes_per_image as usize, + ); + } + Ok(()) + } + Step::GetBytes { + texture, + level, + slice, + region, + bytes_per_row, + bytes_per_image, + length, + } => { + let texture = self.texture(*texture)?; + let mut bytes = vec![0u8; *length]; + // SAFETY: `bytes` is `length` bytes, which the case sized for the region's rows + // and images at these pitches, and the caller waited for the command buffer that + // wrote the texture. + unsafe { + texture.getBytes_bytesPerRow_bytesPerImage_fromRegion_mipmapLevel_slice( + std::ptr::NonNull::from(bytes.as_mut_slice()).cast(), + *bytes_per_row as usize, + *bytes_per_image as usize, + region_of(region), + *level as usize, + *slice as usize, + ); + } + let slot = self.slot(); + self.reads[slot] = Some(bytes); + Ok(()) + } + Step::ReadBuffer { + buffer, + offset, + length, + } => { + let buffer = self.buffer(*buffer)?; + let bytes = read_buffer(&buffer, *offset, *length)?; + let slot = self.slot(); + self.reads[slot] = Some(bytes); + Ok(()) + } + Step::Commit => self.close(), + } + } + + /// Close the blit encoder, if one is open. + fn end_encoding(&mut self) { + if let Some(encoder) = self.encoder.take() { + encoder.endEncoding(); + } + } + + /// Close the encoder, commit the command buffer, wait for it and record its status. + fn close(&mut self) -> Answer<()> { + self.end_encoding(); + let Some(command_buffer) = self.command_buffer.take() else { + return Ok(()); + }; + command_buffer.commit(); + // Metal's own wait, as the probes these cases came from used. A case here encodes copies + // alone, so there is nothing for the GPU to spin on. + command_buffer.waitUntilCompleted(); + self.statuses + .push(crate::metal_side::status_word(command_buffer.status()).to_owned()); + Ok(()) + } +} + +/// `length` bytes of `buffer` from `offset`, as the host reads a shared buffer. +fn read_buffer( + buffer: &ProtocolObject, + offset: u64, + length: usize, +) -> Answer> { + let past = offset + .checked_add(length as u64) + .is_none_or(|end| end > buffer.length() as u64); + if past { + return Err(Failure::named( + "PastTheBuffer", + format!( + "{length} bytes at {offset} of a buffer of {}", + buffer.length() + ), + )); + } + let contents = buffer.contents(); + // SAFETY: `[offset, offset + length)` is inside the buffer's bytes, checked just above; the + // buffer is of shared storage, so the host reaches them; and the caller waited for the command + // buffer that wrote them. + let bytes = unsafe { + std::slice::from_raw_parts(contents.as_ptr().cast::().add(offset as usize), length) + }; + Ok(bytes.to_vec()) +} + +/// The region a rectangle names. +fn region_of(rect: &Rect) -> MTLRegion { + MTLRegion { + origin: origin_of(&rect.origin), + size: size_of(&rect.size), + } +} + +/// The origin an axis triple names. +fn origin_of(origin: &[u64; 3]) -> MTLOrigin { + MTLOrigin { + x: origin[0] as usize, + y: origin[1] as usize, + z: origin[2] as usize, + } +} + +/// The size an axis triple names. +fn size_of(size: &[u64; 3]) -> MTLSize { + MTLSize { + width: size[0] as usize, + height: size[1] as usize, + depth: size[2] as usize, + } +} + +/// The blit option a plane names. +fn option_of(plane: Plane) -> MTLBlitOption { + match plane { + Plane::Whole => MTLBlitOption::empty(), + Plane::Depth => MTLBlitOption::DepthFromDepthStencil, + Plane::Stencil => MTLBlitOption::StencilFromDepthStencil, + } +} diff --git a/crates/metal2vulkan-conformance/src/record.rs b/crates/metal2vulkan-conformance/src/record.rs index 100585496..b570670b5 100644 --- a/crates/metal2vulkan-conformance/src/record.rs +++ b/crates/metal2vulkan-conformance/src/record.rs @@ -124,6 +124,35 @@ pub fn carried( } } +/// The answer a row has where **Metal did not return** from the call: one outcome, which the case +/// states by hand from the probe that died, and a provenance naming the call. +/// +/// Nothing here runs anything. This is the one answer in the suite that cannot be taken by running +/// its own shape -- making the call is what ends Metal's process -- so [`record`] refuses such a +/// row ([`crate::case::MetalSource::forbidden`]) and this is the only way one is built. The +/// validated oracle is [`Validated::NotRun`] for the same reason: Metal's API validation layer was +/// never asked either, and the file says so rather than implying it was content. +pub fn never_returned( + level: MetalLevel, + from: &str, + call: &str, + device: &str, + runs: u32, + transcript: Transcript, +) -> Answer { + Answer { + key: recording::OracleKey::current(level), + provenance: Provenance::NeverReturned { + from: from.to_owned(), + call: call.to_owned(), + }, + device: device.to_owned(), + runs, + outcomes: vec![Outcome { runs, transcript }], + validated: Validated::NotRun, + } +} + /// Write `answers` as `case`'s recording. pub fn write(case: &dyn Case, answers: Vec) -> Result { let shaders = case.shaders()?; diff --git a/crates/metal2vulkan-conformance/src/recording.rs b/crates/metal2vulkan-conformance/src/recording.rs index 3f60b2d72..828e5d872 100644 --- a/crates/metal2vulkan-conformance/src/recording.rs +++ b/crates/metal2vulkan-conformance/src/recording.rs @@ -114,6 +114,18 @@ pub enum Provenance { #[serde(default = "oracle_chip", skip_serializing_if = "is_oracle_chip")] measured_on: String, }, + /// **Metal did not return from the call.** The answer is the absence of one: a probe made this + /// call and Metal never came back, so there is no value, no behaviour and nothing to re-take. + /// + /// It is written by hand from the probe that died, never by running the shape + /// ([`crate::case::MetalSource::DidNotReturn`]), and the site it names holds + /// [`Negative::NeverReturned`](crate::transcript::Negative::NeverReturned) rather than a value. + NeverReturned { + /// Where the probe that died is written down. + from: String, + /// The call Metal did not return from. + call: String, + }, } /// The chip a carried answer was measured on where its recording names none: the oracle's. @@ -137,6 +149,16 @@ impl Provenance { Provenance::Carried { measured_on, .. } if measured_on != ORACLE_CHIP => { Some(measured_on) } + Provenance::Carried { .. } + | Provenance::MetalRun + | Provenance::NeverReturned { .. } => None, + } + } + + /// The call Metal did not return from, where that is what the answer says. + pub fn never_returned_from(&self) -> Option<&str> { + match self { + Provenance::NeverReturned { call, .. } => Some(call), Provenance::Carried { .. } | Provenance::MetalRun => None, } } diff --git a/crates/metal2vulkan-conformance/src/replay.rs b/crates/metal2vulkan-conformance/src/replay.rs index b639fc4b7..581356589 100644 --- a/crates/metal2vulkan-conformance/src/replay.rs +++ b/crates/metal2vulkan-conformance/src/replay.rs @@ -6,7 +6,7 @@ use crate::allowance::{Justification, Offered}; use crate::case::{inputs_node, Case, MetalSource, Side, Venue, INPUTS_SITE}; -use crate::compare::compare_run; +use crate::compare::{compare_run, Unfired}; use crate::recording::{self, Answer, Lookup, Recording}; use crate::transcript::{Node, Sites, Transcript}; use crate::verdict::Verdict; @@ -23,10 +23,36 @@ pub struct Replayed { pub case: String, pub venue: Venue, pub verdict: Verdict, + /// How many allowances the case named, and which of them nothing on this run needed + /// ([`crate::compare::Unfired`]). Empty where no comparison happened at all — a venue that + /// lacks the feature fires nothing, and saying its allowances went unused would be noise. + pub allowances: Allowances, + /// The chip a carried answer was measured on, where that is not the oracle's + /// ([`crate::recording::Provenance::measured_elsewhere`]). The report counts these: an answer + /// carried from a machine that is gone is weaker evidence than one taken here, and the suite's + /// own rule is that a recording of another oracle is stale, so the one place that rule is + /// relaxed has to be visible rather than implied. + pub measured_on: Option, /// What our side observed, for a reader who wants the whole transcript after a failure. pub ours: Transcript, } +/// What a case's allowances did on one row. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Allowances { + /// How many the case named. + pub named: usize, + /// The ones no site of this run needed. + pub unfired: Vec, +} + +impl Allowances { + /// How many fired. + pub fn fired(&self) -> usize { + self.named.saturating_sub(self.unfired.len()) + } +} + /// Why a case could not be replayed at all. These are never verdicts: a stale recording must fail /// loudly rather than resolve to a pass or to a difference nobody can read. #[derive(Clone, Debug, PartialEq)] @@ -135,6 +161,8 @@ pub fn replay_against_known( verdict: Verdict::Unrecorded { why: format!("no Metal answer at Metal level {level}"), }, + allowances: Allowances::default(), + measured_on: None, ours, }) } @@ -153,54 +181,75 @@ pub fn replay_against_known( case: name.to_owned(), venue, verdict: Verdict::LacksFeature { needs: lacks }, + allowances: Allowances::default(), + measured_on: answer.provenance.measured_elsewhere().map(str::to_owned), ours, }); } - let verdict = verdict_over(case, answer, &ours, &announced, abort.is_some()); + let (verdict, allowances) = verdict_over(case, answer, &ours, &announced, abort.is_some()); Ok(Replayed { case: name.to_owned(), venue, verdict, + allowances, + measured_on: answer.provenance.measured_elsewhere().map(str::to_owned), ours, }) } /// The verdict of `ours` against `answer`'s outcomes: the most favourable of them, because Metal -/// produced any of the set and matching one of them is matching Metal. +/// produced any of the set and matching one of them is matching Metal. With it, what the case's +/// allowances did against that outcome. +/// +/// The allowances follow the verdict rather than being gathered over every outcome, because they +/// are a fact about the comparison the verdict came from: a racy case whose run matched the +/// outcome that needed no tolerance did not need the tolerance, however the other outcomes read. fn verdict_over( case: &dyn Case, answer: &Answer, ours: &Transcript, announced: &[String], stopped: bool, -) -> Verdict { +) -> (Verdict, Allowances) { let allowances = case.allowances(); let carried = match case.metal_source() { MetalSource::Carried { from, .. } => Some(from), - MetalSource::Run => None, + MetalSource::Run | MetalSource::DidNotReturn { .. } => None, }; - let mut best: Option = None; + let mut best: Option<(Verdict, Allowances)> = None; for outcome in &answer.outcomes { // The inputs come first: an answer taken from other bytes is no answer for this run. if let Some(why) = inputs_differ(&outcome.transcript, ours) { best = Some(better( best, - Verdict::Unrecorded { - why: match carried { - Some(from) => format!("{why}; the answer is carried from {from}"), - None => why, + ( + Verdict::Unrecorded { + why: match carried { + Some(from) => format!("{why}; the answer is carried from {from}"), + None => why, + }, }, - }, + Allowances::default(), + ), )); continue; } let offered = Offered::new(announced, &answer.validated); let found = compare_run(&outcome.transcript, ours, &allowances, offered, stopped); - best = Some(better(best, Verdict::of(&found, &answer.validated))); + let used = Allowances { + named: found.named, + unfired: found.unfired.clone(), + }; + best = Some(better(best, (Verdict::of(&found, &answer.validated), used))); } - best.unwrap_or(Verdict::Unrecorded { - why: "the recording's answer holds no outcome".to_owned(), + best.unwrap_or_else(|| { + ( + Verdict::Unrecorded { + why: "the recording's answer holds no outcome".to_owned(), + }, + Allowances::default(), + ) }) } @@ -237,10 +286,13 @@ fn input_diff(recorded: &Node, fed: &Node) -> String { moved.join(", ") } -/// The more favourable of two verdicts. -fn better(held: Option, found: Verdict) -> Verdict { +/// The more favourable of two verdicts, with the allowances of whichever is kept. +fn better( + held: Option<(Verdict, Allowances)>, + found: (Verdict, Allowances), +) -> (Verdict, Allowances) { match held { - Some(held) if rank(&held) <= rank(&found) => held, + Some(held) if rank(&held.0) <= rank(&found.0) => held, _ => found, } } @@ -250,10 +302,11 @@ fn rank(verdict: &Verdict) -> u8 { match verdict { Verdict::Exact => 0, Verdict::Announced { .. } => 1, - Verdict::LacksFeature { .. } => 2, - Verdict::Refused { .. } => 3, - Verdict::Divergent { .. } => 4, - Verdict::Unrecorded { .. } => 5, + Verdict::MetalNeverReturned { .. } => 2, + Verdict::LacksFeature { .. } => 3, + Verdict::Refused { .. } => 4, + Verdict::Divergent { .. } => 5, + Verdict::Unrecorded { .. } => 6, } } diff --git a/crates/metal2vulkan-conformance/src/report.rs b/crates/metal2vulkan-conformance/src/report.rs index 737cee6f3..4c6733f3a 100644 --- a/crates/metal2vulkan-conformance/src/report.rs +++ b/crates/metal2vulkan-conformance/src/report.rs @@ -3,6 +3,7 @@ //! Errors are counted apart from verdicts. A stale recording is not a verdict, and printing it as //! one would let it read as coverage. +use crate::compare::Unfired; use crate::known_refusals::{against, Expectation, KnownRefusal}; use crate::replay::{ReplayError, Replayed}; use crate::verdict::Verdict; @@ -99,6 +100,147 @@ impl Report { .collect() } + /// How many allowances the selection named, and how many of them no row needed. + /// + /// A tolerance that never fires is the suite's blind spot made visible. The up-front check + /// over a case's allowances cannot catch it — a degrade notice is announced once per device + /// per kind, so an allowance naming a notice this run did not announce has to be allowed to + /// stand — which means a case could name a tolerance no venue ever justifies and no run would + /// say a word. The day one did fire, the row would read "announced, justified" with nobody + /// having checked whether the tolerance was right. + /// + /// It does not fail a run, because an allowance may legitimately be venue-specific. What the + /// report calls out is the stronger shape: [`Report::unfired_everywhere`]. + pub fn allowance_counts(&self) -> (usize, usize) { + let named = self.rows.iter().map(|row| row.allowances.named).sum(); + let unfired = self + .rows + .iter() + .map(|row| row.allowances.unfired.len()) + .sum(); + (named, unfired) + } + + /// The allowances no row of the report needed, by case and path: those that fired on no venue + /// of this run at all, and what the case named to justify each. + /// + /// An allowance that fires on lavapipe and not on MoltenVK is doing its job; one that fires + /// nowhere is a claim this run cannot vouch for. The key is (case, path, justification), + /// because the same case may name several tolerances at one site — a notice is announced once + /// per device per kind, so which of them a run sees depends on what ran before it — and each + /// is its own claim. + pub fn unfired_everywhere(&self) -> Vec<(&str, &Unfired)> { + // A row says only which of its case's allowances went **unused**, so a claim fired on a + // row where that row compared at all and the claim is absent from its unfired list. A row + // that compared nothing — a venue that lacks the feature, a case with no answer — settles + // nothing either way, which is why `named` is read and not just the list's length. + let fired: BTreeSet<(&str, &str, &str)> = self + .rows + .iter() + .filter(|row| row.allowances.named > 0) + .flat_map(|row| { + let unused: BTreeSet<(&str, &str)> = row + .allowances + .unfired + .iter() + .map(|claim| (claim.path.as_str(), claim.justified_by.as_str())) + .collect(); + self.rows + .iter() + .filter(move |other| other.case == row.case) + .flat_map(|other| &other.allowances.unfired) + .filter(move |claim| { + !unused.contains(&(claim.path.as_str(), claim.justified_by.as_str())) + }) + .map(move |claim| { + ( + row.case.as_str(), + claim.path.as_str(), + claim.justified_by.as_str(), + ) + }) + }) + .collect(); + let mut everywhere: Vec<(&str, &Unfired)> = Vec::new(); + for row in &self.rows { + for claim in &row.allowances.unfired { + let key = ( + row.case.as_str(), + claim.path.as_str(), + claim.justified_by.as_str(), + ); + let already = everywhere.iter().any(|(case, held)| { + (*case, held.path.as_str(), held.justified_by.as_str()) == key + }); + if !fired.contains(&key) && !already { + everywhere.push((row.case.as_str(), claim)); + } + } + } + everywhere + } + + /// The allowances no row needed **and** no row could justify: the case names a tolerance, no + /// site of the run differed inside it, and the notice or entry it names did not hold either. + /// + /// This is the speculative shape at its plainest, and the one worth a stronger word than the + /// rest. Nothing in the run connects the tolerance to anything: it is a sentence about a + /// device that was not here. Two allowances of exactly this shape were written and deleted by + /// hand in this round, which is why the suite now counts them. + /// + /// It is still **reported, not fatal**. A degrade notice fires on the device that needs it, so + /// a tolerance for a notice no venue of this run announces may be right about another venue; + /// what the suite can say honestly is that no run has checked it. Making it fatal would + /// instead force a case to carry only the tolerances this Mac happens to need, which is a + /// worse rule: it would read as proof of a device nobody tested. + pub fn unchecked_everywhere(&self) -> Vec<(&str, &Unfired)> { + self.unfired_everywhere() + .into_iter() + .filter(|(case, claim)| { + // A row that did justify the claim settles it, whether or not it fired there: the + // notice was announced, so the tolerance is about something that happened. + self.rows.iter().all(|row| { + row.case != *case + || row.allowances.unfired.iter().all(|held| { + held.path != claim.path + || held.justified_by != claim.justified_by + || held.why.is_some() + }) + }) + }) + .collect() + } + + /// Each case's allowances, as (fired, named, never fired), for the cases that named any. + /// + /// Per case rather than only in total, because the total says a number and this says which + /// case's claim it is. A case appearing once per venue is summed over its venues. + pub fn allowances_by_case(&self) -> BTreeMap<&str, (usize, usize, usize)> { + let mut by_case: BTreeMap<&str, (usize, usize, usize)> = BTreeMap::new(); + for row in &self.rows { + if row.allowances.named == 0 { + continue; + } + let held = by_case.entry(row.case.as_str()).or_default(); + held.0 += row.allowances.fired(); + held.1 += row.allowances.named; + held.2 += row.allowances.unfired.len(); + } + by_case + } + + /// How many of the report's rows were answered from a chip that is not the oracle's: a carried + /// measurement taken on a machine this round cannot re-record on. + pub fn carried_from_another_chip(&self) -> BTreeMap<&str, usize> { + let mut counts: BTreeMap<&str, usize> = BTreeMap::new(); + for row in &self.rows { + if let Some(chip) = &row.measured_on { + *counts.entry(chip.as_str()).or_default() += 1; + } + } + counts + } + /// Every row that differed inside an allowance, or that the venue could not run. /// /// These are compliant, and they are still the report's most important lines: the claim under @@ -111,7 +253,9 @@ impl Report { .filter(|row| { matches!( row.verdict, - Verdict::Announced { .. } | Verdict::LacksFeature { .. } + Verdict::Announced { .. } + | Verdict::MetalNeverReturned { .. } + | Verdict::LacksFeature { .. } ) }) .collect() @@ -136,6 +280,16 @@ impl Report { out.push_str(&format!("\n{venue} announced as it was made: {codes:?}\n")); } } + out.push_str(&self.allowances_section()); + let carried = self.carried_from_another_chip(); + if !carried.is_empty() { + out.push_str("\ncarried from another chip\n"); + for (chip, count) in carried { + out.push_str(&format!( + " {count} row(s) answered from {chip}, which this round cannot re-record on\n" + )); + } + } out.push_str(&self.matrix()); // Every justified difference is printed, not only the failures. A tolerance that is never // read is a tolerance nobody is checking, and a refusal that Metal's own API validation @@ -170,6 +324,65 @@ impl Report { out } + /// What the selection's allowances did: the counts, what each justification went unused for, + /// and the per-case tally. + /// + /// The whole point of the section is that an allowance which never fires is otherwise + /// invisible, so it is written to be read: the totals first, then one line per justification + /// rather than one per site, because 575 sites naming eleven notices is eleven facts and not + /// 575. + pub fn allowances_section(&self) -> String { + let (named, unfired) = self.allowance_counts(); + if named == 0 { + return String::new(); + } + let mut out = format!( + "\nallowances: {named} named, {} fired, {unfired} never fired\n", + named - unfired + ); + let everywhere = self.unfired_everywhere(); + if everywhere.is_empty() { + out.push_str(" every allowance named fired on some venue of this run\n"); + return out; + } + let unchecked = self.unchecked_everywhere(); + out.push_str(&format!( + " {} of them fired on no venue of this run, and of those {} name nothing this run \ + justifies either, so no run of this suite has checked them:\n", + everywhere.len(), + unchecked.len() + )); + // One line per justification: eleven notices named by sixty cases is eleven claims. + let mut by_justification: BTreeMap<&str, (usize, &str, &str)> = BTreeMap::new(); + for (case, claim) in &unchecked { + let held = by_justification + .entry(claim.justified_by.as_str()) + .or_insert((0, case, claim.path.as_str())); + held.0 += 1; + } + for (justification, (count, case, path)) in &by_justification { + out.push_str(&format!( + " {justification}: {count} site(s), first {case} at {path}\n" + )); + } + let justified = everywhere.len() - unchecked.len(); + if justified > 0 { + out.push_str(&format!( + " the other {justified} name something the run did justify — the device \ + announced the notice, for another case's work — so they are tolerances this run \ + did not need rather than claims nothing stands behind\n" + )); + } + out.push_str(" by case, fired of named:\n"); + for (case, (fired, named, never)) in self.allowances_by_case() { + if never == 0 { + continue; + } + out.push_str(&format!(" {case:<44} {fired} of {named}\n")); + } + out + } + /// The matrix of case against venue, one row per case and one column per venue. pub fn matrix(&self) -> String { let venues: BTreeSet = self.rows.iter().map(|row| row.venue.label()).collect(); @@ -189,7 +402,7 @@ impl Report { .max(4); let widths: Vec = venues .iter() - .map(|venue| venue.len().max("lacks-feature".len())) + .map(|venue| venue.len().max("never-returned".len())) .collect(); let mut out = String::from("\nmatrix\n"); out.push_str(&format!(" {: Result { crate::record::record(case, &mut side, case.record_runs(), level, validated) .map_err(|error| error.to_string())? } + // Never run, and never written from here either: the call this row names is the call + // Metal does not come back from, so there is nothing for record mode to take. Its + // recording is written by hand from the probe that died + // ([`crate::record::never_returned`]). + crate::case::MetalSource::DidNotReturn { call, says, .. } => { + return Err(format!( + "{}: record mode must not run {call}: {says}. Its recording is written by hand \ + from the probe that died, never by running the shape", + case.name() + )) + } crate::case::MetalSource::Carried { from, measured_on, .. } => { diff --git a/crates/metal2vulkan-conformance/src/tests.rs b/crates/metal2vulkan-conformance/src/tests.rs index ddc992f48..55f4f73d4 100644 --- a/crates/metal2vulkan-conformance/src/tests.rs +++ b/crates/metal2vulkan-conformance/src/tests.rs @@ -1053,7 +1053,7 @@ fn a_carried_answer_taken_on_another_chip_names_it() { for case in crate::cases::all() { let claimed = match case.metal_source() { MetalSource::Carried { measured_on, .. } => measured_on, - MetalSource::Run => continue, + MetalSource::Run | MetalSource::DidNotReturn { .. } => continue, }; let recorded = crate::recording::read(case.name()) .unwrap_or_else(|why| panic!("{}: {why}", case.name())) @@ -1075,23 +1075,19 @@ fn a_carried_answer_taken_on_another_chip_names_it() { case.name() ); } - // The two families, and no others. A third would mean a table nobody noticed came from another - // machine. + // One family, and no others. A second would mean a table nobody noticed came from another + // machine. `two_plane_heap_blits` used to be the other one and now records on Metal: nothing + // it does is Apple SPI, so its answer is this chip's. assert!( elsewhere .iter() .any(|name| name.starts_with("texture-fills-")), "texture_fills carries the M4's digests: {elsewhere:?}" ); - assert!( - elsewhere.contains(&crate::cases::two_plane_heap_blits::HEAP_BLITS), - "two_plane_heap_blits carries the M4's digests: {elsewhere:?}" - ); for name in &elsewhere { assert!( - name.starts_with("texture-fills-") - || *name == crate::cases::two_plane_heap_blits::HEAP_BLITS, - "{name} carries another chip's values and is not one of the two known families" + name.starts_with("texture-fills-"), + "{name} carries another chip's values and is not one of the known families" ); } // The file says the chip only where it differs: an oracle-taken recording holds no such field. @@ -1623,3 +1619,431 @@ fn the_ledger_fails_on_a_new_refusal_and_on_one_that_is_gone() { "{found:?}" ); } + +#[test] +fn an_allowance_no_site_needed_is_counted_and_named_rather_than_silently_kept() { + // The hole this closes: the up-front check over a case's allowances has to exempt a degrade + // notice the run did not announce, because a notice is announced once per device per kind. So + // a case could name a tolerance that fires on no venue, naming a notice no venue announces, + // and every run would read green with nobody told. Two allowances of exactly this shape were + // written and deleted by hand in this round. + let mut case = WordsCase::new("words", 2); + case.allowances = vec![ + // A tolerance nothing needs, for a notice nothing announces: speculation. + Allowance::new( + "case/output", + Loosening::Absolute(8.0), + Justification::notice(Degradation::DeviceArithmetic), + ), + // A tolerance nothing needs, for a notice the run did announce: not speculation, just + // unused on this row. + Allowance::new( + "case/output", + Loosening::Absolute(8.0), + Justification::notice(Degradation::ShadowedTexture), + ), + ]; + let bytes = words(&[1, 2]); + // The notice the second allowance names is announced, so it is justified; the run is + // byte-identical, so neither allowance fires. + let announced = [Degradation::ShadowedTexture.code()]; + let recording = recording_of( + &case, + case.transcript(bytes.clone(), "Completed", &announced), + 3, + ); + let mut side = StubSide::new(bytes).announcing(&[Degradation::ShadowedTexture]); + let replayed = replay_against(&case, &mut side, &recording).unwrap(); + + // Report-only: the run is still exact, and still compliant. + assert_eq!(replayed.verdict, Verdict::Exact, "{}", replayed.verdict); + assert_eq!(replayed.allowances.named, 2); + assert_eq!(replayed.allowances.fired(), 0); + assert_eq!( + replayed.allowances.unfired.len(), + 2, + "{:?}", + replayed.allowances.unfired + ); + + let mut report = Report::new(); + report.add(replayed); + assert!(report.is_compliant()); + assert_eq!(report.allowance_counts(), (2, 2)); + assert_eq!(report.unfired_everywhere().len(), 2); + // Only the one nothing justifies is called out as a tolerance no run has checked. + let unchecked = report.unchecked_everywhere(); + assert_eq!(unchecked.len(), 1, "{unchecked:?}"); + assert_eq!( + unchecked[0].1.justified_by, + Justification::notice(Degradation::DeviceArithmetic).describe() + ); + let rendered = report.render(); + assert!( + rendered.contains("2 named, 0 fired, 2 never fired"), + "{rendered}" + ); + assert!( + rendered.contains(Degradation::DeviceArithmetic.code()), + "{rendered}" + ); + assert!(rendered.contains("words "), "{rendered}"); +} + +#[test] +fn an_allowance_that_fires_is_not_counted_as_unfired() { + // The other half of the guard: a tolerance the run needs must not show up in the unfired + // count, or the count would say "nobody checked this" of the one allowance a run did check. + let mut case = WordsCase::new("words", 2); + case.allowances = vec![ + Allowance::new( + "case/output", + Loosening::Absolute(8.0), + Justification::notice(Degradation::DeviceArithmetic), + ), + // The notice site differs too, because the device announced what the tolerance names and + // Metal announces nothing. That allowance fires as well, which is the point: both are + // claims the run used. + crate::replay::notice_allowance(Degradation::DeviceArithmetic.code()), + ]; + let recording = recording_of(&case, case.transcript(words(&[1, 2]), "Completed", &[]), 3); + // One word differs by 7, inside the allowance, and the notice it names is announced. + let mut side = StubSide::new(words(&[1, 9])).announcing(&[Degradation::DeviceArithmetic]); + let replayed = replay_against(&case, &mut side, &recording).unwrap(); + assert!( + matches!(replayed.verdict, Verdict::Announced { .. }), + "{}", + replayed.verdict + ); + assert_eq!(replayed.allowances.fired(), 2); + assert!( + replayed.allowances.unfired.is_empty(), + "{:?}", + replayed.allowances.unfired + ); + let mut report = Report::new(); + report.add(replayed); + assert!(report.unfired_everywhere().is_empty()); + assert!(report.render().contains("2 named, 2 fired, 0 never fired")); +} + +#[test] +fn metal_on_this_chip_answers_the_two_plane_blits_exactly_as_the_probes_printed_them() { + // Two rows lost their Metal leg to a reason that named the wrong thing: `NO_PUBLIC_CALL` said + // the two-plane extended-range formats are Apple's private ones, so Metal had no public call + // for them. The fill is private; the format is not. Both rows now record on Metal, and this + // holds the committed recordings to the tables the probes printed — so the conversion is + // checked rather than asserted, and a Metal that starts answering differently shows up here + // instead of in a quiet re-record. + let held = |case: &dyn Case, carried: &Transcript| { + let recorded = crate::recording::read(case.name()) + .unwrap_or_else(|why| panic!("{}: {why}", case.name())); + let answer = recorded + .answer(MetalLevel::NEWEST) + .unwrap_or_else(|why| panic!("{}: {why}", case.name())); + assert_eq!( + answer.provenance, + Provenance::MetalRun, + "{}: the case records on Metal now", + case.name() + ); + let taken = answer + .deterministic() + .unwrap_or_else(|| panic!("{}: one outcome", case.name())); + // Field by field, through the suite's own comparison: a difference names the site. + let found = compare(carried, taken, &[], Offered::notices(&[])); + // The first few sites, not the whole comparison: a difference has to read on one screen. + assert!( + found.is_exact(), + "{}: Metal's recorded answer is not the probe's table:\n {}", + case.name(), + found + .divergences + .iter() + .take(4) + .map(|divergence| divergence.to_string()) + .collect::>() + .join("\n ") + ); + }; + + let heap_blits = crate::cases::two_plane_heap_blits::heap_blits(); + let (runs, carried) = heap_blits.carried_from_the_m4().unwrap(); + assert_eq!(runs, 6, "the probe's runs behind the carried digests"); + held(&heap_blits, &carried); + + let announced = crate::cases::two_plane_copies::announced_row_blits(); + let printed = announced.printed_by_the_probe().unwrap(); + held(&announced, &printed); + // And the case that still carries, still carries: its reason is the fill, not the format. + let fills = crate::cases::two_plane_copies::row_blits(); + assert!( + matches!( + fills.metal_source(), + MetalSource::Carried { + re_record: ReRecord::Forbidden { reason }, + .. + } if reason.contains("fillTexture:") && !reason.contains("formats are Apple's private") + ), + "{:?}", + fills.metal_source() + ); +} + +/// A case whose Metal leg does not come back: the shape there was no verdict for. +/// +/// `pass`'s call answers on our side, which is what the row pins; `answers` makes it answer +/// instead, which is the break the verdict has to survive. +struct DiedOnMetal { + /// Whether our side answers the call rather than refusing it. + answers: bool, +} + +/// The call the probe died in, as the case names its site. +const DIED_AT: &str = "the-call"; + +/// What the probe saw, in its own words. +const DIED_SAYS: &str = "Metal's process went away inside the call and never came back"; + +impl DiedOnMetal { + /// The transcript the case states by hand: the inputs, and the call Metal never returned + /// from. + fn stated(&self) -> Transcript { + let mut sites = Sites::new(); + sites.push(crate::case::inputs_node(&self.inputs().unwrap())); + sites.value(DIED_AT, Value::Nothing(Negative::NeverReturned)); + sites.notices(NOTICES_SITE, &[] as &[&str]); + sites.finish() + } +} + +impl Case for DiedOnMetal { + fn name(&self) -> &'static str { + "died-on-metal" + } + + fn metal_source(&self) -> MetalSource { + MetalSource::did_not_return("the suite's own tests", DIED_AT, DIED_SAYS) + } + + fn inputs(&self) -> Result, String> { + Ok(vec![Input::bytes("buffer:0", &[0u8; 4])]) + } + + fn carried_transcript(&self) -> Result, String> { + Ok(Some((1, self.stated()))) + } + + fn run(&self, side: &mut dyn Side, sites: &mut Sites) -> Result<(), Abort> { + if self.answers { + // We came back from the call Metal did not: the divergence the row exists to catch. + let _ = made(sites, DIED_AT, side.zeroed_buffer(4))?; + return Ok(()); + } + sites.push(Node::leaf( + DIED_AT, + Observed::value(Failure::named("Unsupported", "this call is not built").value), + )); + Ok(()) + } +} + +#[test] +fn a_call_metal_did_not_return_from_is_its_own_verdict() { + // The hole this closes: a row that ends Metal's process has nothing to carry -- the lane holds + // no line for it -- so it was not recorded-only material, it had no verdict at all. `Exact` + // would claim a value matched where Metal produced none; `Divergent` would claim a behaviour + // of Metal's to differ from; `Refused` is for a call plain Metal answered, and counting it + // there would bury a real gap of ours among rows that are not one. + let case = DiedOnMetal { answers: false }; + let (runs, stated) = case.carried_transcript().unwrap().unwrap(); + let recording = Recording::new( + case.name(), + Vec::new(), + vec![crate::record::never_returned( + MetalLevel::NEWEST, + "the suite's own tests", + DIED_AT, + "the probe's device", + runs, + stated, + )], + ); + let mut side = StubSide::new(Vec::new()); + let replayed = replay_against(&case, &mut side, &recording).unwrap(); + let Verdict::MetalNeverReturned { at, justified } = &replayed.verdict else { + panic!("{}", replayed.verdict); + }; + assert_eq!(at.len(), 1, "{at:?}"); + assert!(at[0].starts_with(&format!("case/{DIED_AT}: ")), "{at:?}"); + assert!(justified.is_empty(), "{justified:?}"); + + // Counted like the others, and it does not loosen compliance: it is a distinct word in the + // report, not a quiet pass hidden inside "exact". + let mut report = Report::new(); + report.add(replayed); + assert_eq!(report.counts().get("never-returned"), Some(&1)); + assert_eq!(report.counts().get("exact"), None); + assert!(report.is_compliant()); + let rendered = report.render(); + assert!(rendered.contains("never-returned"), "{rendered}"); + assert!( + rendered.contains("Metal did not return from the call, and we refused it"), + "{rendered}" + ); + + // No allowance can reach it: a case that loosens the site whole still gets this verdict and + // not `announced`, so the row cannot be dressed up as a justified difference. + let unchecked = vec![Allowance::new( + format!("case/{DIED_AT}"), + Loosening::Unchecked, + Justification::accepted(accepted_differences()[0].clone()), + )]; + let found = compare( + &case.stated(), + &{ + let mut side = StubSide::new(Vec::new()); + replay_against(&case, &mut side, &recording).unwrap().ours + }, + &unchecked, + Offered::notices(&[]), + ); + assert_eq!(found.never_returned.len(), 1, "{found:?}"); + assert!(found.announced.is_empty(), "{found:?}"); +} + +#[test] +fn answering_where_metal_did_not_return_is_divergent() { + // The other half, and the reason the verdict is a mechanism and not a label: the one fact the + // row holds is that *we* refuse where Metal went away. Answering instead has to fail. + let case = DiedOnMetal { answers: true }; + let (runs, stated) = DiedOnMetal { answers: false } + .carried_transcript() + .unwrap() + .unwrap(); + let recording = Recording::new( + case.name(), + Vec::new(), + vec![crate::record::never_returned( + MetalLevel::NEWEST, + "the suite's own tests", + DIED_AT, + "the probe's device", + runs, + stated, + )], + ); + let mut side = StubSide::new(Vec::new()); + let replayed = replay_against(&case, &mut side, &recording).unwrap(); + let Verdict::Divergent { found } = &replayed.verdict else { + panic!("{}", replayed.verdict); + }; + assert!( + found.iter().any(|divergence| matches!( + divergence.kind, + DivergenceKind::AnsweredWhereMetalDidNotReturn { .. } + )), + "{found:?}" + ); + assert!(!replayed.verdict.is_compliant()); +} + +#[test] +fn record_mode_refuses_a_row_metal_does_not_return_from() { + // It may never be produced by running the shape: making the call is what ends Metal's + // process. `forbidden` carries the probe's own words, so `record` refuses before anything is + // encoded, on a host with no Metal as on this one. + let case = DiedOnMetal { answers: false }; + assert_eq!(case.metal_source().forbidden(), Some(DIED_SAYS)); + let mut side = StubSide::new(Vec::new()); + let refused = record(&case, &mut side, 1, MetalLevel::NEWEST, Validated::NotRun); + assert_eq!( + refused, + Err(RecordError::Forbidden { + case: case.name().to_owned(), + reason: DIED_SAYS.to_owned(), + }), + "{refused:?}" + ); + // And the answer that is written instead says so in the file: the provenance names the call, + // and Metal's API validation was never asked either. + let answer = crate::record::never_returned( + MetalLevel::NEWEST, + "the suite's own tests", + DIED_AT, + "the probe's device", + 1, + case.stated(), + ); + assert_eq!(answer.provenance.never_returned_from(), Some(DIED_AT)); + assert_eq!(answer.provenance.measured_elsewhere(), None); + assert_eq!(answer.validated, Validated::NotRun); +} + +#[test] +fn the_report_says_how_many_answers_came_from_another_chip() { + // 53 recordings carried an Apple M4's values and `conformance cases` showed it only through a + // `Debug` print, so a run could read entirely green while a fifth of its answers came from a + // machine that is gone. The suite's own rule is that a recording of another oracle is stale; + // a carried table is the one place that rule is relaxed, so the relaxation has to be counted + // where a reader of the report sees it. + use crate::recording::APPLE_M4; + let carried = |case: &dyn Case, chip: &str| { + let bytes = words(&[1, 2]); + let transcript = WordsCase::new(case.name(), 2).transcript(bytes, "Completed", &[]); + Recording::new( + case.name(), + Vec::new(), + vec![RecordedAnswer { + key: crate::recording::OracleKey::current(MetalLevel::NEWEST), + provenance: Provenance::Carried { + from: "a probe this tree holds".to_owned(), + measured_on: chip.to_owned(), + }, + device: "the probe's device".to_owned(), + runs: 1, + outcomes: vec![Outcome { + runs: 1, + transcript, + }], + validated: Validated::NotRun, + }], + ) + }; + let mut elsewhere = WordsCase::new("from-the-m4", 2); + elsewhere.source = MetalSource::carried("a probe this tree holds").measured_on(APPLE_M4); + let mut here = WordsCase::new("from-the-oracle", 2); + here.source = MetalSource::carried("a probe this tree holds"); + + let mut report = Report::new(); + let mut side = StubSide::new(words(&[1, 2])); + let far = replay_against(&elsewhere, &mut side, &carried(&elsewhere, APPLE_M4)).unwrap(); + assert_eq!(far.verdict, Verdict::Exact, "{}", far.verdict); + assert_eq!(far.measured_on.as_deref(), Some(APPLE_M4)); + report.add(far); + let mut side = StubSide::new(words(&[1, 2])); + let near = replay_against( + &here, + &mut side, + &carried(&here, crate::recording::ORACLE_CHIP), + ) + .unwrap(); + // An answer taken on the oracle names no other chip: the count is of the relaxation, not of + // every carried row. + assert_eq!(near.measured_on, None); + report.add(near); + + assert_eq!( + report.carried_from_another_chip(), + [(APPLE_M4, 1)].into_iter().collect() + ); + let rendered = report.render(); + assert!(rendered.contains("carried from another chip"), "{rendered}"); + assert!( + rendered.contains(&format!("1 row(s) answered from {APPLE_M4}")), + "{rendered}" + ); + // The rows are still compliant: a carried answer from another chip is weaker evidence, not a + // failure. Counting it is the whole mechanism. + assert!(report.is_compliant()); +} diff --git a/crates/metal2vulkan-conformance/src/verdict.rs b/crates/metal2vulkan-conformance/src/verdict.rs index de5af11e8..10553f0b9 100644 --- a/crates/metal2vulkan-conformance/src/verdict.rs +++ b/crates/metal2vulkan-conformance/src/verdict.rs @@ -39,6 +39,26 @@ pub enum Verdict { /// changes is what a reader should do about it. metal_validation: String, }, + /// **Metal did not return from the call, and we gave a typed error there.** + /// + /// Its own verdict, because neither of the others fits and squeezing it into one would say + /// something false. `Exact` would claim a value matched where Metal produced none. `Divergent` + /// would claim a behaviour of Metal's to differ from where the call ended Metal's process. + /// `Refused` is for a call plain Metal **answered**, which is the gap the owner's rule is + /// about, and counting this there would bury a real gap among rows that are not one. + /// + /// It is **compliant**, and it loosens nothing: no allowance can reach it + /// ([`crate::compare::NeverReturned`]), the recording is written by hand from a probe that died + /// rather than by running the shape, and record mode refuses the row. Answering where Metal + /// did not return is a `Divergent` row, not this one, so the verdict can still fail. + MetalNeverReturned { + /// The sites, as their paths and our errors. + at: Vec, + /// What the row still loosened, where it loosened anything: a difference inside a + /// justified allowance at another site is reported here rather than lost, because a row + /// does not stop being a row about tolerances just because one of its calls killed Metal. + justified: Vec, + }, /// No Metal answer stands for this run: none was recorded for the venue's Metal level, or the /// inputs the run fed are not the ones the recording's answer was taken from. Counted, never /// skipped and never a pass. @@ -80,24 +100,24 @@ impl Verdict { metal_validation: validated.describe(), }; } + // After the refusals, because a refusal of something plain Metal answered is a gap of + // ours and must not be hidden behind a call Metal died on; before the announced and exact + // verdicts, because a row where Metal went away is not a row where everything matched. + if !found.never_returned.is_empty() { + return Verdict::MetalNeverReturned { + at: found + .never_returned + .iter() + .map(|site| format!("{}: {}", site.path, site.ours)) + .collect(), + justified: announced_fields(found), + }; + } if found.announced.is_empty() { return Verdict::Exact; } Verdict::Announced { - fields: found - .announced - .iter() - .map(|announced| { - let largest = match announced.largest { - Some(largest) => format!(", the largest difference {largest}"), - None => String::new(), - }; - format!( - "{} x{} ({}{largest})", - announced.path, announced.count, announced.justified_by - ) - }) - .collect(), + fields: announced_fields(found), } } @@ -108,6 +128,7 @@ impl Verdict { Verdict::Announced { .. } => "announced", Verdict::Divergent { .. } => "divergent", Verdict::Refused { .. } => "refused", + Verdict::MetalNeverReturned { .. } => "never-returned", Verdict::Unrecorded { .. } => "unrecorded", Verdict::LacksFeature { .. } => "lacks-feature", } @@ -119,7 +140,10 @@ impl Verdict { pub fn is_compliant(&self) -> bool { matches!( self, - Verdict::Exact | Verdict::Announced { .. } | Verdict::LacksFeature { .. } + Verdict::Exact + | Verdict::Announced { .. } + | Verdict::MetalNeverReturned { .. } + | Verdict::LacksFeature { .. } ) } } @@ -149,12 +173,40 @@ impl std::fmt::Display for Verdict { write!(out, "\n plain Metal answered the call")?; write!(out, "\n Metal's API validation: {metal_validation}") } + Verdict::MetalNeverReturned { at, justified } => { + out.write_str("Metal did not return from the call, and we refused it")?; + for site in at { + write!(out, "\n {site}")?; + } + for field in justified { + write!(out, "\n and differed, justified: {field}")?; + } + Ok(()) + } Verdict::Unrecorded { why } => write!(out, "unrecorded: {why}"), Verdict::LacksFeature { needs } => write!(out, "lacks the device feature: {needs}"), } } } +/// How the report prints each difference a run made inside a justified allowance. +fn announced_fields(found: &Comparison) -> Vec { + found + .announced + .iter() + .map(|announced| { + let largest = match announced.largest { + Some(largest) => format!(", the largest difference {largest}"), + None => String::new(), + }; + format!( + "{} x{} ({}{largest})", + announced.path, announced.count, announced.justified_by + ) + }) + .collect() +} + /// Whether `error` is a device's honest gap rather than ours: the typed refusal names capabilities /// a device could enable, or a measured driver defect. A refusal the translator or the runtime has /// not built, and one Metal itself gives, is ours to answer for. diff --git a/crates/metal2vulkan-conformance/src/work.rs b/crates/metal2vulkan-conformance/src/work.rs index 929fe59a3..e2aab5763 100644 --- a/crates/metal2vulkan-conformance/src/work.rs +++ b/crates/metal2vulkan-conformance/src/work.rs @@ -6,10 +6,13 @@ //! it and answers what it read ([`Done`]). The case body stays a description of the probe, which //! is what makes a port readable beside the lane it came from. //! -//! A side with no public call for this answers [`crate::case::Failure::unavailable`], as the -//! Metal side does: Metal fills a texture through private API, and a two-plane extended-range -//! format is private too, so there is no public call for a Metal side to make. Those cases carry -//! their Metal answer ([`crate::case::MetalSource::Carried`]). +//! A side with no public call for a step answers [`crate::case::Failure::unavailable`] for that +//! step. On the Metal side that is the **fill** and the fill alone: `fillTexture:` and +//! `fillTextureColor:` are Apple SPI ([`crate::metal_work`]). The *formats* a case names are not +//! private — a pixel format is a raw value in `MTLTextureDescriptor`, and Metal makes, writes, +//! blits and reads back Apple's two-plane extended-range 550 and 551 through public calls like any +//! other. So a program that fills carries its Metal answer +//! ([`crate::case::MetalSource::Carried`]); a program of copies records on Metal. //! //! Nothing here names a device, a vendor or an environment variable. A resource the venue cannot //! make comes back as the runtime's typed refusal, and the suite reads the venue's honest gap out @@ -39,7 +42,9 @@ impl Rect { } /// How a texture is shaped. The format is its raw `MTLPixelFormat`, because a case states the -/// probe's number and some of the probes' formats are Apple's private ones. +/// probe's number and some of those numbers have no name in a public header. A number with no +/// public name is still a number Metal takes: `MTLTextureDescriptor`'s pixel format is a raw +/// value, so both sides make, write, blit and read such a texture through public calls. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct TextureSpec { /// The raw `MTLPixelFormat`.