Xpersona
T

Tokio Async Code Review

CLAWHUB · Unverified

Reviews tokio async runtime usage for task management, sync primitives, channel patterns, and runtime configuration. Covers Rust 2024 edition changes includi... Skill: Tokio Async Code Review Owner: anderskev Summary: Reviews tokio async runtime usage for task management, sync primitives, channel patterns, and runtime configuration. Covers Rust 2024 edition changes includi... Tags: latest:1.0.4 Version history: v1.0.4 | 2026-06-01T02:26:42.118Z | auto - Updated protocol gate and findings requirements to refer to the central review-verification-protocol skill by relative path

62
Rank
84
Safety
1.4k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.4K downloads reported by the source. Last updated 10/10/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s17b1fzefm8nj8j1sdkzrze7gn83pfrg:tokio-async-code-review
  1. Setup complexity is classified as HIGH. You must provision dedicated cloud infrastructure or an isolated VM. Do not run this directly on your local workstation.
  2. Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-anderskev-tokio-async-code-review/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

145,505 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: tokio-async-code-review
description: Reviews tokio async runtime usage for task management, sync primitives, channel patterns, and runtime configuration. Covers Rust 2024 edition changes including async fn in traits, RPIT lifetime capture, LazyLock, and if-let temporary scoping. Use when reviewing Rust code that uses tokio, async/await patterns, spawn, channels, or async synchronization. Also covers tokio-util, tower, and hyper integration patterns.
---

# Tokio Async Code Review

## Review Workflow

1. **Check Cargo.toml** — Note tokio feature flags (`full`, `rt-multi-thread`, `macros`, `sync`, etc.). Missing features cause confusing compile errors.
2. **Check runtime setup** — Is `#[tokio::main]` or manual runtime construction used? Multi-thread vs current-thread?
3. **Scan for blocking** — Search for `std::fs`, `std::net`, `std::thread::sleep`, CPU-heavy loops in async functions.
4. **Check channel usage** — Match channel type to communication pattern (mpsc, broadcast, oneshot, watch).
5. **Check sync primitives** — Verify correct mutex type, proper guard lifetimes, no deadlock potential.

## Gates (objective passes before conclusions)

Complete in order for the review scope. Do not assert **Critical** or **Major** until the relevant gate passes.

1. **Dependency surface** — Read the crate (and workspace, if inherited) `Cargo.toml` that supplies `tokio`. **Pass:** Written note of `tokio` version and enabled features, or explicit statement that there is no direct `tokio` dependency and where it comes from (workspace/path).
2. **Runtime model** — Locate runtime construction (`#[tokio::main]`, `Runtime::builder`, tests, or library with no owned runtime). **Pass:** One line naming flavor (`multi_thread` / `current_thread` / tests-only / none) and where it is defined.
3. **Blocking inventory** — Search reviewed paths for blocking APIs (`std::fs::`, `std::net::` without async wrappers, `std::thread::sleep`, heavy CPU loops in `async fn`). **Pass:** Each hit listed as `path:line` (or tool output excerpt), or explicit “no blocking patterns found in reviewed async code” after the search.
4. **Protocol** — Load the [review-verification-protocol](../review-verification-protocol/SKILL.md) skill. **Pass:** Its pass conditions met before any finding is reported (file:line evidence for asserted issues).

## Output Format

Report findings as:

```text
[FILE:LINE] ISSUE_TITLE
Severity: Critical | Major | Minor | Informational
Description of the issue and why it matters.
```

## Quick Reference

