temporalio-sdk 0.3.0

Temporal Rust SDK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use std::{
    cell::{Cell, RefCell},
    collections::{HashMap, VecDeque},
    future::Future,
    pin::Pin,
    rc::Rc,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    task::{Context, Poll, Wake, Waker},
};

thread_local! {
    static SDK_WAKE_DEPTH: Cell<u32> = const { Cell::new(0) };
}

/// Guard that marks the current scope as an SDK-initiated wake source.
///
/// When the tracking waker's `wake()` is called while this guard is active
/// (depth > 0), the wake is recognized as coming from SDK internals and is not
/// flagged as nondeterministic. Nesting is safe via a depth counter, and the
/// `Drop` impl ensures cleanup.
pub(crate) struct SdkWakeGuard {
    _priv: (), // prevent construction outside this module
}

impl SdkWakeGuard {
    pub(crate) fn new() -> Self {
        SDK_WAKE_DEPTH.with(|c| c.set(c.get() + 1));
        Self { _priv: () }
    }
}

impl Drop for SdkWakeGuard {
    fn drop(&mut self) {
        SDK_WAKE_DEPTH.with(|c| c.set(c.get() - 1));
    }
}

fn is_sdk_wake() -> bool {
    SDK_WAKE_DEPTH.with(|c| c.get() > 0)
}

/// Persists across polls to accumulate non-SDK wake detection. Each poll creates a lightweight
/// waker via [`WakeTracker::new_per_poll_waker`] that shares the detection flag but has the
/// current parent waker baked in (no mutex needed).
pub(crate) struct WakeTracker {
    non_sdk_wake_detected: Arc<AtomicBool>,
}

impl WakeTracker {
    pub(crate) fn new() -> Self {
        Self {
            non_sdk_wake_detected: Arc::new(AtomicBool::new(false)),
        }
    }

    /// Create a waker for this poll that forwards to `parent_waker` and sets the shared
    /// detection flag on non-SDK wakes.
    pub(crate) fn new_per_poll_waker(&self, parent_waker: &Waker) -> Waker {
        Waker::from(Arc::new(PerPollWakeTracker {
            non_sdk_wake_detected: self.non_sdk_wake_detected.clone(),
            parent_waker: parent_waker.clone(),
        }))
    }

    pub(crate) fn take_non_sdk_wake(&self) -> bool {
        self.non_sdk_wake_detected.swap(false, Ordering::AcqRel)
    }
}

struct PerPollWakeTracker {
    non_sdk_wake_detected: Arc<AtomicBool>,
    parent_waker: Waker,
}

impl Wake for PerPollWakeTracker {
    fn wake(self: Arc<Self>) {
        self.wake_by_ref();
    }

    fn wake_by_ref(self: &Arc<Self>) {
        if !is_sdk_wake() {
            self.non_sdk_wake_detected.store(true, Ordering::Release);
        }
        self.parent_waker.wake_by_ref();
    }
}

/// A future wrapper that activates [`SdkWakeGuard`] during poll. Use this around futures whose
/// internal waker machinery (e.g., `FuturesOrdered` inside `join_all`) would otherwise trigger
/// false positives in nondeterminism detection.
pub(crate) struct SdkGuardedFuture<F>(pub(crate) F);

impl<F: Future + Unpin> Future for SdkGuardedFuture<F> {
    type Output = F::Output;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let _guard = SdkWakeGuard::new();
        Pin::new(&mut self.0).poll(cx)
    }
}

struct ExecutorShared {
    ready_queue: parking_lot::Mutex<VecDeque<u64>>,
    /// Waker to notify when tasks are enqueued. Set by `shutdown` so it can
    /// park instead of busy-polling when tasks are waiting on external events.
    waker: parking_lot::Mutex<Option<Waker>>,
}

impl ExecutorShared {
    fn enqueue(&self, task_id: u64) {
        self.ready_queue.lock().push_back(task_id);
        if let Some(w) = self.waker.lock().as_ref() {
            w.wake_by_ref();
        }
    }
}

struct TaskNotifier {
    task_id: u64,
    shared: Arc<ExecutorShared>,
}

