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.
In this repository66 other files it gives its agents.
- AGENTS.mdAGENTS.md
- postgres-locking-joinsSkill
- ai-bug-patternsSkill
- compressed-ndjson-boundariesSkill
- http-resume-integritySkill
- linux-io-latency-triageSkill
- macos-disk-space-recoverySkill
- minimal-sufficient-evidenceSkill
- modularize-large-filesSkill
- patch-reproducer-validitySkill
- prompt-cache-boundariesSkill
- proton-drive-selective-backupSkill
- transactional-outbox-deliverySkill
- conventional-commitsSkill
- git-advanced-mergingSkill
- git-bisect-forensicsSkill
- git-data-recoverySkill
- git-hooksSkill
- git-rerereSkill
- git-reset-mechanicsSkill
- git-revisions-syntaxSkill
- git-rewriting-historySkill
- git-submodulesSkill
- git-worktreesSkill
- github-ssh-keysSkill
- npm-publish-ci-pitfallsSkill
- sapling-stacked-pr-workflowSkill
- go-concurrency-patternsSkill
- go-data-idiomsSkill
- go-error-handlingSkill
- go-interfaces-embeddingSkill
- go-pprof-profilingSkill
- marketing-funnel-diagnosisSkill
- marketing-geo-experimentsSkill
- marketing-incrementalitySkill
- marketing-positioning-testsSkill
- python-descriptors-mroSkill
- python-logging-cookbookSkill
- python-scaling-regression-testsSkill
- python-unicode-gotchasSkill
- rust-compile-time-invariantsSkill
- rust-deterministic-concurrency-testsSkill
- rust-error-identity-boundariesSkill
- rust-regex-search-contractsSkill
- rust-runtime-bug-classesSkill
- rust-tokio-actor-deliverySkill
- sales-discovery-qualificationSkill
- sales-mutual-action-plansSkill
- sales-pipeline-forecast-calibrationSkill
- sales-value-negotiationSkill
- ai-triage-evaluationSkill
- container-image-patchingSkill
- dependency-artifact-integritySkill
- dnssec-sentinel-diagnosticsSkill
- iam-policy-change-replaySkill
- rbvm-applicabilitySkill
- rbvm-asset-evidenceSkill
- rbvm-guarded-remediationSkill
- rbvm-priority-decisionsSkill
- rbvm-risk-exceptionsSkill
- The first 60 shown.
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
- Very specific: line 25
Keep frame and offset in the owner.
- Distinctive: line 56
Do not infer safety from a trait or method name.
≈ “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.
Files
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! loop | Progress if another branch wins | Safer pattern |
read / read_buf | Cancellation-safe for one read attempt | Append returned bytes to loop-owned storage. |
read_exact | May consume part of the stream; the helper may not return how much | Read incrementally into persistent framing state. |
write / write_buf | Cancellation-safe for one attempt; completion reports a byte count | Keep the frame and offset outside the branch; advance only by the returned count. |
write_all | May have written a prefix; a retry restarts at byte zero | Resume from a saved offset or keep one operation future alive. |
write_all_buf | May write a prefix; the supplied Buf advances by the bytes written | Retain and resume that same buffer; do not rebuild it from the original payload. |
flush | Cancellation-safe; buffered data may be partially flushed and the writer's buffer advances | Re-poll flush on the same writer; this does not prove peer receipt. |
Preserve protocol state
- Inspect every method and wrapper; an async helper may add non-safe awaits.
- For framed reads, append completed
read/read_bufresults to loop-owned storage, parse complete frames, and retain the incomplete suffix. Bound the buffer; treat EOF with an unfinished frame as truncation. - 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 byn. Never retry canceledwrite_allfrom zero on a stream. - For must-finish work, pin one future and poll
&mut futureacross 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
writedoes not make a sequence atomic.
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
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.

