From 38673ec995b7bc09a24644d74a29743ab7fcc48a Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 14 Nov 2026 08:08:29 -0800 Subject: [PATCH] RUNTIME 2299: a check that fails a submission before its group is split keeps it failed A check may run on the scheduler's thread while a commit's encodings again are pending: the scheduler takes the checks of the batches it holds before the first submission, which waits for the encodings, is submitted. With a check split (RUNTIME 2297), a group whose VkCommandBuffer holds commands of two of Metal's submissions is encoded again apart at the commit; where the check failed one of those submissions first, the split's splice put the failed encoders' encodings into parts the failure had cleared, and they ran. Found by the render fold's check test (a render pass between two compute encoders: the pass drew). fail_submission now marks the failed encoders unrunnable, as a rebound or detached submission's are. The commit's split and a rebind's turn encode no unrunnable encoder again, and an encoding again whose encoder became unrunnable meanwhile takes no place while the unit's others take theirs (before, splice_fits refused the whole unit for a rebound one). Test: encoder_fold's a_check_that_fails_a_submission_before_its_group_is_split_keeps_it_failed holds the command buffer's turn of encodings again (a test-only guard) until the check failed the blit's submission, then expects the blit's fill not to have run and the three compute encoders to have. Verified (msi lavapipe): m3-max-29383 at the tip: clippy -D warnings (runtime, all features and targets) 0 under --cfg m2v_cpu_icd and plain; runtime fold/rebind/ reencode/check/commit tests 374/375 (the other: a queue_share idle-budget timing test under load, no check or re-encode, fixed apart); validation submission_checks and failed_commits 16/16. Negative control m3-max-29384 (unrunnable marks removed): the new test fails, the blit re-encoded (4 against 3). --- .../src/command_buffer/checks.rs | 3 + .../src/command_buffer/mod.rs | 5 +- .../src/command_buffer/reencode.rs | 50 ++++++++++--- .../src/tests/encoder_fold.rs | 74 ++++++++++++++++++- crates/metal2vulkan/src/cache/mod.rs | 2 +- 5 files changed, 120 insertions(+), 14 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/command_buffer/checks.rs b/crates/metal2vulkan-runtime/src/command_buffer/checks.rs index 256983401..70866c7e9 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/checks.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/checks.rs @@ -283,6 +283,9 @@ impl State { planned.failed = true; } let encoders = self.widened(encoders); + // Encoded again after this, by the commit's split of a group or a rebind, they still + // run nothing (`reencode.rs`). + self.unrunnable.extend(encoders.clone()); let from = self.batch_range(index).start; let State { recorded, diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 4a1340a71..5417f9aed 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -1107,8 +1107,9 @@ pub(super) struct State { /// written by it (`copied.rs`); a command buffer whose unnamed reach only reads leaves the /// copies its uses did not write uncompared. pub(super) writes_unnamed: bool, - /// The ended encoders whose submissions failed so: no part of one goes to a queue with work - /// (`submit.rs` holds it to that). + /// The ended encoders whose submissions failed so, or failed a submission check + /// (`State::fail_submission`): no part of one goes to a queue with work (`submit.rs` holds it + /// to that), and none takes an encoding again (`reencode.rs`). unrunnable: BTreeSet, /// What its batches' commands took of buffers over host pages, held from the submission of /// their event group's first batch (`rebind::SubmittedHolds`, `State::event_group`), each with diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 6320baff7..715a2fb8a 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -68,12 +68,16 @@ //! (`State::split_rebound`): the group's other encoders are encoded again apart, as a split at //! the commit's are (below). //! - **Split at the commit.** A commit whose failure fails some of a group's encoders and not the -//! others, or after a command-predication record left out the work of some of them -//! (`encoder_fold.rs`'s **Failed**), marks the command buffer as a rebind does, and its -//! own call encodes the group's encoders that run again, each into `VkCommandBuffer`s of its -//! own, before the scheduler sees its batches; where one cannot be encoded again or does not -//! fit its place, those encoders run nothing after all (`State::fail_unsplit`), as the whole -//! group would have. +//! others, after a command-predication record left out the work of some of them, or with a +//! submission check where the group's `VkCommandBuffer` holds commands of two of Metal's +//! submissions (`encoder_fold.rs`'s **Failed**), marks the command buffer as a rebind does, and +//! its own call encodes those of the group's encoders that run again, each into +//! `VkCommandBuffer`s of its own, before the first submission, which waits for it; where one +//! cannot be encoded again or does not fit its place, those encoders run nothing after all +//! (`State::fail_unsplit`), as the whole group would have. A submission check may run on the +//! scheduler's thread before that call's encodings take their places: an encoder whose +//! submission it failed (`State::fail_submission`) takes no encoding again, here or in a +//! rebind's turn, and the others of its unit take theirs. //! - **What cannot be encoded again stays as before.** An encoder whose log is gone (a compute //! encoder of a command buffer that used command predication whose unit laid a step before it //! opened, or one of its own that the unit's later encoders read, or a loop, or left work out; @@ -151,6 +155,14 @@ impl CommandBufferShared { let splitting: BTreeSet = split.iter().flatten().copied().collect(); let mut units = Vec::new(); for unit in split { + // An encoder whose submission a check failed before this turn + // (`State::fail_submission`) runs nothing: it takes no encoding again. + let unit: Vec = (unit.into_iter()) + .filter(|at| !state.unrunnable.contains(at)) + .collect(); + if unit.is_empty() { + continue; + } let logs: Option)>> = (unit.iter()) .map(|&at| { let log = state.ended.get(at)?.replay.as_ref()?; @@ -165,13 +177,18 @@ impl CommandBufferShared { let submitting = device.shared().rebinds.submitting(); // Its open encoders, logged or not, a command of which named a buffer that // lies elsewhere now. + let encodes = |at: &usize| { + open.contains(at) + && !splitting.contains(at) + && !state.unrunnable.contains(at) + }; let rebound: BTreeSet = (state.ended.iter().enumerate()) - .filter(|(at, _)| open.contains(at) && !splitting.contains(at)) + .filter(|(at, _)| encodes(at)) .filter(|(_, record)| submitting.rebound(&record.taken)) .map(|(at, _)| at) .collect(); let moved: Vec<(usize, Arc)> = (state.ended.iter().enumerate()) - .filter(|(at, _)| open.contains(at) && !splitting.contains(at)) + .filter(|(at, _)| encodes(at)) .filter_map(|(at, record)| { let reset = record.taken.rate_map_reset(); let Some(replay) = record.replay.as_ref() else { @@ -229,6 +246,11 @@ impl CommandBufferShared { // What a refused splice held goes after the lock. let unspliced = { let mut state = lock(&self.state); + // An encoder whose submission a check failed meanwhile runs nothing: its encoding + // again takes no place, and the unit's others take theirs. + let (failed, kept): (Vec, Vec) = + (again.into_iter()).partition(|done| state.unrunnable.contains(&done.at)); + again = kept; let fits = again .iter() .all(|done| state.splice_fits(done.at, &done.replayed)); @@ -269,7 +291,7 @@ impl CommandBufferShared { for (at, _) in &unit { state.ended[*at].group = None; } - Vec::new() + failed } false => { if split { @@ -283,6 +305,7 @@ impl CommandBufferShared { }; state.ended[done.at].refused = Some(refusal.to_owned()); } + again.extend(failed); again } } @@ -862,3 +885,12 @@ pub(super) struct KeptReplays { /// The identities of the rasterization-rate maps its encoders' passes are over. pub(super) maps: Box<[usize]>, } + +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +impl CommandBuffer { + /// Hold its turn of encodings again (`reencoding`), as a rebind's turn holds it: a commit or a + /// rebind that encodes its encoders again waits until the guard drops. A test's. + pub(crate) fn hold_reencoding(&self) -> std::sync::MutexGuard<'_, ()> { + lock(&self.0.reencoding) + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs b/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs index 14d513a1c..08549a40d 100644 --- a/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs +++ b/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs @@ -21,11 +21,13 @@ use super::encoder_holds::words_of; use super::rebind_behind_a_wait::{Page, BYTES}; use crate::{ BlitOption, Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, CommitFailure, - ComputePipelineState, Device, Error, EventRef, FailedEncoders, Origin, ResourceOptions, Size, - Texture, TextureDescriptor, WorkCounts, + ComputePipelineState, Device, EncoderKind, Error, EventRef, FailedEncoders, Origin, + ResourceOptions, Size, Submission, SubmissionCheck, Texture, TextureDescriptor, WorkCounts, }; use metal2vulkan::metal::{DispatchType, PixelFormat, TextureUsage}; use std::collections::BTreeSet; +use std::num::NonZeroU64; +use std::sync::{mpsc, Arc, Mutex}; /// The words of a large write: threadgroups enough that a GPU runs them in many waves. const LARGE: u64 = 1 << 20; @@ -414,6 +416,74 @@ fn failed_with(encoders: FailedEncoders) -> ([bool; 5], u64) { ([ran(0), ran(1), ran(2), ran(3), ran(4)], reencoded) } +/// Three compute encoders and a blit encoder's fill of one group, with a submission check that +/// fails the blit encoder's submission (`command_buffer/checks.rs`): the group's +/// `VkCommandBuffer` holds commands of two of Metal's submissions, so the commit encodes its +/// encoders again apart (`State::split_failure`), and the check may run on the scheduler's +/// thread before those encodings take their places. Here it does: the test holds the command +/// buffer's turn of encodings again until the check failed the blit's submission. The blit +/// encoder then takes no encoding again and runs nothing; the compute encoders take theirs and run. +#[test] +fn a_check_that_fails_a_submission_before_its_group_is_split_keeps_it_failed() { + let scratch = Scratch::new("fold-checked-early"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let input = floats(device, SMALL, |i| i as f32); + let outputs: Vec = (0..4).map(|_| floats(device, SMALL, |_| 0.0)).collect(); + let warm = floats(device, SMALL, |_| 0.0); + let serial = DispatchType::Serial; + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&warm, SMALL)); + kernel.run(&command_buffer); + + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + for output in &outputs[..3] { + kernel.dispatch(&command_buffer, serial, (&input, 0), (output, SMALL)); + } + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(&outputs[3], 0..SMALL * 4, FILL).unwrap(); + blit.end_encoding().unwrap(); + let moved = Moved::of(&before, &device.work_counts()); + assert_eq!((moved.folded, moved.begun), (3, 1), "{moved:?}"); + let (failed, checked) = mpsc::channel(); + let failed = Mutex::new(failed); + let check: SubmissionCheck = Arc::new(move |submission: &Submission<'_>| { + let fails = submission.kind() == EncoderKind::Blit; + if fails { + let _ = failed.lock().unwrap().send(()); + } + fails.then(|| NonZeroU64::new(8).unwrap()) + }); + command_buffer.set_submission_check(check).unwrap(); + let turn = command_buffer.hold_reencoding(); + let committer = { + let command_buffer = command_buffer.clone(); + std::thread::spawn(move || command_buffer.commit()) + }; + checked + .recv_timeout(WAIT) + .expect("the check ran while the encodings again waited for their turn"); + drop(turn); + committer.join().unwrap().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Error); + assert_eq!( + command_buffer.error(), + Some(CommandBufferError::Injected(8)) + ); + let after = device.work_counts(); + assert_eq!(after.encoders_reencoded - before.encoders_reencoded, 3); + for output in &outputs[..3] { + assert_eq!(read(output), expected(SMALL, |i| 2 * i)); + } + assert!( + words_of(&outputs[3]).iter().all(|&word| word == 0), + "the blit encoder's fill" + ); +} + /// A failed set that names one encoder of a group fails that encoder alone, as on Metal: the /// group's other three, the blit encoder among them, are encoded again apart at the commit, and /// the encoder after it runs. diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index b2f37e41b..c5935a412 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 522; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2298; +pub const RUNTIME_VERSION: u32 = 2299; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles