gadk-agent 0.4.3

The gadk agent API: agents, contexts, tools, callbacks and plugins
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
// Copyright 2026 Chris Olson
// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Fibers: the execution identity of agent runs, used by the agent-analytics plugin to tell
//! concurrent runs apart and to record where each was started. A fiber has an id, an [`Origin`]
//! (the spawn site that started it and the fiber it was started from) and an attempt slot.
//!
//! The engine gives every task on which it starts agent runs concurrently a fresh [`Fiber`] with
//! [`spawn_child`], naming the spawn site with one of the creator constants below; the runner's
//! consumer stream carries one with [`FiberStream::consumer`]. Code running under a fiber reads
//! it with [`current`]. Agent runs that are polled as streams on the consumer's task (nested
//! agents, tools, the runner) share that task's fiber.
//!
//! The attempt site is a slot on the fiber: the engine marks one pending
//! attempt with [`with_attempt`] around a workflow node attempt whose node is an agent node, and
//! the first agent run started on the fiber while no other agent run is active there claims it for
//! the duration of its before-agent callbacks ([`current_attempt`]).

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::task::{Context as TaskContext, Poll};

use futures::Stream;
use parking_lot::Mutex;

/// The spawn site of the task on which a workflow agent's scheduler runs a
/// node (gadk-engine `workflow::scheduler` `start_node`).
pub const SCHEDULER_CREATOR: &str = "gadk_engine::workflow::scheduler::start_node";
/// The spawn site of a ParallelAgent branch's task (gadk-engine
/// `agents::parallel_agent`).
pub const ERRGROUP_CREATOR: &str = "gadk_engine::agents::parallel_agent::branch";
/// The spawn site of a ParallelWorker item's task (gadk-engine
/// `workflow::nodes::parallel_worker`); retries of the item stay on it.
pub const PARALLEL_WORKER_CREATOR: &str = "gadk_engine::workflow::nodes::parallel_worker::run";
/// The spawn site of a live session's task (gadk-engine `llm::live::flow`).
pub const LIVE_SESSION_CREATOR: &str = "gadk_engine::llm::live::flow::run_live";

/// The bit that marks a fallback id (a tokio task id, see [`current`]); fiber ids are below it.
const FALLBACK_BIT: u64 = 1 << 63;

/// The next fiber id: process-wide, starting at 1, never reused. Reaching
/// [`FALLBACK_BIT`] would take 2^63 fibers.
static NEXT_ID: AtomicU64 = AtomicU64::new(1);

tokio::task_local! {
    /// The fiber the running code belongs to.
    static CURRENT: Arc<FiberState>;
}

/// The spawn site that started a fiber and the fiber it was started from.
/// The zero value (empty creator, parent 0) is an unknown origin.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Origin {
    /// The spawn site: one of this module's creator constants, or empty.
    pub creator: &'static str,
    /// The id of the fiber that was current when this one was started (0 = unknown).
    pub parent: u64,
}

impl Origin {
    /// Whether this is the zero (unknown) origin.
    pub fn is_zero(&self) -> bool {
        self.creator.is_empty() && self.parent == 0
    }

    /// Whether `creator` started this fiber while running on the fiber
    /// `parent` (never for an unknown parent, 0).
    pub fn started_by(&self, creator: &str, parent: u64) -> bool {
        parent != 0 && self.parent == parent && self.creator == creator
    }
}

/// The agent run is the agent of a workflow node attempt, run alone on its fiber.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AttemptSite {
    /// The agent of an agent node started by the workflow scheduler.
    Node,
    /// The agent of an agent node wrapped by a ParallelWorker item attempt.
    Worker,
}

/// The attempt slot of a fiber.
#[derive(Debug, Default)]
struct AttemptSlot {
    /// Marked by [`with_attempt`] for one attempt, not yet claimed.
    pending: Option<AttemptSite>,
    /// The claimed site, visible through [`current_attempt`] during the claiming run's
    /// before-agent callbacks.
    current: Option<AttemptSite>,
    /// The agent runs started and not yet finished on this fiber.
    active_runs: usize,
}