impl Wake for TaskNotifier {
    fn wake(self: Arc<Self>) {
        self.wake_by_ref();
    }

    fn wake_by_ref(self: &Arc<Self>) {
        self.shared.enqueue(self.task_id);
    }
}

struct LocalTask {
    future: Pin<Box<dyn Future<Output = ()>>>,
    waker: Waker,
}

struct TaskHandleInner<T> {
    result: RefCell<Option<T>>,
    waker: RefCell<Option<Waker>>,
}

/// A `!Send` join handle returned by [`WorkflowExecutor::spawn`].
///
/// Resolves to the spawned future's output when the executor completes it.
pub(crate) struct TaskHandle<T> {
    inner: Rc<TaskHandleInner<T>>,
}

/// Error returned by [`TaskHandle`] if the task was dropped without completing.
#[derive(Debug)]
pub(crate) struct TaskDroppedError;

impl std::fmt::Display for TaskDroppedError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("task was dropped before completing")
    }
}

impl std::error::Error for TaskDroppedError {}

impl<T> Future for TaskHandle<T> {
    type Output = Result<T, TaskDroppedError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if let Some(result) = self.inner.result.borrow_mut().take() {
            Poll::Ready(Ok(result))
        } else {
            *self.inner.waker.borrow_mut() = Some(cx.waker().clone());
            Poll::Pending
        }
    }
}

/// A minimal single-threaded async executor for workflow futures.
///
/// Replaces [tokio::task::LocalSet] + `spawn_local` for workflow tasks. Runs inside the existing
/// tokio runtime (driven as an async future) but provides its own task management with custom
/// wakers, enabling nondeterminism detection via [WakeTracker]
///
/// All spawned futures are `!Send` (they use `Rc<RefCell<...>>` internally). The executor itself is
/// `!Send` and must be driven from a `LocalSet` or single-threaded context.
pub(crate) struct WorkflowExecutor {
    tasks: RefCell<HashMap<u64, LocalTask>>,
    next_id: Cell<u64>,
    shared: Arc<ExecutorShared>,
}

impl WorkflowExecutor {
    pub(crate) fn new() -> Self {
        Self {
            tasks: RefCell::new(HashMap::new()),
            next_id: Cell::new(0),
            shared: Arc::new(ExecutorShared {
                ready_queue: parking_lot::Mutex::new(VecDeque::new()),
                waker: parking_lot::Mutex::new(None),
            }),
        }
    }

    /// Spawn a future onto this executor, returning a `!Send` join handle.
    pub(crate) fn spawn<F, T>(&self, future: F) -> TaskHandle<T>
    where
        F: Future<Output = T> + 'static,
        T: 'static,
    {
        let id = self.next_id.get();
        self.next_id.set(id + 1);

        let handle_inner = Rc::new(TaskHandleInner {
            result: RefCell::new(None),
            waker: RefCell::new(None),
        });

        let inner_clone = handle_inner.clone();
        let wrapped = async move {
            let output = future.await;
            *inner_clone.result.borrow_mut() = Some(output);
            if let Some(w) = inner_clone.waker.borrow_mut().take() {
                w.wake();
            }
        };

        self.tasks.borrow_mut().insert(
            id,
            LocalTask {
                future: Box::pin(wrapped),
                waker: Waker::from(Arc::new(TaskNotifier {
                    task_id: id,
                    shared: self.shared.clone(),
                })),
            },
        );

        self.shared.enqueue(id);

        TaskHandle {
            inner: handle_inner,
        }
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.tasks.borrow().is_empty()
    }

    /// Drain remaining tasks until all complete.
    pub(crate) async fn shutdown(&self) {
        std::future::poll_fn(|cx| {
            *self.shared.waker.lock() = Some(cx.waker().clone());
            self.process_tasks();
            if self.is_empty() {
                Poll::Ready(())
            } else {
                Poll::Pending
            }
        })
        .await
    }

