Skip to main content

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 context for host work that the current VM awaits inline.
39    ///
40    /// The parent is parked until the host future completes, so the context
41    /// must share its execution deadline and inherited lock set. Using a plain
42    /// `child_vm()` here would fork the outer deadline: admission could pause
43    /// the fork while the real caller still timed out.
44    pub(crate) fn from_inline_parent(parent: &Vm) -> Self {
45        Self::new(parent.child_vm_inline())
46    }
47
48    /// Construct a standalone ctx around `vm` for tests that drive an async
49    /// builtin directly. Reuse the fixture's active execution registries just
50    /// as the production dispatch scope would; production never calls this.
51    #[cfg(test)]
52    pub fn for_test(mut vm: Vm) -> Self {
53        vm.worker_registry = crate::stdlib::agents::agents_workers::active_worker_registry();
54        vm.daemon_registry = crate::stdlib::agents_daemon::active_daemon_registry();
55        vm.trigger_registry = crate::triggers::registry::active_trigger_registry();
56        vm.session_runtime = crate::agent_sessions::active_session_runtime();
57        vm.tracing_runtime = crate::tracing::active_tracing_runtime();
58        vm.agent_host_session_runtime =
59            crate::llm::agent_session_host::active_agent_host_session_runtime();
60        Self::new(vm)
61    }
62
63    /// Clone a fresh child VM from this context. The returned `Vm` shares the
64    /// parent's heavy state, so each closure-invoking handler gets its own
65    /// cheap execution context.
66    ///
67    /// Uses the *inline* clone: this child runs while the original parent is
68    /// parked awaiting the builtin, so it inherits the parent's held-lock keys
69    /// for cross-context self-deadlock detection (HARN-ORC-011). Long-lived /
70    /// detached contexts use [`AsyncBuiltinCtx::child_ctx`] instead, which does
71    /// not inherit, since the parent keeps running there.
72    pub fn child_vm(&self) -> Vm {
73        self.child.lock().child_vm_inline()
74    }
75
76    /// Harn-owned identity of the execution awaiting this builtin.
77    pub(crate) fn execution_id(&self) -> String {
78        self.child.lock().execution_id().to_string()
79    }
80
81    /// Pool tasks may execute on any Tokio worker thread, so pool lookup state
82    /// is shared through the VM context rather than thread-local storage.
83    pub(crate) fn pool_registry(&self) -> Arc<crate::stdlib::pool::PoolRegistry> {
84        self.child.lock().pool_registry.clone()
85    }
86
87    pub(crate) fn wait_for_graph(&self) -> Arc<crate::wait_for_graph::VmWaitForGraph> {
88        self.child.lock().wait_for_graph.clone()
89    }
90
91    pub(crate) fn package_snapshot_registry(&self) -> Arc<crate::stdlib::PackageSnapshotRegistry> {
92        self.child.lock().package_snapshot_registry.clone()
93    }
94
95    /// Resolve a connector client from this VM tree's eager projection or its
96    /// execution-owned lazy resolver. The runtime handle is cloned before the
97    /// await so no VM lock crosses user/provider initialization work.
98    pub(crate) async fn connector_client(
99        &self,
100        provider: &str,
101    ) -> Result<Option<Arc<dyn crate::connectors::ConnectorClient>>, crate::connectors::ClientError>
102    {
103        let runtime = self.child.lock().connector_clients.clone();
104        runtime.resolve(provider).await
105    }
106
107    /// Create an independent context rooted at a fresh child VM. Long-lived
108    /// local tasks use this instead of sharing the parent builtin's output
109    /// buffer after the parent future has returned.
110    ///
111    /// This is a *detached* context: the new task runs independently of the
112    /// original parent, so it must NOT inherit the parent's held-lock keys
113    /// (blocking on a parent-held lock is legitimately resolvable here). Uses
114    /// the plain, non-inheriting `child_vm()` rather than `Self::child_vm`.
115    pub fn child_ctx(&self) -> Self {
116        Self::new(self.child.lock().child_vm())
117    }
118
119    /// Forward captured output from a transient child VM (typically created via
120    /// [`AsyncBuiltinCtx::child_vm`] and used to invoke a closure) back into this
121    /// context's output buffer. The dispatch loop drains that buffer back to the
122    /// original parent VM after the async builtin returns.
123    ///
124    /// Without this hook, `harness.stdio.log()`/`__io_print()` calls inside
125    /// `post_turn_callback` closures, tool handlers, and other VM-side closures
126    /// invoked from async builtins would silently disappear because the transient
127    /// child VM's output buffer is dropped on scope exit.
128    pub fn forward_output(&self, text: &str) {
129        if text.is_empty() {
130            return;
131        }
132        self.child.lock().append_output(text);
133    }
134
135    /// Snapshot the cancellation and deadline sources for a host operation
136    /// that must move its blocking work to Tokio's blocking pool.
137    pub fn interrupt_sources(&self) -> (Option<Arc<AtomicBool>>, Option<Instant>) {
138        self.child.lock().interrupt_sources()
139    }
140
141    /// Pause the outer host execution rail while an embedder-owned resource is
142    /// not runnable. Catchable script deadlines remain unchanged.
143    pub(crate) fn pause_execution_deadline(
144        &self,
145        clock: Arc<dyn harn_clock::Clock>,
146    ) -> Option<super::state::ExecutionDeadlinePauseGuard> {
147        self.child.lock().execution_deadline.pause(clock)
148    }
149
150    #[cfg(test)]
151    pub(crate) fn execution_deadline_offset_for_test(&self) -> u64 {
152        self.child
153            .lock()
154            .execution_deadline
155            .encoded_offset_for_test()
156    }
157}
158
159/// Run an async builtin's future with `child` installed as its explicit
160/// [`AsyncBuiltinCtx`]. `make_fut` receives the ctx handle and returns the
161/// handler's future; the ctx is moved into the future, so it lives exactly as
162/// long as the call. Returns the future's output plus any output that VM-side
163/// closures forwarded into the context, which the dispatch loop appends to the
164/// real parent VM. Cancel-safe: if the returned future is dropped, the ctx +
165/// child `Vm` are dropped with it.
166pub(crate) fn run_async_builtin_with<F, M>(
167    child: Vm,
168    make_fut: M,
169) -> impl Future<Output = (F::Output, String)>
170where
171    F: Future + Send,
172    M: FnOnce(AsyncBuiltinCtx) -> F,
173{
174    // Build the context + scope synchronously so the by-value `child: Vm` moves
175    // onto the heap *before* any async state machine exists. If this were
176    // an `async fn`, the future would reserve a Vm-sized slot for `child` up to
177    // its first await, and that bloat propagates into every caller's stack
178    // frame, which can trip clippy::large_stack_frames in large dispatch
179    // functions.
180    let ctx = AsyncBuiltinCtx::new(child);
181    let registry = ctx.pool_registry();
182    let sink = Arc::clone(&ctx.child);
183    let fut = make_fut(ctx);
184    async move {
185        let output = crate::stdlib::pool::with_pool_registry_scope(registry, fut).await;
186        let captured = sink.lock().take_output();
187        (output, captured)
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    use crate::Vm;
195
196    #[tokio::test]
197    async fn explicit_ctx_mints_child_and_captures_forwarded_output() {
198        let (present, captured) = run_async_builtin_with(Vm::new(), |ctx| async move {
199            // The handler holds the explicit ctx — no ambient lookup needed.
200            let _child = ctx.child_vm();
201            ctx.forward_output("hello ");
202            ctx.forward_output("world");
203            true
204        })
205        .await;
206        assert!(present);
207        // `forward_output` appends into the same buffer the dispatch loop drains.
208        assert_eq!(captured, "hello world");
209    }
210
211    #[tokio::test]
212    async fn child_context_has_independent_output_buffer() {
213        let (_result, captured) = run_async_builtin_with(Vm::new(), |ctx| async move {
214            let child = ctx.child_ctx();
215            child.forward_output("child");
216            ctx.forward_output("parent");
217        })
218        .await;
219        assert_eq!(captured, "parent");
220    }
221
222    #[tokio::test]
223    async fn cancelled_scope_strands_nothing() {
224        use std::future::pending;
225        // Build a future that never completes, then drop it without polling to
226        // completion. The ctx is owned by that future, so dropping it releases
227        // the child VM without any ambient cleanup.
228        let never = run_async_builtin_with(Vm::new(), |_ctx| pending::<()>());
229        drop(never);
230    }
231}