agentleFS
narenaryannarenaryan/agent-skills/skills/rust/rust-tokio-cancellation-safety/SKILL.md

rust-tokio-cancellation-safety

Skill0 starsChanged 41 days agoMITView on GitHub

Use when a Tokio loop races I/O, shutdown, timers, or receives with `select!` and may restart an operation after cancellation; prevent lost input, duplicated output.

The file

We split this skill into the rules it gives an agent

2 rules. About 0 are common, 1 is distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Keep frame and offset in the owner.

    line 25
  2. Distinctive:

    Do not infer safety from a trait or method name.

    line 56

≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Tokio Cancellation Safety

select! drops losing futures; recreation starts over. Cancellation-safe means drop/recreate is a no-op, not rollback.

Audit branch operations

Operation in a select! loopProgress if another branch winsSafer pattern
read / read_bufCancellation-safe for one read attemptAppend returned bytes to loop-owned storage.
read_exactMay consume part of the stream; the helper may not return how muchRead incrementally into persistent framing state.
write / write_bufCancellation-safe for one attempt; completion reports a byte countKeep the frame and offset outside the branch; advance only by the returned count.
write_allMay have written a prefix; a retry restarts at byte zeroResume from a saved offset or keep one operation future alive.
write_all_bufMay write a prefix; the supplied Buf advances by the bytes writtenRetain and resume that same buffer; do not rebuild it from the original payload.
flushCancellation-safe; buffered data may be partially flushed and the writer's buffer advancesRe-poll flush on the same writer; this does not prove peer receipt.

Preserve protocol state

  1. Inspect every method and wrapper; an async helper may add non-safe awaits.
  2. For framed reads, append completed read/read_buf results to loop-owned storage, parse complete frames, and retain the incomplete suffix. Bound the buffer; treat EOF with an unfinished frame as truncation.
  3. Keep frame and offset in the owner. Resume only with the same frame and offset. Write its unsent suffix, reject zero as WriteZero, then advance by n. Never retry canceled write_all from zero on a stream.
  4. For must-finish work, pin one future and poll &mut future across selects, or use one owner task. Dropping the owner still drops its state.
async fn write_frame_until_shutdown<W: tokio::io::AsyncWrite + Unpin>(
    writer: &mut W,
    shutdown_rx: &mut tokio::sync::oneshot::Receiver<()>,
    frame: &[u8],
    offset: &mut usize,
) -> std::io::Result<bool> {
    use tokio::io::AsyncWriteExt;
    if *offset > frame.len() {
        return Err(std::io::ErrorKind::InvalidInput.into());
    }
    while *offset < frame.len() {
        let n = tokio::select! {
            _ = &mut *shutdown_rx => return Ok(false), // sender drop stops too
            result = writer.write(&frame[*offset..]) => result?,
        };
        if n == 0 { return Err(std::io::ErrorKind::WriteZero.into()); }
        *offset += n;
    }
    Ok(true) // all bytes accepted by this AsyncWrite, not necessarily flushed
}

Offset is not atomic delivery. Choose whether shutdown may abandon partial frames. Default polling is randomized; biased; makes fairness yours.

Pitfalls

  • A timeout or shutdown branch is not rollback: prior writes accepted by a writer, dequeues, or external side effects may already have happened.
  • Do not infer safety from a trait or method name; check the specific contract and SOURCES.md.
  • A cancel-safe write does not make a sequence atomic.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.