Skip to main content

singe_cuda/submission/
mod.rs

1//! Owned CUDA operations, explicit-stream execution and range-based ordering.
2//!
3//! Submission retains native owners independently of outputs and futures.
4//! Pending device values remain pending until the caller establishes successful completion.
5
6mod completion;
7mod operation;
8mod resource;
9mod tracker;
10pub mod transfer;
11
12use std::{
13    future::Future,
14    mem, panic,
15    panic::AssertUnwindSafe,
16    pin::Pin,
17    result::Result as StdResult,
18    sync::Arc,
19    task::{Context, Poll},
20};
21
22use singe_core::report_cleanup_failure;
23
24pub(crate) use self::tracker::{AccessGuard, AccessTracker, lock_access};
25pub use self::{
26    completion::Completion,
27    operation::{DeviceOperation, Map, Operation, Pair, Shared, StreamPool, Then},
28    resource::{Access, AccessMode, Resources},
29};
30use crate::{
31    error::{Error, Result},
32    event::{Event, EventFlags, EventRecordFlags},
33    stream::Stream,
34};
35
36/// Retains every resource registered before an operation enqueues work.
37/// On error or unwind, drains submitted work before releasing its ledger.
38#[derive(Debug)]
39pub struct Execution {
40    stream: Stream,
41    resources: Resources,
42    events: Vec<Arc<Event>>,
43    submitted: bool,
44}
45
46impl Execution {
47    /// Starts an owned execution ledger on an explicit stream outside capture.
48    ///
49    /// # Errors
50    ///
51    /// Returns an error if capture is active or CUDA cannot query the stream.
52    pub fn create(stream: &Stream) -> Result<Self> {
53        stream.ensure_not_capturing()?;
54        Ok(Self {
55            stream: stream.clone(),
56            resources: Resources::new(),
57            events: Vec::new(),
58            submitted: false,
59        })
60    }
61
62    /// Returns the explicit stream used by this execution ledger.
63    #[must_use]
64    pub fn stream(&self) -> &Stream {
65        &self.stream
66    }
67
68    /// Registers all owners and accesses before invoking an asynchronous native operation.
69    ///
70    /// # Safety
71    ///
72    /// Retain every owner in the ledger or keep borrowed storage live until stream completion.
73    /// Stream-ordered allocations may rely on deallocation ordered after this work.
74    /// Owned [`Operation`] implementations must retain their resources independently of returned values.
75    /// Declare every accessed byte range and uphold the native operation's bounds and value contracts.
76    /// External raw access must participate in ordering or be excluded through completion.
77    /// The closure must only enqueue work on the supplied stream and must not submit nested operations.
78    ///
79    /// # Errors
80    ///
81    /// Converts access-context mismatches, nested access, failed or poisoned tracking, dependency failures, stream-ordering errors, and completion-event creation or recording failures into `E`.
82    /// Errors returned by `enqueue` pass through after completion is recorded.
83    /// A later event-recording failure takes precedence over the callback result; native work may already be queued.
84    ///
85    /// # Panics
86    ///
87    /// Resumes unwinding if `enqueue` panics, after attempting to synchronize its submitted work.
88    /// The execution ledger continues to retain its registered resources during cleanup.
89    pub unsafe fn enqueue<T, E: From<Error>>(
90        &mut self,
91        mut resources: Resources,
92        enqueue: impl FnOnce(&Stream) -> StdResult<T, E>,
93    ) -> StdResult<T, E> {
94        let context = Arc::clone(self.stream.context());
95        for access in &resources.accesses {
96            access.validate_context(&context)?;
97        }
98
99        let mut tracker = lock_access(&context.access_tracker, &resources.accesses)?;
100        tracker.order(&self.stream, &resources.accesses)?;
101        for dependency in &resources.dependencies {
102            dependency.query()?;
103            dependency.order_on(&self.stream)?;
104        }
105
106        let access_start = self.resources.accesses.len();
107        tracker.retain(&mut resources);
108        self.resources.extend(resources);
109        let event = Arc::new(context.create_event(EventFlags::DISABLE_TIMING)?);
110        self.submitted = true;
111        let result = match panic::catch_unwind(AssertUnwindSafe(|| enqueue(&self.stream))) {
112            Ok(result) => result,
113            Err(payload) => {
114                if self.stream.synchronize().is_err() {
115                    tracker.fail();
116                }
117
118                drop(tracker);
119                panic::resume_unwind(payload);
120            }
121        };
122        if let Err(error) = event.record(&self.stream, EventRecordFlags::DEFAULT) {
123            if self.stream.synchronize().is_err() {
124                tracker.fail();
125            }
126            return Err(error.into());
127        }
128
129        tracker.record(&self.resources.accesses[access_start..], &event);
130        self.events.push(event);
131        result
132    }
133
134    /// Completes current work before running host code that consumes its values.
135    ///
136    /// # Errors
137    ///
138    /// Returns an error if stream synchronization or waiting for any declared dependency fails.
139    /// Dependencies are waited on in order, stopping at the first error.
140    pub fn synchronize(&self) -> Result<()> {
141        self.stream.synchronize()?;
142        for dependency in &self.resources.dependencies {
143            dependency.wait()?;
144        }
145        Ok(())
146    }
147
148    /// Transfers the ledger to checked completion independently of the returned output.
149    ///
150    /// # Errors
151    ///
152    /// Returns an error if CUDA cannot record completion or start its completion worker.
153    pub fn finish<T>(self, output: T) -> Result<Submission<T>> {
154        self.finish_with(output, |output| Ok(output))
155    }
156
157    fn finish_with<T, P>(
158        mut self,
159        pending: P,
160        resolve: unsafe fn(P) -> Result<T>,
161    ) -> Result<Submission<T, P>> {
162        let event = if let Some(event) = self.events.last() {
163            Arc::clone(event)
164        } else {
165            let event = Arc::new(
166                self.stream
167                    .context()
168                    .create_event(EventFlags::DISABLE_TIMING)?,
169            );
170            event.record(&self.stream, EventRecordFlags::DEFAULT)?;
171            event
172        };
173        // Earlier events keep their access declarations live until the entire chain completes.
174        for event in mem::take(&mut self.events) {
175            self.resources.retain(event);
176        }
177
178        let resources = mem::take(&mut self.resources);
179        let completion = Completion::start(event, self.stream.clone(), resources)?;
180        self.submitted = false;
181        Ok(Submission {
182            completion,
183            pending: Some(pending),
184            resolve,
185        })
186    }
187}
188
189impl Drop for Execution {
190    fn drop(&mut self) {
191        if self.submitted
192            && let Err(error) = self.stream.synchronize()
193        {
194            // The submission did not complete, so its live resources stay retained.
195            report_cleanup_failure("synchronize", "cuda submission", &error);
196            match lock_access(
197                &self.stream.context().access_tracker,
198                &self.resources.accesses,
199            ) {
200                Ok(mut tracker) => tracker.fail(),
201                Err(lock_error) => {
202                    report_cleanup_failure("lock", "cuda access tracker", &lock_error);
203                }
204            }
205
206            mem::forget(mem::take(&mut self.resources));
207            mem::forget(mem::take(&mut self.events));
208        }
209    }
210}
211
212/// An owned result and checked completion.
213/// Dropping this value never cancels CUDA work or releases its independent resource ledger.
214#[derive(Debug)]
215pub struct Submission<T, P = T> {
216    completion: Completion,
217    pending: Option<P>,
218    resolve: unsafe fn(P) -> Result<T>,
219}
220
221impl<T, P> Submission<T, P> {
222    /// Borrows the shared completion state without consuming the pending result.
223    pub fn completion(&self) -> &Completion {
224        &self.completion
225    }
226
227    /// Blocks for checked completion, then resolves and returns the operation's host result.
228    ///
229    /// Resolution runs on the calling thread after successful completion and resource retirement.
230    ///
231    /// # Errors
232    ///
233    /// Propagates completion, dependency, and resource-retirement errors.
234    /// After successful completion, errors returned by the operation's resolver are propagated.
235    ///
236    /// # Panics
237    ///
238    /// Panics if this submission already yielded its output when polled as a future.
239    /// A user-provided resolver or mapping callback can also panic.
240    pub fn wait(mut self) -> Result<T> {
241        self.completion.wait()?;
242        // SAFETY: successful checked completion establishes the resolver's precondition.
243        unsafe { (self.resolve)(self.pending.take().expect("submission already resolved")) }
244    }
245}
246
247impl<T, P> Unpin for Submission<T, P> {}
248
249impl<T, P> Future for Submission<T, P> {
250    type Output = Result<T>;
251
252    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
253        match Pin::new(&mut self.completion).poll(cx) {
254            Poll::Ready(Ok(())) => {
255                let pending = self.pending.take().expect("submission already resolved");
256                // SAFETY: successful checked completion establishes the resolver's precondition.
257                Poll::Ready(unsafe { (self.resolve)(pending) })
258            }
259            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
260            Poll::Pending => Poll::Pending,
261        }
262    }
263}
264
265impl Stream {
266    /// Submits owned work with independent resource retention and checked completion.
267    ///
268    /// # Errors
269    ///
270    /// Propagates errors from the operation's [`Operation::submit_on`] implementation, including execution setup, enqueue, and completion registration failures.
271    /// An error can occur after some native work has been queued; the execution ledger retains its resources through cleanup.
272    pub fn submit<O: Operation>(&self, operation: O) -> Result<Submission<O::Output, O::Pending>> {
273        operation.submit_on(self)
274    }
275}
276
277impl Stream {
278    /// Submits arbitrary raw work with an explicitly supplied ownership ledger.
279    ///
280    /// # Safety
281    ///
282    /// The resources must retain every native owner and declare all accesses before `enqueue` runs.
283    /// Follow [`crate::submission::Execution::enqueue`]'s native execution contract.
284    ///
285    /// # Errors
286    ///
287    /// Propagates capture-state, context, access-tracking, dependency-ordering, and completion-event errors, errors returned by `enqueue`, and failures to start or submit to the completion worker.
288    /// The callback may already have enqueued work when a later step fails.
289    pub unsafe fn enqueue_async<T, F>(
290        &self,
291        resources: Resources,
292        enqueue: F,
293    ) -> Result<Submission<T>>
294    where
295        F: FnOnce(&Self) -> Result<T>,
296    {
297        let mut execution = Execution::create(self)?;
298        // SAFETY: the caller guarantees `resources` retains every native owner and declares every access `enqueue` makes, and that `enqueue` follows the execution contract.
299        let output = unsafe { execution.enqueue(resources, enqueue)? };
300        execution.finish(output)
301    }
302}