Xpersona
R

Rust Code Review

CLAWHUB · Unverified

Reviews Rust code for ownership, borrowing, lifetime, error handling, trait design, unsafe usage, and common mistakes. Use when reviewing .rs files, checking... Skill: Rust Code Review Owner: anderskev Summary: Reviews Rust code for ownership, borrowing, lifetime, error handling, trait design, unsafe usage, and common mistakes. Use when reviewing .rs files, checking... Tags: latest:1.0.5 Version history: v1.0.5 | 2026-06-01T02:26:17.815Z | auto - Updated reference links and best-practices guidance to use new skill-based paths for improved interoperability. - Checklist and ga

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:rust-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-rust-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

146,685 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: rust-code-review
description: Reviews Rust code for ownership, borrowing, lifetime, error handling, trait design, unsafe usage, and common mistakes. Use when reviewing .rs files, checking borrow checker issues, error handling patterns, or trait implementations. Covers Rust 2024 edition patterns and modern idioms.
---

# Rust Code Review

## Review Workflow

Follow this sequence to avoid false positives and catch edition-specific issues:

1. **Check `Cargo.toml`** — Note the Rust edition (2018, 2021, 2024) and MSRV if set. Edition 2024 introduces breaking changes to unsafe semantics, RPIT lifetime capture, temporary scoping, and `!` type fallback. This determines which patterns apply. Check workspace structure if present.
2. **Check dependencies** — Note key crates (thiserror vs anyhow, tokio features, serde features). These inform which patterns are expected.
3. **Scan changed files** — Read full functions, not just diffs. Many Rust bugs hide in ownership flow across a function.
4. **Check each category** — Work through the checklist below, loading references as needed.
5. **Verify before reporting** — Complete **Gates** (below), including the verification-protocol gate, before submitting findings.

## Gates

These steps are **sequenced**: do not skip ahead with “mental verification.” Each step has an objective **Pass** you can satisfy from files on disk and your own read path.

1. **Crate context** — Before relying on edition-specific checklist rows (Edition 2024, MSRV-sensitive APIs) or dependency assumptions. **Pass:** You opened the relevant `Cargo.toml` (package or workspace manifest) and can state `edition` and `rust-version` (if set) in one line.
2. **Expanded read** — Before reporting a **Major** or **Critical** finding. **Pass:** You read the full function, `unsafe` block, or `impl` / trait item that contains the cited line (not only a diff hunk).
3. **Severity match** — Before each finding line in the report. **Pass:** The **Severity** label matches **Severity Calibration** for that issue class, or you use **Informational** and give a one-line rationale.
4. **Verification protocol** — Before finalizing the report. **Pass:** the [review-verification-protocol](../review-verification-protocol/SKILL.md) skill is loaded and every step in it that applies to this review is completed (do not substitute a vague “I checked”).

## 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 |
|------------|-----------|
| Ownership transfers, borrowing, lifetimes, clone traps, iterators | [references/ownership-borrowing.md](references/ownership-borrowing.md) |
| Lifetime variance, covariance/invariance, memory regions | [references/lifetime-variance.md](references/lifetime-variance.md) |
| Result/Option handling, thiserror, anyhow, opaque vs enumerated errors, deferred-cleanup with `?` | 

_meta.json

{
  "ownerId": "kn79190nfmdb20hk6xjhzt2zv583844x",
  "slug": "rust-code-review",
  "version": "1.0.5",
  "publishedAt": 1780280777815
}

references/async-concurrency.md

# Async and Concurrency

## Critical Anti-Patterns

### 1. Blocking in Async Context

Blocking operations inside async functions starve the tokio runtime's thread pool, causing latency spikes and potential deadlocks.

```rust
// BAD - blocks the async runtime thread
async fn read_config() -> Config {
    let data = std::fs::read_to_string("config.toml").unwrap(); // BLOCKING!
    toml::from_str(&data).unwrap()
}

// GOOD - use async I/O
async fn read_config() -> Result<Config, Error> {
    let data = tokio::fs::read_to_string("config.toml").await?;
    let config: Config = toml::from_str(&data)?;
    Ok(config)
}

// GOOD - offload blocking work to a dedicated thread
async fn compute_hash(data: Vec<u8>) -> Result<Hash, Error> {
    tokio::task::spawn_blocking(move || {
        expensive_hash(&data)
    }).await?
}
```