/// The shared state of a fiber: what the task-local holds. It holds no [`Fiber`], so it drops
/// with the last fiber, scope or stream that refers to it.
#[derive(Debug)]
struct FiberState {
    id: u64,
    origin: Origin,
    slot: Mutex<AttemptSlot>,
}

impl FiberState {
    fn new(id: u64, origin: Origin) -> Arc<FiberState> {
        Arc::new(FiberState {
            id,
            origin,
            slot: Mutex::new(AttemptSlot::default()),
        })
    }
}

/// An execution identity: its id, its origin and, for fibers made by this
/// module, the attempt slot it shares with every clone and every re-entry.
#[derive(Debug, Clone)]
pub struct Fiber {
    /// The fiber id: from 1 below `1 << 63` for fibers made by this module, `(1 << 63) | <tokio
    /// task id>` for a fallback, 0 when unknown.
    pub id: u64,
    /// Where the fiber was started (zero for roots and fallbacks).
    pub origin: Origin,
    /// `None` for fallback fibers.
    state: Option<Arc<FiberState>>,
}

impl Fiber {
    /// A new fiber with a new id and a zero origin.
    pub fn root() -> Fiber {
        Fiber::with_origin(Origin::default())
    }

    fn with_origin(origin: Origin) -> Fiber {
        let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
        Fiber {
            id,
            origin,
            state: Some(FiberState::new(id, origin)),
        }
    }

    /// The state to make current: a fallback fiber is given one with its id first.
    fn into_state(self) -> Arc<FiberState> {
        match self.state {
            Some(state) => state,
            None => FiberState::new(self.id, self.origin),
        }
    }

    /// Runs `fut` with this fiber current (every poll of it, and everything it polls in the same
    /// task).
    pub fn scope<F: Future>(self, fut: F) -> impl Future<Output = F::Output> {
        CURRENT.scope(self.into_state(), fut)
    }

    /// Wraps `stream` so that this fiber is current for every poll of it, whichever task polls it.
    pub fn instrument<S>(self, stream: S) -> FiberStream<S> {
        FiberStream {
            fiber: Some(self.into_state()),
            inner: stream,
        }
    }
}

/// The fiber the running code belongs to: the fiber of the innermost [`Fiber::scope`] or
/// [`FiberStream`]; else, in a tokio task, a fallback `{ id: (1 << 63) | <task id>, origin: zero }`
/// with no attempt slot; else `{ id: 0, origin: zero }` (unknown).
// Fallback ids are tokio task ids, unique only among running tasks, and the id is 0 outside any
// task or fiber.
pub fn current() -> Fiber {
    CURRENT
        .try_with(|state| Fiber {
            id: state.id,
            origin: state.origin,
            state: Some(Arc::clone(state)),
        })
        .unwrap_or_else(|_| fallback())
}

fn fallback() -> Fiber {
    let id = tokio::task::try_id().map_or(0, |task| {
        // `tokio::task::Id` exposes its number only through `Display`; a parse failure still
        // yields a non-zero fallback id.
        FALLBACK_BIT | task.to_string().parse::<u64>().unwrap_or(0)
    });
    Fiber {
        id,
        origin: Origin::default(),
        state: None,
    }
}

/// A new fiber started by `creator` from the current fiber: a new id and `origin = { creator,
/// parent: current().id }`.
pub fn spawn_child(creator: &'static str) -> Fiber {
    Fiber::with_origin(Origin {
        creator,
        parent: current().id,
    })
}

/// A stream polled under a fiber: [`Fiber::instrument`] fixes the fiber when wrapping,
/// [`FiberStream::consumer`] at the first poll. The fiber is current for every poll, so the
/// stream keeps it when it is moved to and polled from another task.
// A started agent stream moved to another task keeps its fiber only when wrapped in a
// `FiberStream`, and agent streams polled concurrently in one task share that task's fiber.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct FiberStream<S> {
    fiber: Option<Arc<FiberState>>,
    inner: S,
}

