mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
fix(gpu): wait for this renderer's own timed-out request, and test it without a driver
Review follow-ups: - A timed-out request now returns `GpuContextError::TimedOut` with an `AbandonedRequest` handle (same message as before). `GpuRenderer` keeps only its own handle and waits on that when dropped, so an ordinary adapter failure no longer waits for another renderer's abandoned request. - The result goes through a rendezvous channel, and the receiver is dropped on timeout, so an unclaimed context is dropped on the worker before the request counts as finished. - The timeout is now `run_with_timeout`, unit-tested with held work: it counts as running until released, and an unclaimed result is dropped first. - The docs say what a `false` from either wait means. Signed-off-by: FredApps <[email protected]>
This commit is contained in:
1 parent
8543937a76
commit
c06ae97029
6 files changed
+200
-65
No files matched your search
@@ -3,7 +3,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_doc::{DocId, Document, Rect};
|
||||
use photocraft_gpu::context::{NativeContext, NativeContextOptions};
|
||||
use photocraft_gpu::context::{AbandonedRequest, GpuContextError, NativeContext, NativeContextOptions};
|
||||
use photocraft_gpu::{Compositor, readback};
|
||||
use photocraft_io::{BandRenderer, IoError, RenderBand, RenderError};
|
||||
|
||||
@@ -22,6 +22,8 @@ pub struct GpuRenderer {
|
||||
init_error: Option<String>,
|
||||
diagnostics: Vec<String>,
|
||||
adapter_reported: bool,
|
||||
/// This renderer's GPU request that timed out, still running inside the driver.
|
||||
abandoned: Option<AbandonedRequest>,
|
||||
}
|
||||
|
||||
impl GpuRenderer {
|
||||
@@ -43,6 +45,7 @@ impl GpuRenderer {
|
||||
init_error: None,
|
||||
diagnostics: Vec::new(),
|
||||
adapter_reported: false,
|
||||
abandoned: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,6 +60,7 @@ impl GpuRenderer {
|
||||
init_error: None,
|
||||
diagnostics: Vec::new(),
|
||||
adapter_reported: false,
|
||||
abandoned: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +103,9 @@ impl GpuRenderer {
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
if let GpuContextError::TimedOut { pending, .. } = &e {
|
||||
self.abandoned = Some(pending.clone());
|
||||
}
|
||||
let msg = format!("no GPU adapter available: {e}");
|
||||
self.push_diag(msg.clone());
|
||||
self.init_error = Some(msg.clone());
|
||||
@@ -149,15 +156,14 @@ impl GpuRenderer {
|
||||
}
|
||||
|
||||
impl Drop for GpuRenderer {
|
||||
/// A request that timed out left its thread inside the driver. Give it time to finish, so the
|
||||
/// process does not exit under it: Lavapipe then crashes the process. A driver that really
|
||||
/// hangs costs this wait once, after its request already failed.
|
||||
/// This renderer's request that timed out left its thread inside the driver. Give it time to
|
||||
/// finish, so the process does not exit under it: Lavapipe then crashes the process. A driver
|
||||
/// that really hangs costs this wait once, after its request already failed. Past the limit the
|
||||
/// drop returns anyway and accepts that risk rather than hanging.
|
||||
fn drop(&mut self) {
|
||||
if self.context.is_none()
|
||||
&& self.init_error.is_some()
|
||||
&& let Some(timeout) = self.options.timeout
|
||||
{
|
||||
NativeContext::wait_for_abandoned_requests(timeout.max(ABANDONED_REQUEST_WAIT));
|
||||
if let Some(pending) = self.abandoned.take() {
|
||||
let timeout = self.options.timeout.unwrap_or_default();
|
||||
pending.wait(timeout.max(ABANDONED_REQUEST_WAIT));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -293,7 +293,10 @@ mod tests {
|
||||
let mut gpu_renderer = GpuRenderer::with_options(options);
|
||||
let doc = make_test_doc(16, 16, SampleType::U8);
|
||||
let res = gpu_renderer.render_bands(&doc, doc.bounds(), 16, &photocraft_raster::Interrupt::NONE, &mut |_| Ok::<(), photocraft_io::IoError>(()));
|
||||
assert!(matches!(res, Err(photocraft_io::RenderError::Unavailable(_))), "a zero timeout must leave the renderer unavailable: {res:?}");
|
||||
assert!(
|
||||
matches!(&res, Err(photocraft_io::RenderError::Unavailable(msg)) if msg.contains("timed out")),
|
||||
"a zero timeout must time the request out: {res:?}"
|
||||
);
|
||||
|
||||
drop(gpu_renderer);
|
||||
assert!(NativeContext::wait_for_abandoned_requests(std::time::Duration::ZERO), "the drop returned with the request still inside the driver");
|
||||
|
||||
+124
-49
@@ -18,6 +18,10 @@ pub enum GpuContextError {
|
||||
Compositor(String),
|
||||
#[error("GPU device was lost: {0}")]
|
||||
DeviceLost(String),
|
||||
/// Initialization did not finish within [`NativeContextOptions::timeout`]. Its thread is
|
||||
/// still running inside wgpu and the driver; `pending` tells when it has finished.
|
||||
#[error("no suitable GPU adapter found: timed out after {timeout:?} requesting GPU adapter/device")]
|
||||
TimedOut { timeout: Duration, pending: AbandonedRequest },
|
||||
}
|
||||
|
||||
impl From<Unsupported> for GpuContextError {
|
||||
@@ -43,8 +47,11 @@ pub struct NativeContextOptions {
|
||||
/// If initialization times out, the background initialization thread cannot be forcibly terminated
|
||||
/// in standard Rust and continues detached until wgpu completes or fails. Callers should avoid
|
||||
/// repeatedly requesting initialization in tight loops when timeouts occur to prevent thread and
|
||||
/// resource leaks. Before the process exits, call [`NativeContext::wait_for_abandoned_requests`]:
|
||||
/// exiting while that thread is still inside the driver can crash the process.
|
||||
/// resource leaks. Exiting while that thread is still inside the driver can crash the process,
|
||||
/// so wait for it first: [`AbandonedRequest::wait`] on the one in
|
||||
/// [`GpuContextError::TimedOut`], or [`NativeContext::wait_for_abandoned_requests`] for all.
|
||||
/// Either returns `false` when the thread is still running at the limit; the process then
|
||||
/// either waits longer or exits accepting that risk.
|
||||
pub timeout: Option<Duration>,
|
||||
}
|
||||
|
||||
@@ -135,26 +142,11 @@ impl NativeContext {
|
||||
};
|
||||
|
||||
if let Some(timeout) = options.timeout {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let request = Arc::new(InitThread::default());
|
||||
let thread_request = Arc::clone(&request);
|
||||
let thread_res = std::thread::Builder::new().name("pc_gpu_init".into()).spawn(move || {
|
||||
// Declared first so it is dropped last: an abandoned request counts as running
|
||||
// until the context nobody waits for any more has been dropped too.
|
||||
let _finish = FinishOnDrop(thread_request);
|
||||
let res = init_work();
|
||||
let _ = tx.send(res);
|
||||
});
|
||||
match thread_res {
|
||||
Ok(_handle) => match rx.recv_timeout(timeout) {
|
||||
Ok(res) => res,
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
|
||||
request.abandon();
|
||||
Err(GpuContextError::NoAdapter(format!("timed out after {timeout:?} requesting GPU adapter/device")))
|
||||
}
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(GpuContextError::NoAdapter("GPU initialization thread disconnected".into())),
|
||||
},
|
||||
Err(e) => Err(GpuContextError::NoAdapter(format!("failed to spawn GPU initialization thread: {e}"))),
|
||||
match run_with_timeout("pc_gpu_init", timeout, init_work) {
|
||||
Ok(res) => res,
|
||||
Err(InitWait::TimedOut(pending)) => Err(GpuContextError::TimedOut { timeout, pending }),
|
||||
Err(InitWait::Disconnected) => Err(GpuContextError::NoAdapter("GPU initialization thread disconnected".into())),
|
||||
Err(InitWait::Spawn(e)) => Err(GpuContextError::NoAdapter(format!("failed to spawn GPU initialization thread: {e}"))),
|
||||
}
|
||||
} else {
|
||||
init_work()
|
||||
@@ -167,24 +159,12 @@ impl NativeContext {
|
||||
/// A request that timed out leaves its thread inside wgpu and the driver. If the process
|
||||
/// exits meanwhile, the driver's state is torn down under that thread, and software drivers
|
||||
/// such as Lavapipe crash the whole process (a SIGSEGV or heap corruption after every test
|
||||
/// already passed). Call this before exiting after a timed-out request.
|
||||
/// already passed). Call this before exiting after a timed-out request. To wait for one
|
||||
/// request only, use the [`AbandonedRequest`] in its [`GpuContextError::TimedOut`].
|
||||
///
|
||||
/// Returns `false` when one is still running at `limit`; see [`NativeContextOptions::timeout`].
|
||||
pub fn wait_for_abandoned_requests(limit: Duration) -> bool {
|
||||
// A limit too far ahead to represent waits as long as it takes.
|
||||
let deadline = Instant::now().checked_add(limit);
|
||||
let mut running = ABANDONED.running.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
while *running > 0 {
|
||||
running = match deadline {
|
||||
Some(deadline) => {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
return false;
|
||||
}
|
||||
ABANDONED.done.wait_timeout(running, left).unwrap_or_else(PoisonError::into_inner).0
|
||||
}
|
||||
None => ABANDONED.done.wait(running).unwrap_or_else(PoisonError::into_inner),
|
||||
};
|
||||
}
|
||||
true
|
||||
wait_until(&ABANDONED.running, &ABANDONED.done, limit, |running| *running == 0)
|
||||
}
|
||||
|
||||
/// Build a new [`Compositor`] wired to this context's device and health flag.
|
||||
@@ -259,6 +239,90 @@ impl NativeContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why [`run_with_timeout`] returned without the work's result.
|
||||
enum InitWait {
|
||||
TimedOut(AbandonedRequest),
|
||||
Disconnected,
|
||||
Spawn(std::io::Error),
|
||||
}
|
||||
|
||||
/// Run `work` on a thread named `name` and wait up to `timeout` for its result. On a timeout the
|
||||
/// thread keeps running, and the returned [`AbandonedRequest`] tells when it has finished.
|
||||
fn run_with_timeout<T, F>(name: &str, timeout: Duration, work: F) -> Result<T, InitWait>
|
||||
where
|
||||
T: Send + 'static,
|
||||
F: FnOnce() -> T + Send + 'static,
|
||||
{
|
||||
// A rendezvous channel: a result is either handed to this thread or, once it stopped
|
||||
// waiting, dropped on the worker before the worker counts as finished.
|
||||
let (tx, rx) = std::sync::mpsc::sync_channel(0);
|
||||
let request = AbandonedRequest(Arc::new(InitThread::default()));
|
||||
let thread_request = request.clone();
|
||||
let spawned = std::thread::Builder::new().name(name.into()).spawn(move || {
|
||||
// Declared first so it is dropped last, after an unclaimed result.
|
||||
let _finish = FinishOnDrop(thread_request);
|
||||
let res = work();
|
||||
let _ = tx.send(res);
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
return Err(InitWait::Spawn(e));
|
||||
}
|
||||
match rx.recv_timeout(timeout) {
|
||||
Ok(res) => Ok(res),
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
|
||||
request.0.abandon();
|
||||
// Stop taking the result, so the worker drops it itself.
|
||||
drop(rx);
|
||||
Err(InitWait::TimedOut(request))
|
||||
}
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(InitWait::Disconnected),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait up to `limit` until `done` holds for the state behind `lock`, re-checking whenever `cv`
|
||||
/// is notified. A limit too far ahead to represent waits as long as it takes.
|
||||
fn wait_until<S>(lock: &Mutex<S>, cv: &Condvar, limit: Duration, done: impl Fn(&S) -> bool) -> bool {
|
||||
let deadline = Instant::now().checked_add(limit);
|
||||
let mut state = lock.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
while !done(&state) {
|
||||
state = match deadline {
|
||||
Some(deadline) => {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
return false;
|
||||
}
|
||||
cv.wait_timeout(state, left).unwrap_or_else(PoisonError::into_inner).0
|
||||
}
|
||||
None => cv.wait(state).unwrap_or_else(PoisonError::into_inner),
|
||||
};
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// An initialization thread that [`NativeContext::request`] stopped waiting for after its
|
||||
/// timeout, still running inside wgpu and the driver until it finishes.
|
||||
#[derive(Clone)]
|
||||
pub struct AbandonedRequest(Arc<InitThread>);
|
||||
|
||||
impl AbandonedRequest {
|
||||
/// Wait up to `limit` for this thread to finish. Returns `false` when it is still running;
|
||||
/// see [`NativeContextOptions::timeout`].
|
||||
pub fn wait(&self, limit: Duration) -> bool {
|
||||
wait_until(&self.0.state, &self.0.done, limit, |state| state.finished)
|
||||
}
|
||||
|
||||
/// Whether the thread has finished, including dropping a context nobody claimed.
|
||||
pub fn is_finished(&self) -> bool {
|
||||
self.0.state.lock().unwrap_or_else(PoisonError::into_inner).finished
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for AbandonedRequest {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("AbandonedRequest").field("finished", &self.is_finished()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// How many initialization threads [`NativeContext::request`] gave up on are still running.
|
||||
struct Abandoned {
|
||||
running: Mutex<usize>,
|
||||
@@ -267,28 +331,36 @@ struct Abandoned {
|
||||
|
||||
static ABANDONED: Abandoned = Abandoned { running: Mutex::new(0), done: Condvar::new() };
|
||||
|
||||
/// One initialization thread: whether its request gave up on it, and whether it has finished.
|
||||
#[derive(Default)]
|
||||
struct ThreadState {
|
||||
/// The request stopped waiting for the thread.
|
||||
abandoned: bool,
|
||||
/// The thread has finished.
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
/// One initialization thread and a condition variable notified when it finishes.
|
||||
#[derive(Default)]
|
||||
struct InitThread {
|
||||
state: Mutex<(bool, bool)>,
|
||||
state: Mutex<ThreadState>,
|
||||
done: Condvar,
|
||||
}
|
||||
|
||||
impl InitThread {
|
||||
/// The request stopped waiting: count the thread in [`ABANDONED`] unless it already finished.
|
||||
fn abandon(&self) {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let (abandoned, finished) = &mut *state;
|
||||
if !*finished && !*abandoned {
|
||||
*abandoned = true;
|
||||
if !state.finished && !state.abandoned {
|
||||
state.abandoned = true;
|
||||
*ABANDONED.running.lock().unwrap_or_else(PoisonError::into_inner) += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&self) {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let (abandoned, finished) = &mut *state;
|
||||
*finished = true;
|
||||
if *abandoned {
|
||||
state.finished = true;
|
||||
self.done.notify_all();
|
||||
if state.abandoned {
|
||||
let mut running = ABANDONED.running.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
*running = running.saturating_sub(1);
|
||||
ABANDONED.done.notify_all();
|
||||
@@ -297,10 +369,13 @@ impl InitThread {
|
||||
}
|
||||
|
||||
/// Marks the initialization thread finished when it ends, also when it panics.
|
||||
struct FinishOnDrop(Arc<InitThread>);
|
||||
struct FinishOnDrop(AbandonedRequest);
|
||||
|
||||
impl Drop for FinishOnDrop {
|
||||
fn drop(&mut self) {
|
||||
self.0.finish();
|
||||
self.0.0.finish();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,53 @@
|
||||
//! The timeout around GPU initialization, with test-controlled work instead of a driver.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, mpsc};
|
||||
use std::time::Duration;
|
||||
|
||||
use super::{InitWait, run_with_timeout};
|
||||
|
||||
const LONG: Duration = Duration::from_secs(60);
|
||||
|
||||
#[test]
|
||||
fn work_that_finishes_in_time_returns_its_result() {
|
||||
assert!(matches!(run_with_timeout("t_in_time", LONG, || 7), Ok(7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timed_out_request_counts_as_running_until_its_work_finishes() {
|
||||
let (release, released) = mpsc::channel::<()>();
|
||||
let res = run_with_timeout("t_abandoned", Duration::from_millis(10), move || released.recv().is_ok());
|
||||
let Err(InitWait::TimedOut(pending)) = res else { panic!("held work must time out") };
|
||||
assert!(!pending.is_finished());
|
||||
assert!(!pending.wait(Duration::from_millis(50)), "the wait returned while the work was still held");
|
||||
|
||||
release.send(()).unwrap();
|
||||
assert!(pending.wait(LONG), "the work finished but the wait never saw it");
|
||||
assert!(pending.is_finished());
|
||||
}
|
||||
|
||||
/// A result that arrives after the timeout is dropped on the worker before it counts as
|
||||
/// finished: a context's device must be gone before a waiter lets the process exit.
|
||||
#[test]
|
||||
fn an_unclaimed_result_is_dropped_before_the_request_finishes() {
|
||||
struct SlowDrop(Arc<AtomicBool>);
|
||||
impl Drop for SlowDrop {
|
||||
fn drop(&mut self) {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
self.0.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
let dropped = Arc::new(AtomicBool::new(false));
|
||||
let (release, released) = mpsc::channel::<()>();
|
||||
let result_dropped = Arc::clone(&dropped);
|
||||
let res = run_with_timeout("t_unclaimed", Duration::from_millis(10), move || {
|
||||
let _ = released.recv();
|
||||
SlowDrop(result_dropped)
|
||||
});
|
||||
let Err(InitWait::TimedOut(pending)) = res else { panic!("held work must time out") };
|
||||
|
||||
release.send(()).unwrap();
|
||||
assert!(pending.wait(LONG));
|
||||
assert!(dropped.load(Ordering::SeqCst), "the request finished before its unclaimed result was dropped");
|
||||
}
|
||||
@@ -153,7 +153,7 @@ use batch::{BATCH, batch_kernel, batch_op_words, batch_runs, op_words, run_start
|
||||
use consts::OP_UNIFORM;
|
||||
pub use consts::{ACC_FORMAT, CHUNK, FX_BUDGET, PAGE, PATTERN_BUDGET, PATTERN_IDLE_FRAMES, RESIDENT_BUDGET};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use context::{GpuContextError, NativeContext, NativeContextOptions};
|
||||
pub use context::{AbandonedRequest, GpuContextError, NativeContext, NativeContextOptions};
|
||||
use convert::W;
|
||||
#[cfg(test)]
|
||||
use convert::{CONVERT_BATCH, colour_managed, convert_tile, convert_tiles, rgb_gray16_to_f16, rgb_gray32_to_f16};
|
||||
|
||||
@@ -14,10 +14,8 @@ fn a_timed_out_request_can_be_waited_for_before_exit() {
|
||||
let _gpu = GPU_LOCK.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let opts = NativeContextOptions { timeout: Some(Duration::ZERO), ..Default::default() };
|
||||
let res = NativeContext::request(&opts);
|
||||
assert!(
|
||||
matches!(&res, Err(GpuContextError::NoAdapter(msg)) if msg.contains("timed out")),
|
||||
"a zero timeout must give up before the adapter is ready: {res:?}"
|
||||
);
|
||||
assert!(NativeContext::wait_for_abandoned_requests(Duration::from_secs(120)), "the abandoned initialization thread never finished");
|
||||
let Err(GpuContextError::TimedOut { pending, .. }) = &res else { panic!("a zero timeout must give up before the adapter is ready: {res:?}") };
|
||||
assert!(pending.wait(Duration::from_secs(120)), "the abandoned initialization thread never finished");
|
||||
assert!(pending.is_finished());
|
||||
assert!(NativeContext::wait_for_abandoned_requests(Duration::ZERO), "a finished thread must not count as running");
|
||||
}
|
||||
Reference in new issue
Block a user