Skip to content

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

Fix return code of cancelled stream reads/writes (#14953)

Alex Crichton160593b8feb3
diff --git a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
index 4001bf6c67..1d7875ecf1 100644
--- a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
@@ -2313,11 +2313,26 @@ impl fmt::Debug for ReadState {
}
}
-fn return_code(kind: TransmitKind, state: StreamResult, count: ItemCount) -> Result<ReturnCode> {
- Ok(match state {
- StreamResult::Dropped => ReturnCode::Dropped(count),
- StreamResult::Completed => ReturnCode::completed(kind, count),
- StreamResult::Cancelled => ReturnCode::Cancelled(count),
+fn return_code(
+ kind: TransmitKind,
+ state: StreamResult,
+ count: ItemCount,
+ cancel: bool,
+) -> Result<ReturnCode> {
+ // The spec says that for streams the priority of return codes is
+ //
+ // DROPPED > CANCELLED > COMPLETED
+ //
+ // where for futures it's
+ //
+ // COMPLETED > DROPPED > CANCELLED
+ //
+ // which is what's implemented here.
+ Ok(match (state, kind) {
+ (StreamResult::Dropped, _) => ReturnCode::Dropped(count),
+ (StreamResult::Completed, TransmitKind::Stream) if cancel => ReturnCode::Cancelled(count),
+ (StreamResult::Completed, _) => ReturnCode::completed(kind, count),
+ (StreamResult::Cancelled, _) => ReturnCode::Cancelled(count),
})
}
@@ -2329,12 +2344,13 @@ fn settle_host_read(
let ReadState::HostReady {
consume,
guest_offset,
+ cancel,
..
} = mem::replace(&mut transmit.read, ReadState::Open)
else {
bail_bug!("expected ReadState::HostReady")
};
- let code = return_code(kind, state, guest_offset)?;
+ let code = return_code(kind, state, guest_offset, cancel)?;
transmit.read = match state {
StreamResult::Dropped => ReadState::Dropped,
StreamResult::Completed | StreamResult::Cancelled => ReadState::HostReady {
@@ -2356,12 +2372,13 @@ fn settle_host_write(
produce,
try_into,
guest_offset,
+ cancel,
..
} = mem::replace(&mut transmit.write, WriteState::Open)
else {
bail_bug!("expected WriteState::HostReady")
};
- let code = return_code(kind, state, guest_offset)?;
+ let code = return_code(kind, state, guest_offset, cancel)?;
transmit.write = match state {
StreamResult::Dropped => WriteState::Dropped,
StreamResult::Completed | StreamResult::Cancelled => WriteState::HostReady {
@@ -2714,7 +2731,6 @@ impl<T> StoreContextMut<'_, T> {
{
let WriteState::HostReady {
guest_offset,
- cancel,
cancel_waker,
..
} = &mut transmit.write
@@ -2722,7 +2738,7 @@ impl<T> StoreContextMut<'_, T> {
bail_bug!("expected WriteState::HostReady")
};
- if poll.is_pending() {
+ *cancel_waker = if poll.is_pending() {
if !buffer.remaining().is_empty()
|| *guest_offset > 0
|| host_offset > 0
@@ -2732,11 +2748,10 @@ impl<T> StoreContextMut<'_, T> {
after producing at least one item"
)
}
- *cancel_waker = Some(cx.waker().clone());
+ Some(cx.waker().clone())
} else {
- *cancel_waker = None;
- *cancel = false;
- }
+ None
+ };
}
Ok(poll.map(|v| v.map(|result| (result, cancel))))
@@ -2874,18 +2889,14 @@ impl<T> StoreContextMut<'_, T> {
cancel,
);
- if let ReadState::HostReady {
- cancel_waker,
- cancel,
- ..
- } = &mut store.concurrent_state_mut()?.get_mut(id)?.read
+ if let ReadState::HostReady { cancel_waker, .. } =
+ &mut store.concurrent_state_mut()?.get_mut(id)?.read
{
- if poll.is_pending() {
- *cancel_waker = Some(cx.waker().clone());
+ *cancel_waker = if poll.is_pending() {
+ Some(cx.waker().clone())
} else {
- *cancel_waker = None;
- *cancel = false;
- }
+ None
+ };
}
Ok(poll.map(|v| v.map(|result| (result, cancel))))
diff --git a/tests/all/component_model/async.rs b/tests/all/component_model/async.rs
index 0fa2ed557e..7dc6633c55 100644
--- a/tests/all/component_model/async.rs
+++ b/tests/all/component_model/async.rs
@@ -3823,3 +3823,77 @@ async fn max_fibers() -> Result<()> {
assert!(run(10).await.is_err());
Ok(())
}
+
+#[tokio::test]
+#[cfg_attr(miri, ignore)]
+async fn cancel_stream_read_completed_by_host() -> Result<()> {
+ let mut config = Config::new();
+ config.wasm_component_model_async(true);
+ let engine = Engine::new(&config)?;
+ let component = Component::new(
+ &engine,
+ 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))
+ (core func $task.return (canon task.return (result u32)))
+ (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)))
+ (import "" "task.return" (func $task.return (param i32)))
+ (func (export "run") (param $r i32) (result i32)
+ (if (i32.ne (call $stream.read (local.get $r) (i32.const 0) (i32.const 4))
+ (i32.const -1 (; BLOCKED ;)))
+ (then unreachable))
+ (call $task.return (call $stream.cancel-read (local.get $r)))
+ (i32.const 0 (; EXIT ;)))
+ (func (export "cb") (param i32 i32 i32) (result i32) unreachable)
+ )
+ (core instance $i (instantiate $m (with "" (instance
+ (export "stream.read" (func $stream.read))
+ (export "stream.cancel-read" (func $stream.cancel-read))
+ (export "task.return" (func $task.return))))))
+ (func (export "run") async (param "s" $s) (result u32)
+ (canon lift (core func $i "run") async (callback (core func $i "cb"))))
+)
+ "#,
+ )?;
+
+ 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>,), (u32,)>(&mut store, "run")?;
+
+ // The host only completes the read, with one item, once the guest cancels
+ // it, which must still report CANCELLED(1).
+ let reader = StreamReader::new(&mut store, ProduceOnFinish)?;
+ let (code,) = run.call_async(&mut store, (reader,)).await?;
+ assert_eq!(code, (1 << 4) | 2, "{code:#x}");
+ return Ok(());
+
+ struct ProduceOnFinish;
+
+ impl StreamProducer<()> for ProduceOnFinish {
+ type Item = u8;
+ type Buffer = Option<u8>;
+
+ fn poll_produce<'a>(
+ self: Pin<&mut Self>,
+ _cx: &mut Context<'_>,
+ _store: StoreContextMut<'a, ()>,
+ mut destination: Destination<'a, u8, Option<u8>>,
+ finish: bool,
+ ) -> Poll<Result<StreamResult>> {
+ if finish {
+ destination.set_buffer(Some(0));
+ Poll::Ready(Ok(StreamResult::Completed))
+ } else {
+ Poll::Pending
+ }
+ }
+ }
+}