Common blockers to watch for: `std::fs`, `std::net`, `std::thread::sleep`, CPU-heavy computation, synchronous database drivers.

### 2. Holding Locks Across Await Points

A `MutexGuard` held across an `.await` can cause deadlocks and prevents `Send` bounds from being satisfied.

```rust
// BAD - guard held across await
async fn update(state: &Mutex<State>) {
    let mut guard = state.lock().await;
    let data = fetch_data().await; // guard still held!
    guard.data = data;
}

// GOOD - drop guard before await
async fn update(state: &Mutex<State>) {
    let current = {
        let guard = state.lock().await;
        guard.data.clone()
    }; // guard dropped here
    let new_data = fetch_data().await;
    let mut guard = state.lock().await;
    guard.data = new_data;
}
```

### 3. Using std::sync::Mutex in Async Code

`std::sync::Mutex` blocks the thread while waiting. In async code, use `tokio::sync::Mutex` which yields to the runtime, or use `std::sync::Mutex` only for short, non-async critical sections.

```rust
// RISKY - std mutex in async context
use std::sync::Mutex;
async fn process(shared: &Mutex<Vec<Item>>) {
    let mut guard = shared.lock().unwrap(); // blocks thread
    guard.push(item);
}

// GOOD - tokio mutex for async-aware locking
use tokio::sync::Mutex;
async fn process(shared: &Mutex<Vec<Item>>) {
    let mut guard = shared.lock().await; // yields to runtime
    guard.push(item);
}
```

Exception: `std::sync::Mutex` is fine when the critical section is very short (no async operations, just field access) because it avoids the overhead of tokio's async mutex. The tokio docs themselves recommend this pattern.

> For a detailed comparison of `tokio::sync::Mutex` vs `std::sync::Mutex` and other sync primitives (`RwLock`, `Semaphore`, `Notify`), see the [tokio-async-code-review](../../tokio-async-code-review/SKILL.md) skill (`references/sync-primitives.md`).

### 4. Spawning Tasks Without Join Handles

Fire-and-forget tasks can silently fail, leak resources, or outlive their logical scope.

```rust
// BAD - task error is lost, no lifecycle management
tokio::spawn(async {
    process_batch(items).await;
});

// GOOD -

references/common-mistakes.md

# Unsafe Code, API Design, and Derive Patterns

> For performance, pointer types, clippy config, iterators, generics, and documentation guidance, see the [rust-best-practices](../../rust-best-practices/SKILL.md) skill.

## Unsafe Code

### Missing Safety Comments

Every `unsafe` block must explain why the invariants are upheld. This isn't a style preference — it's how future maintainers verify the code is correct.

```rust
// BAD - no justification
let value = unsafe { &*ptr };

// GOOD - documents the invariant
// SAFETY: `ptr` was allocated by `Box::into_raw` in `new()` and
// is guaranteed to be valid until `drop()` is called. We hold &self,
// which prevents concurrent mutation.
let value = unsafe { &*ptr };
```

### Unsafe Operations in `unsafe fn` (Edition 2024)

In edition 2024, `unsafe_op_in_unsafe_fn` is deny by default. Being inside an `unsafe fn` no longer implicitly permits unsafe operations — each one needs its own `unsafe {}` block with a safety comment.

```rust
// BAD in edition 2024 — unsafe ops without explicit blocks
unsafe fn process_raw(ptr: *const u8, len: usize) -> &[u8] {
    std::slice::from_raw_parts(ptr, len) // ERROR: requires unsafe block
}

// GOOD — explicit unsafe block inside unsafe fn
unsafe fn process_raw(ptr: *const u8, len: usize) -> &[u8] {
    // SAFETY: caller guarantees ptr is valid for len bytes and
    // the resulting slice does not outlive the allocation.
    unsafe { std::slice::from_raw_parts(ptr, len) }
}
```

This makes `unsafe fn` bodies auditable at the same granularity as regular functions. Every unsafe operation gets its own safety justification.

### `unsafe extern` Blocks (Edition 2024)

In edition 2024, `extern` blocks must be marked `unsafe` because declaring foreign functions is inherently unsafe (the compiler cannot verify the signatures are correct).

```rust
// BAD in edition 2024
extern "C" {
    fn strlen(s: *const c_char) -> usize;
}