| Issue Type | Reference |
|------------|-----------|
| Task spawning, JoinHandle, structured concurrency | [references/task-management.md](references/task-management.md) |
| Mutex, RwLock, Semaphore, Notify, Barrier | [references/sync-primitives.md](references/sync-primitives.md) |
| mpsc, broadcast, oneshot, watch channel patterns | [references/channels.md](references/channels.md) |
| Pin, cancellation, Future internals, select!, blocking bridge | [reference

_meta.json

{
  "ownerId": "kn79190nfmdb20hk6xjhzt2zv583844x",
  "slug": "tokio-async-code-review",
  "version": "1.0.4",
  "publishedAt": 1780280802118
}

references/channels.md

# Channels

## Choosing the Right Channel

| Pattern | Channel | Key Trait |
|---------|---------|-----------|
| Many producers → one consumer, back-pressure | `mpsc` | Bounded, async send blocks when full |
| One value, one time | `oneshot` | Request-response, task result |
| Every consumer gets every message | `broadcast` | Fan-out, event bus |
| Latest value, no queue | `watch` | Config changes, state snapshots |

## mpsc (Multi-Producer Single-Consumer)

The most common channel. Use bounded for back-pressure, unbounded only when you have external flow control.

```rust
// Bounded - preferred, provides back-pressure
let (tx, mut rx) = tokio::sync::mpsc::channel::<Event>(100);

// Unbounded - use with caution (OOM risk)
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Event>();
```

### Capacity Sizing

- Too small (1-10): senders block frequently, throughput suffers
- Too large (100K+): memory pressure, defeats back-pressure purpose
- Rule of thumb: 2-4x the expected burst size

### Graceful Shutdown via Drop

When all senders are dropped, `rx.recv()` returns `None`. This is the idiomatic way to signal "no more items."

```rust
// Producer side
drop(tx); // signals completion

// Consumer side
while let Some(item) = rx.recv().await {
    process(item);
}
// Loop exits when all senders dropped
```

### Common Mistakes

```rust
// BAD - holding tx clone prevents shutdown
let tx_clone = tx.clone();
drop(tx);
// rx.recv() will never return None because tx_clone still exists

// BAD - send without handling closed channel
tx.send(item).await.unwrap(); // panics if receiver dropped

// GOOD - handle send errors
if tx.send(item).await.is_err() {
    tracing::warn!("receiver dropped, stopping producer");
    break;
}
```

## broadcast

Every active subscriber receives every message. Messages are stored in a shared ring buffer.

```rust
let (tx, _rx) = tokio::sync::broadcast::channel::<Event>(16_384);

// Each subscriber gets their own receiver
let mut rx1 = tx.subscribe();
let mut rx2 = tx.subscribe();
```

### Handling Lag

When a receiver falls behind, older messages are overwritten. The receiver gets `RecvError::Lagged(n)` indicating how many messages were missed.

```rust
loop {
    match rx.recv().await {
        Ok(event) => handle(event),
        Err(broadcast::error::RecvError::Lagged(n)) => {
            tracing::warn!(missed = n, "receiver lagged, some events lost");
            // Continue processing — data may be stale
        }
        Err(broadcast::error::RecvError::Closed) => break,
    }
}
```

### Capacity Considerations

Broadcast stores messages until the slowest receiver consumes them (up to capacity). Size the buffer for the slowest expected consumer, not the average case.

## oneshot

Single value, single use. The sender can only send once, and the receiver can only receive once.

```rust
let (tx, rx) = tokio::sync::oneshot::channel::<Result<Response, Error>>();

// Responder
tokio::spawn(async move {
    let result = co

references/pinning-cancellation.md

# Pinning, Cancellation, and Async Internals

## Pin<P<T>> Semantics

`Pin<P>` wraps a pointer type `P` (e.g., `&mut T`, `Box<T>`) and guarantees the target `T` will not move after being pinned. Required for self-referential types like async state machines, where internal references would be invalidated by a move.

- `Pin::new_unchecked()` is unsafe -- caller must guarantee the referent won't move
- `get_unchecked_mut()` is unsafe -- caller must not move `T` through the returned `&mut T`
- `Pin` always implements `Deref<Target = T>` safely (shared refs can't move `T`)
- **When required**: Futures from `async fn`/blocks (self-referential across `.await` points), any struct storing data and pointers into that data

### Unpin Trait

`Unpin` is an auto-trait indicating a type is safe to move out of a `Pin`. Most standard types are `Unpin`. Compiler-generated futures from `async` blocks are `!Unpin`.

```rust
// Unpin types can use the safe Pin::new constructor
let mut fut = ready(42);
let pinned = Pin::new(&mut fut); // safe, ready() is Unpin

// !Unpin types require heap or stack pinning
let fut = async { do_work().await };
let pinned = Box::pin(fut); // heap pinning, always safe
```

## Stack vs Heap Pinning

**`Box::pin(value)`** (heap): Always safe. Allocates on the heap, so the `Pin` can move freely without moving `T`.

**`std::pin::pin!(value)`** (stack, stable since 1.68): Avoids heap allocation. Pins the value to the current stack frame via variable shadowing.

```rust
use std::pin::pin;

// GOOD - stack pinning with std::pin::pin! (stable 1.68+)
let fut = pin!(async { long_running().await });
fut.await;

// GOOD - heap pinning when you need to store or move the pinned future
let fut = Box::pin(async { long_running().await });
tokio::spawn(fut);
```

Flag when: `pin_mut!` from `pin-utils` or `futures` crate is used instead of `std::pin::pin!` on Rust 1.68+.

## Future Trait Internals

The actual `Future` trait requires pinning and a waker context:

```rust
trait Future {
    type Output;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
```

- **`Poll::Pending`**: Future cannot make progress. Must arrange for `cx.waker().wake()` to be called when progress is possible.
- **`Poll::Ready(T)`**: Future has resolved. Do not poll again (may panic).
- **Waker contract**: If `poll` returns `Pending`, the future must ensure `wake()` is called eventually. Leaf futures store the waker where the event source can trigger it.

## Executor Model

Executors manage tasks (top-level futures) and decide which to poll when wakers fire.

- **Work-stealing (tokio multi-thread)**: Multiple threads share a task queue. Idle threads steal work from busy ones. Good for I/O-bound workloads with many tasks.
- **Single-threaded (tokio current_thread)**: One thread polls all tasks. No `Send` requirement on futures. Simpler, lower overhead, but no parallelism.

Check for: Blocking operations in async context. A future that runs >1ms without yi

references/sync-primitives.md

# Sync Primitives

## Choosing the Right Primitive

| Need | Primitive | Notes |
|------|-----------|-------|
| Exclusive access to data | `Mutex<T>` | `std::sync` by default; `tokio::sync` only if held across `.await` |
| Single integer / bool / pointer of state | `Atomic*` | No lock needed; see "Atomics beat locks" below |
| Read-heavy, write-rare access | `RwLock<T>` | Benchmark vs `Mutex`; consider `arc_swap::ArcSwap` for replace-not-mutate |
| Limit concurrent operations | `Semaphore` | Rate limiting, connection pooling, bounded fan-out |
| Signal one waiter | `Notify` | Lightweight, no data transfer; mind the lost-wakeup hazard |
| Signal all waiters | `Notify` + `notify_waiters()` | Broadcast wake-up |
| One-time initialization (sync init) | `OnceLock` / `LazyLock` | Stable in std since 1.70 / 1.80 |
| One-time initialization (async init) | `tokio::sync::OnceCell` | When the initializer must `.await` |
| High-contention sync code | `parking_lot::Mutex` / `RwLock` | Smaller, faster, no poisoning |

## Mutex decision matrix: std vs tokio vs parking_lot

Default to `std::sync::Mutex` even in async code, provided the critical section is short and contains no `.await`. This is what the Tokio tutorial itself recommends.

| Want | Use | Why |
|------|-----|-----|
| Short critical section, no `.await` inside | `std::sync::Mutex` | Cheapest; uses OS primitive |
| Lock genuinely must span an `.await` | `tokio::sync::Mutex` | Async-aware; suspends the task instead of the thread |
| High contention on sync code, no poisoning desired, fair RwLock, or `Send` guard via `send_guard` | `parking_lot::Mutex` / `RwLock` | Smaller, faster lock; no `unwrap()` on `lock()` |
| Single integer / bool / pointer of state | atomic (see below) | No lock, no guard, no await question |

`tokio::sync::Mutex` is a `Semaphore` under the hood. The Tokio docs and Mara both note it is materially more expensive (commonly cited as ~3x slower) than `std::sync::Mutex` for short critical sections because of its async-wakeup machinery. Reserve it for the case where you genuinely cannot extract or clone the data out before the `.await`.

`parking_lot::Mutex::lock()` returns the guard directly — no `Result`. A `.unwrap()` here is a smell. Its `RwLock` is fair by default; `std::sync::RwLock` is platform-dependent and can starve writers (or, on glibc, readers) — see the RwLock section below.

```rust
// GOOD - std::sync::Mutex in async code, no .await inside the critical section
use std::sync::Mutex;
struct Counter(Mutex<u64>);

impl Counter {
    async fn bump_and_log(&self) {
        let n = {
            let mut count = self.0.lock().unwrap();
            *count += 1;
            *count
        }; // guard dropped here, before any .await
        log(n).await;
    }
}

// GOOD - tokio::sync::Mutex only when the lock truly spans an await
use tokio::sync::Mutex;
struct Cache(Mutex<HashMap<String, Data>>);

impl Cache {
    async fn get_or_fetch(&self, key: &str) -> Data {
        let mu

Sponsored

Ads related to Tokio Async Code Review and adjacent AI workflows.