Skip to main content

singe_cuda/stream/
mod.rs

1//! CUDA streams, capture scopes, synchronization, and ordered operations.
2
3mod callback;
4mod capture;
5mod context;
6mod raw;
7mod scope;
8
9pub mod memory;
10
11mod cleanup;
12
13mod sealed {
14    #[expect(
15        unnameable_types,
16        reason = "sealed supertrait that other crates must not name or implement"
17    )]
18    pub trait Sealed {}
19}
20
21use std::{
22    collections::HashMap,
23    fmt::{self, Display, Formatter},
24    hash::{Hash, Hasher},
25    mem, ptr,
26    sync::{Arc, Mutex, MutexGuard, OnceLock, Weak},
27};
28
29use bitflags::parser;
30use singe_core::{abort_after_cleanup_failure, report_cleanup_failure};
31use singe_cuda_sys::runtime;
32
33use crate::{
34    context::Context,
35    device::Device,
36    error::{Error, Result, Status},
37    event::{Event, EventFlags, EventRecordFlags, EventWaitFlags},
38    memory::DeferredFree,
39    try_ffi,
40    utility::lock_for_cleanup,
41    view::DeviceRegion,
42};
43
44use self::raw::ForeignOwner;
45pub use self::{
46    capture::{
47        StreamCaptureDependencyUpdate, StreamCaptureInfo, StreamCaptureMode, StreamCaptureScope,
48        StreamCaptureStatus, exchange_capture_mode,
49    },
50    raw::{RawStream, RawStreamOwnership},
51    scope::StreamScope,
52};
53
54bitflags::bitflags! {
55    /// Flags for CUDA stream creation ([`StreamOptions::flags`]).
56    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
57    pub struct StreamFlags: u32 {
58        /// Creates a stream that participates in implicit synchronization with the legacy default stream.
59        const DEFAULT = runtime::cudaStreamDefault;
60        /// Creates a stream without implicit synchronization with the legacy default stream.
61        const NON_BLOCKING = runtime::cudaStreamNonBlocking;
62    }
63}
64
65impl Display for StreamFlags {
66    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
67        parser::to_writer(self, f)
68    }
69}
70
71/// Options for [`Context::create_stream`].
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub struct StreamOptions {
74    /// Stream creation behavior, [`StreamFlags::DEFAULT`] by default.
75    pub flags: StreamFlags,
76    /// Scheduling priority, where lower numbers are higher priorities and `0` is the default priority.
77    ///
78    /// CUDA clamps a priority outside [`Device::stream_priority_range`] to the nearest end of that range.
79    pub priority: i32,
80}
81
82impl Default for StreamOptions {
83    fn default() -> Self {
84        Self {
85            flags: StreamFlags::DEFAULT,
86            priority: 0,
87        }
88    }
89}
90
91/// A shared CUDA stream retaining its actual context.
92///
93/// Clones share native ownership and capture cleanup.
94/// Owned handles are synchronized and destroyed when their last wrapper drops.
95/// Externally owned handles instead retain an ownership token and are not destroyed by this wrapper.
96#[derive(Debug, Clone)]
97pub struct Stream {
98    inner: Arc<StreamInner>,
99}
100
101#[derive(Debug)]
102struct StreamInner {
103    handle: runtime::cudaStream_t,
104    context: Arc<Context>,
105    capture_cleanup: Arc<Mutex<CaptureCleanup>>,
106    foreign_owner: Option<ForeignOwner>,
107}
108
109impl PartialEq for Stream {
110    fn eq(&self, other: &Self) -> bool {
111        self.identity() == other.identity()
112    }
113}
114
115impl Eq for Stream {}
116
117impl Hash for Stream {
118    fn hash<H: Hasher>(&self, state: &mut H) {
119        Hash::hash(&self.identity(), state);
120    }
121}
122
123/// A CUDA stream handle without native destruction responsibility.
124///
125/// Values returned by [`Stream::to_borrowed`] retain the owning stream.
126/// Raw borrowed streams rely on the lifetime contract of [`Self::from_raw`].
127#[derive(Debug, Clone)]
128pub struct BorrowedStream {
129    handle: runtime::cudaStream_t,
130    context: Arc<Context>,
131    _owner: Option<Stream>,
132}
133
134/// An explicit CUDA stream selection with its retained context.
135#[derive(Debug, Clone)]
136#[non_exhaustive]
137pub enum StreamBinding {
138    /// Selects the legacy default stream in the retained context.
139    Default(Arc<Context>),
140    /// Selects a borrowed stream and its associated context.
141    Borrowed(BorrowedStream),
142}
143
144/// A CUDA stream selection that work can be ordered on.
145///
146/// Implemented by [`Stream`], [`BorrowedStream`], [`StreamBinding`], and [`StreamScope`].
147/// The trait is sealed.
148pub trait AsStream: sealed::Sealed {
149    /// Returns the context the stream belongs to.
150    fn context(&self) -> &Arc<Context>;
151
152    /// Returns the native stream handle without transferring ownership.
153    fn as_raw(&self) -> runtime::cudaStream_t;
154
155    /// Blocks until the stream has completed all queued work.
156    ///
157    /// # Errors
158    ///
159    /// Returns an error if the context cannot be bound, synchronization fails, or earlier asynchronous work reported an error.
160    fn synchronize(&self) -> Result<()> {
161        self.context().bind()?;
162        // SAFETY: the handle is a live stream of the bound context.
163        unsafe { try_ffi!(runtime::cudaStreamSynchronize(self.as_raw())) }
164    }
165
166    /// Waits for queued work on the stream, or prints the error and aborts the process if the wait fails.
167    ///
168    /// Cleanup code calls this before releasing borrowed storage that queued work may still access.
169    fn synchronize_or_abort(&self) {
170        if let Err(error) = self.synchronize() {
171            abort_after_cleanup_failure("synchronize", "cuda stream", &error);
172        }
173    }
174
175    /// Reports the stream's capture state without invalidating an active capture.
176    ///
177    /// # Errors
178    ///
179    /// Returns an error if the context cannot be bound or CUDA cannot query the capture state.
180    fn capture_status(&self) -> Result<StreamCaptureStatus> {
181        self.context().bind()?;
182        let mut status = runtime::cudaStreamCaptureStatus::CU_STREAM_CAPTURE_STATUS_NONE;
183        // SAFETY: the handle is a live stream of the bound context, and `status` is a valid output location.
184        unsafe {
185            try_ffi!(runtime::cudaStreamIsCapturing(
186                self.as_raw(),
187                &raw mut status
188            ))?;
189        }
190        Ok(status.try_into()?)
191    }
192
193    /// Rejects active or invalidated capture before an operation that cannot be recorded.
194    ///
195    /// # Errors
196    ///
197    /// Returns the stream-capture-unsupported status for active capture, the stream-capture-invalidated status for invalidated capture, or an error if the capture state cannot be queried.
198    fn ensure_not_capturing(&self) -> Result<()> {
199        match self.capture_status()? {
200            StreamCaptureStatus::None => Ok(()),
201            StreamCaptureStatus::Active => Err(Status::StreamCaptureUnsupported.into()),
202            StreamCaptureStatus::Invalidated => Err(Status::StreamCaptureInvalidated.into()),
203        }
204    }
205
206    /// Makes work submitted to the stream after this call wait for the work captured in `event`.
207    ///
208    /// `event` may belong to another context or device.
209    ///
210    /// # Errors
211    ///
212    /// Returns an error if the context cannot be bound, CUDA rejects the wait or flags, or earlier asynchronous work reported an error.
213    fn wait_event(&self, event: &Event, flags: EventWaitFlags) -> Result<()> {
214        self.context().bind()?;
215        // SAFETY: both handles are live and the stream's context is bound.
216        unsafe {
217            try_ffi!(runtime::cudaStreamWaitEvent(
218                self.as_raw(),
219                event.as_raw(),
220                flags.bits(),
221            ))
222        }
223    }
224
225    /// Orders subsequent work on the stream after the readiness streams of these device regions.
226    ///
227    /// Each distinct producer stream contributes one event dependency.
228    /// This does not establish initialization or retain allocations for later work.
229    ///
230    /// # Errors
231    ///
232    /// Returns `Error::MemoryContextMismatch` before submitting dependencies if any region belongs to another context, or an error if an event cannot be recorded or waited on.
233    fn join_regions(&self, regions: &[DeviceRegion<'_>]) -> Result<()> {
234        if regions
235            .iter()
236            .any(|region| region.context() != self.context())
237        {
238            return Err(Error::MemoryContextMismatch);
239        }
240
241        let identity = StreamIdentity::new(self.context(), self.as_raw());
242        for (index, region) in regions.iter().enumerate() {
243            if let Some(producer) = region.stream()
244                && producer.identity() != identity
245                && !regions[..index]
246                    .iter()
247                    .any(|earlier| earlier.stream() == Some(producer))
248            {
249                let event = producer
250                    .context()
251                    .create_event(EventFlags::DISABLE_TIMING)?;
252                event.record(producer, EventRecordFlags::DEFAULT)?;
253                self.wait_event(&event, EventWaitFlags::DEFAULT)?;
254            }
255        }
256        Ok(())
257    }
258}
259
260const LEGACY_STREAM: usize = 1;
261const PER_THREAD_STREAM: usize = 2;
262
263/// Native stream identity shared by independent wrappers and legacy stream aliases.
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
265pub(crate) struct StreamIdentity {
266    context: usize,
267    handle: usize,
268}
269
270impl StreamIdentity {
271    pub(crate) fn new(context: &Context, handle: runtime::cudaStream_t) -> Self {
272        let handle = handle.addr();
273        Self {
274            context: context.as_raw().addr(),
275            handle: if handle == LEGACY_STREAM { 0 } else { handle },
276        }
277    }
278}
279
280#[derive(Debug, Default)]
281pub(crate) struct CaptureCleanup {
282    owners: Vec<Arc<dyn fmt::Debug + Send + Sync>>,
283    frees: Vec<DeferredFree>,
284    foreign: Vec<ForeignOwner>,
285}
286
287impl CaptureCleanup {
288    fn for_stream(key: StreamIdentity) -> Result<Arc<Mutex<Self>>> {
289        type Registry = HashMap<StreamIdentity, Weak<Mutex<CaptureCleanup>>>;
290
291        static LIFECYCLES: OnceLock<Mutex<Registry>> = OnceLock::new();
292        let mut lifecycles = LIFECYCLES
293            .get_or_init(Mutex::default)
294            .lock()
295            .map_err(|_| Error::lock_poisoned("stream lifecycles"))?;
296        lifecycles.retain(|_, lifecycle| lifecycle.strong_count() != 0);
297        if let Some(lifecycle) = lifecycles.get(&key).and_then(Weak::upgrade) {
298            return Ok(lifecycle);
299        }
300
301        let lifecycle = Arc::new(Mutex::new(Self::default()));
302        lifecycles.insert(key, Arc::downgrade(&lifecycle));
303        drop(lifecycles);
304        Ok(lifecycle)
305    }
306
307    fn is_empty(&self) -> bool {
308        self.owners.is_empty() && self.frees.is_empty() && self.foreign.is_empty()
309    }
310
311    fn flush_frees(&mut self, stream: runtime::cudaStream_t) -> Result<()> {
312        while let Some(free) = self.frees.last() {
313            free.enqueue(stream)?;
314            self.frees.pop();
315        }
316
317        self.foreign.clear();
318        Ok(())
319    }
320}
321
322impl Stream {
323    pub(crate) fn identity(&self) -> StreamIdentity {
324        StreamIdentity::new(self.context(), self.as_raw())
325    }
326
327    /// Defers destruction of an unused resource until capture ends, if active.
328    /// This permits eager APIs to reject capture without calling a capture-incompatible destructor while releasing their arguments.
329    /// It does not retain resources for graph replay.
330    /// End capture through this stream wrapper to release these owners.
331    /// Avoid owners that retain this stream, which would create a reference cycle.
332    ///
333    /// # Errors
334    ///
335    /// Propagates capture-state query and context binding errors.
336    /// If capture is inactive, `owner` is dropped before this call returns.
337    pub fn defer_drop_until_capture_end<T>(&self, owner: Arc<T>) -> Result<()>
338    where
339        T: fmt::Debug + Send + Sync + 'static,
340    {
341        let mut cleanup = lock_for_cleanup(&self.inner.capture_cleanup);
342        if self.capture_status()? != StreamCaptureStatus::None {
343            cleanup.owners.push(owner);
344        }
345
346        drop(cleanup);
347        Ok(())
348    }
349
350    fn capture_cleanup_lock(&self) -> Result<MutexGuard<'_, CaptureCleanup>> {
351        self.inner
352            .capture_cleanup
353            .lock()
354            .map_err(|_| Error::lock_poisoned("stream capture cleanup"))
355    }
356
357    pub(crate) fn allocation_guard(&self) -> Result<MutexGuard<'_, CaptureCleanup>> {
358        let mut cleanup = self.capture_cleanup_lock()?;
359        self.ensure_not_capturing()?;
360        cleanup.flush_frees(self.as_raw())?;
361        Ok(cleanup)
362    }
363
364    pub(crate) fn defer_free(&self, free: DeferredFree) -> Result<()> {
365        let mut cleanup = lock_for_cleanup(&self.inner.capture_cleanup);
366        cleanup.frees.push(free);
367        if self.capture_status()? == StreamCaptureStatus::None {
368            cleanup.flush_frees(self.as_raw())?;
369        }
370
371        drop(cleanup);
372        Ok(())
373    }
374
375    /// Returns a borrowed stream wrapper retaining a clone of this stream's owner.
376    #[must_use]
377    pub fn to_borrowed(&self) -> BorrowedStream {
378        BorrowedStream {
379            handle: self.as_raw(),
380            context: Arc::clone(&self.inner.context),
381            _owner: Some(self.clone()),
382        }
383    }
384
385    /// Returns a borrowed stream wrapper that does not retain this stream's owner.
386    ///
387    /// A native owner passed to [`Self::defer_drop_until_capture_end`] holds one, since retaining the stream would form a reference cycle.
388    ///
389    /// # Safety
390    ///
391    /// The returned wrapper must not be used after the last owner of this stream is dropped.
392    #[must_use]
393    pub unsafe fn to_unretained(&self) -> BorrowedStream {
394        BorrowedStream {
395            handle: self.as_raw(),
396            context: Arc::clone(&self.inner.context),
397            _owner: None,
398        }
399    }
400
401    /// Blocks until stream has completed all operations.
402    /// If [`ContextFlags::SCHEDULE_BLOCKING_SYNC`](crate::context::ContextFlags::SCHEDULE_BLOCKING_SYNC) was set for this device, the host thread will block until the stream is finished with all of its tasks.
403    ///
404    /// Uses standard `default stream` semantics.
405    ///
406    /// # Errors
407    ///
408    /// Returns an error if stream synchronization fails or if a previous asynchronous launch reported an error.
409    /// CUDA may also return initialization-related errors such as [`crate::error::Status::NotInitialized`], [`crate::error::Status::CallRequiresNewerDriver`], or [`crate::error::Status::NoDevice`] if this call initializes internal runtime state.
410    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`].
411    pub fn synchronize(&self) -> Result<()> {
412        AsStream::synchronize(self)
413    }
414
415    /// Waits for queued work on this stream, or prints the error and aborts the process if the wait fails.
416    ///
417    /// Cleanup code calls this before releasing borrowed storage that queued work may still access.
418    pub fn synchronize_or_abort(&self) {
419        AsStream::synchronize_or_abort(self);
420    }
421
422    /// Synchronizes this stream and releases its native ownership.
423    ///
424    /// Owned handles are destroyed.
425    /// Borrowed handles release their external owner token after synchronization instead of destroying the handle.
426    /// This may block while waiting for stream work and callbacks.
427    /// For owned handles, destruction is attempted even if synchronization fails, and the synchronization error takes precedence over a destruction error.
428    ///
429    /// # Errors
430    ///
431    /// Returns `Error::OwnershipShared` if another stream clone or borrowed owner still retains the handle.
432    /// Also propagates capture-state rejection, deferred-free enqueue, context binding, synchronization, or owned-handle destruction errors.
433    /// Synchronization errors take precedence over destruction errors.
434    pub fn shutdown(self) -> Result<()> {
435        let lifecycle = Arc::clone(&self.inner.capture_cleanup);
436        let mut cleanup = lifecycle
437            .lock()
438            .map_err(|_| Error::lock_poisoned("stream capture cleanup"))?;
439        self.ensure_not_capturing()?;
440        cleanup.flush_frees(self.as_raw())?;
441        let mut inner = match Arc::try_unwrap(self.inner) {
442            Ok(inner) => inner,
443            Err(inner) => {
444                // Releasing this reference can destroy the last wrapper after a concurrent drop.
445                drop(cleanup);
446                drop(inner);
447                return Err(Error::ownership_shared("stream"));
448            }
449        };
450        let result = if inner.foreign_owner.is_some() {
451            inner
452                .context
453                .bind()
454                // SAFETY: `inner.handle` is the live foreign stream this last wrapper still holds, and its context is bound here.
455                .and_then(|()| unsafe { try_ffi!(runtime::cudaStreamSynchronize(inner.handle)) })
456        } else {
457            Self::destroy_handle(inner.context.as_ref(), inner.handle)
458        };
459        inner.handle = ptr::null_mut();
460        let owner = inner.foreign_owner.take();
461        // An external token may itself own a Singe wrapper for this native stream.
462        drop(cleanup);
463        drop(owner);
464        result
465    }
466
467    /// Returns `true` if all operations in stream have completed, or `false` if not.
468    ///
469    /// For the purposes of Unified Memory, a return value of `true` is equivalent to having called [`Stream::synchronize`].
470    ///
471    /// Uses standard `default stream` semantics.
472    ///
473    /// # Errors
474    ///
475    /// Returns an error if querying the stream fails or if a previous asynchronous launch reported an error.
476    /// CUDA may also return initialization-related errors such as [`crate::error::Status::NotInitialized`], [`crate::error::Status::CallRequiresNewerDriver`], or [`crate::error::Status::NoDevice`] if this call initializes internal runtime state.
477    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`].
478    pub fn query(&self) -> Result<bool> {
479        self.inner.context.bind()?;
480        // SAFETY: `self.as_raw()` is the live stream this wrapper retains, in the context bound above.
481        let error = unsafe { runtime::cudaStreamQuery(self.as_raw()) };
482        match error {
483            runtime::cudaError_t::CUDA_SUCCESS => Ok(true),
484            runtime::cudaError_t::CUDA_ERROR_NOT_READY => Ok(false),
485            _ => Err(error.into()),
486        }
487    }
488
489    /// Makes all future work submitted to stream wait for all work captured in event.
490    /// See [`sys::cudaEventRecord`](singe_cuda_sys::runtime::cudaEventRecord) for details on what is captured by an event.
491    /// `flags` controls how strictly the wait is enforced during capture.
492    /// Synchronization is performed efficiently on the device when applicable.
493    /// `event` may be from a different device than `stream`.
494    ///
495    /// # Errors
496    ///
497    /// Returns an error if the stream cannot wait on the event or if a previous asynchronous launch reported an error.
498    pub fn wait_event(&self, event: &Event, flags: EventWaitFlags) -> Result<()> {
499        AsStream::wait_event(self, event, flags)
500    }
501
502    /// Creates a nonblocking stream ordered after this stream's current work.
503    ///
504    /// The new stream uses this stream's context and priority.
505    /// Later submissions to either stream can execute independently.
506    /// Call [`Stream::join`] to order subsequent work after a branch completes.
507    /// During capture, keep the branch alive until capture ends and join it back into the capturing stream before ending capture.
508    ///
509    /// # Errors
510    ///
511    /// Returns an error if CUDA cannot create the stream or establish its event dependency.
512    pub fn fork(&self) -> Result<Self> {
513        let branch = self.context().create_stream(StreamOptions {
514            flags: StreamFlags::NON_BLOCKING,
515            priority: self.priority()?,
516        })?;
517        branch.join(self)?;
518        Ok(branch)
519    }
520
521    /// Orders subsequent work on this stream after the other stream's current work.
522    ///
523    /// Records an event on `other` and enqueues a wait on this stream without blocking the host.
524    /// The other stream may belong to a different CUDA context or device.
525    /// Work submitted to `other` after this call is independent of the dependency.
526    ///
527    /// # Errors
528    ///
529    /// Returns an error if CUDA cannot record the event or enqueue the wait.
530    pub fn join(&self, other: &Self) -> Result<()> {
531        if self == other {
532            return Ok(());
533        }
534
535        let event = other.context().create_event(EventFlags::DISABLE_TIMING)?;
536        event.record(other, EventRecordFlags::DEFAULT)?;
537        self.wait_event(&event, EventWaitFlags::DEFAULT)
538    }
539
540    /// Orders subsequent work after the readiness streams of these device regions.
541    ///
542    /// All regions must belong to this stream's context.
543    /// Each distinct producer stream contributes one event dependency.
544    /// This does not establish initialization or retain allocations for later work.
545    /// Borrowed consumers must keep their resources in a draining scope; raw queued consumers must uphold their resource and access contracts.
546    ///
547    /// # Errors
548    ///
549    /// Returns `Error::MemoryContextMismatch` before submitting dependencies if any region belongs to another context, or a CUDA error if an event cannot be recorded or waited on.
550    pub fn join_regions(&self, regions: &[DeviceRegion<'_>]) -> Result<()> {
551        AsStream::join_regions(self, regions)
552    }
553
554    /// Query the flags of a stream.
555    /// Returns the stream flags.
556    /// See [`StreamFlags`] for the valid flags.
557    ///
558    /// Uses standard `default stream` semantics.
559    ///
560    /// # Errors
561    ///
562    /// Returns an error if CUDA cannot query the flags or if a previous asynchronous launch reported an error.
563    /// CUDA may also return initialization-related errors such as [`crate::error::Status::NotInitialized`], [`crate::error::Status::CallRequiresNewerDriver`], or [`crate::error::Status::NoDevice`] if this call initializes internal runtime state.
564    /// Callbacks must not call CUDA functions; see [`Stream::add_callback`].
565    pub fn flags(&self) -> Result<StreamFlags> {
566        self.inner.context.bind()?;
567        let mut flags_raw = 0u32;
568        // SAFETY: `self.as_raw()` is the live stream this wrapper retains, and `flags_raw` is a writable local.
569        unsafe {
570            try_ffi!(runtime::cudaStreamGetFlags(
571                self.as_raw(),
572                &raw mut flags_raw
573            ))?;
574        }
575        Ok(StreamFlags::from_bits_retain(flags_raw))
576    }
577
578    /// Query the priority of a stream.
579    /// Returns the stream priority.
580    /// If the stream was created with a priority outside the meaningful numerical range returned by [`Device::stream_priority_range`], this returns the clamped priority.
581    /// See [`StreamOptions::priority`] for details about priority clamping.
582    ///
583    /// # Errors
584    ///
585    /// Returns an error if the context cannot be bound, CUDA cannot query the priority, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
586    pub fn priority(&self) -> Result<i32> {
587        self.inner.context.bind()?;
588        let mut priority = 0i32;
589        // SAFETY: `self.as_raw()` is the live stream this wrapper retains, and `priority` is a writable local.
590        unsafe {
591            try_ffi!(runtime::cudaStreamGetPriority(
592                self.as_raw(),
593                &raw mut priority
594            ))?;
595        }
596        Ok(priority)
597    }
598
599    /// Returns a stream identifier that remains unique for the life of the program.
600    ///
601    /// The stream handle may refer to any of the following:
602    ///
603    /// * a stream created via any of the CUDA runtime APIs such as [`sys::cudaStreamCreate`](singe_cuda_sys::runtime::cudaStreamCreate), [`Context::create_stream`], or their driver API equivalents such as [`sys::cuStreamCreate`](singe_cuda_sys::driver::cuStreamCreate) or [`sys::cuStreamCreateWithPriority`](singe_cuda_sys::driver::cuStreamCreateWithPriority).
604    ///   Passing an invalid handle results in undefined behavior.
605    /// * the special legacy default stream and per-thread default stream.
606    ///   The driver API equivalents of these are also accepted.
607    ///
608    /// # Errors
609    ///
610    /// Returns an error if the context cannot be bound, CUDA cannot query the stream identifier, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
611    pub fn id(&self) -> Result<u64> {
612        self.inner.context.bind()?;
613        let mut id = 0u64;
614        // SAFETY: `self.as_raw()` is the live stream this wrapper retains, and `id` is a writable local.
615        unsafe {
616            try_ffi!(runtime::cudaStreamGetId(self.as_raw(), &raw mut id))?;
617        }
618        Ok(id)
619    }
620
621    /// Returns the device of the stream.
622    ///
623    /// # Errors
624    ///
625    /// Returns an error if the context cannot be bound, CUDA cannot query the stream device, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
626    pub fn device(&self) -> Result<Device> {
627        self.inner.context.bind()?;
628        let mut device = 0i32;
629        // SAFETY: `self.as_raw()` is the live stream this wrapper retains, and `device` is a writable local.
630        unsafe {
631            try_ffi!(runtime::cudaStreamGetDevice(self.as_raw(), &raw mut device))?;
632        }
633        Ok(Device::new(device))
634    }
635
636    /// Returns the context retained by this stream.
637    #[must_use]
638    pub fn context(&self) -> &Arc<Context> {
639        &self.inner.context
640    }
641
642    /// Returns the borrowed native stream handle without transferring ownership.
643    #[must_use]
644    pub fn as_raw(&self) -> runtime::cudaStream_t {
645        self.inner.handle
646    }
647}
648
649impl BorrowedStream {
650    /// Wraps an existing CUDA stream handle without taking ownership.
651    ///
652    /// # Safety
653    ///
654    /// `handle` must be a valid CUDA stream associated with `context`, and it must remain valid for every operation using the returned borrowed stream.
655    pub const unsafe fn from_raw(handle: runtime::cudaStream_t, context: Arc<Context>) -> Self {
656        Self {
657            handle,
658            context,
659            _owner: None,
660        }
661    }
662}
663
664impl StreamBinding {
665    /// Returns whether this binding uses the [`Self::Default`] variant.
666    #[must_use]
667    pub fn is_default(&self) -> bool {
668        matches!(self, Self::Default(..))
669    }
670}
671
672impl sealed::Sealed for Stream {}
673
674impl AsStream for Stream {
675    fn context(&self) -> &Arc<Context> {
676        &self.inner.context
677    }
678
679    fn as_raw(&self) -> runtime::cudaStream_t {
680        self.inner.handle
681    }
682}
683
684impl sealed::Sealed for BorrowedStream {}
685
686impl AsStream for BorrowedStream {
687    fn context(&self) -> &Arc<Context> {
688        &self.context
689    }
690
691    fn as_raw(&self) -> runtime::cudaStream_t {
692        self.handle
693    }
694}
695
696impl sealed::Sealed for StreamBinding {}
697
698impl AsStream for StreamBinding {
699    fn context(&self) -> &Arc<Context> {
700        match self {
701            Self::Default(context) => context,
702            Self::Borrowed(stream) => &stream.context,
703        }
704    }
705
706    fn as_raw(&self) -> runtime::cudaStream_t {
707        match self {
708            Self::Default(_) => ptr::null_mut(),
709            Self::Borrowed(stream) => stream.handle,
710        }
711    }
712}
713
714// SAFETY: a CUDA stream may be used and destroyed from any thread once its context is bound, and the other fields are `Send`.
715unsafe impl Send for StreamInner {}
716
717// SAFETY: `&self` methods only pass the immutable handle to thread-safe runtime calls, and the capture cleanup state sits behind a mutex.
718unsafe impl Sync for StreamInner {}
719
720impl Drop for StreamInner {
721    fn drop(&mut self) {
722        if self.handle.is_null() && self.foreign_owner.is_none() {
723            return;
724        }
725
726        let mut cleanup = lock_for_cleanup(&self.capture_cleanup);
727        if Arc::strong_count(&self.capture_cleanup) == 1 && !cleanup.is_empty() {
728            // SAFETY: the last stream owner passes its live stream in the context bound here, `status` and `graph` are writable locals, and it destroys only the graph that ending its own capture returned.
729            let ended = self.context.bind().and_then(|()| unsafe {
730                let mut status = runtime::cudaStreamCaptureStatus::CU_STREAM_CAPTURE_STATUS_NONE;
731                try_ffi!(runtime::cudaStreamIsCapturing(self.handle, &raw mut status))?;
732                if status != runtime::cudaStreamCaptureStatus::CU_STREAM_CAPTURE_STATUS_NONE {
733                    let mut graph = ptr::null_mut();
734                    // An invalidated capture also ends here with an error; the status query below decides.
735                    if let Err(error) =
736                        try_ffi!(runtime::cudaStreamEndCapture(self.handle, &raw mut graph))
737                    {
738                        report_cleanup_failure("end", "cuda stream capture", &error);
739                    }
740
741                    if !graph.is_null()
742                        && let Err(error) = try_ffi!(runtime::cudaGraphDestroy(graph))
743                    {
744                        report_cleanup_failure("destroy", "cuda graph", &error);
745                    }
746
747                    try_ffi!(runtime::cudaStreamIsCapturing(self.handle, &raw mut status))?;
748                    if status != runtime::cudaStreamCaptureStatus::CU_STREAM_CAPTURE_STATUS_NONE {
749                        return Err(Error::out_of_range("stream capture status"));
750                    }
751                }
752                Ok(())
753            });
754            if let Err(error) = ended {
755                // CUDA may still retain captured addresses. Preserve their owners.
756                report_cleanup_failure(
757                    "end the capture to release deferred owners of",
758                    "cuda stream",
759                    &error,
760                );
761                mem::forget(mem::take(&mut *cleanup));
762            } else {
763                if let Err(error) = cleanup.flush_frees(self.handle) {
764                    report_cleanup_failure("enqueue", "deferred cuda frees", &error);
765                    mem::forget(mem::take(&mut cleanup.frees));
766                }
767
768                cleanup.owners.clear();
769            }
770        }
771
772        drop(cleanup);
773        if self.foreign_owner.is_some() {
774            // SAFETY: the foreign stream stays live while this last wrapper holds its owner token, its context is bound here, and `status` is a writable local.
775            let result = self.context.bind().and_then(|()| unsafe {
776                let mut status = runtime::cudaStreamCaptureStatus::CU_STREAM_CAPTURE_STATUS_NONE;
777                try_ffi!(runtime::cudaStreamIsCapturing(self.handle, &raw mut status))?;
778                if status == runtime::cudaStreamCaptureStatus::CU_STREAM_CAPTURE_STATUS_NONE {
779                    try_ffi!(runtime::cudaStreamSynchronize(self.handle))?;
780                }
781                Ok(())
782            });
783            if let Err(error) = result {
784                report_cleanup_failure("synchronize", "foreign cuda stream", &error);
785            }
786        } else {
787            if let Err(error) = self.context.bind() {
788                report_cleanup_failure("bind the cuda context to destroy", "cuda stream", &error);
789                return;
790            }
791
792            if let Err(error) = Stream::destroy_handle(self.context.as_ref(), self.handle) {
793                report_cleanup_failure("destroy", "cuda stream", &error);
794            }
795        }
796    }
797}
798
799#[cfg(all(test, feature = "testing"))]
800mod tests {
801    use std::{
802        panic,
803        sync::{
804            Arc,
805            atomic::{AtomicBool, Ordering},
806        },
807        thread,
808    };
809
810    use super::*;
811    use crate::{
812        context::ContextFlags,
813        event::EventRecordFlags,
814        graph::{GraphDependency, GraphEdgeAttributes, GraphInstantiateFlags, GraphNode},
815        memory::{DeviceMemory, MemoryCopyKind},
816        testing,
817    };
818
819    #[test]
820    fn test_it_works() -> Result<()> {
821        let test_device = testing::bootstrap()?;
822        let context = Arc::clone(test_device.context());
823        let stream1 = context.create_stream(StreamOptions::default())?;
824        let _stream2 = context.create_stream(StreamOptions {
825            flags: StreamFlags::NON_BLOCKING,
826            ..StreamOptions::default()
827        })?;
828
829        let stream1_called = Arc::new(AtomicBool::new(false));
830        stream1.add_callback(Box::new({
831            let stream1_called = Arc::clone(&stream1_called);
832            move |_status| {
833                stream1_called.store(true, Ordering::SeqCst);
834            }
835        }))?;
836
837        let is_done = stream1.query()?;
838        assert!(!is_done);
839
840        stream1.synchronize()?;
841
842        let is_done_after = stream1.query()?;
843        assert!(is_done_after);
844
845        assert!(stream1_called.load(Ordering::SeqCst));
846
847        Ok(())
848    }
849
850    #[test]
851    fn test_event_query_uses_event_context() -> Result<()> {
852        let test_device = testing::bootstrap()?;
853        let context = Arc::clone(test_device.context());
854        let stream = context.create_stream(StreamOptions::default())?;
855        let event = context.create_event(EventFlags::DEFAULT)?;
856
857        event.record(&stream, EventRecordFlags::DEFAULT)?;
858        stream.synchronize()?;
859
860        assert!(event.query()?);
861        Ok(())
862    }
863
864    #[test]
865    fn test_shutdown_synchronizes_and_destroys_stream() -> Result<()> {
866        let test_device = testing::bootstrap()?;
867        let context = Arc::clone(test_device.context());
868        let stream = context.create_stream(StreamOptions::default())?;
869
870        let called = Arc::new(AtomicBool::new(false));
871        stream.add_callback(Box::new({
872            let called = Arc::clone(&called);
873            move |_status| {
874                called.store(true, Ordering::SeqCst);
875            }
876        }))?;
877
878        stream.shutdown()?;
879        assert!(called.load(Ordering::SeqCst));
880        Ok(())
881    }
882
883    #[test]
884    fn test_launch_host_func_runs_after_stream_work() -> Result<()> {
885        let test_device = testing::bootstrap()?;
886        let context = Arc::clone(test_device.context());
887        let stream = context.create_stream(StreamOptions::default())?;
888
889        let called = Arc::new(AtomicBool::new(false));
890        stream.launch_host_func({
891            let called = Arc::clone(&called);
892            move || {
893                called.store(true, Ordering::SeqCst);
894            }
895        })?;
896        stream.synchronize()?;
897
898        assert!(called.load(Ordering::SeqCst));
899        Ok(())
900    }
901
902    #[test]
903    fn test_scoped_capture_returns_context_associated_graph() -> Result<()> {
904        let test_device = testing::bootstrap()?;
905        let context = Arc::clone(test_device.context());
906        let stream = context.create_stream(StreamOptions::default())?;
907
908        let graph = stream.capture(StreamCaptureMode::Relaxed, |scope| {
909            assert_eq!(scope.stream().context(), &context);
910            Ok(())
911        })?;
912
913        assert_eq!(graph.context(), &context);
914        Ok(())
915    }
916
917    #[test]
918    fn test_capture_to_graph_rejects_graph_from_different_context() -> Result<()> {
919        let test_device = testing::bootstrap()?;
920        let context = Arc::clone(test_device.context());
921        let other_context = Context::create_dedicated(context.device(), ContextFlags::empty())?;
922
923        let stream = context.create_stream(StreamOptions::default())?;
924        let graph = other_context.create_graph()?;
925
926        assert!(matches!(
927            // SAFETY: the test ends the capture before the graph is dropped.
928            unsafe { stream.begin_capture_to_graph(&graph, &[], StreamCaptureMode::Relaxed) },
929            Err(Error::ContextMismatch { .. })
930        ));
931        assert_eq!(stream.capture_status()?, StreamCaptureStatus::None);
932        Ok(())
933    }
934
935    #[test]
936    fn test_capture_to_graph_rejects_node_from_different_graph() -> Result<()> {
937        let test_device = testing::bootstrap()?;
938        let context = Arc::clone(test_device.context());
939
940        let stream = context.create_stream(StreamOptions::default())?;
941        let graph = context.create_graph()?;
942        let mut other_graph = context.create_graph()?;
943        let other_node = other_graph.add_empty_node(&[])?;
944
945        assert!(matches!(
946            // SAFETY: the test ends the capture before the graph is dropped.
947            unsafe {
948                stream.begin_capture_to_graph(
949                    &graph,
950                    &[GraphDependency {
951                        node: other_node,
952                        data: GraphEdgeAttributes::default(),
953                    }],
954                    StreamCaptureMode::Relaxed,
955                )
956            },
957            Err(Error::GraphNodeMismatch)
958        ));
959        assert_eq!(stream.capture_status()?, StreamCaptureStatus::None);
960        Ok(())
961    }
962
963    #[test]
964    fn test_capture_to_graph_rejects_unassociated_raw_dependency_node() -> Result<()> {
965        let test_device = testing::bootstrap()?;
966        let context = Arc::clone(test_device.context());
967
968        let stream = context.create_stream(StreamOptions::default())?;
969        let graph = context.create_graph()?;
970        // SAFETY: the fake handle is only compared, never passed to CUDA.
971        let raw_node = unsafe { GraphNode::from_raw(0x1usize as _) };
972
973        assert!(matches!(
974            // SAFETY: the test ends the capture before the graph is dropped.
975            unsafe {
976                stream.begin_capture_to_graph(
977                    &graph,
978                    &[GraphDependency {
979                        node: raw_node,
980                        data: GraphEdgeAttributes::default(),
981                    }],
982                    StreamCaptureMode::Relaxed,
983                )
984            },
985            Err(Error::GraphNodeMismatch)
986        ));
987        assert_eq!(stream.capture_status()?, StreamCaptureStatus::None);
988        Ok(())
989    }
990
991    #[test]
992    fn test_capture_dependency_update_rejects_node_from_different_context() -> Result<()> {
993        let test_device = testing::bootstrap()?;
994        let context = Arc::clone(test_device.context());
995        let other_context = Context::create_dedicated(context.device(), ContextFlags::empty())?;
996
997        let stream = context.create_stream(StreamOptions::default())?;
998        let mut other_graph = other_context.create_graph()?;
999        let other_node = other_graph.add_empty_node(&[])?;
1000
1001        let result = stream.capture(StreamCaptureMode::Relaxed, |_scope| {
1002            stream.update_capture_dependencies(
1003                &[GraphDependency {
1004                    node: other_node,
1005                    data: GraphEdgeAttributes::default(),
1006                }],
1007                StreamCaptureDependencyUpdate::Add,
1008            )
1009        });
1010
1011        assert!(matches!(result, Err(Error::ContextMismatch { .. })));
1012        assert_eq!(stream.capture_status()?, StreamCaptureStatus::None);
1013        Ok(())
1014    }
1015
1016    #[test]
1017    fn test_capture_dependency_update_rejects_node_from_different_graph() -> Result<()> {
1018        let test_device = testing::bootstrap()?;
1019        let context = Arc::clone(test_device.context());
1020
1021        let stream = context.create_stream(StreamOptions::default())?;
1022        let mut other_graph = context.create_graph()?;
1023        let other_node = other_graph.add_empty_node(&[])?;
1024
1025        stream.begin_capture(StreamCaptureMode::Relaxed)?;
1026        assert!(matches!(
1027            stream.update_capture_dependencies(
1028                &[GraphDependency {
1029                    node: other_node,
1030                    data: GraphEdgeAttributes::default(),
1031                }],
1032                StreamCaptureDependencyUpdate::Add,
1033            ),
1034            Err(Error::GraphNodeMismatch)
1035        ));
1036        drop(stream.end_capture());
1037        assert_eq!(stream.capture_status()?, StreamCaptureStatus::None);
1038        Ok(())
1039    }
1040
1041    #[test]
1042    fn test_capture_dependency_update_rejects_unassociated_raw_node() -> Result<()> {
1043        let test_device = testing::bootstrap()?;
1044        let context = Arc::clone(test_device.context());
1045
1046        let stream = context.create_stream(StreamOptions::default())?;
1047        // SAFETY: the fake handle is only compared, never passed to CUDA.
1048        let raw_node = unsafe { GraphNode::from_raw(0x1usize as _) };
1049
1050        stream.begin_capture(StreamCaptureMode::Relaxed)?;
1051        assert!(matches!(
1052            stream.update_capture_dependencies(
1053                &[GraphDependency {
1054                    node: raw_node,
1055                    data: GraphEdgeAttributes::default(),
1056                }],
1057                StreamCaptureDependencyUpdate::Add,
1058            ),
1059            Err(Error::GraphNodeMismatch)
1060        ));
1061        drop(stream.end_capture());
1062        assert_eq!(stream.capture_status()?, StreamCaptureStatus::None);
1063        Ok(())
1064    }
1065
1066    #[test]
1067    fn test_captures_on_separate_streams_can_overlap() -> Result<()> {
1068        let test_device = testing::bootstrap()?;
1069        let context = Arc::clone(test_device.context());
1070        let stream_a = context.create_stream(StreamOptions::default())?;
1071        let stream_b = context.create_stream(StreamOptions::default())?;
1072
1073        thread::scope(|scope| {
1074            let a = scope.spawn(|| {
1075                let graph = stream_a.capture(StreamCaptureMode::Relaxed, |_scope| Ok(()))?;
1076                assert_eq!(graph.context(), &context);
1077                Result::<()>::Ok(())
1078            });
1079            let b = scope.spawn(|| {
1080                let graph = stream_b.capture(StreamCaptureMode::Relaxed, |_scope| Ok(()))?;
1081                assert_eq!(graph.context(), &context);
1082                Result::<()>::Ok(())
1083            });
1084
1085            a.join().expect("capture thread panicked")?;
1086            b.join().expect("capture thread panicked")?;
1087            Result::<()>::Ok(())
1088        })?;
1089
1090        Ok(())
1091    }
1092
1093    #[test]
1094    fn test_scoped_capture_error_leaves_stream_usable() -> Result<()> {
1095        let test_device = testing::bootstrap()?;
1096        let context = Arc::clone(test_device.context());
1097        let stream = context.create_stream(StreamOptions::default())?;
1098
1099        let result = stream.capture(StreamCaptureMode::Relaxed, |_scope| {
1100            Err(Error::out_of_range("capture body"))
1101        });
1102
1103        assert!(matches!(result, Err(Error::OutOfRange { .. })));
1104        stream.synchronize()?;
1105        Ok(())
1106    }
1107
1108    #[test]
1109    fn test_scoped_capture_panic_leaves_stream_usable() -> Result<()> {
1110        let test_device = testing::bootstrap()?;
1111        let context = Arc::clone(test_device.context());
1112        let stream = context.create_stream(StreamOptions::default())?;
1113
1114        let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
1115            let _ = stream.capture(StreamCaptureMode::Relaxed, |_scope| -> Result<()> {
1116                panic!("capture body panic");
1117            });
1118        }));
1119
1120        assert!(result.is_err());
1121        stream.synchronize()?;
1122        Ok(())
1123    }
1124
1125    #[test]
1126    fn test_scoped_capture_records_memory_operations() -> Result<()> {
1127        let test_device = testing::bootstrap()?;
1128        let context = Arc::clone(test_device.context());
1129        let stream = context.create_stream(StreamOptions::default())?;
1130
1131        let input = [1u8, 2, 3, 4];
1132        let source = DeviceMemory::from_slice(&context, &input)?;
1133        let copied = DeviceMemory::<u8>::zeroed(&context, input.len())?;
1134        let filled = DeviceMemory::<u8>::zeroed(&context, input.len())?;
1135
1136        let graph = stream.capture(StreamCaptureMode::Relaxed, |scope| {
1137            // SAFETY: both buffers outlive the captured graph launches in this test.
1138            unsafe {
1139                DeviceMemory::copy_async(
1140                    copied.as_mut_ptr(),
1141                    source.as_ptr(),
1142                    input.len(),
1143                    MemoryCopyKind::DeviceToDevice,
1144                    scope.stream(),
1145                )?;
1146                DeviceMemory::<u8>::set_async(
1147                    filled.as_mut_ptr(),
1148                    0xab,
1149                    input.len(),
1150                    scope.stream(),
1151                )
1152            }
1153        })?;
1154
1155        let executable = graph.instantiate(GraphInstantiateFlags::empty())?;
1156        // SAFETY: the buffers captured by the graph outlive the launch, which the test drains.
1157        unsafe {
1158            executable.launch_async(&stream)?;
1159        }
1160        stream.synchronize()?;
1161
1162        assert_eq!(copied.copy_to_host_vec()?, input);
1163        assert_eq!(filled.copy_to_host_vec()?, [0xab; 4]);
1164        Ok(())
1165    }
1166}