    /// Drain the ready queue, polling all ready tasks once.
    pub(crate) fn process_tasks(&self) {
        loop {
            let task_id = self.shared.ready_queue.lock().pop_front();
            let Some(task_id) = task_id else { break };

            let Some(mut task) = self.tasks.borrow_mut().remove(&task_id) else {
                continue;
            };

            let mut task_cx = Context::from_waker(&task.waker);
            if task.future.as_mut().poll(&mut task_cx).is_pending() {
                self.tasks.borrow_mut().insert(task_id, task);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::sync::oneshot;

    #[tokio::test]
    async fn executor_spawn_and_complete() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let executor = WorkflowExecutor::new();
                let handle = executor.spawn(async { 42 });
                executor.shutdown().await;
                let result = handle.await.unwrap();
                assert_eq!(result, 42);
            })
            .await;
    }

    #[tokio::test]
    async fn executor_multiple_tasks() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let executor = WorkflowExecutor::new();
                let h1 = executor.spawn(async { 1 });
                let h2 = executor.spawn(async { 2 });
                let h3 = executor.spawn(async { 3 });
                executor.shutdown().await;
                assert_eq!(h1.await.unwrap(), 1);
                assert_eq!(h2.await.unwrap(), 2);
                assert_eq!(h3.await.unwrap(), 3);
            })
            .await;
    }

    #[tokio::test]
    async fn executor_wake_forwarding_through_oneshot() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let executor = Rc::new(WorkflowExecutor::new());
                let (tx, rx) = oneshot::channel::<i32>();

                let handle = executor.spawn(async move { rx.await.unwrap() });

                let executor_clone = executor.clone();
                tokio::task::spawn_local(async move {
                    executor_clone.shutdown().await;
                });

                // Send after a yield to ensure the future has parked
                tokio::task::yield_now().await;
                tx.send(99).unwrap();

                let result = handle.await.unwrap();
                assert_eq!(result, 99);
            })
            .await;
    }

    #[tokio::test]
    async fn spawn_while_parked_drains_new_task() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let executor = WorkflowExecutor::new();

                // Spawn a task and drain it. The oneshot isn't ready yet so the
                // task will park.
                let (tx, rx) = oneshot::channel::<()>();
                let handle = executor.spawn(async move {
                    rx.await.unwrap();
                    42
                });
                executor.process_tasks();

                // Resolve the oneshot, then drain again to complete the task.
                tx.send(()).unwrap();
                executor.process_tasks();

                let result = handle.await.unwrap();
                assert_eq!(result, 42);
            })
            .await;
    }

    #[test]
    fn sdk_wake_guard_nesting() {
        assert!(!is_sdk_wake());

        let _g1 = SdkWakeGuard::new();
        assert!(is_sdk_wake());

        {
            let _g2 = SdkWakeGuard::new();
            assert!(is_sdk_wake());
        }
        // g2 dropped, but g1 still active
        assert!(is_sdk_wake());

        drop(_g1);
        assert!(!is_sdk_wake());
    }

    #[test]
    fn sdk_wake_guard_panic_safety() {
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _guard = SdkWakeGuard::new();
            panic!("test panic");
        }));
        assert!(result.is_err());
        // Guard was cleaned up by Drop despite the panic
        assert!(!is_sdk_wake());
    }

    #[test]
    fn wake_tracker_detects_non_sdk_wake() {
        let tracker = WakeTracker::new();
        let noop = Waker::noop();
        let waker = tracker.new_per_poll_waker(noop);

        // Wake without SDK guard -- should be detected
        waker.wake_by_ref();
        assert!(tracker.take_non_sdk_wake());

        // Wake with SDK guard -- should not be detected
        let _guard = SdkWakeGuard::new();
        waker.wake_by_ref();
        assert!(!tracker.take_non_sdk_wake());
    }

    #[test]
    fn wake_tracker_cross_thread_detection() {
        let tracker = WakeTracker::new();
        let noop = Waker::noop();
        let waker = tracker.new_per_poll_waker(noop);

        // Set SDK guard on THIS thread
        let _guard = SdkWakeGuard::new();

        // Wake from another thread -- thread-local not set there
        let handle = std::thread::spawn(move || {
            waker.wake_by_ref();
        });
        handle.join().unwrap();

        assert!(tracker.take_non_sdk_wake());
    }
}