> ## Content Index
> Fetch the complete content index at: https://debugly.dev/llms.txt
> Use this file to discover other available public pages before exploring further.

# Did Tokio select! Throw Away Part of Your Frame?
- URL: https://debugly.dev/tokio-select-read-exact-cancellation-safety/
- Published: 2026-11-14T03:46:00.000Z
- Updated: 2026-11-14T03:46:00.000Z
- Description: A timer can cancel read_exact after it consumes part of a header. Preserve framing progress across select! calls instead of starting a fresh read.
- Author: Rohit Bhadani
- Tags: Rust, Concurrency, Debugging

A timer wins a `tokio::select!` race, the loop continues, and the next message header looks wrong. Before blaming the peer, check whether the losing branch was `read_exact()`. It isn’t cancellation safe: it may already have consumed part of the header before its future is dropped. Starting a new exact read doesn’t put those bytes back. Keep framing progress outside the cancelled operation, or give one reader ownership of the stream until it has a complete frame.

*This is an AI-prepared, documentation-based explainer, not a personally reproduced incident. The code and event sequence are illustrative and were not executed for this article. See the* [*editorial policy*](https://debugly.dev/editorial-policy/)*.*

## The timer didn’t lose a packet. The parser lost its place.

Imagine a small binary protocol with a four-byte header. The reader used to wait for a full header and then read the payload. A progress timer gets added so the task can report that it’s still alive while waiting. Under some timings, the parser starts reporting nonsense lengths. Removing the timer appears to fix it. That doesn’t establish a timer bug; it gives the read a new place to be cancelled.

This illustrative fragment assumes an existing mutable stream, a Tokio interval and the `AsyncReadExt` trait in scope. It sketches the problematic loop rather than a complete protocol implementation:

```
loop {
    let mut header = [0_u8; 4];

    tokio::select! {
        result = stream.read_exact(&mut header) => {
            // Parse only after checking result for success.
        }
        _ = ticker.tick() => {
            // Report progress; then the loop starts a fresh read.
        }
    }
}
```

The [select! contract](https://docs.rs/tokio/latest/tokio/macro.select.html?ref=debugly.dev) says the other branches are cancelled when one branch completes. It also lists `read_exact` among operations that are not cancellation safe. The [read\_exact documentation](https://docs.rs/tokio/latest/tokio/io/trait.AsyncReadExt.html?ref=debugly.dev#method.read%5Fexact) makes the consequence explicit: some data may already have been read when another branch completes first.

## Follow the partial header through one cancellation

Consider this possible sequence in the example:

1. The peer sends the first two bytes of a four-byte header.
2. `read_exact` consumes those bytes and remains pending while waiting for the other two.
3. The timer branch completes. The pending exact-read future is dropped, and the loop discards its local header buffer.
4. The next loop creates a new header and starts reading at the stream’s current position.

The new read can combine the remaining header bytes with bytes from the payload. From the parser’s perspective, the frame boundary has moved. The bytes weren’t necessarily lost on the network; the application consumed them without preserving the state needed to interpret them. A packet capture showing a complete message won’t contradict that explanation.

This isn’t guaranteed to happen on every iteration. If the full read completes before the competing branch wins, the header can be fine. Test controlled partial delivery rather than relying on a loop that only fails when the scheduler is in the mood.

## Make partial progress belong to something that survives

One design is to keep the header buffer and a filled-byte count in a persistent parser state, outside the repeated `select!` calls. Use [read()](https://docs.rs/tokio/latest/tokio/io/trait.AsyncReadExt.html?ref=debugly.dev#method.read) into the remaining slice, add the returned count, and parse only once enough bytes have accumulated. Tokio documents this read operation as cancellation safe in a select race: if another branch completes first, no data is read by that cancelled call. Previously accumulated bytes must still remain in your state.

That is a state-machine change, not a search-and-replace from `read_exact` to `read`. Handle short reads, errors and end-of-stream. A zero-length read into a nonempty remaining slice needs an explicit EOF policy. Reset the header state only after consuming a complete header, and preserve the payload length and payload progress too. Tokio’s [framing tutorial](https://tokio.rs/tokio/tutorial/framing?ref=debugly.dev) shows why a connection keeps a buffer across attempts to parse a frame.

Another design is to let a dedicated task own the stream and frame parser, and send completed frames to other tasks through a channel. The timer can race against receiving a completed frame instead of racing against a temporary multi-read operation. Tokio lists [mpsc::Receiver::recv](https://docs.rs/tokio/latest/tokio/sync/mpsc/struct.Receiver.html?ref=debugly.dev#method.recv) as cancellation safe. That moves the boundary; it doesn’t remove the need to define what happens when the reader fails or shuts down.

Keeping the same pending read future alive across timer events is also different from dropping it and constructing a replacement. If you choose that design, retain the future itself and review its borrow and completion lifecycle. Pinning a newly created future on every loop iteration does not preserve the old operation’s progress.

## Cancellation safety belongs to the whole boundary

An async helper with a local buffer doesn’t become cancellation safe merely because it uses `read` internally. If its caller races the whole helper against another event and drops it, that local buffer and count can still disappear. Store progress in an owner that survives the cancellation boundary you actually use. If cancellation means closing the connection permanently, discarding partial framing state may be intentional; reusing the same stream afterward is the dangerous combination.

For a regression check, use a controlled in-memory stream or test peer. Send only part of the header, arrange for the competing branch to complete, then send the rest and a known payload. Verify the decoded frame, not just that the task stayed alive. Repeat at payload boundaries, and cover EOF and shutdown separately. This walkthrough does not claim those tests were run.

Debugly’s [Tokio blocking-timeout explainer](https://debugly.dev/tokio-timeout-spawn-blocking-task-running/) concerns work that can keep running after a waiter times out. Here the losing read future is dropped and progress can be forgotten. The useful question in both cases is where ownership ends. A timer can report that the task is alive; it shouldn’t quietly decide which bytes the parser remembers.