Skip to content
Back to skills

Rust Tokio Cancellation Safe Io

ASecurity

Use when retries after a Tokio select! or timeout corrupt framed reads or writes because an interrupted operation already consumed bytes.

  • 50,717 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added December 2, 2026
ai-agentsrustgogitdocumentation

Security analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned December 2, 2026

npx -y skills add sickn33/agentic-awesome-skills --skill rust-tokio-cancellation-safe-io --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Rust Tokio Cancellation Safe Io?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Rust Tokio Cancellation Safe Io
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/sickn33-rust-tokio-cancellation-safe-io/badge)](https://www.skillsdirectory.com/skills/sickn33-rust-tokio-cancellation-safe-io)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: rust-tokio-cancellation-safe-io
description: "Use when retries after a Tokio select! or timeout corrupt framed reads or writes because an interrupted operation already consumed bytes."
category: development
risk: critical
source: self
source_type: self
date_added: "2026-12-01"
author: ShianMike
tags: [rust, tokio, async-io, cancellation, select, framing]
---

# Rust Tokio Cancellation-Safe I/O

## When to Use

- A stream frame loses or duplicates bytes after a time limit, shutdown signal, or another `tokio::select!` branch wins.
- A reader retries `read_exact` on the same stream after cancelling the previous read.
- A protocol needs to pause work and resume with the same connection and parsing state.

## Prerequisites

- Identify the Tokio version, transport, framing rules, and exact operation that can be dropped.
- Find every path that reuses the connection after a cancellation. Verify who owns the reader, the buffer, and the count of bytes already assembled.
- Reproduce with a local partial-frame fixture before changing a production read loop.

## 1. Locate progress that can be lost on cancellation

1. Inspect each composed read or write inside `tokio::select!` or a timeout. A dropped `read_exact` can have consumed bytes even though it never returned a complete frame. A dropped `write_all` can have written a prefix.
2. Check the actual method's cancellation contract. Tokio documents `read`, `read_buf`, and `write` as cancellation-safe operations in a select branch. A wrapper with additional awaits needs to preserve any progress it makes between them.
3. Decide whether to keep the connection for another attempt or close it. Resuming requires enough state to know where to continue. Reconnection and resending also need the protocol's duplicate-delivery rules.

## 2. Persist frame state across attempts

1. Let one reader own the bytes and the number of bytes already filled outside the future that can be dropped. Read into the remaining part of the buffer and update the count immediately after each successful `read`.
2. Yield a frame when all its bytes are available. Reset the count only after producing that frame. Check length limits before allocating buffers for variable-length formats.
3. Treat a zero-byte read into a nonempty slice as EOF. Report clean EOF at a frame boundary and a truncated frame when any bytes are pending.
4. For resumable writes, keep the payload and written offset and advance the offset by the completed `write` result. A byte count confirms local write progress. Application-level delivery depends on the protocol.

## 3. Verify the cancellation path without sleeps

1. Feed a known prefix through `tokio::io::duplex` while leaving the write side open. Force cancellation after a read has had a chance to take that prefix.
2. Feed the suffix and the next frame. Assert the exact bytes of both frames and the EOF behavior, including a truncated frame.
3. The fixture uses `biased;` to control polling order. Evaluate fairness and shutdown latency separately for the production loop.

## Example

Run the [partial-frame cancellation fixture](references/resume-partial-frame.md). It uses two four-byte frames with the cancellation point in the middle of the first.

```text
First write       AB
Cancel            The read attempt has polled and is waiting for more bytes
Second write      CDEFGH
Expected frames   ABCD and EFGH
```

## Limitations

- The fixture uses in-memory Tokio I/O and fixed-size frames. Socket handling, TLS, variable-length codec limits, and writes under backpressure require their own tests.
- Frame tracking addresses local byte progress. Recovery after a dropped connection also depends on peer state and protocol acknowledgements.

## Safety and Side Effects

- The example uses synthetic data in memory. Cargo builds local artifacts in the scratch project and can read a package registry when filling its cache.
- Frame recovery changes stream handling. Test truncation and retry behavior with a disposable stream before using it on a live connection.

## Related Skills and Documentation

- For task and channel patterns, see [Rust Async Patterns](https://github.com/sickn33/agentic-awesome-skills/blob/main/skills/rust-async-patterns/SKILL.md).
- For general Rust development, see [Rust Pro](https://github.com/sickn33/agentic-awesome-skills/blob/main/skills/rust-pro/SKILL.md).
- Tokio documents [select! cancellation safety](https://docs.rs/tokio/latest/tokio/macro.select.html#cancellation-safety), [AsyncReadExt](https://docs.rs/tokio/latest/tokio/io/trait.AsyncReadExt.html), and [duplex streams](https://docs.rs/tokio/latest/tokio/io/fn.duplex.html).

Files in this skill

  • SKILL.md4.6 KB
  • references/resume-partial-frame.md3.9 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.