Skip to content
Draft
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
33 changes: 33 additions & 0 deletions crates/wasmtime/src/runtime/component/concurrent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2733,6 +2733,39 @@ impl StoreOpaque {
Ok(())
}

/// Dual of `host_task_create` for a host call that failed while it was
/// still a deferred host call.
///
/// The deferred host call that `host_task_create` recorded is removed and
/// the caller becomes the current thread again, as `host_task_delete`
/// does, so that a Store which keeps running host work after the failure
/// does not see a deferred call context without its deferred thread.
/// Nothing changes when the call is no longer deferred: `host_task_delete`
/// already ran, or the call was materialized into a host task.
pub(crate) fn host_task_delete_after_error(
&mut self,
original_task: EnteredHostTask,
) -> Result<()> {
match original_task {
Some(caller) => {
let CurrentThread::DeferredHost(current) = self.current_thread()? else {
return Ok(());
};
debug_assert!(
current == caller,
"a failed host call left another deferred call"
);
self.set_thread(caller)?;
let state = self.concurrent_state_mut()?;
state.deferred_host_call.take();
state.deferred_host_call_context.take();
state.debug_assert_deferred_host_invariant();
}
None => self.exit_call_not_concurrent(),
}
Ok(())
}

/// Helper function to retrieve the `InstanceState` for the
/// specified instance.
fn instance_state(&mut self, instance: RuntimeInstance) -> &mut InstanceState {
Expand Down
4 changes: 4 additions & 0 deletions crates/wasmtime/src/runtime/component/concurrent_disabled.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,10 @@ impl StoreOpaque {
Ok(self.exit_call_not_concurrent())
}

pub(crate) fn host_task_delete_after_error(&mut self, (): ()) -> Result<()> {
Ok(self.exit_call_not_concurrent())
}

pub(crate) fn current_materialized_host_task(&mut self) -> Result<()> {
Ok(())
}
Expand Down
61 changes: 60 additions & 1 deletion crates/wasmtime/src/runtime/component/func/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,36 @@ where
storage: &mut [MaybeUninit<ValRaw>],
) -> Result<()> {
let entered_host_task = store.0.host_task_create()?;
let mut task_deleted = false;
let result = self.call_sync_lower_entered(
store.as_context_mut(),
instance,
ty,
options,
storage,
entered_host_task,
&mut task_deleted,
);
if result.is_err() && !task_deleted {
store.0.host_task_delete_after_error(entered_host_task)?;
}
result
}

