skip to content

In Rust, what makes an async read method cancellation-safe, and why does a frame reader collecting bytes into a local `Vec` lose data when dropped?

level: seniorimportance: must knowfreq 50%

answer

  1. state in the future dies with it
  2. data loss, not memory safety
  3. take only when returning Ready
  4. partial progress in the struct

basics

~20 s

An async method is cancellation-safe when dropping its future before completion loses nothing, so a later call resumes cleanly. A frame reader that moves bytes into a local Vec loses them on drop, because that Vec lives only in the future.

solid answer

~50 s

Cancellation safety is a logic property, not a memory-safety one: if the future is dropped at any `.await`, nothing has been consumed that the next call cannot see. A channel receive is safe when a message leaves the queue only in the poll that returns it as `Ready`, so a dropped receive took nothing. A frame reader that pulls bytes off a source one at a time into a local `Vec` is not: the bytes are gone from the source and the `Vec` is destroyed with the future, so the next call starts mid-frame and returns misaligned data. The fix is to keep partial progress outside the future, for example a `partial: Vec<u8>` field that `read_frame(&mut self)` appends to, so a cancelled call leaves the bytes where the next one finds them. Document which methods are safe, because the signature cannot show it.

code

rust · 41 lines
rust
use futures::channel::mpsc::{UnboundedReceiver, unbounded};
use futures::{FutureExt, StreamExt};

// Not cancellation-safe: bytes already taken live only in the future's local `buf`.
async fn read_frame(rx: &mut UnboundedReceiver<u8>) -> Vec<u8> {
    let mut buf = Vec::new();
    while buf.len() < 4 {
        buf.push(rx.next().await.unwrap());
    }
    buf
}

// Cancellation-safe: partial progress lives in the reader, not in the future.
struct FrameReader {
    rx: UnboundedReceiver<u8>,
    partial: Vec<u8>,
}
impl FrameReader {
    async fn read_frame(&mut self) -> Vec<u8> {
        while self.partial.len() < 4 {
            self.partial.push(self.rx.next().await.unwrap());
        }
        std::mem::take(&mut self.partial)
    }
}

fn main() {
    let (tx, mut rx) = unbounded();
    for b in [1, 2] { tx.unbounded_send(b).unwrap(); }
    // Poll once, then drop: the future takes 1 and 2, hits Pending, is dropped.
    assert!(read_frame(&mut rx).now_or_never().is_none());
    for b in [3, 4, 5, 6] { tx.unbounded_send(b).unwrap(); }
    println!("unsafe: {:?}", read_frame(&mut rx).now_or_never().unwrap());

    let (tx, rx) = unbounded();
    let mut reader = FrameReader { rx, partial: Vec::new() };
    for b in [1, 2] { tx.unbounded_send(b).unwrap(); }
    assert!(reader.read_frame().now_or_never().is_none());
    for b in [3, 4] { tx.unbounded_send(b).unwrap(); }
    println!("safe:   {:?}", reader.read_frame().now_or_never().unwrap());
}

go deeper

for a junior

Recall that dropping a future destroys everything it stored, including any data it had already pulled from a channel or socket.

for a middle

Explain the definition: cancellation-safe means a dropped call loses nothing, and that depends on where partial progress is kept.

for a senior

Diagnose misaligned or missing data after timeouts by finding state split between a future and its source, then move it into the struct.

for a principal

Treat cancellation safety as a documented contract on shared async APIs and decide where a team allows unsafe methods to be raced.

