Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/capabilities.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
74 changes: 60 additions & 14 deletions src/vm/asynchronous.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Value>) -> Result<Value> {
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
}
Expand Down Expand Up @@ -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")
}
Expand Down Expand Up @@ -665,8 +688,16 @@ async fn invoke<'a, E: Holder + 'a, L: Lane<E>>(
}
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 {
Expand All @@ -682,8 +713,9 @@ async fn invoke<'a, E: Holder + 'a, L: Lane<E>>(
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,
Expand Down Expand Up @@ -824,6 +856,9 @@ impl Driver<Worker> {
}
}

/// How often a [`Watch`] looks for an interruption.
pub(super) const WATCH_INTERVAL: Duration = Duration::from_millis(5);

struct Watch {
cancellation: CancellationToken,
deadline: Option<Instant>,
Expand All @@ -839,17 +874,20 @@ 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;
}
crate::asynchronous::pause(Duration::from_millis(5)).await;
crate::asynchronous::pause(WATCH_INTERVAL).await;
}
}
}
Expand Down Expand Up @@ -1513,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| {
Expand Down Expand Up @@ -1923,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(|_| ()),
Expand All @@ -1948,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(|_| ()),
Expand Down
170 changes: 170 additions & 0 deletions src/vm/asynchronous_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,173 @@ 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::<crate::Result<Value>>().await
})
}),
);
// 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::<crate::Result<Value>>()),
),
);
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 {
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}");
}
}
24 changes: 4 additions & 20 deletions src/vm/checked_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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:?}");
}
}

Expand Down Expand Up @@ -636,21 +628,17 @@ 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
.store(block.is_err_and(|e| is_internal(&e)), Ordering::Relaxed);
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()
})
}),
Expand All @@ -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);
}
}

Expand Down
Loading