Skip to main content

singe_cuda/
future.rs

1//! Checked stream completion futures.
2
3use std::{
4    future::Future,
5    pin::Pin,
6    sync::Arc,
7    task::{Context as TaskContext, Poll},
8};
9
10use crate::{
11    error::Result,
12    event::{EventFlags, EventRecordFlags},
13    stream::Stream,
14    submission::{Completion, Resources},
15};
16
17/// Checked event-backed completion that observes CUDA errors even when callbacks do not run.
18///
19/// The completion worker retains the stream until the recorded work finishes.
20/// Dropping the future does not cancel queued work.
21/// The future does not retain owners of raw pointers or graph code; those lifetimes follow the submission API's contract.
22#[derive(Debug)]
23pub struct CheckedStreamFuture {
24    completion: Completion,
25}
26
27impl Future for CheckedStreamFuture {
28    type Output = Result<()>;
29
30    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
31        Pin::new(&mut self.completion).poll(cx)
32    }
33}
34
35impl Stream {
36    /// Returns a future that resolves with CUDA's status once the work queued so far on this stream completes.
37    ///
38    /// An event wait observes CUDA status independently of notification callbacks.
39    /// Registration is rejected while stream capture is active.
40    ///
41    /// # Errors
42    ///
43    /// Returns an error if capture is active or invalidated, CUDA cannot query capture state, create or record the completion event, or bind the context, or the completion worker cannot be started or accept work.
44    /// The returned future reports asynchronous CUDA completion errors.
45    pub fn completion(&self) -> Result<CheckedStreamFuture> {
46        self.ensure_not_capturing()?;
47
48        let event = Arc::new(self.context().create_event(EventFlags::DISABLE_TIMING)?);
49        event.record(self, EventRecordFlags::DEFAULT)?;
50        Ok(CheckedStreamFuture {
51            completion: Completion::start(event, self.clone(), Resources::new())?,
52        })
53    }
54}
55
56#[cfg(all(test, feature = "testing"))]
57mod tests {
58    use std::sync::Arc;
59
60    use crate::{
61        error::{Error, Result, Status},
62        event::{EventFlags, EventRecordFlags, EventWaitFlags},
63        graph::GraphInstantiateFlags,
64        memory::DeviceMemory,
65        stream::{StreamCaptureMode, StreamOptions},
66        testing,
67    };
68
69    #[tokio::test]
70    async fn test_stream_completion_waits_for_memset() -> Result<()> {
71        let test_device = testing::bootstrap()?;
72        let context = Arc::clone(test_device.context());
73        let stream = context.create_stream(StreamOptions::default())?;
74        let mut device = DeviceMemory::<u8>::zeroed(&context, 16)?;
75
76        // SAFETY: the test drains the stream before the memory is dropped or read.
77        unsafe {
78            device.set_value_async(7, &stream)?;
79        }
80        stream.completion()?.await?;
81
82        let mut host = vec![0; 16];
83        device.copy_to_host(&mut host)?;
84        assert_eq!(host, vec![7; 16]);
85
86        Ok(())
87    }
88
89    #[tokio::test]
90    async fn test_dropping_pending_future_does_not_cancel_stream_work() -> Result<()> {
91        let test_device = testing::bootstrap()?;
92        let context = Arc::clone(test_device.context());
93        let stream = context.create_stream(StreamOptions::default())?;
94        let mut device = DeviceMemory::<u8>::zeroed(&context, 8)?;
95
96        // SAFETY: the test drains the stream before the memory is dropped or read.
97        unsafe {
98            device.set_value_async(11, &stream)?;
99        }
100        let future = stream.completion()?;
101        drop(future);
102
103        stream.synchronize()?;
104        let mut host = vec![0; 8];
105        device.copy_to_host(&mut host)?;
106        assert_eq!(host, vec![11; 8]);
107
108        Ok(())
109    }
110
111    #[tokio::test]
112    async fn test_stream_completion_is_rejected_during_capture() -> Result<()> {
113        let test_device = testing::bootstrap()?;
114        let context = Arc::clone(test_device.context());
115        let stream = context.create_stream(StreamOptions::default())?;
116
117        stream.begin_capture(StreamCaptureMode::Relaxed)?;
118        let error = stream.completion().unwrap_err();
119        drop(stream.end_capture());
120
121        assert!(matches!(
122            error,
123            Error::Cuda {
124                code: Status::StreamCaptureUnsupported,
125                ..
126            }
127        ));
128
129        Ok(())
130    }
131
132    #[tokio::test]
133    async fn test_event_wait_orders_completion_across_streams() -> Result<()> {
134        let test_device = testing::bootstrap()?;
135        let context = Arc::clone(test_device.context());
136        let stream_a = context.create_stream(StreamOptions::default())?;
137        let stream_b = context.create_stream(StreamOptions::default())?;
138        let event = context.create_event(EventFlags::DEFAULT)?;
139        let mut device = DeviceMemory::<u8>::zeroed(&context, 4)?;
140
141        // SAFETY: the test drains the stream before the memory is dropped or read.
142        unsafe {
143            device.set_value_async(5, &stream_a)?;
144        }
145        event.record(&stream_a, EventRecordFlags::DEFAULT)?;
146        stream_b.wait_event(&event, EventWaitFlags::DEFAULT)?;
147        stream_b.completion()?.await?;
148
149        let mut host = vec![0; 4];
150        device.copy_to_host(&mut host)?;
151        assert_eq!(host, vec![5; 4]);
152
153        Ok(())
154    }
155
156    #[tokio::test]
157    async fn test_graph_launch_completion_resolves() -> Result<()> {
158        let test_device = testing::bootstrap()?;
159        let context = Arc::clone(test_device.context());
160        let stream = context.create_stream(StreamOptions::default())?;
161        let mut graph = context.create_graph()?;
162
163        graph.add_empty_node(&[])?;
164        let executable = graph.instantiate(GraphInstantiateFlags::empty())?;
165        // SAFETY: the graph has no operands, and the test drains the stream.
166        unsafe { executable.launch_async(&stream)? };
167        stream.completion()?.await?;
168
169        Ok(())
170    }
171}