Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

use reference counting for guest tasks (#14548)

Joel Diceee1a0973901d
diff --git a/crates/wasmtime/src/runtime/component/concurrent.rs b/crates/wasmtime/src/runtime/component/concurrent.rs
index c71a14bd8f..b281236d0b 100644
--- a/crates/wasmtime/src/runtime/component/concurrent.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent.rs
@@ -2025,7 +2025,6 @@ impl StoreOpaque {
} else {
Caller::Host {
tx: None,
- host_future_present: false,
caller: self.materialize_host_task_id()?,
}
};
@@ -2106,7 +2105,10 @@ impl StoreOpaque {
self.switch_or_trap_if_may_not_suspend(instance)?;
}
- self.cleanup_thread(thread, instance, CleanupTask::Yes)?;
+ self.cleanup_thread(thread, instance)?;
+
+ self.concurrent_state_mut()?
+ .decrement_task_ref_count(thread.task)?;
let state = self.concurrent_state_mut()?;
let Some(item) = state.saved_next_switch_items.pop() else {
@@ -2171,7 +2173,7 @@ impl StoreOpaque {
"delete host task with caller {original_task:?} and materialized as {materialized_task:?}"
);
if let Some(task) = materialized_task {
- Waitable::Host(task).delete_from(self)?;
+ self.concurrent_state_mut()?.delete_host_task(task)?;
}
}
None => {
@@ -2570,7 +2572,6 @@ impl StoreOpaque {
&mut self,
guest_thread: QualifiedThreadId,
runtime_instance: RuntimeInstance,
- cleanup_task: CleanupTask,
) -> Result<()> {
let state = self.concurrent_state_mut()?;
// If we never suspended, we never had a chance to deliver a subtask
@@ -2589,13 +2590,12 @@ impl StoreOpaque {
for waitable in mem::take(&mut state.get_mut(sync_call_set)?.ready) {
if let Some(Event::Subtask {
status: Status::Returned | Status::ReturnCancelled,
- }) = waitable.common(self.concurrent_state_mut()?)?.event
+ }) = waitable.common(state)?.event
{
- waitable.delete_from(self)?;
+ waitable.delete_from(state)?;
}
}
- let state = self.concurrent_state_mut()?;
state.delete(guest_thread.thread)?;
state.delete(sync_call_set)?;
let task = state.get_mut(guest_thread.task)?;
@@ -2604,7 +2604,6 @@ impl StoreOpaque {
if task.threads.is_empty() && !task.returned_or_cancelled() {
bail!(Trap::NoAsyncResult);
}
- let ready_to_delete = task.ready_to_delete();
if !task.decremented_interesting_task_count && task.exited && task.returned_or_cancelled() {
task.decremented_interesting_task_count = true;
@@ -2618,14 +2617,7 @@ impl StoreOpaque {
}
}
- match cleanup_task {
- CleanupTask::Yes => {
- if ready_to_delete {
- Waitable::Guest(guest_thread.task).delete_from(self)?;
- }
- }
- CleanupTask::No => {}
- }
+ state.decrement_task_ref_count(guest_thread.task)?;
Ok(())
}
@@ -2668,7 +2660,6 @@ impl StoreOpaque {
thread,
},
caller_instance,
- CleanupTask::No,
)?;
// Not yet started; cancel and remove from pending
@@ -2746,11 +2737,6 @@ impl StoreOpaque {
}
}
-enum CleanupTask {
- Yes,
- No,
-}
-
impl Instance {
/// Get the next pending event for the specified task and (optional)
/// waitable set, along with the waitable handle if applicable.
@@ -2851,7 +2837,7 @@ impl Instance {
// exiting this thread:
store.switch_or_trap_if_may_not_suspend(runtime_instance)?;
- store.cleanup_thread(guest_thread, runtime_instance, CleanupTask::Yes)?;
+ store.cleanup_thread(guest_thread, runtime_instance)?;
}
callback_code::YIELD => {
// Set `GuestTask::wake_on_cancel` to allow `subtask.cancel` to
@@ -3211,7 +3197,7 @@ impl Instance {
}
// This is a callback-less call, so the implicit thread has now completed
- store.cleanup_thread(guest_thread, callee_instance, CleanupTask::Yes)?;
+ store.cleanup_thread(guest_thread, callee_instance)?;
Ok(())
})
};
@@ -3643,10 +3629,12 @@ impl Instance {
// Reset the current thread to point to the caller as it resumes control.
store.0.set_thread(caller)?;
+
store
.0
.concurrent_state_mut()?
.set_thread_running(caller.thread)?;
+
log::trace!("popped current thread {guest_thread:?}; new thread is {caller:?}");
if async_caller {
@@ -3659,17 +3647,18 @@ impl Instance {
// if any, has been stashed in `GuestTask::sync_result`.
let state = store.0.concurrent_state_mut()?;
let task = state.get_mut(guest_thread.task)?;
- if let Some(result) = task.sync_result.take()? {
- if let Some(result) = result {
- storage[0] = MaybeUninit::new(result);
- }
-
- if task.exited && task.ready_to_delete() {
- Waitable::Guest(guest_thread.task).delete_from(store.0)?;
- }
+ if let Some(Some(result)) = task.sync_result.take()? {
+ storage[0] = MaybeUninit::new(result);
}
}
+ if status == Status::Returned {
+ store
+ .0
+ .concurrent_state_mut()?
+ .decrement_task_ref_count(guest_thread.task)?;
+ }
+
Ok(())
}
@@ -4043,7 +4032,7 @@ impl Instance {
.subtask_remove(task_id)?;
let concurrent_state = store.concurrent_state_mut()?;
- let (waitable, delete) = if is_host {
+ let waitable = if is_host {
let id = TableId::<HostTask>::new(rep);
let task = concurrent_state.get_mut(id)?;
match &task.state {
@@ -4056,17 +4045,14 @@ impl Instance {
}
}
- (Waitable::Host(id), true)
+ Waitable::Host(id)
} else {
let id = TableId::<GuestTask>::new(rep);
let task = concurrent_state.get_mut(id)?;
if task.lift_result.is_some() {
bail!(Trap::SubtaskDropNotResolved);
}
- (
- Waitable::Guest(id),
- concurrent_state.get_mut(id)?.ready_to_delete(),
- )
+ Waitable::Guest(id)
};
waitable.common(concurrent_state)?.handle = None;
@@ -4077,9 +4063,7 @@ impl Instance {
bail!(Trap::SubtaskDropNotResolved);
}
- if delete {
- waitable.delete_from(store)?;
- }
+ waitable.delete_from(concurrent_state)?;
log::trace!("subtask_drop {waitable:?} (handle {task_id})");
Ok(())
@@ -4206,9 +4190,7 @@ impl Instance {
.0
.switch_or_trap_if_may_not_suspend(runtime_instance)?;
- store
- .0
- .cleanup_thread(guest_thread, runtime_instance, CleanupTask::Yes)?;
+ store.0.cleanup_thread(guest_thread, runtime_instance)?;
log::trace!("explicit thread {guest_thread:?} completed");
let state = store.0.concurrent_state_mut()?;
@@ -5245,9 +5227,6 @@ enum Caller {
Host {
/// If present, may be used to deliver the result.
tx: Option<oneshot::Sender<LiftedResult>>,
- /// If true, there's a host future that must be dropped before the task
- /// can be deleted.
- host_future_present: bool,
/// The host task which called into the guest, or `None` for a call from
/// the top-level host. The task may belong to an entirely unrelated
/// top-level component instance than the one the host called into.
@@ -5419,6 +5398,7 @@ impl GuestThread {
dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync,
>,
) -> Result<Self> {
+ state.increment_task_ref_count(parent_task)?;
let sync_call_set = state.push(WaitableSet {
is_sync_call_set: true,
..WaitableSet::default()
@@ -5459,13 +5439,6 @@ impl SyncResult {
}
}
-#[derive(Debug)]
-enum HostFutureState {
- NotApplicable,
- Live,
- Dropped,
-}
-
/// Represents a pending guest task.
pub(crate) struct GuestTask {
/// See `WaitableCommon`
@@ -5510,19 +5483,22 @@ pub(crate) struct GuestTask {
exited: bool,
/// Threads belonging to this task
threads: HashSet<TableId<GuestThread>>,
- /// The state of the host future that represents an async task, which must
- /// be dropped before we can delete the task.
- host_future_state: HostFutureState,
/// Indicates whether this task was created for a call to an async-typed
/// export.
async_typed: bool,
/// Indicates whether this task was created for a call to an async-lifted
/// export.
async_lifted: bool,
-
+ /// Whether `ConcurrentState::interesting_tasks` has been decremented for
+ /// this task yet.
decremented_interesting_task_count: bool,
-
+ /// The `TaskGroup` to which this task belongs.
group: TaskGroupId,
+ /// The number of outstanding references to this task.
+ ///
+ /// When this goes to zero, the task will be removed from
+ /// `ConcurrentState::table`.
+ ref_count: usize,
}
impl GuestTask {
@@ -5536,29 +5512,6 @@ impl GuestTask {
self.lift_result.is_none()
}
- fn ready_to_delete(&self) -> bool {
- let threads_completed = self.threads.is_empty();
- let has_sync_result = matches!(self.sync_result, SyncResult::Produced(_));
- let pending_completion_event = matches!(
- self.common.event,
- Some(Event::Subtask {
- status: Status::Returned | Status::ReturnCancelled
- })
- );
- let ready = threads_completed
- && !has_sync_result
- && !pending_completion_event
- && !matches!(self.host_future_state, HostFutureState::Live);
- log::trace!(
- "ready to delete? {ready} (threads_completed: {}, has_sync_result: {}, pending_completion_event: {}, host_future_state: {:?})",
- threads_completed,
- has_sync_result,
- pending_completion_event,
- self.host_future_state
- );
- ready
- }
-
fn new(
state: &mut ConcurrentState,
lower_params: RawLower,
@@ -5569,20 +5522,6 @@ impl GuestTask {
async_typed: bool,
async_lifted: bool,
) -> Result<QualifiedThreadId> {
- let host_future_state = match &caller {
- Caller::Guest { .. } => HostFutureState::NotApplicable,
- Caller::Host {
- host_future_present,
- ..
- } => {
- if *host_future_present {
- HostFutureState::Live
- } else {
- HostFutureState::NotApplicable
- }
- }
- };
-
let group = match caller {
Caller::Guest { thread } => {
let group = state.get_mut(thread.task)?.group;
@@ -5607,11 +5546,13 @@ impl GuestTask {
event: None,
exited: false,
threads: HashSet::new(),
- host_future_state,
async_typed,
async_lifted,
decremented_interesting_task_count: false,
group,
+ // One for the caller and one for the implicit guest thread we're
+ // about to create:
+ ref_count: 2,
})?;
let new_thread = GuestThread::new_implicit(state, task)?;
let thread = state.push(new_thread)?;
@@ -5780,37 +5721,14 @@ impl Waitable {
Ok(())
}
- /// Remove this waitable from the store's rep table.
- fn delete_from(&self, store: &mut StoreOpaque) -> Result<()> {
+ /// Remove this waitable from the store's rep table (or decrement the ref
+ /// count if it's a guest task).
+ fn delete_from(&self, state: &mut ConcurrentState) -> Result<()> {
match self {
- Self::Host(task) => {
- log::trace!("delete host task {task:?}");
- let state = store.concurrent_state_mut()?;
- let task = state.delete(*task)?;
-
- state.decrement_group_ref_count(task.group)?;
- }
- Self::Guest(task) => {
- log::trace!("delete guest task {task:?}");
- let state = store.concurrent_state_mut()?;
- let task = state.delete(*task)?;
-
- state.decrement_group_ref_count(task.group)?;
-
- // When a guest task is created it increments the
- // `ConcurrentState::interesting_tasks` counter, and that needs
- // to be paired with a decrement. There are a few situations in
- // which the decrement needs to happen which don't all funnel
- // through here, so in lieu of that at least try to catch issues
- // where we forgot to do a decrement.
- debug_assert!(task.decremented_interesting_task_count);
- }
- Self::Transmit(task) => {
- store.concurrent_state_mut()?.delete(*task)?;
- }
+ Self::Host(task) => state.delete_host_task(*task),
+ Self::Guest(task) => state.decrement_task_ref_count(*task),
+ Self::Transmit(task) => Ok(state.delete(*task).map(drop)?),
}
-
- Ok(())
}
}
@@ -6636,6 +6554,43 @@ impl ConcurrentState {
_ => bail_bug!("current scope is not a deferred host scope"),
}
}
+
+ fn increment_task_ref_count(&mut self, task: TableId<GuestTask>) -> Result<()> {
+ let count = &mut self.get_mut(task)?.ref_count;
+ *count += 1;
+ log::trace!("increment {task:?} to {count}");
+ Ok(())
+ }
+
+ fn decrement_task_ref_count(&mut self, task: TableId<GuestTask>) -> Result<()> {
+ let count = &mut self.get_mut(task)?.ref_count;
+ if *count == 0 {
+ bail_bug!("can't decrement task ref count that's already zero");
+ }
+ *count -= 1;
+ log::trace!("decrement {task:?} to {count}");
+ if *count == 0 {
+ let task = self.delete(task)?;
+
+ self.decrement_group_ref_count(task.group)?;
+
+ // When a guest task is created it increments the
+ // `ConcurrentState::interesting_tasks` counter, and that needs
+ // to be paired with a decrement. There are a few situations in
+ // which the decrement needs to happen which don't all funnel
+ // through here, so in lieu of that at least try to catch issues
+ // where we forgot to do a decrement.
+ debug_assert!(task.decremented_interesting_task_count);
+ }
+ Ok(())
+ }
+
+ fn delete_host_task(&mut self, task: TableId<HostTask>) -> Result<()> {
+ log::trace!("delete host task {task:?}");
+ let task = self.delete(task)?;
+
+ self.decrement_group_ref_count(task.group)
+ }
}
/// Provide a type hint to compiler about the shape of a parameter lower
@@ -6713,12 +6668,21 @@ pub(crate) struct PreparedCall<R> {
}
impl<R> PreparedCall<R> {
- /// Get a copy of the `TaskId` for this `PreparedCall`.
- pub(crate) fn task_id(&self) -> TaskId {
- TaskId {
+ /// Acquire a reference to the `TaskId` for this `PreparedCall`.
+ ///
+ /// Note that this increments the reference count for the task, and
+ /// `TaskId::host_future_dropped` decrements it. Hence,
+ /// `TaskId::host_future_dropped` _must_ be called before the `TaskId` is
+ /// dropped to avoid leaking the task.
+ pub(crate) fn acquire_task_id(&self, store: &mut StoreOpaque) -> Result<TaskId> {
+ store
+ .concurrent_state_mut()?
+ .increment_task_ref_count(self.thread.task)?;
+
+ Ok(TaskId {
task: self.thread.task,
runtime_instance: self.runtime_instance,
- }
+ })
}
}
@@ -6729,26 +6693,26 @@ pub(crate) struct TaskId {
}
impl TaskId {
- /// The host future for an async task was dropped. If the parameters have not been lowered yet,
- /// it is no longer valid to do so, as the lowering closure would see a dangling pointer. In this case,
- /// we delete the task eagerly. Otherwise, there may be running threads, or ones that are suspended
- /// and can be resumed by other tasks for this component, so we mark the future as dropped
- /// and delete the task when all threads are done.
+ /// The host future for an async task was dropped. If the parameters have
+ /// not been lowered yet, it is no longer valid to do so, as the lowering
+ /// closure would see a dangling pointer. In this case, we clear
+ /// `GuestTask::lower_params` and cancel the task to ensure that doesn't
+ /// happen. If the parameters _have_ already been lowered, then the closure
+ /// is no longer reachable, in which case we only need to decrement the task
+ /// refcount.
pub(crate) fn host_future_dropped(&self, store: &mut StoreOpaque) -> Result<()> {
let task = store.concurrent_state_mut()?.get_mut(self.task)?;
- let delete = if !task.already_lowered_parameters() {
+ if !task.already_lowered_parameters() {
store.cancel_guest_subtask_without_lowered_parameters(
self.runtime_instance,
self.task,
)?;
- true
- } else {
- task.host_future_state = HostFutureState::Dropped;
- task.ready_to_delete()
- };
- if delete {
- Waitable::Guest(self.task).delete_from(store)?
}
+
+ store
+ .concurrent_state_mut()?
+ .decrement_task_ref_count(self.task)?;
+
Ok(())
}
}
@@ -6762,7 +6726,6 @@ pub(crate) fn prepare_call<T, R>(
mut store: StoreContextMut<T>,
handle: Func,
param_count: usize,
- host_future_present: bool,
lower_params: impl FnOnce(StoreContextMut<T>, &mut [MaybeUninit<ValRaw>]) -> Result<()>
+ Send
+ Sync
@@ -6813,7 +6776,6 @@ pub(crate) fn prepare_call<T, R>(
},
Caller::Host {
tx: Some(tx),
- host_future_present,
caller,
},
callback.map(|callback| {
@@ -6845,6 +6807,13 @@ pub(crate) struct StagedCall<R> {
store: StoreId,
rx: oneshot::Receiver<LiftedResult>,
_marker: PhantomData<fn() -> R>,
+ /// The task group to which the underlying task belongs.
+ ///
+ /// Note that this must be treated as opaque and not used to look up the
+ /// corresponding `TaskGroup` since we decrement the task refcount in
+ /// `StagedCall::new` which may cause the group to be disposed. This field
+ /// is only present to enable `[Typed]FuncCallConcurrent::group`, allowing
+ /// the embedder to correlate the task group with `TaskGroupHook` events.
group: TaskGroupId,
}
@@ -6852,6 +6821,10 @@ impl<R> StagedCall<R> {
/// Queue a call previously prepared using `prepare_call` to be run as part of
/// the associated `ComponentInstance`'s event loop.
///
+ /// Note that this has the side-effect of disposing the specified
+ /// `PrepareCall` and decrementing the task reference count since
+ /// `StagedCall` has no further need to access the task directly.
+ ///
/// The returned future will resolve to the result once it is available, but
/// must only be polled via the instance's event loop. See
/// `StoreContextMut::run_concurrent` for details.
@@ -6869,11 +6842,15 @@ impl<R> StagedCall<R> {
stage_call0(store.as_context_mut(), handle, thread, param_count)?;
+ let state = store.0.concurrent_state_mut()?;
+ let group = state.get_mut(thread.task)?.group;
+ state.decrement_task_ref_count(thread.task)?;
+
Ok(StagedCall {
store: store.0.id(),
rx,
_marker: PhantomData,
- group: store.0.concurrent_state_mut()?.get_mut(thread.task)?.group,
+ group,
})
}
}
diff --git a/crates/wasmtime/src/runtime/component/concurrent/func.rs b/crates/wasmtime/src/runtime/component/concurrent/func.rs
index b0976868e2..ee710b1233 100644
--- a/crates/wasmtime/src/runtime/component/concurrent/func.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent/func.rs
@@ -160,7 +160,7 @@ impl Func {
/// Completes a call that was initiated via
/// [`Func::start_call_concurrent`].
- pub async fn finish_call_concurrent<T: Send>(
+ pub async fn finish_call_concurrent<T: Send + 'static>(
self,
accessor: impl AsAccessor<Data = T>,
call: FuncCallConcurrent<'_, T>,
@@ -193,7 +193,6 @@ impl Func {
store,
self,
MAX_FLAT_PARAMS,
- false,
move |store, params_out| {
Func::with_lower_context(instance, store, options, flags, ty, |cx, ty| {
Self::lower_args(cx, &params, ty, params_out)
@@ -236,7 +235,7 @@ where
{
let mut store = store.as_context_mut();
let ptr = SendSyncPtr::from(NonNull::from(&params).cast::<u8>());
- let prepared = self.prepare_call(store.as_context_mut(), true, move |cx, ty, dst| {
+ let prepared = self.prepare_call(store.as_context_mut(), move |cx, ty, dst| {
// SAFETY: The goal here is to get `Params`, a non-`'static`
// value, to live long enough to the lowering of the
// parameters. We're guaranteed that `Params` lives in the
@@ -270,16 +269,18 @@ where
}
}
- let mut wrapper = SignalOnDrop {
- store,
- task: prepared.task_id(),
- };
+ // This will increment the task's refcount, and the
+ // `TaskId::host_future_dropped` function called from
+ // `SignalOnDrop::drop` wiil decrement it.
+ let task = prepared.acquire_task_id(store.0)?;
+
+ let mut wrapper = SignalOnDrop { store, task };
let result = concurrent::StagedCall::new(wrapper.store.as_context_mut(), prepared)?;
wrapper
.store
.as_context_mut()
- .run_concurrent_trap_on_idle(async |_| Ok(result.await?))
+ .run_concurrent_trap_on_idle(async |_| result.await)
.await?
}
@@ -382,7 +383,7 @@ where
"cannot use `call_concurrent` Config::concurrency_support disabled",
);
- let prepared = self.prepare_call(store.as_context_mut(), false, move |cx, ty, dst| {
+ let prepared = self.prepare_call(store.as_context_mut(), move |cx, ty, dst| {
Self::lower_args(cx, ty, dst, &params)
})?;
let call = concurrent::StagedCall::new(store, prepared)?;
@@ -404,8 +405,8 @@ where
Params: 'static,
Return: 'static,
{
- // This is intentionally part of the public API but not used yet.
- // This'll likely want to be used in future refactorings.
+ // Intentionally not used today, but left here for future API
+ // compatibility with using this.
let _ = accessor;
call.call.await
}
@@ -417,7 +418,6 @@ where
fn prepare_call<T>(
self,
store: StoreContextMut<'_, T>,
- host_future_present: bool,
lower: impl FnOnce(
&mut LowerContext<T>,
InterfaceType,
@@ -450,7 +450,6 @@ where
store,
*self.func(),
param_count,
- host_future_present,
move |store, params_out| {
Func::with_lower_context(instance, store, options, flags, ty, |cx, ty| {
lower(cx, ty, params_out)
diff --git a/crates/wasmtime/src/runtime/component/concurrent/task_group_hook.rs b/crates/wasmtime/src/runtime/component/concurrent/task_group_hook.rs
index c941f64bc4..2d8c828803 100644
--- a/crates/wasmtime/src/runtime/component/concurrent/task_group_hook.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent/task_group_hook.rs
@@ -1,3 +1,4 @@
+use crate::bail_bug;
use crate::component::concurrent::table::{TableDebug, TableId};
use crate::component::concurrent::{ConcurrentState, CurrentThread};
use crate::error::Result;
@@ -195,7 +196,9 @@ impl ConcurrentState {
pub(super) fn decrement_group_ref_count(&mut self, group: TaskGroupId) -> Result<()> {
let count = &mut self.get_mut(group.0)?.ref_count;
- assert!(*count >= 1);
+ if *count == 0 {
+ bail_bug!("can't decrement task group ref count that's already zero");
+ }
*count -= 1;
log::trace!("decrement {group:?} to {count}");
if *count == 0 {
diff --git a/tests/all/component_model/async.rs b/tests/all/component_model/async.rs
index 66387c1545..c338890b6c 100644
--- a/tests/all/component_model/async.rs
+++ b/tests/all/component_model/async.rs
@@ -2266,3 +2266,75 @@ async fn retry_cancelled_future_write_to_host() -> Result<()> {
}
}
}
+
+const THUNK_COMPONENT: &str = r#"
+ (component
+ (core module $m
+ (func (export "thunk"))
+ )
+ (core instance $i (instantiate $m))
+ (func (export "thunk") async
+ (canon lift (core func $i "thunk"))
+ )
+ )
+"#;
+
+/// Dropping the result of `start_call_concurrent` outside of the store's event
+/// loop should not panic.
+#[tokio::test]
+#[cfg_attr(miri, ignore)]
+async fn drop_start_call_concurrent_outside_event_loop() -> Result<()> {
+ let engine = super::async_engine();
+ let component = Component::new(&engine, THUNK_COMPONENT)?;
+ let mut store = Store::new(&engine, ());
+ let instance = Linker::new(&engine)
+ .instantiate_async(&mut store, &component)
+ .await?;
+
+ let thunk = instance.get_typed_func::<(), ()>(&mut store, "thunk")?;
+
+ let call = thunk.start_call_concurrent(&mut store, ())?;
+ drop(call);
+
+ Ok(())
+}
+
+/// An error returned from `TaskGroupHook::handle_finish` for a
+/// `call_concurrent` should not panic.
+#[tokio::test]
+#[cfg_attr(miri, ignore)]
+async fn task_group_hook_finish_error_call_concurrent() -> Result<()> {
+ _ = env_logger::try_init();
+ struct FailFinish;
+
+ impl TaskGroupHook for FailFinish {
+ fn handle_start(&mut self, _: TaskGroupId) -> Result<()> {
+ Ok(())
+ }
+ fn handle_enter(&mut self, _: TaskGroupId) -> Result<()> {
+ Ok(())
+ }
+ fn handle_exit(&mut self, _: TaskGroupId) -> Result<()> {
+ Ok(())
+ }
+ fn handle_finish(&mut self, _: TaskGroupId) -> Result<()> {
+ wasmtime::bail!("handle_finish failed")
+ }
+ }
+
+ let engine = super::async_engine();
+ let component = Component::new(&engine, THUNK_COMPONENT)?;
+ let mut store = Store::new(&engine, ());
+ let instance = Linker::new(&engine)
+ .instantiate_async(&mut store, &component)
+ .await?;
+ let thunk = instance.get_typed_func::<(), ()>(&mut store, "thunk")?;
+ store.task_group_hook(FailFinish);
+
+ let result = store
+ .run_concurrent(async |store| thunk.call_concurrent(store, ()).await)
+ .await;
+ assert!(result.is_err() || result.unwrap().is_err());
+
+ Ok(())
+}
diff --git a/tests/misc_testsuite/component-model/async/subtask-drop-exited.wast b/tests/misc_testsuite/component-model/async/subtask-drop-exited.wast
new file mode 100644
index 0000000000..a71a41f5c8
--- /dev/null
+++ b/tests/misc_testsuite/component-model/async/subtask-drop-exited.wast
@@ -0,0 +1,78 @@
+;;! component_model_async = true
+;;! reference_types = true
+;;! gc_types = true
+
+(component
+ (component $C
+ (canon task.return (core func $task.return))
+
+ (core module $M
+ (import "" "task.return" (func $task.return))
+ (global $yield-count (mut i32) (i32.const 0))
+ (func (export "f") (result i32)
+ (i32.const 1 (; YIELD ;)))
+ (func (export "f-cb") (param i32 i32 i32) (result i32)
+ (if (i32.eq (global.get $yield-count) (i32.const 0))
+ (then (call $task.return)))
+ (global.set $yield-count (i32.add (global.get $yield-count) (i32.const 1)))
+ (if (result i32) (i32.ge_u (global.get $yield-count) (i32.const 5))
+ (then (i32.const 0 (; EXIT ;)))
+ (else (i32.const 1 (; YIELD ;)))))
+ )
+
+ (core instance $m (instantiate $M (with "" (instance
+ (export "task.return" (func $task.return))))))
+ (func $f (export "f") async (canon lift (core func $m "f") async (callback (core func $m "f-cb"))))
+ )
+
+ (component $D
+ (import "f" (func $f async))
+ (canon lower (func $f) async (core func $f))
+ (canon task.return (core func $task.return))
+ (canon subtask.drop (core func $subtask.drop))
+ (canon subtask.cancel (core func $subtask.cancel))
+
+ (core module $M
+ (import "" "task.return" (func $task.return))
+ (import "" "subtask.drop" (func $subtask.drop (param i32)))
+ (import "" "subtask.cancel" (func $subtask.cancel (param i32) (result i32)))
+ (import "" "f" (func $f (result i32)))
+ (global $subtask (mut i32) (i32.const 0))
+ (global $yield-count (mut i32) (i32.const 0))
+ (func (export "f") (result i32)
+ (local $result i32)
+ (local.set $result (call $f))
+ (if (i32.ne (i32.and (local.get $result) (i32.const 0xf)) (i32.const 1 (; STARTED ;)))
+ (then unreachable))
+ (global.set $subtask (i32.shr_u (local.get $result) (i32.const 4)))
+ (i32.const 1 (; YIELD ;)))
+ (func (export "f-cb") (param i32 i32 i32) (result i32)
+ (if (i32.eq (global.get $yield-count) (i32.const 0))
+ (then
+ (if (i32.ne (call $subtask.cancel (global.get $subtask)) (i32.const 2 (; RETURNED ;)))
+ (then unreachable))))
+ (global.set $yield-count (i32.add (global.get $yield-count) (i32.const 1)))
+ (if (result i32) (i32.ge_u (global.get $yield-count) (i32.const 10))
+ (then
+ (call $subtask.drop (global.get $subtask))
+ (call $task.return)
+ (i32.const 0 (; EXIT ;)))
+ (else (i32.const 1 (; YIELD ;)))))
+ )
+
+ (core instance $m (instantiate $M (with "" (instance
+ (export "f" (func $f))
+ (export "task.return" (func $task.return))
+ (export "subtask.drop" (func $subtask.drop))
+ (export "subtask.cancel" (func $subtask.cancel))))))
+ (func (export "f") async (canon lift (core func $m "f") async (callback (core func $m "f-cb"))))
+ )
+
+ (instance $c (instantiate $C))
+ (instance $d (instantiate $D
+ (with "f" (func $c "f"))
+ ))
+ (func (export "run") (alias export $d "f"))
+)
+
+(assert_return (invoke "run"))