From 818c68271c964e2a24cb5dbd0e1505c4a1f1fba1 Mon Sep 17 00:00:00 2001 From: Yori Date: Thu, 3 Dec 2026 18:16:46 -0500 Subject: [PATCH 1/4] Name the interval at which async host waits look for interruptions --- src/vm/asynchronous.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/vm/asynchronous.rs b/src/vm/asynchronous.rs index e17376520..70dc1cfe6 100644 --- a/src/vm/asynchronous.rs +++ b/src/vm/asynchronous.rs @@ -824,6 +824,9 @@ impl Driver { } } +/// How often a [`Watch`] looks for an interruption. +pub(super) const WATCH_INTERVAL: Duration = Duration::from_millis(5); + struct Watch { cancellation: CancellationToken, deadline: Option, @@ -849,7 +852,7 @@ impl Watch { { return; } - crate::asynchronous::pause(Duration::from_millis(5)).await; + crate::asynchronous::pause(WATCH_INTERVAL).await; } } } From e7994745df382a80929b649f72e71f6ba4254971 Mon Sep 17 00:00:00 2001 From: Yori Date: Thu, 3 Dec 2026 18:19:54 -0500 Subject: [PATCH 2/4] Let an async host waiting on its block receive the block's interruption The watch that interrupts async host futures fired as soon as the invocation was cancelled or latched an error, even while the host was only waiting on its own block. A block runs under the same limits and returns the interruption itself, so dropping the host first only lost the block's result. When the block had panicked, recovery then rethrew the panic past the host that would have caught it, and the call failed as a host error ("script worker failed: nested host panic") instead of with the latched kind. The block's own panic latches an internal error, so the race was open on every caught nested panic. The watch now stands aside while the host's latest poll left it waiting on a live block call; it interrupts the host at its next look once the host waits on anything else. --- docs/capabilities.md | 2 +- src/vm/asynchronous.rs | 69 ++++++++++++--- src/vm/asynchronous_tests.rs | 159 +++++++++++++++++++++++++++++++++++ 3 files changed, 216 insertions(+), 14 deletions(-) diff --git a/docs/capabilities.md b/docs/capabilities.md index 8bfdb213f..45a35d576 100644 --- a/docs/capabilities.md +++ b/docs/capabilities.md @@ -134,6 +134,6 @@ assert_eq!(result.value.as_int(), Some(21)); `Runner` executes script and synchronous host work on bounded blocking workers. A native async wait releases its worker so another invocation can run. A synchronous host callback that invokes an async block still occupies its existing worker and keeps its reservation until it returns. Nested script work uses that same thread, including with a single-thread blocking pool. No additional Tokio runtime is created. Calling an async method through `Script::call` produces a catchable host error requiring `Runner`. -Cancellation, deadlines and latched quota failures interrupt pending host futures. Host code must keep each future poll bounded and cooperate during synchronous work. A block's `break` and nonlocal `return` remain pending if the host ignores their control-flow error. Async or worker panics unwind the invocation and become host errors at the runner boundary. Dropping an invocation releases unreachable cycles without executing script cleanup effects; retained values stay valid and charged. +Cancellation, deadlines and latched quota failures interrupt pending host futures. A host future waiting on its block is not dropped: the block runs under the same limits and returns the interruption, or a panic it raised, to the host. Host code must keep each future poll bounded and cooperate during synchronous work. A block's `break` and nonlocal `return` remain pending if the host ignores their control-flow error. Async or worker panics unwind the invocation and become host errors at the runner boundary. Dropping an invocation releases unreachable cycles without executing script cleanup effects; retained values stay valid and charged. Dropping an unpolled block future has no effect. Dropping a polled block future cancels and retires the invocation, even if the host returns a successful value afterward. `context()` reports an error while its state remains on a retiring worker, and the engine recovers that worker before finishing the callback. Engine-owned suspended state, block arguments and bridge storage count against memory limits. Arbitrary allocations and captures made by trusted host code remain host-owned. diff --git a/src/vm/asynchronous.rs b/src/vm/asynchronous.rs index 70dc1cfe6..add6fb281 100644 --- a/src/vm/asynchronous.rs +++ b/src/vm/asynchronous.rs @@ -40,6 +40,10 @@ use tokio::{runtime::Handle, sync::Semaphore}; /// ``` pub struct AsyncHostCall<'a> { backend: &'a mut dyn Backend, + /// Whether the host's latest poll left it waiting on its block. A block + /// call sets it when its poll leaves the block pending and clears it when + /// it ends; the invocation clears it before each poll of the host. + waiting: &'a AtomicBool, } trait Backend: Send { @@ -101,13 +105,23 @@ impl AsyncHostCall<'_> { /// Arguments are isolated and accounted before script execution. `break` /// and nonlocal `return` remain pending even if the host ignores the returned /// control-flow error. Cancellation, exhausted limits and internal errors - /// cannot be swallowed. A nested panic is rethrown after retiring the block - /// and restoring the context. Catching it leaves the invocation terminal; - /// an earlier quota or cancellation failure keeps priority. + /// cannot be swallowed. While the host waits on the block, an interruption + /// reaches it through the block's result rather than by dropping the host's + /// future. A nested panic is rethrown after retiring the block and + /// restoring the context. Catching it leaves the invocation terminal; an + /// earlier quota or cancellation failure keeps priority. pub async fn call_block(&mut self, args: Vec) -> Result { let cancellation = self.backend.start_block(args)?; let mut guard = RetireOnDrop(Some(cancellation)); - let result = std::future::poll_fn(|cx| self.backend.poll_block(cx)).await; + let waiting = Waiting(self.waiting); + let result = std::future::poll_fn(|cx| { + let poll = self.backend.poll_block(cx); + if poll.is_pending() { + waiting.0.store(true, Ordering::Relaxed); + } + poll + }) + .await; guard.0 = None; result } @@ -253,6 +267,15 @@ impl Drop for RetireOnDrop { } } +/// Clears a host's waiting flag when its block call ends, including when the +/// host drops the call or the block's panic unwinds through it. +struct Waiting<'a>(&'a AtomicBool); +impl Drop for Waiting<'_> { + fn drop(&mut self) { + self.0.store(false, Ordering::Relaxed); + } +} + fn retiring() -> Error { Error::new(ErrorKind::Cancelled, "block execution is retiring") } @@ -665,8 +688,16 @@ async fn invoke<'a, E: Holder + 'a, L: Lane>( } Err(error) => return Ok(HostResult::Returned(Err(error))), }; + // A host waiting on its block is left to receive the interruption from + // that block, which runs under the same limits: dropping the host instead + // would lose the block's result, and a panic the host would have caught + // would escape the invocation. + let waiting = AtomicBool::new(false); let result = { - let mut handle = AsyncHostCall { backend: call }; + let mut handle = AsyncHostCall { + backend: call, + waiting: &waiting, + }; // Catch construction and polling before unwinding can poison the driver. // The block caller receives the panic only after its execution is restored. let future = async { @@ -682,8 +713,9 @@ async fn invoke<'a, E: Holder + 'a, L: Lane>( tokio::pin!(future); tokio::select! { biased; - _ = watch.wait() => HostResult::Returned(Err(retiring())), + _ = watch.wait(&waiting) => HostResult::Returned(Err(retiring())), result = std::future::poll_fn(|cx| { + waiting.store(false, Ordering::Relaxed); match catch_unwind(AssertUnwindSafe(|| future.as_mut().poll(cx))) { Ok(Poll::Ready(result)) => Poll::Ready(HostResult::Returned(result)), Ok(Poll::Pending) => Poll::Pending, @@ -842,13 +874,16 @@ impl Watch { } } - async fn wait(&self) { + /// Returns once the invocation is interrupted while its host is not + /// `waiting` on its block. + async fn wait(&self, waiting: &AtomicBool) { loop { - if self.cancellation.is_cancelled() - || self - .deadline - .is_some_and(|deadline| Instant::now() >= deadline) - || self.memory.interrupted.load(Ordering::Acquire) + if !waiting.load(Ordering::Relaxed) + && (self.cancellation.is_cancelled() + || self + .deadline + .is_some_and(|deadline| Instant::now() >= deadline) + || self.memory.interrupted.load(Ordering::Acquire)) { return; } @@ -1516,7 +1551,11 @@ mod tests { cancellation, }; { - let mut handle = AsyncHostCall { backend: &mut call }; + let waiting = AtomicBool::new(false); + let mut handle = AsyncHostCall { + backend: &mut call, + waiting: &waiting, + }; let future = handle.call_block(vec![]); tokio::pin!(future); std::future::poll_fn(|cx| { @@ -1926,8 +1965,10 @@ mod tests { failure: None, cancellation, }; + let waiting = AtomicBool::new(false); let mut call = AsyncHostCall { backend: &mut invocation, + waiting: &waiting, }; match access { "receiver" => call.receiver().map(|_| ()), @@ -1951,8 +1992,10 @@ mod tests { failure: None, cancellation, }; + let waiting = AtomicBool::new(false); let mut call = AsyncHostCall { backend: &mut invocation, + waiting: &waiting, }; let result = match access { "receiver" => call.receiver().map(|_| ()), diff --git a/src/vm/asynchronous_tests.rs b/src/vm/asynchronous_tests.rs index d33df7b77..3be1ce4d8 100644 --- a/src/vm/asynchronous_tests.rs +++ b/src/vm/asynchronous_tests.rs @@ -211,3 +211,162 @@ fn a_wake_during_a_blocking_poll_still_resumes_the_synchronous_bridge() { runtime.shutdown_timeout(Duration::from_secs(1)); assert_eq!(finished.expect("the call finished").unwrap(), Some(7)); } + +/// An interruption that a block raises reaches the host waiting on that +/// block through the block's own result. The invocation's watch must not drop +/// the host first: a panic the host would have caught then escapes the call +/// as a host error instead. +#[tokio::test] +#[cfg_attr(not(panic = "unwind"), ignore = "catching a panic requires unwinding")] +async fn a_host_waiting_on_its_block_receives_the_blocks_interruption() { + use std::{ + future::poll_fn, + panic::{AssertUnwindSafe, catch_unwind}, + sync::atomic::{AtomicUsize, Ordering}, + task::Poll, + }; + + for nested in [false, true] { + for kind in [ErrorKind::Internal, ErrorKind::Memory, ErrorKind::Cancelled] { + let label = format!("nested={nested}/kind={kind:?}"); + let entered = Arc::new(Notify::new()); + // One message, so the send never waits for its receive. + let (release, released) = std::sync::mpsc::sync_channel::<()>(1); + let released = Actor::new(released); + let caught = Arc::new(AtomicUsize::new(0)); + let mut engine = crate::Engine::new(); + let ready = entered.clone(); + engine.register("leaf", move |ctx, _| { + match kind { + // As a panic's own abandonment of the block latches. + ErrorKind::Internal => { + let _latched = + ctx.latch_internal::<()>(Err(super::host_blocks::abandoned().into())); + } + ErrorKind::Memory => { + let _ignored = ctx.bytes(&[0; 65_536]); + } + _ => ctx.cancellation().cancel(), + } + ready.notify_one(); + released + .with(|released| released.recv_timeout(Duration::from_secs(3))) + .unwrap(); + panic!("nested host panic"); + }); + let observed = caught.clone(); + engine.register_method( + "inspect", + HostMethod::new_async("inspect", move |call, _, _| { + let observed = observed.clone(); + Box::pin(async move { + let caught = { + let future = call.call_block(vec![]); + tokio::pin!(future); + poll_fn(|cx| { + match catch_unwind(AssertUnwindSafe(|| future.as_mut().poll(cx))) { + Ok(Poll::Pending) => Poll::Pending, + result => Poll::Ready(result), + } + }) + .await + }; + let panic = caught.expect_err("the block must propagate its panic"); + assert_eq!(panic.downcast_ref::<&str>(), Some(&"nested host panic")); + observed.fetch_add(1, Ordering::SeqCst); + Ok(Value::int(7)) + }) + }), + ); + engine.register_method( + "relay", + HostMethod::new_async("relay", |call, _, _| { + Box::pin(async move { call.call_block(vec![]).await }) + }), + ); + let leaf = if nested { "relay { leaf() }" } else { "leaf()" }; + let script = engine + .compile(&format!("def run -> any; inspect {{ {leaf} }}; end")) + .unwrap(); + let runner = Runner::new(1).unwrap(); + let options = CallOptions { + limits: crate::Limits { + memory_bytes: Some(32_768), + ..crate::Limits::default() + }, + ..CallOptions::default() + }; + let (outcome, ()) = tokio::join!( + within( + Duration::from_secs(3), + &label, + runner.call(script, "run".into(), vec![], options), + ), + async { + within(Duration::from_secs(3), &label, entered.notified()).await; + // The block holds its worker past the watch's next look, + // which comes before this pause ends. + pause(4 * super::asynchronous::WATCH_INTERVAL).await; + release.send(()).unwrap(); + }, + ); + let error = outcome.unwrap_err(); + assert_eq!(error.kind, kind, "{label}: {}", error.message); + assert_eq!(caught.load(Ordering::SeqCst), 1, "{label}"); + assert_eq!(runner.available_slots(), 1, "{label}"); + } + } +} + +/// A host that stops waiting on its block is interrupted again, whether it +/// dropped the block call it polled or still holds it unpolled. +#[tokio::test] +async fn a_host_that_stops_waiting_on_its_block_is_interrupted() { + use std::{future::poll_fn, task::Poll}; + + for hold in [false, true] { + let label = format!("hold={hold}"); + let entered = Arc::new(Notify::new()); + let ready = entered.clone(); + let mut engine = crate::Engine::new(); + engine.register_method( + "visit", + HostMethod::new_async("visit", move |call, _, _| { + let ready = ready.clone(); + Box::pin(async move { + let mut block = Box::pin(call.call_block(vec![])); + poll_fn(|cx| { + assert!(block.as_mut().poll(cx).is_pending()); + Poll::Ready(()) + }) + .await; + if !hold { + drop(block); + } + ready.notify_one(); + pending::>().await + }) + }), + ); + let script = engine.compile("def run -> any; visit { 7 }; end").unwrap(); + let runner = Runner::new(1).unwrap(); + let cancellation = crate::CancellationToken::new(); + let options = CallOptions { + cancellation: cancellation.clone(), + ..CallOptions::default() + }; + let (outcome, ()) = tokio::join!( + within( + Duration::from_secs(3), + &label, + runner.call(script, "run".into(), vec![], options), + ), + async { + within(Duration::from_secs(3), &label, entered.notified()).await; + cancellation.cancel(); + }, + ); + assert_eq!(outcome.unwrap_err().kind, ErrorKind::Cancelled, "{label}"); + assert_eq!(runner.available_slots(), 1, "{label}"); + } +} From 90f4f5f831e229070d2574306481febc7c07f2df Mon Sep 17 00:00:00 2001 From: Yori Date: Thu, 3 Dec 2026 18:19:55 -0500 Subject: [PATCH 3/4] Require an async callback to see its block's internal error The callback was allowed to be retired before it saw the error, because the watch could drop it while it waited on its block. That race is gone, so check what the callback observed again on every run. --- src/vm/checked_tests.rs | 24 ++++-------------------- 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/src/vm/checked_tests.rs b/src/vm/checked_tests.rs index e84b595f7..1a1405a88 100644 --- a/src/vm/checked_tests.rs +++ b/src/vm/checked_tests.rs @@ -150,19 +150,11 @@ struct Observed { impl Observed { fn check(&self, result: Result<()>, reaction: Reaction) { - self.check_terminal(result, reaction); - self.check_callback(reaction); - } - - fn check_terminal(&self, result: Result<()>, reaction: Reaction) { let error = result.expect_err("the corrupted block target must fail the call"); assert!(is_internal(&error), "{reaction:?}: {error}"); - assert_eq!(self.handlers.load(Ordering::Relaxed), 0, "{reaction:?}"); - } - - fn check_callback(&self, reaction: Reaction) { assert!(self.block.load(Ordering::Relaxed), "{reaction:?}"); assert!(self.later.load(Ordering::Relaxed), "{reaction:?}"); + assert_eq!(self.handlers.load(Ordering::Relaxed), 0, "{reaction:?}"); } } @@ -636,13 +628,10 @@ mod asynchronous { let observed = Arc::new(Observed::default()); let mut engine = marking(&observed); let seen = observed.clone(); - let finished = Arc::new(AtomicBool::new(false)); - let returned = finished.clone(); engine.register_method( "visit", HostMethod::new_async("visit", move |call, _, _| { let seen = seen.clone(); - let returned = returned.clone(); Box::pin(async move { let block = call.call_block(vec![]).await; seen.block @@ -650,7 +639,6 @@ mod asynchronous { let later = call.context().and_then(|ctx| ctx.checkpoint()); seen.later .store(later.is_err_and(|e| is_internal(&e)), Ordering::Relaxed); - returned.store(true, Ordering::Relaxed); reaction.result() }) }), @@ -664,13 +652,9 @@ mod asynchronous { let result = runner .call(script, "run".into(), vec![], CallOptions::default()) .await; - // The watchdog can retire the callback at its await as soon as - // the block latches Internal. Both outcomes must be terminal; - // only a callback that finished can have consumed the error. - observed.check_terminal(result.map(drop), reaction); - if finished.load(Ordering::Relaxed) { - observed.check_callback(reaction); - } + // The block's latched error reaches the callback waiting on it; + // the callback is not retired before it can see the error. + observed.check(result.map(drop), reaction); } } From bd5b5b5b2f8b7382e9d02593b3ab2712ae850c8c Mon Sep 17 00:00:00 2001 From: Yori Date: Thu, 3 Dec 2026 19:33:16 -0500 Subject: [PATCH 4/4] Keep the block pending in the stops-waiting test The test assumed a block of `7` is still pending at the host's first poll. On a slow runner the block's worker finished first, so the first poll returned the result and the host's assertion failed. The block now calls an async host that ends only on cancellation. --- src/vm/asynchronous_tests.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/vm/asynchronous_tests.rs b/src/vm/asynchronous_tests.rs index 3be1ce4d8..2b40283f0 100644 --- a/src/vm/asynchronous_tests.rs +++ b/src/vm/asynchronous_tests.rs @@ -348,7 +348,18 @@ async fn a_host_that_stops_waiting_on_its_block_is_interrupted() { }) }), ); - let script = engine.compile("def run -> any; visit { 7 }; end").unwrap(); + // The block can end only once cancelled, so it is still pending at + // the host's first poll however fast its worker runs. + engine.register_method( + "wait", + HostMethod::new_async( + "wait", + |_, _, _| Box::pin(pending::>()), + ), + ); + let script = engine + .compile("def run -> any; visit { wait() }; end") + .unwrap(); let runner = Runner::new(1).unwrap(); let cancellation = crate::CancellationToken::new(); let options = CallOptions {