Skip to main content

singe_cuda/submission/
operation.rs

1use std::{
2    fmt::{self, Debug, Formatter},
3    sync::{
4        Arc, Mutex,
5        atomic::{AtomicUsize, Ordering},
6    },
7};
8
9use crate::{
10    context::Context,
11    error::{Error, Result},
12    graph::owned::{Recordable, Recording},
13    stream::{Stream, StreamFlags, StreamOptions},
14    submission::{Completion, Execution, Resources, Submission},
15};
16
17/// Lazy owned CUDA work.
18///
19/// # Safety
20///
21/// Implementations must register all resources and accesses through [`Execution::enqueue`] before submitting native work, including on error and unwind paths.
22/// Returned pending values must not permit safe initialized reads before successful completion.
23/// Keep capture-incompatible preparation outside implementations intended for graph recording.
24pub unsafe trait Operation: Sized {
25    /// Value produced by enqueue before successful CUDA completion.
26    /// It must not permit safe reads of results that are still pending.
27    type Pending;
28
29    /// Host-visible result produced by resolution after successful completion.
30    type Output: 'static;
31
32    /// Registers resources and enqueues this operation on the execution's stream, returning its pending result.
33    ///
34    /// # Errors
35    ///
36    /// Returns operation-specific preparation or enqueue errors, including resource, context, dependency, and CUDA failures.
37    /// Implementations must retain resources for any work already queued when an error occurs.
38    fn enqueue(self, execution: &mut Execution) -> Result<Self::Pending>;
39
40    /// Resolves host results after successful native completion and resource retirement.
41    ///
42    /// # Safety
43    ///
44    /// `pending` must come from this operation's enqueue and its execution must have completed successfully.
45    ///
46    /// # Errors
47    ///
48    /// Returns operation-specific result-conversion or host-resolution errors after native work has completed successfully.
49    unsafe fn resolve(pending: Self::Pending) -> Result<Self::Output>;
50
51    /// Enqueues this operation on `stream` and returns its pending result with independent checked completion.
52    ///
53    /// Dropping the returned submission does not cancel its native work.
54    ///
55    /// # Errors
56    ///
57    /// Propagates execution setup, operation enqueue, and completion registration errors.
58    /// An execution ledger drains already submitted work on failure before releasing its resources, or preserves the resources if completion cannot be established.
59    fn submit_on(self, stream: &Stream) -> Result<Submission<Self::Output, Self::Pending>> {
60        let mut execution = Execution::create(stream)?;
61        let output = self.enqueue(&mut execution)?;
62        execution.finish_with(output, Self::resolve)
63    }
64
65    /// Chains dependent device work on the same stream without promoting pending values.
66    fn then<F, N>(self, next: F) -> Then<Self, F>
67    where
68        Self: DeviceOperation,
69        F: FnOnce(Self::Output) -> N,
70        N: Operation,
71    {
72        Then { first: self, next }
73    }
74
75    /// Pairs independent work on the selected stream; separate submissions can overlap.
76    fn pair<O: Operation>(self, other: O) -> Pair<Self, O> {
77        Pair(self, other)
78    }
79
80    /// Runs host code on the waiting or polling thread after successful completion.
81    /// Dropping the submission before resolution discards this callback.
82    fn map<F, T: 'static>(self, map: F) -> Map<Self, F>
83    where
84        F: FnOnce(Self::Output) -> T,
85    {
86        Map {
87            operation: self,
88            map,
89        }
90    }
91
92    /// Shares one execution and orders every consuming stream after its completion event.
93    fn shared(self) -> Shared<Self>
94    where
95        Self: DeviceOperation,
96        Self::Output: Send + Sync,
97    {
98        Shared {
99            state: Arc::new(Mutex::new(SharedState::New(Some(self)))),
100        }
101    }
102}
103
104/// Device work whose pending output is already suitable for composing further device work.
105/// Host consumers still need checked completion before reading produced values.
106///
107/// # Safety
108///
109/// Resolution must be the identity function, and pending outputs must uphold [`Operation`]'s contract.
110/// Enqueue must never rely on host resolution to schedule native work or initialize output metadata.
111pub unsafe trait DeviceOperation: Operation<Pending = <Self as Operation>::Output> {}
112
113/// Two operations composed so the second consumes the first device operation's pending output on the same stream.
114///
115/// Construct with [`Operation::then`].
116#[derive(Debug)]
117pub struct Then<O, F> {
118    first: O,
119    next: F,
120}
121
122// SAFETY: both stages enqueue through the same execution, so each registers its own resources first, and the pending value is `N`'s, which upholds the contract.
123unsafe impl<O, F, N> Operation for Then<O, F>
124where
125    O: DeviceOperation,
126    F: FnOnce(O::Output) -> N,
127    N: Operation,
128{
129    type Pending = N::Pending;
130
131    type Output = N::Output;
132
133    fn enqueue(self, execution: &mut Execution) -> Result<Self::Pending> {
134        let output = self.first.enqueue(execution)?;
135        (self.next)(output).enqueue(execution)
136    }
137
138    unsafe fn resolve(pending: Self::Pending) -> Result<Self::Output> {
139        // SAFETY: the caller guarantees `pending` came from this enqueue, which returns `N`'s pending value, and that execution completed.
140        unsafe { N::resolve(pending) }
141    }
142}
143
144/// Two operations enqueued in order on one execution stream and resolved as a pair.
145///
146/// Construct with [`Operation::pair`].
147#[derive(Debug)]
148pub struct Pair<A, B>(A, B);
149
150// SAFETY: each half enqueues through the same execution and registers its own resources, and the pending pair exposes only the halves' pending values.
151unsafe impl<A: Operation, B: Operation> Operation for Pair<A, B> {
152    type Pending = (A::Pending, B::Pending);
153
154    type Output = (A::Output, B::Output);
155
156    fn enqueue(self, execution: &mut Execution) -> Result<Self::Pending> {
157        Ok((self.0.enqueue(execution)?, self.1.enqueue(execution)?))
158    }
159
160    unsafe fn resolve(pending: Self::Pending) -> Result<Self::Output> {
161        // SAFETY: the caller guarantees the pair came from this enqueue, whose halves came from `A` and `B`, and that the shared execution completed.
162        unsafe { Ok((A::resolve(pending.0)?, B::resolve(pending.1)?)) }
163    }
164}
165
166/// An operation whose successful host result is transformed by a callback on the waiting or polling thread.
167///
168/// Construct with [`Operation::map`].
169/// The callback is discarded if the submission is dropped before resolution.
170#[derive(Debug)]
171pub struct Map<O, F> {
172    operation: O,
173    map: F,
174}
175
176// SAFETY: `enqueue` delegates to `O`, and the pending value holds `O`'s pending value beside a host callback that runs only on resolution.
177unsafe impl<O, F, T: 'static> Operation for Map<O, F>
178where
179    O: Operation,
180    F: FnOnce(O::Output) -> T,
181{
182    type Pending = (O::Pending, F);
183
184    type Output = T;
185
186    fn enqueue(self, execution: &mut Execution) -> Result<Self::Pending> {
187        Ok((self.operation.enqueue(execution)?, self.map))
188    }
189
190    unsafe fn resolve((pending, map): Self::Pending) -> Result<T> {
191        // SAFETY: the caller guarantees `pending` came from `O`'s enqueue within this one and that execution completed.
192        Ok(map(unsafe { O::resolve(pending)? }))
193    }
194}
195
196#[derive(Debug)]
197enum SharedState<O: DeviceOperation> {
198    New(Option<O>),
199    Submitted {
200        output: Arc<O::Output>,
201        completion: Completion,
202    },
203    Failed(Arc<Error>),
204}
205
206/// Clones of one lazily submitted device operation, sharing its output and checked completion.
207///
208/// The first consumer submits the producer.
209/// Later consumers order their streams after its completion event and retain the output.
210/// Producer submission errors are shared with consumers.
211/// Construct with [`Operation::shared`].
212pub struct Shared<O: DeviceOperation> {
213    state: Arc<Mutex<SharedState<O>>>,
214}
215
216impl<O: DeviceOperation> Debug for Shared<O> {
217    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
218        f.debug_struct("Shared").finish_non_exhaustive()
219    }
220}
221
222impl<O: DeviceOperation> Clone for Shared<O> {
223    fn clone(&self) -> Self {
224        Self {
225            state: Arc::clone(&self.state),
226        }
227    }
228}
229
230// SAFETY: the producer registers its own resources when first submitted, and each consumer registers the producer's completion and retains its output before ordering on it; `O: DeviceOperation` makes the shared output pending device metadata.
231unsafe impl<O: DeviceOperation> Operation for Shared<O>
232where
233    O::Output: Send + Sync,
234{
235    type Pending = Arc<O::Output>;
236
237    type Output = Arc<O::Output>;
238
239    unsafe fn resolve(pending: Self::Pending) -> Result<Self::Output> {
240        Ok(pending)
241    }
242
243    fn enqueue(self, execution: &mut Execution) -> Result<Self::Output> {
244        let mut state = self
245            .state
246            .lock()
247            .map_err(|_| Error::lock_poisoned("shared operation"))?;
248        if let SharedState::New(operation) = &mut *state {
249            let operation = operation.take().expect("shared operation has not executed");
250            *state = match operation.submit_on(execution.stream()) {
251                Ok(mut submission) => SharedState::Submitted {
252                    output: Arc::new(submission.pending.take().expect("new shared output")),
253                    completion: submission.completion.clone(),
254                },
255                Err(error) => SharedState::Failed(Arc::new(error)),
256            };
257        }
258        match &*state {
259            SharedState::Submitted { output, completion } => {
260                let mut resources = Resources::new();
261                resources.depend_on(completion.clone());
262                resources.retain(Arc::clone(output));
263                // SAFETY: the producer owns all native work; this operation only enqueues its dependency.
264                unsafe {
265                    execution.enqueue(resources, |_| Ok::<_, Error>(()))?;
266                }
267                Ok(Arc::clone(output))
268            }
269            SharedState::Failed(error) => Err(Error::Completion(Arc::clone(error))),
270            SharedState::New(_) => unreachable!("shared operation was submitted"),
271        }
272    }
273}
274
275/// Optional context-bound round-robin scheduling with no global stream selection.
276#[derive(Debug)]
277pub struct StreamPool {
278    streams: Vec<Stream>,
279    next: AtomicUsize,
280}
281
282impl StreamPool {
283    /// Creates `streams` nonblocking CUDA streams in `context` for round-robin submission.
284    ///
285    /// # Errors
286    ///
287    /// Returns `Error::NotPositive` if `streams` is zero.
288    /// Also propagates context binding or stream creation errors.
289    /// Streams already created are dropped if a later creation fails.
290    pub fn create(context: &Arc<Context>, streams: usize) -> Result<Self> {
291        if streams == 0 {
292            return Err(Error::not_positive("stream pool size"));
293        }
294        Ok(Self {
295            streams: (0..streams)
296                .map(|_| {
297                    context.create_stream(StreamOptions {
298                        flags: StreamFlags::NON_BLOCKING,
299                        ..StreamOptions::default()
300                    })
301                })
302                .collect::<Result<_>>()?,
303            next: AtomicUsize::new(0),
304        })
305    }
306
307    /// Submits `operation` on the next stream selected in round-robin order.
308    ///
309    /// The selection advances even when submission fails.
310    /// Separate operations can overlap unless their declared accesses or dependencies require ordering.
311    ///
312    /// # Errors
313    ///
314    /// Propagates errors from the operation's [`Operation::submit_on`] implementation.
315    /// An error can occur after native work has been queued; its execution ledger retains resources through cleanup.
316    pub fn submit<O: Operation>(&self, operation: O) -> Result<Submission<O::Output, O::Pending>> {
317        let index = self.next.fetch_add(1, Ordering::Relaxed) % self.streams.len();
318        operation.submit_on(&self.streams[index])
319    }
320
321    /// Borrows the pool's streams in creation order.
322    pub fn streams(&self) -> &[Stream] {
323        &self.streams
324    }
325}
326
327// SAFETY: each half records through the same recording, registering its own owners and accesses, and the output pair exposes only the halves' outputs.
328unsafe impl<A: Recordable, B: Recordable> Recordable for Pair<A, B> {
329    type Output = (A::Output, B::Output);
330
331    fn record(self, recording: &mut Recording) -> Result<Self::Output> {
332        Ok((self.0.record(recording)?, self.1.record(recording)?))
333    }
334}
335
336// SAFETY: an `Err` enqueues no native work, and an `Ok` delegates both enqueue and resolution to `O`.
337unsafe impl<O: Operation> Operation for Result<O> {
338    type Pending = O::Pending;
339
340    type Output = O::Output;
341
342    fn enqueue(self, execution: &mut Execution) -> Result<Self::Pending> {
343        self?.enqueue(execution)
344    }
345
346    unsafe fn resolve(pending: Self::Pending) -> Result<Self::Output> {
347        // SAFETY: the caller guarantees `pending` came from `O`'s enqueue within this one and that execution completed.
348        unsafe { O::resolve(pending) }
349    }
350}
351
352// SAFETY: `Then` resolves through `N`, whose resolution is the identity, and enqueues both stages eagerly.
353unsafe impl<O: DeviceOperation, F, N: DeviceOperation> DeviceOperation for Then<O, F> where
354    F: FnOnce(O::Output) -> N
355{
356}
357
358// SAFETY: both halves resolve by identity, so the pair does too, and both enqueue eagerly.
359unsafe impl<A: DeviceOperation, B: DeviceOperation> DeviceOperation for Pair<A, B> {}
360
361// SAFETY: `Result<O>` resolves through `O`'s identity resolution and enqueues `O` eagerly.
362unsafe impl<O: DeviceOperation> DeviceOperation for Result<O> {}
363
364// SAFETY: `Shared` resolves by returning its pending `Arc` unchanged, and the producer is submitted during enqueue, not on resolution.
365unsafe impl<O: DeviceOperation> DeviceOperation for Shared<O> where O::Output: Send + Sync {}