Announce each recovery's own wait, slow failing and failed making

After a device's first recovery, a later recovery's step notices were
never shown: a call's wait for the recovery past 10 seconds, its command
buffers taking past 10 seconds to fail, and its new VkDevice's failure
all went through degrade_once(DeviceRecovered), whose record carries
across generations, and the first recovery's own notice set that record.
So a slow second recovery announced nothing, and a second recovery whose
VkDevice could not be made left the device answering as lost with no
notice (rule 2: a degradation is announced).

Each recovery's notices are now its own (Device::degrade_recovery_step,
whatever the kind's record says), still bounded: the wait is announced
once per recovery by the first call to wait past the bound (a flag in
the line's Lost state, so N waiting calls give one notice, not N), the
slow failing once per recovery by the call that claimed it, the failed
making once (the line fails). degrade_recovered no longer sets the
kind's record, which nothing reads for this kind now.

Tests (tests::device_recovery, device builds): with the bound set to
zero through a per-device test hook, each_recovery_announces_its_own_wait
runs a first recovery, then recoveries with three threads calling the
device, and requires a later recovery to announce one wait (never two);
a_later_recovery_announces_its_failure fails the second recovery's
making through a hook and requires its notice to reach the sink.

(cherry picked from commit fefe1396ef30708568c6811e98659fbe08771671)
This commit is contained in:
Anees Iqbal committed 2026-11-07 21:09:20 -08:00
1 parent 0f28b4b79e
commit 0529a98e4c
4 files changed
+232 -32

No files matched your search

+19 -4
View File
@@ -2186,9 +2186,11 @@ degradations! {
/// (`GpuRecoveryVictim`); every later call goes to the new `VkDevice`. Announced at each
/// recovery, from the call that made it; the payload names the culprit (where two or more
/// `VkQueue`s had work in flight it is an inference, and says so) and the recovery's
/// time. Announced as well, once per device, where a call waited past 10 seconds for a
/// recovery under way (it waits on), and where the new `VkDevice` could not be made (the
/// device then answers as a lost one).
/// time. Announced as well, at most once each per recovery, whatever an earlier recovery
/// announced: where a call waited past 10 seconds for the recovery under way (it waits
/// on), where its command buffers in flight took past 10 seconds to fail (it waits on),
/// and where its new `VkDevice` could not be made (the device then answers as a lost
/// one).
DeviceRecovered = "device-recovered", Performance,
"the objects made before the recovery are refused (`MadeBeforeRecovery`), where \
Metal's go on; the calls during it wait for it";
@@ -3272,13 +3274,26 @@ impl Device {
/// says, since each names its own culprit; inside the program's call that made it.
pub(super) fn degrade_recovered(&self, describe: impl FnOnce() -> (String, String)) {
let degradation = Degradation::DeviceRecovered;
self.shared().announced.now(degradation);
let misplaced = check_announcement(degradation, true);
let (object, reason) = describe();
let message = DegradeNotice::new(degradation, object, reason).message();
self.deliver_placed(degradation, message, misplaced);
}
/// Announce a step of a recovery of the device that went past its bound or failed
/// (`Degradation::DeviceRecovered`, `device/line.rs`): a call's wait for the recovery past
/// `RECOVERY_NOTICE`, its command buffers in flight taking past it to fail, or its new
/// `VkDevice`'s failure. Whatever the kind's record says, as each recovery's notices are its
/// own, the line announcing each step at most once per recovery; met where no program call
/// may be (a runtime thread's call waiting for the recovery), as `degrade_once`'s kinds are.
pub(super) fn degrade_recovery_step(&self, describe: impl FnOnce() -> (String, String)) {
let degradation = Degradation::DeviceRecovered;
let misplaced = check_announcement(degradation, false);
let (object, reason) = describe();
let message = DegradeNotice::new(degradation, object, reason).message();
self.deliver_placed(degradation, message, misplaced);
}
/// Announce `degradation` once per device, whatever `DeviceOptions::announce_each` says,
/// `describe` giving the object and the reason: for a kind met where no program call or host
/// step may be (a runtime thread letting go of what it held).
+85 -23
View File
@@ -17,9 +17,9 @@
//! meets the new generation (`RuntimeGap::MadeBeforeRecovery`, `error.rs`).
//! - **The states.** [`State`]: the line serves one generation (`Live`); once it is lost, the
//! first call that needs the device recovers it (`Lost`, then claimed), while every other call
//! waits for that recovery, announcing a wait past [`RECOVERY_NOTICE`] and waiting on; a line
//! that cannot recover (a device the consumer made, `Device::from_raw`, or one whose new
//! `VkDevice` failed) answers as the lost device does (`Failed`).
//! waits for that recovery, the first to wait past [`RECOVERY_NOTICE`] announcing it and waiting
//! on; a line that cannot recover (a device the consumer made, `Device::from_raw`, or one whose
//! new `VkDevice` failed) answers as the lost device does (`Failed`).
//! - **The recovery** ([`Line::recover`]), on the program's thread whose call claimed it: the lost
//! generation's command buffers in flight fail through its completion path, the oldest
//! incomplete batch's as the hang and the others as its victims (`command_buffer/completion.rs`);
@@ -29,6 +29,13 @@
//! records kept on disk warm. The calls waiting go on with it, the command queues made before
//! take a new place on it at their next command buffer (`queue.rs`), and it announces
//! `Degradation::DeviceRecovered`.
//! - **Each recovery's notices are its own.** The kinds a device announced go on across its
//! generations, each kind announced once for the device, but a recovery's notices
//! (`Degradation::DeviceRecovered`) are announced at every recovery, whatever an earlier one
//! announced: the recovery itself, and at most one each of a call's wait for it past
//! [`RECOVERY_NOTICE`], its command buffers in flight taking past it to fail, and its new
//! `VkDevice`'s failure. So a slow second recovery says so as the first did, and repeated losses
//! announce a few notices each, never one per waiting call.
//! - **What goes on across generations**: the line's handles and holds (`holds.rs`), its counts
//! (`WorkCounts`), the Metal address space with its reserved pools, the resource IDs and the
//! `uniqueIdentifier`s, so nothing made after a recovery takes an address or an identity one made
@@ -43,7 +50,7 @@ use super::create;
use super::{holds, lock, Device, DeviceOptions, DeviceShared, InstanceShared};
use crate::address::AddressSpace;
use crate::capabilities::DeviceProperties;
use crate::degradation::{Announced, Degradation};
use crate::degradation::Announced;
use crate::error::{invalid, Error, Problem, RuntimeGap};
use crate::resource_ids::{PassingHolds, ResourceIds};
use crate::shader_cache::CacheSetup;
@@ -58,7 +65,8 @@ use std::sync::{Arc, Condvar, Mutex, Weak};
use std::time::{Duration, Instant};
/// How long a call waits for a recovery under way before it announces the wait
/// (`Degradation::DeviceRecovered`, once per wait); it waits on past it.
/// (`Degradation::DeviceRecovered`, once per recovery), and how long a recovery waits for its
/// command buffers in flight to fail before it announces that; each waits on past it.
pub(crate) const RECOVERY_NOTICE: Duration = Duration::from_secs(10);
/// What a line's every generation answers alike: they are made of the same physical device with
@@ -96,8 +104,8 @@ pub(super) struct Carried {
/// The counts of the commit path's work (`WorkCounts`).
pub(super) counts: Arc<Counters>,
/// The kinds of degradation announced, so each is announced once for the device, not once per
/// generation (`degradation.rs`); a recovery's own notice is announced at each
/// (`Device::degrade_recovered`).
/// generation (`degradation.rs`); a recovery's notices are announced at each recovery
/// (`Device::degrade_recovered`, `Device::degrade_recovery_step`; the module docs).
pub(super) announced: Arc<Announced>,
}
@@ -152,11 +160,14 @@ enum State {
/// It serves this generation.
Live(Arc<DeviceShared>),
/// This generation was lost; `claimed` once a call took its recovery on; `culprit` the
/// command buffer its completion failed as the hang, once it named one.
/// command buffer its completion failed as the hang, once it named one; `waited` once a call
/// announced its wait for this recovery past [`RECOVERY_NOTICE`], which no other call waiting
/// for it announces again.
Lost {
lost: Arc<DeviceShared>,
claimed: bool,
culprit: Option<Culprit>,
waited: bool,
},
/// It cannot recover (a device the consumer made, or one whose new `VkDevice` failed): this
/// lost generation answers every call, as a lost device does.
@@ -195,6 +206,9 @@ pub(crate) struct Line {
queues: Mutex<Vec<Weak<crate::queue::QueueLine>>>,
/// The generation a root handle's `Device::raw` lent (`Line::lend`).
lent: Mutex<Lent>,
/// What the device tests set of its recoveries ([`hooks`]), in their builds only.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) hooks: hooks::Hooks,
}
/// What a line lent a root handle's `Device::raw` ([`Line::lend`]).
@@ -232,9 +246,22 @@ impl Line {
changed: Condvar::new(),
queues: Mutex::default(),
lent: Mutex::new(Lent::Nothing),
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
hooks: hooks::Hooks::default(),
})
}
/// How long a call waits for a recovery under way, or a recovery for its command buffers in
/// flight to fail, before it announces the wait: [`RECOVERY_NOTICE`], or in the device tests'
/// builds what a test set (`hooks::Hooks::notice_after`).
fn notice_after(&self) -> Duration {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
if let Some(after) = *lock(&self.hooks.notice_after) {
return after;
}
RECOVERY_NOTICE
}
/// Whether the line makes a new `VkDevice` once one is lost: a device the runtime made.
pub(crate) fn recovers(&self) -> bool {
self.recipe.is_some()
@@ -276,6 +303,7 @@ impl Line {
lost: serving,
claimed: false,
culprit: None,
waited: false,
}
}
false => State::Failed(serving),
@@ -289,8 +317,7 @@ impl Line {
/// cannot recover answers with its lost generation. A handle for the call, counted as the
/// program's.
pub(super) fn current(self: &Arc<Self>, device: &Device) -> Device {
let mut waited: Option<Instant> = None;
let mut announced = false;
let mut began: Option<Instant> = None;
let mut state = lock(&self.state);
loop {
match &mut *state {
@@ -319,17 +346,16 @@ impl Line {
drop(state);
return self.recover(lost);
}
State::Lost { lost, .. } => {
let lost = Arc::clone(lost);
let began = *waited.get_or_insert_with(Instant::now);
let (next, _) = (self.changed)
.wait_timeout(state, RECOVERY_NOTICE)
.unwrap_or_else(std::sync::PoisonError::into_inner);
state = next;
if !announced && began.elapsed() >= RECOVERY_NOTICE {
announced = true;
State::Lost { lost, waited, .. } => {
let began = *began.get_or_insert_with(Instant::now);
let after = self.notice_after();
// The first call to wait past the bound for this recovery announces it, once
// per recovery whatever an earlier recovery announced (the module docs).
if !*waited && began.elapsed() >= after {
*waited = true;
let lost = Arc::clone(lost);
drop(state);
holds::program(lost).degrade_once(Degradation::DeviceRecovered, || {
holds::program(lost).degrade_recovery_step(|| {
(
"a call made during the device's recovery".to_owned(),
format!(
@@ -339,7 +365,16 @@ impl Line {
)
});
state = lock(&self.state);
continue;
}
let timeout = match *waited {
true => RECOVERY_NOTICE,
false => after.saturating_sub(began.elapsed()),
};
let (next, _) = (self.changed)
.wait_timeout(state, timeout)
.unwrap_or_else(std::sync::PoisonError::into_inner);
state = next;
}
// No handle of a line in either exists but the caller's own: it answers.
State::Making | State::Gone => return device.clone(),
@@ -359,6 +394,10 @@ impl Line {
// (vkspec 5.2.3), and on one the test hook marked lost waits for the work it ran.
old.drain_queues();
let made = match &self.recipe {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
Some(_) if self.hooks.making_fails.swap(false, Ordering::AcqRel) => {
Err(Error::DeviceLost)
}
Some(recipe) => create::create_on(
&recipe.instance,
recipe.physical,
@@ -373,7 +412,7 @@ impl Line {
Err(error) => {
*lock(&self.state) = State::Failed(lost);
self.changed.notify_all();
old.degrade_once(Degradation::DeviceRecovered, || {
old.degrade_recovery_step(|| {
(
"the device".to_owned(),
format!(
@@ -606,12 +645,14 @@ impl Device {
shared.completion.fail_in_flight();
shared.scheduler.wake();
let began = Instant::now();
let after = self.line().notice_after();
let mut announced = false;
while !shared.completion.settled() {
std::thread::sleep(Duration::from_millis(1));
if !announced && began.elapsed() >= RECOVERY_NOTICE {
// Once per recovery: only the call that claimed it fails its command buffers.
if !announced && began.elapsed() >= after {
announced = true;
self.degrade_once(Degradation::DeviceRecovered, || {
self.degrade_recovery_step(|| {
(
"the device's recovery".to_owned(),
format!(
@@ -624,3 +665,24 @@ impl Device {
}
}
}
/// The device tests' hooks into a line's recoveries (`tests::device_recovery`), in those tests'
/// builds only: each set on one device, so a test's settings reach no other test's device.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) mod hooks {
use std::sync::atomic::AtomicBool;
use std::sync::Mutex;
use std::time::Duration;
/// What a test set of a line's recoveries.
#[derive(Default)]
pub(crate) struct Hooks {
/// How long a call waits for a recovery under way, or a recovery for its command buffers
/// in flight to fail, before it announces the wait, in place of
/// [`RECOVERY_NOTICE`](super::RECOVERY_NOTICE): zero announces every such wait.
pub(crate) notice_after: Mutex<Option<Duration>>,
/// The next recovery's new `VkDevice` fails to be made, as a driver's refusal fails it:
/// the line fails, and answers as the lost device does from then on.
pub(crate) making_fails: AtomicBool,
}
}
@@ -5,15 +5,22 @@
//! completes with no error, as Metal's on the queue of a hang in flight, and one committed on
//! another queue fails as the recovery's victim. Then the device and the hang's queue serve on.
//!
//! Each recovery announces its own notices (`Degradation::DeviceRecovered`), whatever an earlier
//! one announced: a later recovery's wait and its new `VkDevice`'s failure reach the sink as the
//! first's would.
//!
//! A device test: compiled only under the validation crate's GPU safety cfgs, on the kind of device
//! the cfg selects (docs/VALIDATION.md). No GPU fault: the loss is marked, and the work in flight
//! completes before the failures post (`Device::drain_queues`).
use crate::{
Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, CommandQueue, Device,
DeviceKind, DeviceOptions, ResourceOptions, ShaderCacheOptions,
Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, CommandQueue, Degradation,
DegradeNotice, Device, DeviceKind, DeviceOptions, Error, MessageSink, ResourceOptions,
ShaderCacheOptions,
};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
/// The bytes each copy of the busy command buffer moves: enough that it is still in flight as the
@@ -46,6 +53,27 @@ impl Drop for Scratch {
/// The device the cfg selects: a CPU device under `m2v_cpu_icd`, else a GPU, its shader cache
/// in `cache`.
fn device(cache: &Path) -> Device {
device_with(cache, None)
}
/// The degrade notices a device's sink heard, in order.
type Heard = Arc<Mutex<Vec<DegradeNotice>>>;
/// [`device`], its degrade notices kept in `heard`.
fn heard_device(cache: &Path, heard: &Heard) -> Device {
let heard = Arc::clone(heard);
device_with(
cache,
Some(MessageSink::new(move |message| {
if let Some(notice) = &message.degradation {
heard.lock().unwrap().push(notice.clone());
}
})),
)
}
/// [`device`], its messages sent to `messages` where given.
fn device_with(cache: &Path, messages: Option<MessageSink>) -> Device {
let options = DeviceOptions {
kinds: match cfg!(m2v_cpu_icd) {
true => vec![DeviceKind::Cpu],
@@ -59,6 +87,7 @@ fn device(cache: &Path) -> Device {
directory: Some(cache.to_owned()),
..ShaderCacheOptions::default()
},
messages,
..DeviceOptions::default()
};
Device::system_default_with(&options).unwrap()
@@ -244,3 +273,96 @@ fn work_that_completed_before_a_failed_wait_completes() {
assert_eq!(outcome(&next), (CommandBufferStatus::Completed, None));
assert_eq!(device.work_counts().device_recoveries, 1);
}
/// The threads that call the device while it recovers ([`each_recovery_announces_its_own_wait`]).
const WAITERS: usize = 3;
/// The recovery notices `heard` holds from `from` on whose object is `object`: a recovery's own
/// is "the device", a call's wait for one "a call made during the device's recovery", its command
/// buffers' failing past the bound "the device's recovery" (`device/line.rs`).
fn recovery_notices(heard: &Heard, from: usize, object: &str) -> Vec<String> {
heard.lock().unwrap()[from..]
.iter()
.filter(|notice| notice.degradation == Degradation::DeviceRecovered)
.filter(|notice| notice.object == object)
.map(|notice| notice.reason.clone())
.collect()
}
/// A recovery's wait is announced at a later recovery as at the first, once per recovery however
/// many calls wait: the kinds a device announced go on across its generations, a recovery's
/// notices do not. The bound is zero here, so a call that meets the recovery under way announces
/// its wait at once. The first recovery, which no call waits for, announces itself alone.
#[test]
fn each_recovery_announces_its_own_wait() {
let scratch = Scratch::new();
let heard = Heard::default();
let device = heard_device(&scratch.0, &heard);
*device.line().hooks.notice_after.lock().unwrap() = Some(Duration::ZERO);
device.recover_for_test().unwrap();
assert_eq!(recovery_notices(&heard, 0, "the device").len(), 1);
let queue = device.new_command_queue().unwrap();
for _ in 0..ATTEMPTS {
let from = heard.lock().unwrap().len();
// Work in flight, so the recovery waits for it to fail before it makes its `VkDevice`.
let in_flight = busy(&device, &queue);
let recovered = AtomicBool::new(false);
std::thread::scope(|scope| {
for _ in 0..WAITERS {
scope.spawn(|| {
while !recovered.load(Ordering::Acquire) {
drop(device.new_buffer(4096, ResourceOptions::shared()).unwrap());
}
});
}
device.recover_for_test().unwrap();
recovered.store(true, Ordering::Release);
});
drop(in_flight);
let made = recovery_notices(&heard, from, "the device");
assert_eq!(made.len(), 1, "one recovery announced {made:?}");
let failing = recovery_notices(&heard, from, "the device's recovery");
assert!(failing.len() <= 1, "one recovery announced {failing:?}");
let waits = recovery_notices(&heard, from, "a call made during the device's recovery");
match waits.len() {
0 => continue,
1 => return,
_ => panic!(
"{} calls announced their wait for one recovery: {waits:?}",
waits.len()
),
}
}
panic!(
"no call of {WAITERS} threads met any of {ATTEMPTS} recoveries after the first under way"
);
}
/// A recovery whose new `VkDevice` cannot be made announces it after an earlier recovery as on
/// the first, and the device answers as a lost one from then on.
#[test]
fn a_later_recovery_announces_its_failure() {
let scratch = Scratch::new();
let heard = Heard::default();
let device = heard_device(&scratch.0, &heard);
device.recover_for_test().unwrap();
assert_eq!(recovery_notices(&heard, 0, "the device").len(), 1);
let from = heard.lock().unwrap().len();
device
.line()
.hooks
.making_fails
.store(true, Ordering::Release);
assert!(matches!(device.recover_for_test(), Err(Error::DeviceLost)));
let failed = recovery_notices(&heard, from, "the device");
assert_eq!(failed.len(), 1, "the failed recovery announced {failed:?}");
assert!(
failed[0].contains("its new VkDevice could not be made"),
"{failed:?}"
);
assert!(matches!(
device.new_buffer(4096, ResourceOptions::shared()),
Err(Error::DeviceLost)
));
assert_eq!(device.work_counts().device_recoveries, 1);
}
+4 -3
View File
@@ -3068,9 +3068,10 @@ bound.
(`GpuRecoveryVictim`), and every later call of the device and of its command queues goes to the
new `VkDevice`. Announced at each recovery, by the call that made it; the reason names the hang's
command buffer (an inference, said so, where two or more `VkQueue`s had work in flight) and how
long the recovery took. Announced too where a call waited past 10 seconds for a recovery under
way, and where the new `VkDevice` could not be made, after which the device answers as a lost
one. `Device::recover_for_test` runs the same recovery with no GPU fault. Cost: the objects made
long the recovery took. Announced too, at most once each per recovery whatever an earlier
recovery announced: where a call waited past 10 seconds for the recovery under way, where its
command buffers in flight took past 10 seconds to fail, and where its new `VkDevice` could not
be made, after which the device answers as a lost one. `Device::recover_for_test` runs the same recovery with no GPU fault. Cost: the objects made
before the recovery are refused (`MadeBeforeRecovery`), where Metal's go on; the calls during it
wait for it.
- `metal2vulkan-degrade-private-properties-unknown` (precision). `PrivatePropertiesUnknown`: Apple's