singe_cuda/stream/scope.rs
1use std::{marker::PhantomData, result::Result as StdResult, sync::Arc};
2
3use singe_cuda_sys::runtime;
4
5use super::{AsStream, Stream, StreamBinding, StreamCaptureStatus, sealed};
6use crate::{
7 context::Context,
8 error::{Error, Result, Status},
9 submission::{Access, Execution, Resources},
10};
11
12/// A borrowed stream scope that drains queued work before borrowed storage can be released.
13///
14/// Constructed by [`Stream::sync_scope`].
15/// Cleanup also drains during unwinding and aborts the process if completion cannot be established.
16#[derive(Debug)]
17pub struct StreamScope<'scope, 'env> {
18 stream: &'scope Stream,
19 _env: PhantomData<&'env mut &'env ()>,
20}
21
22struct ScopeDrain {
23 stream: StreamBinding,
24 drained: bool,
25}
26
27impl Drop for ScopeDrain {
28 fn drop(&mut self) {
29 // Returning or unwinding would release borrowed storage that CUDA might still access.
30 // Unlike owned submissions, a scope cannot retain or leak its caller's stack storage after it exits.
31 if !self.drained {
32 self.stream.synchronize_or_abort();
33 }
34 }
35}
36
37impl Stream {
38 /// Runs `f` with a stream scope and synchronizes this stream before returning.
39 ///
40 /// Use this for scoped asynchronous operations that borrow host or device memory until stream completion.
41 /// For CUDA graph capture, use [`Stream::capture`] or [`Stream::capture_executable`].
42 /// The completion wait also runs when `f` unwinds.
43 /// If CUDA completion cannot be established, the process aborts before returning borrowed storage to the caller.
44 ///
45 /// # Errors
46 ///
47 /// Propagates capture-state query errors, rejects active or invalidated capture, and returns errors from `f` or stream synchronization.
48 /// If both `f` and synchronization fail and cleanup can drain the stream, the closure error takes precedence.
49 pub fn sync_scope<'env, F, R>(&self, f: F) -> Result<R>
50 where
51 F: for<'scope> FnOnce(&'scope StreamScope<'scope, 'env>) -> Result<R>,
52 {
53 let scope = StreamScope {
54 stream: self,
55 _env: PhantomData,
56 };
57 self.complete(|| f(&scope))
58 }
59
60 /// Runs `f`, then waits for this stream even when `f` fails or unwinds, so borrowed operands outlive the work `f` enqueues.
61 ///
62 /// Capture is rejected before `f` runs.
63 /// This is [`StreamBinding::sync_scope`] on a borrowed binding of this stream.
64 ///
65 /// # Errors
66 ///
67 /// Converts capture-query, context binding, capture rejection, and stream synchronization errors into `E`.
68 /// Errors returned by `f` take precedence over a synchronization error.
69 pub fn complete<R, E>(&self, f: impl FnOnce() -> StdResult<R, E>) -> StdResult<R, E>
70 where
71 E: From<Error>,
72 {
73 StreamBinding::Borrowed(self.to_borrowed()).sync_scope(f)
74 }
75}
76
77impl<'scope> StreamScope<'scope, '_> {
78 /// Enqueues work on the scope's stream after declaring the accesses it makes.
79 ///
80 /// The declared accesses order the work after conflicting tracked work and make later tracked work wait for it.
81 /// Wrapper `_scoped` functions use this to record their operands' accesses.
82 ///
83 /// # Safety
84 ///
85 /// `enqueue` must only enqueue work on [`Self::stream`] that touches the declared accesses, in the declared modes.
86 /// Borrowed operands must be `'env` borrows, which the scope keeps alive until it drains.
87 ///
88 /// # Errors
89 ///
90 /// Propagates access-tracking, dependency-ordering, and completion-event errors, and errors returned by `enqueue`.
91 pub unsafe fn enqueue<T>(
92 &self,
93 accesses: &[Access],
94 enqueue: impl FnOnce() -> Result<T>,
95 ) -> Result<T> {
96 let mut resources = Resources::new();
97 resources.accesses.extend_from_slice(accesses);
98 let mut execution = Execution::create(self.stream)?;
99 // Caller borrows stay alive until the scope drains, including error and unwind paths.
100 // SAFETY: the caller guarantees `enqueue` touches only the declared accesses on this scope's stream, and the scope keeps its `'env` borrows alive until it drains.
101 let output = unsafe { execution.enqueue(resources, |_| enqueue())? };
102 execution.finish(())?;
103 Ok(output)
104 }
105
106 /// Returns the stream borrowed by this synchronous scope.
107 #[must_use]
108 pub const fn stream(&self) -> &'scope Stream {
109 self.stream
110 }
111}
112
113impl sealed::Sealed for StreamScope<'_, '_> {}
114
115impl AsStream for StreamScope<'_, '_> {
116 fn context(&self) -> &Arc<Context> {
117 self.stream.context()
118 }
119
120 fn as_raw(&self) -> runtime::cudaStream_t {
121 self.stream.as_raw()
122 }
123}
124
125impl StreamBinding {
126 /// Completes borrowed work on this stream before returning or unwinding.
127 ///
128 /// Capture is rejected before calling `f`.
129 /// Default and externally borrowed streams use the same completion contract as owned streams.
130 /// If completion cannot be established, the process aborts before releasing borrowed storage.
131 ///
132 /// # Errors
133 ///
134 /// Converts capture-query, context binding, capture rejection, and stream synchronization errors into `E`.
135 /// Errors returned by `f` pass through after cleanup drains the stream and take precedence over a synchronization error if both occur.
136 pub fn sync_scope<R, E>(&self, f: impl FnOnce() -> StdResult<R, E>) -> StdResult<R, E>
137 where
138 E: From<Error>,
139 {
140 match self.capture_status()? {
141 StreamCaptureStatus::None => {}
142 StreamCaptureStatus::Active => {
143 return Err(Error::from(Status::StreamCaptureUnsupported).into());
144 }
145 StreamCaptureStatus::Invalidated => {
146 return Err(Error::from(Status::StreamCaptureInvalidated).into());
147 }
148 }
149
150 let mut drain = ScopeDrain {
151 stream: self.clone(),
152 drained: false,
153 };
154 let result = f();
155 let completion = self.synchronize();
156 drain.drained = completion.is_ok();
157 drop(drain);
158 match (result, completion) {
159 (Ok(value), Ok(())) => Ok(value),
160 (Err(error), _) => Err(error),
161 (Ok(_), Err(error)) => Err(error.into()),
162 }
163 }
164}