A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Fix cancelling a future/stream while cancellation is in progress (#14665)
Alex Crichtonae9c64deabcc
diff --git a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rsindex 05f484f7f5..c99a43fc67 100644--- a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs+++ b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs@@ -4269,17 +4269,21 @@ impl Instance {TransmitLocalState::Read { .. } => {bail!("passed read end to `{{stream|future}}.cancel-write`")}+ TransmitLocalState::Cancelling => {+ bail!("stream or future write cancelled when a cancellation is already pending")+ }TransmitLocalState::Busy => {}}let transmit_id = store.concurrent_state_mut()?.get_mut(id)?.state;let code = self.cancel_write(store, caller, transmit_id, async_)?;- if !matches!(code, ReturnCode::Blocked) {- let state =- get_mut_by_index_from(self.id().get_mut(store).table_for_transmit(ty), ty, writer)?- .1;- if let TransmitLocalState::Busy = state {- *state = TransmitLocalState::Write { done: false };- }+ let state =+ get_mut_by_index_from(self.id().get_mut(store).table_for_transmit(ty), ty, writer)?.1;+ if let TransmitLocalState::Busy = state {+ *state = if matches!(code, ReturnCode::Blocked) {+ TransmitLocalState::Cancelling+ } else {+ TransmitLocalState::Write { done: false }+ };}Ok(code)}@@ -4304,17 +4308,21 @@ impl Instance {TransmitLocalState::Write { .. } => {bail!("passed write end to `{{stream|future}}.cancel-read`")}+ TransmitLocalState::Cancelling => {+ bail!("stream or future read cancelled when a cancellation is already pending")+ }TransmitLocalState::Busy => {}}let transmit_id = store.concurrent_state_mut()?.get_mut(id)?.state;let code = self.cancel_read(store, caller, transmit_id, async_)?;- if !matches!(code, ReturnCode::Blocked) {- let state =- get_mut_by_index_from(self.id().get_mut(store).table_for_transmit(ty), ty, reader)?- .1;- if let TransmitLocalState::Busy = state {- *state = TransmitLocalState::Read { done: false };- }+ let state =+ get_mut_by_index_from(self.id().get_mut(store).table_for_transmit(ty), ty, reader)?.1;+ if let TransmitLocalState::Busy = state {+ *state = if matches!(code, ReturnCode::Blocked) {+ TransmitLocalState::Cancelling+ } else {+ TransmitLocalState::Read { done: false }+ };}Ok(code)}@@ -5002,8 +5010,11 @@ impl Waitable {if rep != self.rep() {bail_bug!("unexpected rep mismatch");}- if *state != TransmitLocalState::Busy {- bail_bug!("expected state to be busy");+ if !matches!(+ *state,+ TransmitLocalState::Busy | TransmitLocalState::Cancelling+ ) {+ bail_bug!("expected state to be busy or cancelling");}let done = matches!(code, ReturnCode::Dropped(_));*state = match event {diff --git a/crates/wasmtime/src/runtime/vm/component/handle_table.rs b/crates/wasmtime/src/runtime/vm/component/handle_table.rsindex 978500ad44..50c9b6d019 100644--- a/crates/wasmtime/src/runtime/vm/component/handle_table.rs+++ b/crates/wasmtime/src/runtime/vm/component/handle_table.rs@@ -29,6 +29,9 @@ pub enum TransmitLocalState {},/// A read or write is in progress.Busy,+ /// A read or write is in progress and an asynchronous cancellation of it+ /// has been requested but has not yet completed.+ Cancelling,}/// Return value from [`HandleTable::remove_resource`].@@ -364,7 +367,9 @@ impl HandleTable {TransmitLocalState::Write { .. } => {bail!("handle is not a readable end of a stream")}- TransmitLocalState::Busy => bail!("cannot remove busy stream"),+ TransmitLocalState::Busy | TransmitLocalState::Cancelling => {+ bail!("cannot remove busy stream")+ }};(*rep, is_done)}@@ -390,7 +395,9 @@ impl HandleTable {TransmitLocalState::Read { .. } => {bail!("passed read end to `stream.drop-writable`")}- TransmitLocalState::Busy => bail!("cannot drop busy stream"),+ TransmitLocalState::Busy | TransmitLocalState::Cancelling => {+ bail!("cannot drop busy stream")+ }}*rep}@@ -467,7 +474,9 @@ impl HandleTable {TransmitLocalState::Write { .. } => {bail!("handle is not a readable end of a future")}- TransmitLocalState::Busy => bail!("cannot remove busy future"),+ TransmitLocalState::Busy | TransmitLocalState::Cancelling => {+ bail!("cannot remove busy future")+ }};(*rep, is_done)}@@ -495,7 +504,9 @@ impl HandleTable {TransmitLocalState::Read { .. } => {bail!("passed read end to `future.drop-writable`")}- TransmitLocalState::Busy => bail!("cannot drop busy future"),+ TransmitLocalState::Busy | TransmitLocalState::Cancelling => {+ bail!("cannot drop busy future")+ }};(*rep, is_done)}diff --git a/tests/all/component_model/async.rs b/tests/all/component_model/async.rsindex c338890b6c..cb07a798b0 100644--- a/tests/all/component_model/async.rs+++ b/tests/all/component_model/async.rs@@ -2338,3 +2338,73 @@ async fn task_group_hook_finish_error_call_concurrent() -> Result<()> {Ok(())}++#[tokio::test]+#[cfg_attr(miri, ignore)]+async fn cancel_read_while_cancelling() -> Result<()> {+ let component = r#"+ (component+ (core module $libc (memory (export "memory") 1))+ (core instance $libc (instantiate $libc))+ (type $s (stream u8))+ (core func $stream.read (canon stream.read $s async (memory (core memory $libc "memory"))))+ (core func $stream.cancel-read (canon stream.cancel-read $s async))+ (core module $m+ (import "" "stream.read" (func $stream.read (param i32 i32 i32) (result i32)))+ (import "" "stream.cancel-read" (func $stream.cancel-read (param i32) (result i32)))+ (func (export "run") (param $s i32)+ ;; Both the read and its cancellation block on the host.+ (if (i32.ne (call $stream.read (local.get $s) (i32.const 0) (i32.const 1))+ (i32.const -1))+ (then unreachable))+ (if (i32.ne (call $stream.cancel-read (local.get $s)) (i32.const -1))+ (then unreachable))+ ;; This must trap since a cancellation is already pending.+ (drop (call $stream.cancel-read (local.get $s)))+ unreachable)+ )+ (core instance $i (instantiate $m (with "" (instance+ (export "stream.read" (func $stream.read))+ (export "stream.cancel-read" (func $stream.cancel-read))+ ))))+ (func (export "run") (param "s" $s)+ (canon lift (core func $i "run")))+ )+ "#;++ let mut config = Config::new();+ config.wasm_component_model_async(true);+ config.wasm_component_model_more_async_builtins(true);+ let engine = Engine::new(&config)?;+ let component = Component::new(&engine, component)?;+ let mut store = Store::new(&engine, ());+ let instance = Linker::new(&engine)+ .instantiate_async(&mut store, &component)+ .await?;+ let run = instance.get_typed_func::<(StreamReader<u8>,), ()>(&mut store, "run")?;+ let reader = StreamReader::new(&mut store, Pending)?;+ let err = run.call_async(&mut store, (reader,)).await.unwrap_err();+ assert!(+ format!("{err:?}").contains("when a cancellation is already pending"),+ "{err:?}"+ );+ return Ok(());++ /// A producer which never produces anything.+ struct Pending;++ impl StreamProducer<()> for Pending {+ type Item = u8;+ type Buffer = Option<u8>;++ fn poll_produce<'a>(+ self: Pin<&mut Self>,+ _cx: &mut Context<'_>,+ _store: StoreContextMut<'a, ()>,+ _destination: Destination<'a, Self::Item, Self::Buffer>,+ _finish: bool,+ ) -> Poll<Result<StreamResult>> {+ Poll::Pending+ }+ }+}