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