use std::cell::RefCell;
use anyhow::{Context, Result};
use mlx_native::MlxDevice;
pub(crate) fn settle(device: &MlxDevice) -> Result<()> {
#[cfg(test)]
if let Some(outcome) = fault::next() {
return outcome;
}
device
.command_encoder()
.context("create the encoder that settles the device")?
.commit_and_wait()
.context("commit the staged residency removals and wait for the queue")?;
Ok(())
}
thread_local! {
static UNSETTLED: RefCell<Option<String>> = const { RefCell::new(None) };
}
pub(crate) fn record_thread_unsettled(reason: impl Into<String>) {
UNSETTLED.with(|unsettled| {
unsettled.borrow_mut().get_or_insert_with(|| reason.into());
});
}
pub(crate) fn take_thread_unsettled() -> Option<String> {
UNSETTLED.with(|unsettled| unsettled.borrow_mut().take())
}
pub(crate) fn settle_or_record(device: &MlxDevice) -> Result<()> {
let settled = settle(device);
if let Err(error) = &settled {
tracing::error!(
reason = %format!("{error:#}"),
"a device's command queue could not be settled"
);
record_thread_unsettled(format!("{error:#}"));
}
settled
}
pub(crate) struct SettledDevice {
device: MlxDevice,
settled: bool,
}
impl SettledDevice {
pub(crate) fn new() -> mlx_native::Result<Self> {
MlxDevice::new().map(|device| Self {
device,
settled: false,
})
}
pub(crate) fn settle(mut self) -> Result<()> {
self.settled = true;
settle_or_record(&self.device)
}
}
impl std::ops::Deref for SettledDevice {
type Target = MlxDevice;
fn deref(&self) -> &MlxDevice {
&self.device
}
}
impl Drop for SettledDevice {
fn drop(&mut self) {
if !self.settled {
let _ = settle_or_record(&self.device);
}
}
}
#[cfg(test)]
pub(crate) mod fault {
use std::cell::RefCell;
type Fault = Box<dyn FnMut() -> anyhow::Result<()>>;
thread_local! {
static FAULT: RefCell<Option<Fault>> = const { RefCell::new(None) };
}
pub(crate) fn inject(fault: impl FnMut() -> anyhow::Result<()> + 'static) {
FAULT.with(|slot| *slot.borrow_mut() = Some(Box::new(fault)));
}
pub(crate) fn clear() {
FAULT.with(|slot| slot.borrow_mut().take());
}
pub(super) fn next() -> Option<anyhow::Result<()>> {
let mut fault = FAULT.with(|slot| slot.borrow_mut().take())?;
let outcome = fault();
FAULT.with(|slot| {
slot.borrow_mut().get_or_insert(fault);
});
Some(outcome)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use std::rc::Rc;
fn failing_settle() -> Rc<Cell<u32>> {
let calls = Rc::new(Cell::new(0));
let counted = Rc::clone(&calls);
fault::inject(move || {
counted.set(counted.get() + 1);
anyhow::bail!("synthetic Metal failure")
});
calls
}
fn device_or_skip() -> Option<SettledDevice> {
let device = SettledDevice::new().ok();
if device.is_none() {
eprintln!("skipping: no Metal device");
}
device
}
#[test]
fn a_settled_device_is_the_device_and_settles_a_healthy_queue() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let Some(device) = device_or_skip() else {
return;
};
assert!(take_thread_unsettled().is_none());
let buffer = device
.alloc_buffer(1024, mlx_native::DType::F32, vec![256])
.expect("buffer");
let mut encoder = device.command_encoder().expect("encoder");
encoder.commit();
drop(buffer);
device.settle().expect("a healthy queue settles");
drop(device_or_skip());
assert!(take_thread_unsettled().is_none());
}
#[test]
fn a_step_that_succeeds_reports_a_settle_failure_as_its_own() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let Some(device) = device_or_skip() else {
return;
};
let calls = failing_settle();
let error = device.settle().expect_err("the step fails");
assert!(format!("{error:#}").contains("synthetic Metal failure"));
assert_eq!(calls.get(), 1);
assert!(take_thread_unsettled()
.expect("recorded")
.contains("synthetic Metal failure"));
fault::clear();
}
#[test]
fn a_step_that_fails_or_unwinds_leaves_the_failure_on_the_threads_record() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let (Some(failed), Some(unwound)) = (device_or_skip(), device_or_skip()) else {
return;
};
let calls = failing_settle();
let step = |device: SettledDevice| -> Result<()> {
let _device = device;
anyhow::bail!("the step's own error")
};
assert!(step(failed).is_err());
assert_eq!(calls.get(), 1);
assert!(take_thread_unsettled().is_some());
let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _device = unwound;
panic!("the step panicked");
}));
assert!(panicked.is_err());
assert_eq!(calls.get(), 2);
assert!(take_thread_unsettled().is_some());
fault::clear();
}
#[test]
fn a_recorded_failure_survives_the_error_that_overtakes_it() {
let _gpu = crate::inference::hf2q_gpu_test_lock();
let Some(device) = device_or_skip() else {
return;
};
let calls = failing_settle();
let provision = || -> Result<()> {
let runtime: Result<()> = Err(anyhow::anyhow!("the drafter did not load"));
let released = settle_or_record(&device);
runtime?;
released
};
let error = provision().expect_err("fails");
assert!(format!("{error:#}").contains("the drafter did not load"));
assert_eq!(calls.get(), 1);
assert!(take_thread_unsettled()
.expect("the cleanup failure is not lost")
.contains("synthetic Metal failure"));
fault::clear();
device.settle().expect("settles");
}
#[test]
fn an_unsettled_queue_is_recorded_once_for_the_thread() {
std::thread::spawn(|| {
assert!(take_thread_unsettled().is_none());
record_thread_unsettled("first");
record_thread_unsettled("second");
assert_eq!(take_thread_unsettled().as_deref(), Some("first"));
assert!(take_thread_unsettled().is_none());
})
.join()
.expect("thread");
}
}