impl<S> FiberStream<S> {
    /// Wraps a consumer stream (the one the caller polls): the
    /// first poll adopts the current fiber if one is set, else a new [`Fiber::root`], and every
    /// later poll re-enters it.
    pub fn consumer(stream: S) -> FiberStream<S> {
        FiberStream {
            fiber: None,
            inner: stream,
        }
    }

    /// The stream's fiber (`None` for a consumer stream not polled yet).
    pub fn fiber(&self) -> Option<Fiber> {
        self.fiber.as_ref().map(|state| Fiber {
            id: state.id,
            origin: state.origin,
            state: Some(Arc::clone(state)),
        })
    }
}

impl<S: Stream + Unpin> Stream for FiberStream<S> {
    type Item = S::Item;

    fn poll_next(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<S::Item>> {
        let this = self.get_mut();
        let state = this
            .fiber
            .get_or_insert_with(|| {
                CURRENT
                    .try_with(Arc::clone)
                    .unwrap_or_else(|_| Fiber::root().into_state())
            })
            .clone();
        let inner = &mut this.inner;
        CURRENT.sync_scope(state, || Pin::new(inner).poll_next(cx))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

/// Runs `fut` with `site` marked as the pending attempt of the current fiber (engine: around one
/// workflow node attempt whose node is an agent node). The mark is cleared (the previous one
/// restored) when `fut` completes or is dropped. Without a current fiber it does nothing.
pub async fn with_attempt<F: Future>(site: AttemptSite, fut: F) -> F::Output {
    let _pending = PendingAttempt::mark(site);
    fut.await
}

/// The pending mark of one [`with_attempt`].
struct PendingAttempt {
    state: Option<Arc<FiberState>>,
    prev: Option<AttemptSite>,
}

impl PendingAttempt {
    fn mark(site: AttemptSite) -> PendingAttempt {
        let state = CURRENT.try_with(Arc::clone).ok();
        let prev = state
            .as_ref()
            .and_then(|s| s.slot.lock().pending.replace(site));
        PendingAttempt { state, prev }
    }
}

impl Drop for PendingAttempt {
    fn drop(&mut self) {
        if let Some(state) = &self.state {
            state.slot.lock().pending = self.prev;
        }
    }
}

/// The attempt site claimed by the agent run whose before-agent callbacks are running on the
/// current fiber (the claim taken for the before-agent callbacks), else
pub fn current_attempt() -> Option<AttemptSite> {
    CURRENT
        .try_with(|state| state.slot.lock().current)
        .ok()
        .flatten()
}

/// Registers an agent run on
/// the current fiber and, if no other agent run is active there, moves the pending attempt to the
/// current one (else the current one is `None` for this nested run). Dropping the claim restores
/// the previous current attempt; [`AttemptClaim::into_active_run`] keeps the run registered.
pub(crate) fn claim_attempt() -> AttemptClaim {
    let Ok(state) = CURRENT.try_with(Arc::clone) else {
        return AttemptClaim {
            state: None,
            prev: None,
            run: None,
        };
    };
    let prev = {
        let mut slot = state.slot.lock();
        let prev = slot.current;
        slot.current = if slot.active_runs == 0 {
            slot.pending.take()
        } else {
            None
        };
        slot.active_runs += 1;
        prev
    };
    AttemptClaim {
        state: Some(Arc::clone(&state)),
        prev,
        run: Some(ActiveRun { state: Some(state) }),
    }
}

/// A claimed attempt, held for the duration of an agent run's before-agent callbacks.
#[must_use = "dropping the claim ends the attempt and the run's registration"]
pub(crate) struct AttemptClaim {
    state: Option<Arc<FiberState>>,
    prev: Option<AttemptSite>,
    run: Option<ActiveRun>,
}

impl AttemptClaim {
    /// Ends the attempt (restores the previous current attempt) and keeps the run registered as
    /// active on its fiber for as long as the returned guard lives.
    pub(crate) fn into_active_run(mut self) -> ActiveRun {
        self.run.take().unwrap_or_default()
    }
}

impl Drop for AttemptClaim {
    fn drop(&mut self) {
        if let Some(state) = &self.state {
            state.slot.lock().current = self.prev;
        }
    }
}

/// An agent run registered as active on a fiber; dropping it unregisters the run.
#[derive(Default)]
pub(crate) struct ActiveRun {
    state: Option<Arc<FiberState>>,
}

impl Drop for ActiveRun {
    fn drop(&mut self) {
        if let Some(state) = &self.state {
            let mut slot = state.slot.lock();
            slot.active_runs = slot.active_runs.saturating_sub(1);
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use futures::StreamExt;

    use super::*;

    /// A stream whose items are the fiber current while each is produced.
    fn ids(n: usize) -> futures::stream::BoxStream<'static, u64> {
        futures::stream::iter(0..n).map(|_| current().id).boxed()
    }

    #[test]
    fn creators_are_the_engine_spawn_sites() {
        assert_eq!(
            SCHEDULER_CREATOR,
            "gadk_engine::workflow::scheduler::start_node"
        );
        assert_eq!(
            ERRGROUP_CREATOR,
            "gadk_engine::agents::parallel_agent::branch"
        );
        assert_eq!(
            PARALLEL_WORKER_CREATOR,
            "gadk_engine::workflow::nodes::parallel_worker::run"
        );
        assert_eq!(
            LIVE_SESSION_CREATOR,
            "gadk_engine::llm::live::flow::run_live"
        );
    }

    #[test]
    fn ids_strictly_increase_below_the_fallback_range() {
        let a = Fiber::root();
        let b = Fiber::root();
        let c = spawn_child(SCHEDULER_CREATOR);
        assert!(0 < a.id && a.id < b.id && b.id < c.id && c.id < FALLBACK_BIT);
        assert!(a.origin.is_zero() && b.origin.is_zero());
    }

    #[test]
    fn current_outside_any_runtime_is_unknown() {
        let f = current();
        assert_eq!(f.id, 0);
        assert!(f.origin.is_zero());
        assert_eq!(current_attempt(), None);
    }

    #[tokio::test]
    async fn current_in_a_test_body_is_unknown() {
        // A `#[tokio::test]` body runs in `block_on`, not in a task.
        assert_eq!(current().id, 0);
        assert!(current().origin.is_zero());
    }

    #[tokio::test]
    async fn current_in_a_spawned_task_is_a_fallback() {
        let (a, b) = tokio::join!(
            tokio::spawn(async { current() }),
            tokio::spawn(async { current() })
        );
        let (a, b) = (a.unwrap(), b.unwrap());
        assert!(
            a.id > FALLBACK_BIT && b.id > FALLBACK_BIT,
            "{} {}",
            a.id,
            b.id
        );
        assert!(a.origin.is_zero());
        let same = tokio::spawn(async { (current().id, current().id) })
            .await
            .unwrap();
        assert_eq!(same.0, same.1, "stable within one task");
    }

    #[tokio::test]
    async fn scope_makes_the_fiber_current() {
        let outer = Fiber::root();
        let inner = Fiber::root();
        let (outer_id, inner_id) = (outer.id, inner.id);
        let seen = outer
            .scope(async move {
                let before = current().id;
                let nested = inner.scope(async { current().id }).await;
                (before, nested, current().id)
            })
            .await;
        assert_eq!(seen, (outer_id, inner_id, outer_id));
        assert_eq!(current().id, 0, "scope ended");
    }

    #[tokio::test]
    async fn scoping_a_fallback_fiber_keeps_its_id() {
        let (fallback_id, scoped_id) = tokio::spawn(async {
            let f = current();
            let id = f.id;
            (id, f.scope(async { current().id }).await)
        })
        .await
        .unwrap();
        assert!(fallback_id > FALLBACK_BIT);
        assert_eq!(scoped_id, fallback_id);
    }

    #[tokio::test]
    async fn spawn_child_records_creator_and_parent() {
        let root = Fiber::root();
        let root_id = root.id;
        let child = root.scope(async { spawn_child(ERRGROUP_CREATOR) }).await;
        assert!(child.id > root_id);
        assert_eq!(
            child.origin,
            Origin {
                creator: ERRGROUP_CREATOR,
                parent: root_id,
            }
        );
        assert!(child.origin.started_by(ERRGROUP_CREATOR, root_id));
        assert!(!child.origin.started_by(SCHEDULER_CREATOR, root_id));
        assert!(!child.origin.started_by(ERRGROUP_CREATOR, 0));

        // Outside any fiber or task the parent is unknown.
        assert_eq!(spawn_child(SCHEDULER_CREATOR).origin.parent, 0);
        // In a task without a fiber the parent is the task's fallback id.
        let (task_id, parent) =
            tokio::spawn(async { (current().id, spawn_child(SCHEDULER_CREATOR).origin.parent) })
                .await
                .unwrap();
        assert!(task_id > FALLBACK_BIT);
        assert_eq!(parent, task_id);
    }

    #[tokio::test]
    async fn instrumented_stream_keeps_its_fiber_on_another_task() {
        let f = Fiber::root();
        let id = f.id;
        let mut s = f.instrument(ids(3));
        assert_eq!(s.fiber().map(|f| f.id), Some(id));
        assert_eq!(s.next().await, Some(id));
        let rest = tokio::spawn(async move { s.collect::<Vec<_>>().await })
            .await
            .unwrap();
        assert_eq!(rest, vec![id, id]);
    }

    #[tokio::test]
    async fn consumer_stream_adopts_the_current_fiber_at_first_poll() {
        let f = Fiber::root();
        let id = f.id;
        let mut s = FiberStream::consumer(ids(3));
        assert!(s.fiber().is_none(), "fixed at first poll, not when wrapped");
        let first = f.scope(async { s.next().await }).await;
        assert_eq!(first, Some(id));
        let rest = tokio::spawn(async move { s.collect::<Vec<_>>().await })
            .await
            .unwrap();
        assert_eq!(rest, vec![id, id]);
    }

    #[tokio::test]
    async fn consumer_stream_without_a_fiber_keeps_a_new_root() {
        let mut s = FiberStream::consumer(ids(3));
        let first = s.next().await.unwrap();
        assert!(0 < first && first < FALLBACK_BIT);
        let fiber = s.fiber().unwrap();
        assert_eq!(fiber.id, first);
        assert!(fiber.origin.is_zero());
        let rest = tokio::spawn(async move { s.collect::<Vec<_>>().await })
            .await
            .unwrap();
        assert_eq!(rest, vec![first, first]);
        assert_eq!(
            current().id,
            0,
            "the stream's fiber is current only while it is polled"
        );
    }

    #[tokio::test]
    async fn fiber_state_drops_with_its_last_user() {
        let f = Fiber::root();
        let weak = Arc::downgrade(f.state.as_ref().unwrap());
        f.scope(async {
            let again = current();
            again.scope(async {}).await;
        })
        .await;
        assert!(
            weak.upgrade().is_none(),
            "no reference cycle keeps the state"
        );

        let f = Fiber::root();
        let weak = Arc::downgrade(f.state.as_ref().unwrap());
        let mut s = f.instrument(ids(1));
        assert!(s.next().await.is_some());
        drop(s);
        assert!(weak.upgrade().is_none());
    }

    #[tokio::test]
    async fn with_attempt_without_a_fiber_does_nothing() {
        let claimed = with_attempt(AttemptSite::Node, async {
            let _claim = claim_attempt();
            current_attempt()
        })
        .await;
        assert_eq!(claimed, None);
    }

    #[tokio::test]
    async fn pending_attempt_is_visible_only_once_claimed() {
        let seen = Fiber::root()
            .scope(with_attempt(AttemptSite::Node, async {
                let before = current_attempt();
                let claim = claim_attempt();
                let during = current_attempt();
                drop(claim);
                (before, during, current_attempt())
            }))
            .await;
        assert_eq!(seen, (None, Some(AttemptSite::Node), None));
    }

    #[tokio::test]
    async fn a_consumed_attempt_is_not_claimed_again() {
        let seen = Fiber::root()
            .scope(with_attempt(AttemptSite::Node, async {
                let first = {
                    let _claim = claim_attempt();
                    current_attempt()
                };
                let second = {
                    let _claim = claim_attempt();
                    current_attempt()
                };
                (first, second)
            }))
            .await;
        assert_eq!(seen, (Some(AttemptSite::Node), None));
    }

    #[tokio::test]
    async fn a_nested_run_sees_none_and_restores_the_outer_attempt() {
        let seen = Fiber::root()
            .scope(with_attempt(AttemptSite::Worker, async {
                let outer = claim_attempt();
                let outer_site = current_attempt();
                let inner_site = {
                    let _inner = claim_attempt();
                    current_attempt()
                };
                (outer_site, inner_site, current_attempt(), outer)
            }))
            .await;
        assert_eq!(
            (seen.0, seen.1, seen.2),
            (Some(AttemptSite::Worker), None, Some(AttemptSite::Worker))
        );
    }

    #[tokio::test]
    async fn an_active_run_blocks_claims_until_it_ends() {
        let f = Fiber::root();
        let seen = f
            .scope(async {
                let run = claim_attempt().into_active_run();
                // The run's callbacks are over, the run is still active (Go: its frame is still
                // on the stack while it yields).
                let while_active = with_attempt(AttemptSite::Node, async {
                    let _claim = claim_attempt();
                    current_attempt()
                })
                .await;
                drop(run);
                let after = with_attempt(AttemptSite::Node, async {
                    let _claim = claim_attempt();
                    current_attempt()
                })
                .await;
                (while_active, after)
            })
            .await;
        assert_eq!(seen, (None, Some(AttemptSite::Node)));
    }

    #[tokio::test]
    async fn re_entering_a_fiber_shares_its_slot() {
        let f = Fiber::root();
        let run = f
            .clone()
            .scope(async { claim_attempt().into_active_run() })
            .await;
        let while_active = f
            .clone()
            .scope(with_attempt(AttemptSite::Node, async {
                let _claim = claim_attempt();
                current_attempt()
            }))
            .await;
        drop(run);
        let after = f
            .scope(with_attempt(AttemptSite::Node, async {
                let _claim = claim_attempt();
                current_attempt()
            }))
            .await;
        assert_eq!((while_active, after), (None, Some(AttemptSite::Node)));
    }

    #[tokio::test]
    async fn the_mark_is_cleared_after_the_attempt() {
        let seen = Fiber::root()
            .scope(async {
                with_attempt(AttemptSite::Worker, async {}).await;
                let _claim = claim_attempt();
                current_attempt()
            })
            .await;
        assert_eq!(seen, None);
    }

    #[tokio::test]
    async fn each_retry_attempt_is_claimed() {
        let seen = Fiber::root()
            .scope(async {
                let mut seen = Vec::new();
                for _ in 0..2 {
                    seen.push(
                        with_attempt(AttemptSite::Worker, async {
                            let _claim = claim_attempt();
                            current_attempt()
                        })
                        .await,
                    );
                }
                seen
            })
            .await;
        assert_eq!(seen, vec![Some(AttemptSite::Worker); 2]);
    }
}