// GOOD in edition 2024
unsafe extern "C" {
    fn strlen(s: *const c_char) -> usize;
}
```

### `unsafe` Attributes (Edition 2024)

Attributes that affect ABI or symbol names are now safety-sensitive and must be wrapped in `unsafe(...)`:

```rust
// BAD in edition 2024
#[no_mangle]
pub extern "C" fn my_func() {}

#[export_name = "custom_name"]
pub fn another_func() {}

// GOOD in edition 2024
#[unsafe(no_mangle)]
pub extern "C" fn my_func() {}

#[unsafe(export_name = "custom_name")]
pub fn another_func() {}
```

### Overly Broad Unsafe Blocks

Only the minimum necessary code should be inside `unsafe`. Surrounding safe code makes it harder to audit.

```rust
// BAD - safe operations inside unsafe block
unsafe {
    let len = data.len();          // safe
    let ptr = data.as_ptr();       // safe
    std::slice::from_raw_parts(ptr, len)  // this is the only unsafe part
}

// GOOD - narrow unsafe boundary
let len = data.len();
let ptr = data.as_ptr();
// SAFETY: ptr and len come from the same slice, which is still alive
unsafe { std::slice::from_raw_parts

references/concurrency-models.md

# Concurrency Models

Concurrency is a design decision, not a tactical choice. Pick the model — shared memory, worker pool, or actor — *before* reaching for primitives, then let the model dictate which primitives belong. Jon Gjengset's framing: most concurrency bugs come from accidentally mixing two models in one design. This file covers model selection and the review hazards specific to each. For primitive-level review (Mutex vs RwLock, atomics, UnsafeCell, OnceLock/LazyLock), see [concurrency-primitives.md](concurrency-primitives.md). For ordering semantics, see [memory-ordering.md](memory-ordering.md). For async-specific patterns, see [async-concurrency.md](async-concurrency.md) and [../../tokio-async-code-review/SKILL.md](../../tokio-async-code-review/SKILL.md).

## Shared memory model

Threads cooperate by reading and writing common memory protected by mutexes, RW-locks, or atomics.

**Valid when:** workload accesses small shared state from many threads (cache, counter, config, in-memory registry); critical sections are short (microseconds); updates are non-commutative (`f(g(s)) != g(f(s))`).

**Dangerous when:** the critical section holds I/O, network calls, allocator pressure, or unbounded work; a lock is held across `.await` on an async runtime (deadlocks the executor); one lock guards composite state where independent fields are touched by independent code paths.

**Review questions:** who holds the lock? for how long is it held in the worst case? is the critical section measured, or assumed-short? could this be an `AtomicX`, `arc-swap`, or a sharded design instead? `Mutex` (mutual exclusion, ~40 bytes on Linux), `RwLock` (read-heavy only — writer overhead exceeds `Mutex` if writes are frequent), or `parking_lot` variants (smaller, faster, fair) — which tradeoff is the code actually paying for?

The deadly shape in async code is a sync mutex held across `.await`:

```rust
// BAD: std::sync::Mutex guard alive across .await.
let mut g = state.lock().unwrap();
g.pending += 1;
let row = db.fetch(g.id).await?; // executor may suspend with guard held
g.cache.insert(row.key, row);

// GOOD: drop the guard first, or use tokio::sync::Mutex.
let id = { let g = state.lock().unwrap(); g.id };
let row = db.fetch(id).await?;
state.lock().unwrap().cache.insert(row.key, row);
```

## Worker pool model

N identical threads (or tasks) pull jobs from a shared queue and execute them independently. Every worker runs the same code; jobs differ only in data. Web servers, `rayon` parallel iterators, `tokio` multi-threaded runtime, DB connection pools.

**Valid when:** CPU-bound work that partitions cleanly (rayon, `crossbeam-channel` + threads, `tokio::task::spawn_blocking`); I/O multiplexing on a fixed pool; resource pooling (DB connections, HTTP clients) with N established handles.

**Dangerous when:** the queue is unbounded (producer outruns workers → OOM); tasks hold per-thread state that breaks when reassigned (rayon work-stealing moves tasks between threa

Sponsored

Ads related to Rust Code Review and adjacent AI workflows.