harn_vm/vm/async_builtin.rs
1use std::future::Future;
2use std::sync::atomic::AtomicBool;
3use std::sync::Arc;
4use std::time::Instant;
5
6use super::Vm;
7
8/// Explicit handle to the parent VM's execution context for the duration of one
9/// async-builtin call. Threaded into every async builtin by the dispatch loop
10/// (and the `#[harn_builtin]` macro), so context can no longer be "lost across a
11/// spawn boundary": a handler that needs VM access receives or clones this
12/// handle deliberately instead of reading ambient state.
13///
14/// Holds the "template" child VM that closure-invoking host helpers clone via
15/// [`AsyncBuiltinCtx::child_vm`], and whose `output` buffer collects text
16/// forwarded from VM-side closures via [`AsyncBuiltinCtx::forward_output`]. The
17/// dispatch loop drains that buffer back to the original parent VM after the
18/// async builtin returns. Cheap to clone: it is an `Arc` handle and everything
19/// heavy inside the `Vm` is shared.
20#[derive(Clone)]
21pub struct AsyncBuiltinCtx {
22 child: Arc<parking_lot::Mutex<Vm>>,
23}
24
25impl AsyncBuiltinCtx {
26 fn new(vm: Vm) -> Self {
27 Self {
28 child: Arc::new(parking_lot::Mutex::new(vm)),
29 }
30 }
31
32 /// Construct a context around `vm` for host adapters that are not themselves
33 /// async builtins but need to run VM-side closures.
34 pub fn from_vm(vm: Vm) -> Self {
35 Self::new(vm)
36 }
37
38 /// Construct a standalone ctx around `vm` for unit tests that drive an async
39 /// builtin handler directly (outside the dispatch loop). Production code
40 /// receives its ctx from the dispatch path, never this.
41 #[cfg(test)]
42 pub fn for_test(vm: Vm) -> Self {
43 Self::new(vm)
44 }
45
46 /// Clone a fresh child VM from this context. The returned `Vm` shares the
47 /// parent's heavy state, so each closure-invoking handler gets its own
48 /// cheap execution context.
49 ///
50 /// Uses the *inline* clone: this child runs while the original parent is
51 /// parked awaiting the builtin, so it inherits the parent's held-lock keys
52 /// for cross-context self-deadlock detection (HARN-ORC-011). Long-lived /
53 /// detached contexts use [`AsyncBuiltinCtx::child_ctx`] instead, which does
54 /// not inherit, since the parent keeps running there.
55 pub fn child_vm(&self) -> Vm {
56 self.child.lock().child_vm_inline()
57 }
58
59 /// Pool tasks may execute on any Tokio worker thread, so pool lookup state
60 /// is shared through the VM context rather than thread-local storage.
61 pub(crate) fn pool_registry(&self) -> Arc<crate::stdlib::pool::PoolRegistry> {
62 self.child.lock().pool_registry.clone()
63 }
64
65 pub(crate) fn wait_for_graph(&self) -> Arc<crate::wait_for_graph::VmWaitForGraph> {
66 self.child.lock().wait_for_graph.clone()
67 }
68
69 pub(crate) fn package_snapshot_registry(&self) -> Arc<crate::stdlib::PackageSnapshotRegistry> {
70 self.child.lock().package_snapshot_registry.clone()
71 }
72
73 /// Create an independent context rooted at a fresh child VM. Long-lived
74 /// local tasks use this instead of sharing the parent builtin's output
75 /// buffer after the parent future has returned.
76 ///
77 /// This is a *detached* context: the new task runs independently of the
78 /// original parent, so it must NOT inherit the parent's held-lock keys
79 /// (blocking on a parent-held lock is legitimately resolvable here). Uses
80 /// the plain, non-inheriting `child_vm()` rather than `Self::child_vm`.
81 pub fn child_ctx(&self) -> Self {
82 Self::new(self.child.lock().child_vm())
83 }
84
85 /// Forward captured output from a transient child VM (typically created via
86 /// [`AsyncBuiltinCtx::child_vm`] and used to invoke a closure) back into this
87 /// context's output buffer. The dispatch loop drains that buffer back to the
88 /// original parent VM after the async builtin returns.
89 ///
90 /// Without this hook, `harness.stdio.log()`/`__io_print()` calls inside
91 /// `post_turn_callback` closures, tool handlers, and other VM-side closures
92 /// invoked from async builtins would silently disappear because the transient
93 /// child VM's output buffer is dropped on scope exit.
94 pub fn forward_output(&self, text: &str) {
95 if text.is_empty() {
96 return;
97 }
98 self.child.lock().append_output(text);
99 }
100
101 /// Snapshot the cancellation and deadline sources for a host operation
102 /// that must move its blocking work to Tokio's blocking pool.
103 pub fn interrupt_sources(&self) -> (Option<Arc<AtomicBool>>, Option<Instant>) {
104 self.child.lock().interrupt_sources()
105 }
106}
107
108/// Run an async builtin's future with `child` installed as its explicit
109/// [`AsyncBuiltinCtx`]. `make_fut` receives the ctx handle and returns the
110/// handler's future; the ctx is moved into the future, so it lives exactly as
111/// long as the call. Returns the future's output plus any output that VM-side
112/// closures forwarded into the context, which the dispatch loop appends to the
113/// real parent VM. Cancel-safe: if the returned future is dropped, the ctx +
114/// child `Vm` are dropped with it.
115pub(crate) fn run_async_builtin_with<F, M>(
116 child: Vm,
117 make_fut: M,
118) -> impl Future<Output = (F::Output, String)>
119where
120 F: Future + Send,
121 M: FnOnce(AsyncBuiltinCtx) -> F,
122{
123 // Build the context + scope synchronously so the by-value `child: Vm` moves
124 // onto the heap *before* any async state machine exists. If this were
125 // an `async fn`, the future would reserve a Vm-sized slot for `child` up to
126 // its first await, and that bloat propagates into every caller's stack
127 // frame, which can trip clippy::large_stack_frames in large dispatch
128 // functions.
129 let ctx = AsyncBuiltinCtx::new(child);
130 let registry = ctx.pool_registry();
131 let sink = Arc::clone(&ctx.child);
132 let fut = make_fut(ctx);
133 async move {
134 let output = crate::stdlib::pool::with_pool_registry_scope(registry, fut).await;
135 let captured = sink.lock().take_output();
136 (output, captured)
137 }
138}
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143 use crate::Vm;
144
145 #[tokio::test]
146 async fn explicit_ctx_mints_child_and_captures_forwarded_output() {
147 let (present, captured) = run_async_builtin_with(Vm::new(), |ctx| async move {
148 // The handler holds the explicit ctx — no ambient lookup needed.
149 let _child = ctx.child_vm();
150 ctx.forward_output("hello ");
151 ctx.forward_output("world");
152 true
153 })
154 .await;
155 assert!(present);
156 // `forward_output` appends into the same buffer the dispatch loop drains.
157 assert_eq!(captured, "hello world");
158 }
159
160 #[tokio::test]
161 async fn child_context_has_independent_output_buffer() {
162 let (_result, captured) = run_async_builtin_with(Vm::new(), |ctx| async move {
163 let child = ctx.child_ctx();
164 child.forward_output("child");
165 ctx.forward_output("parent");
166 })
167 .await;
168 assert_eq!(captured, "parent");
169 }
170
171 #[tokio::test]
172 async fn cancelled_scope_strands_nothing() {
173 use std::future::pending;
174 // Build a future that never completes, then drop it without polling to
175 // completion. The ctx is owned by that future, so dropping it releases
176 // the child VM without any ambient cleanup.
177 let never = run_async_builtin_with(Vm::new(), |_ctx| pending::<()>());
178 drop(never);
179 }
180}