## A definition about data, not memory In Rust, a future can be cancelled at any `.await` simply by being dropped: a timeout, a race or an aborted task all end that way. Safe Rust guarantees that dropping a future is **memory-safe**; destructors run and nothing dangles. It does not guarantee that the program's *data* is still consistent afterwards. An async method is **cancellation-safe** when dropping its future at any suspension point, before it completes, loses or duplicates nothing: a later call can pick up exactly where the cancelled one left off. A method that is not cancellation-safe has no memory bug; it has a **logic bug** that only appears when the future is dropped mid-operation. The property belongs to a method together with the state it touches, and it only matters when the future can actually be dropped early. A method that is unsafe in this sense is perfectly correct when every caller awaits it to completion; it becomes a bug the day someone puts it inside a timeout or a race. ## Where the data goes when a future is dropped Everything an `async fn` keeps across an `.await` lives inside its future's state machine. When the future is dropped, that state is destroyed. Trouble starts when the function has already **taken** something from a shared source and holds it only in that state: 1. `read_frame(rx)` wants four bytes; it takes byte 1, then byte 2, from the channel. 2. The channel is empty, so `rx.next().await` returns `Pending` and the future parks. 3. A timeout or race drops the future; its local `buf` holding `[1, 2]` is freed. 4. Bytes 1 and 2 are no longer in the channel and no longer anywhere else. 5. The next `read_frame` call reads `[3, 4, 5, 6]`: a frame built from the wrong bytes. The root cause is **state split between the future and the source**: the source has advanced, but the record of what was taken lived in the future. ## Making the reader resumable Move partial progress out of the future and into something that outlives it, usually the reader itself: - give the reader a `partial: Vec<u8>` field; - make `read_frame(&mut self)` append to `self.partial` instead of a local buffer; - take the finished frame with `std::mem::take(&mut self.partial)` only when it is complete. Now a dropped call leaves `[1, 2]` in `self.partial`, and the next call continues from byte 3. The method has become cancellation-safe, which the example below shows by polling each version once with `FutureExt::now_or_never` (which drops the future if it is pending) and then calling again. The building block underneath matters too. `StreamExt::next` on a futures channel receiver only removes a message in the same poll that returns it as `Ready`, so a dropped `next()` future took nothing. Methods built only from such steps, keeping their own progress in `&mut self`, stay safe. ## Recognising safe and unsafe operations | Operation | Cancellation-safe? | Why | |---|---|---| | Receive that removes a message only on `Ready` | Yes | Nothing is taken before the result is returned | | Read exactly N bytes into a local buffer across awaits | No | Earlier chunks die with the future | | Write a whole buffer in several writes | No | The caller cannot tell how much was written | | Method whose partial progress lives in `&mut self` | Yes, if the next call resumes it | State survives the dropped future | Libraries document this per method because the compiler cannot check it: Tokio's docs, for example, carry a cancel-safety section on many of its async methods, and mark its `read_line` as not cancel safe. ## Where it bites - **Races in a loop**: a branch that loses each iteration is dropped every time, so an unsafe method there loses data repeatedly. - **Timeouts** around a multi-step read or write. - **Handlers dropped on disconnect**, when a server drops a request's future because the client went away mid-request. - **Retries** that call an unsafe method again after a cancelled attempt, which see a source that has already moved on. When an unsafe operation must be raced, keep the same future alive across iterations instead of recreating it, so it is resumed rather than dropped.

  • Is `StreamExt::next` on a `futures::channel::mpsc::UnboundedReceiver` cancellation-safe?
    Yes. The `Next` future only borrows the receiver, and a message leaves the queue in the same poll that returns it as `Ready`. If the future is dropped while pending, nothing was removed and the next call sees the same message, which is why the fixed reader in the example loses nothing.
  • Why can't rustc check cancellation safety for you?
    Nothing in a signature says where a method keeps intermediate state; an async fn returns an opaque future, and whether bytes sit in its locals or in `&mut self` is an implementation detail. The compiler only guarantees that the drop is memory-safe. Data loss is a logic error, so libraries document it per method and reviewers read those notes.
  • How would you test a method for cancellation safety?
    Feed it from a source that delivers data in pieces, poll the future once with `FutureExt::now_or_never` so it parks mid-operation, drop it, then call again and assert the full, correctly ordered result. Repeat with the cut at each possible await point.

  • Cancellation safety means the future cannot cause undefined behaviour when dropped.
  • Any method that takes &mut self is automatically cancellation-safe.
  • The compiler rejects futures that would lose data when dropped.
  • Dropping a reader's future puts its buffered bytes back into the source.
  • A new call picks up the bytes the dropped call was holding.