/// The part of `call_sync_lower` that runs inside the host task entered
/// by `host_task_create`. `task_deleted` records whether it reached
/// `host_task_delete`, so that its caller leaves the task exactly once on
/// an error.
fn call_sync_lower_entered(
&self,
mut store: StoreContextMut<'_, T>,
instance: Instance,
ty: TypeFuncIndex,
options: OptionsIndex,
storage: &mut [MaybeUninit<ValRaw>],
entered_host_task: EnteredHostTask,
task_deleted: &mut bool,
) -> Result<()> {
let mut lift = LiftContext::new(store.0.store_opaque_mut(), options, instance)?;
let (params, rest) = self.load_params(&mut lift, ty, MAX_FLAT_PARAMS, storage)?;

Expand Down Expand Up @@ -613,6 +642,7 @@ where
let materialized_host_task = lower.store.0.current_materialized_host_task()?;
#[cfg(feature = "component-model-async")]
let observer = lower.store.0.take_current_terminal_observer()?;
*task_deleted = true;
lower
.store
.0
Expand All @@ -632,20 +662,49 @@ where
/// be either sync or async, and that's handled here too.
#[cfg(feature = "component-model-async")]
fn call_async_lower(
&self,
mut store: StoreContextMut<'_, T>,
instance: Instance,
ty: TypeFuncIndex,
options: OptionsIndex,
storage: &mut [MaybeUninit<ValRaw>],
) -> Result<()> {
let entered_host_task = store.0.host_task_create()?;
let result = self.call_async_lower_entered(
store.as_context_mut(),
instance,
ty,
options,
storage,
entered_host_task,
);
// Async lowering needs concurrency support, so the task is a deferred
// host call until `lower` deletes it or the call is materialized;
// `host_task_delete_after_error` leaves it alone in both cases.
if result.is_err() {
store.0.host_task_delete_after_error(entered_host_task)?;
}
result
}

/// The part of `call_async_lower` that runs inside the host task entered
/// by `host_task_create`.
#[cfg(feature = "component-model-async")]
fn call_async_lower_entered(
&self,
store: StoreContextMut<'_, T>,
instance: Instance,
ty: TypeFuncIndex,
options: OptionsIndex,
storage: &mut [MaybeUninit<ValRaw>],
entered_host_task: EnteredHostTask,
) -> Result<()> {
use wasmtime_environ::component::MAX_FLAT_ASYNC_PARAMS;

let (component, store) = instance.component_and_store_mut(store.0);
let mut store = StoreContextMut(store);
let types = component.types();
let fty = &types[ty];
let entered_host_task = store.0.host_task_create()?;

// Lift the parameters, either from flat storage or from linear
// memory.
Expand Down
113 changes: 113 additions & 0 deletions crates/wasmtime/tests/guest_task_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -643,3 +643,116 @@ async fn legacy_async_resource_destructor_keeps_ambient_guest_task_context() ->
let run = instance.get_typed_func::<(Resource<u32>,), ()>(&mut store, "run")?;
run.call_async(&mut store, (Resource::new_own(1),)).await
}

// A host call that fails, whether in the host function or while lifting its
// parameters, leaves no deferred host call behind, so the Store can keep
// running host work after the trap, such as a host task that the guest left
// pending.
#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn failed_host_call_leaves_no_deferred_host_call() -> Result<()> {
let mut config = Config::new();
config.wasm_component_model_async(true);
let engine = Engine::new(&config)?;
let mut linker = Linker::new(&engine);
linker.root().func_wrap_concurrent("pending", |_, ()| {
Box::pin(async {
std::future::pending::<()>().await;
Ok(())
})
})?;
linker
.root()
.func_wrap("fail", |_: StoreContextMut<()>, ()| -> Result<()> {
Err(wasmtime::format_err!("host failure"))
})?;
linker.root().func_wrap_concurrent("fail-async", |_, ()| {
Box::pin(async { Err::<(), _>(wasmtime::format_err!("host failure")) })
})?;
linker
.root()
.func_wrap("take", |_: StoreContextMut<()>, (_,): (String,)| Ok(()))?;

// Each case: how `run` makes the failing call, and the expected error.
let cases = [
("host error, sync lower", "(call $fail)", "host failure"),
(
"host error, async lower",
"(drop (call $fail_async))",
"host failure",
),
(
"lift error, sync lower",
"(call $take (i32.const 65536) (i32.const 8))",
"out of bounds",
),
];
for (name, call, expected) in cases {
let component = Component::new(
&engine,
format!(
r#"
(component
(import "pending" (func $pending async))
(import "fail" (func $fail))
(import "fail-async" (func $fail-async async))
(import "take" (func $take (param "s" string)))

(core module $libc (memory (export "memory") 1))
(core instance $libc (instantiate $libc))

(core module $m
(import "" "pending" (func $pending (result i32)))
(import "" "fail" (func $fail))
(import "" "fail_async" (func $fail_async (result i32)))
(import "" "take" (func $take (param i32 i32)))

(func (export "run") (result i32)
(drop (call $pending))
{call}
unreachable)

(func (export "callback") (param i32 i32 i32) (result i32)
unreachable)
)

(core func $pending (canon lower (func $pending) async))
(core func $fail (canon lower (func $fail)))
(core func $fail_async (canon lower (func $fail-async) async))
(core func $take (canon lower (func $take) (memory (core memory $libc "memory"))))
(core instance $i (instantiate $m (with "" (instance
(export "pending" (func $pending))
(export "fail" (func $fail))
(export "fail_async" (func $fail_async))
(export "take" (func $take))
))))
(func (export "run") async
(canon lift (core func $i "run") async
(callback (core func $i "callback"))))
)
"#
),
)?;
let mut store = Store::new(&engine, ());
let instance = linker.instantiate_async(&mut store, &component).await?;
let func = instance.get_typed_func::<(), ()>(&mut store, "run")?;

let error = store
.run_concurrent(async |store| func.call_concurrent(store, ()).await)
.await
.and_then(std::convert::identity)
.unwrap_err();
assert!(format!("{error:?}").contains(expected), "{name}: {error:?}");

// Polling the pending host task switches threads, which checks the
// deferred host state.
store
.run_concurrent(async |_| {
for _ in 0..5 {
tokio::task::yield_now().await;
}
})
.await?;
}
Ok(())
}