google/capsem/dev-rust-patterns
Claude Code and agent skill by google/capsem
- vendor
Checking that the SKILL.md file is still in the repository.
Rust patterns and hard-won lessons. Use when writing Rust in capsem-core, capsem-app, or capsem-agent: async/tokio, non-blocking I/O, cross-compilation.
Install
npx vskill@latest install google/capsem/dev-rust-patternsSKILL.md
The same SKILL.md was published earlier as google/capsem/dev-rust-patterns.
Rust Patterns
Data paths: zero-copy first, no speculative hashing or JSON
Read data-path performance before changing transport, admission, serialization, hashing or buffer ownership. Prefer moving or borrowing bytes and one bounded encoding into the final frame. Hashing and JSON require a concrete, documented contract; neither is a default safety step.
Async / non-blocking
Capsem uses tokio for all async I/O. The MITM proxy, vsock manager, and file monitor are all async.
Publish matching in-memory ownership inside the serialized blocking admission, before releasing its I/O permit. A reader can observe the durable record before the async caller resumes after spawn_blocking; publishing its ticket after .await exposed valid managed-session claims to recovery_pending. The controller regression pauses that continuation and claims through the real store.
Never block the tokio runtime
Long-running synchronous work (FUSE request processing, disk I/O, compression) must run on a dedicated thread via tokio::task::spawn_blocking or a dedicated std::thread. Blocking inside a tokio task starves other tasks.
The VirtioFS FUSE server runs on its own thread for this reason -- FUSE ops are synchronous by nature (read, write, lookup) and can't be made async without significant complexity.
Blocking-in-async anti-pattern (systemic -- audit, don't spot-fix)
Any code path that does blocking I/O inside an async function or while holding a tokio::sync::Mutex is a bug. This causes the tokio worker thread to stall, freezing the entire gateway, UI, or network stack until the blocking operation completes.
What counts as blocking I/O:
std::process::Command(subprocess execution)std::fs::*(read, write, copy, remove_dir_all, create_dir_all)walkdir::WalkDir(directory traversal)blake3::Hasheron large data (hash computation)std::thread::sleep
The fix pattern -- in capsem-service, route handlers go through ServiceState::off_worker (crates/capsem-service/src/blocking.rs), and crates/capsem-service/src/tests/async_io_contract.rs refuses direct blocking calls. Elsewhere, the shape is:
Example site: the fork clone (crates/capsem-service/src/vm_files/fork.rs) runs clone_sandbox_state -- fsync, clonefile, and a full tree walk -- on the blocking pool. Any new tree copy, hash, or directory walk reachable from an async handler needs the same treatment.
Channel patterns
tokio::sync::mpscfor producer-consumer (vsock data flow, telemetry events)tokio::sync::broadcastfor fan-out (serial output to multiple subscribers)tokio::sync::oneshotfor single-response request-reply (control messages)
Logger DB boundary
capsem-logger owns SQLite connection/thread/storage mechanics. Rust service, gateway, MCP, UI, and benchmark code must not call rusqlite::Connection::open or DbReader::open directly for telemetry/security ledgers, and must not add service-owned projection caches.
Callers may own query intent, but the DB object owns execution:
db.write(event).await is an accept boundary: the DB-owned producer buffer has taken responsibility for the event. Read-after-write tests must use the DB flush barrier or shutdown/reopen before asserting route-visible rows. Never add route sleeps, route projection caches, or caller-owned SQLite reads to force visibility.
Do not hide route SQL by adding route-specific helpers to DbWriter; the DB writer is not a product route registry. Put connection threads, mem/disk tables, batching, flushing, WAL tuning, and future FTS5/search in the DB layer. Empty tables are fine. Missing tables or columns are schema contract failures and must not be converted into empty results.
Coalescing buffer
Terminal output uses a CoalesceBuffer (8ms window, 64KB cap) to batch small vsock reads into larger writes. This prevents xterm.js from choking on thousands of tiny updates. The pattern: accumulate into a buffer, flush on timer or size threshold.
Graceful shutdown
Use tokio::select! with a cancellation token or shutdown signal. Every long-running task must respect shutdown. Dangling tasks after VM exit cause resource leaks.
Cross-compilation
Guest binaries target aarch64-unknown-linux-musl and x86_64-unknown-linux-musl. Key gotchas:
- Platform-specific types:
libc::ioctlrequest param isc_ulongon macOS butc_inton Linux. Useas _to let the compiler infer the correct type. - Linker:
.cargo/config.tomlsetslinker = "rust-lld"for both musl targets. - No std dependencies: musl builds are fully static. Avoid crates that link to system libraries.
- Test on both:
cargo check --target aarch64-unknown-linux-muslcatches cross-compile errors without needing to boot a VM.
Error handling
- Use
anyhow::Resultfor application code (capsem-app, scripts) - Use
thiserrorfor library errors in capsem-core (typed, matchable) - Propagate errors up, don't swallow them. If a function returns
Result, the caller must handle it. - Log errors at the point where you have context, then propagate. Don't log AND propagate (causes duplicate log lines).
Host Unix boundary
Reusable host Unix mechanics belong in the small modules under capsem_foundation::unix; application crates consume their typed APIs instead of calling nix or libc directly. This keeps ownership, EINTR handling, errno classification, CLOEXEC, no-follow behavior, and race checks identical across the CLI, service, process, guard, credentials, and core.
- Accept
BorrowedFdand returnOwnedFdorFile. Never return a raw
descriptor whose close responsibility is implicit, and never pair ManuallyDrop<File> with a manual close.
- Expected races are typed outcomes: a missing process and lock contention are
not generic errors. Keep expected disconnects quiet; log unexpected failures once where the caller knows the operation, object identity, and errno.
- Use
unix::contained::ContainedDirfor guest-influenced paths. Its
descriptor-relative traversal, constrained open options, and regular-file checks must remain in the same syscall sequence; do not put a path-based check in front of a separate path-based action.
- Use
unix::fsfor owner-only directories, no-follow regular-file access,
filesystem capacity, atomic private publication, permission bits (set_mode), durability (sync, sync_before_barrier, sync_filesystem) and copy-on-write cloning (clone_file_into, copy_sparse). Use unix::tree_clone to copy a directory tree a guest can write. Use unix::lock for advisory locks, including synchronous read-modify-write sections.
- When foundation lacks a primitive, add it to foundation with its tests;
never reach for nix or libc at the call site "just this once".
- Inside foundation,
nixis the syscall layer andunix::errno::ioconverts
its errors. A raw libc:: call is allowed only where nix cannot express it (no wrapper, or a platform gap such as MSG_NOSIGNAL on macOS), and each one is listed with that reason in tests/citadel/unix_boundary_debt.toml.
- Put each primitive in its own module with tests in the sibling
tests.rs.
Cover errno preservation, ownership after the source is dropped, symlink and path-replacement races, special files, exact modes, and concurrent callers.
When transferring connected sockets with unix::router_channel, retain the original socket until a request-bound receipt confirms that the receiver owns and validated its descriptor. A completed sendmsg only queues SCM_RIGHTS; Darwin may collect sockets with no owner outside that queue. Bound the receipt wait, reject wrong identities, directions and extra descriptors, and preserve scope cancellation and positive child reaping. The native MCP regression is upstream_broker/mcp_spawn/tests.rs: it delays adoption, checks that the original stays alive, and proves it is released after the receipt. Keeping an extra socket for the child's entire lifetime masks disconnects and leaks descriptors. The same rule covers startup policy, proxy traffic/MCP/trace hints, ledger clients, gateway connections and the aggregator's owner connection. Auditing only the native MCP bootstrap missed these paths and left a macOS policy-update broken pipe. tests/citadel/test_descriptor_adoption_lifetime.py guards the early-drop sites, including private cable handoff: its table reference can be replaced by a reconnect before adoption. Gateway and upstream grant tests drop the received copy before acknowledging to prove the sender still owns its original, then assert EOF after adoption to rule out retention leaks.
Direct Unix calls remain valid only in modules that implement a kernel or platform ABI rather than reusable host policy, such as KVM/FUSE and guest audit plumbing. tests/citadel/test_unix_boundary.py and its exact domain-ABI inventory enforce that distinction; extending the inventory requires explicit review, not a convenience exemption. The same guard inventories every raw libc:: call and extern "C" binding inside foundation itself, rejects a new one that nix already wraps, and catches aliased imports (use ::libc as sys), extern "C" { fn ... } blocks and renamed or table-form manifest dependencies. Before it did, foundation's own internals were unscanned and raw calls with nix wrappers accumulated there unnoticed.
Guest RAM and VirtioFS performance
Before changing guest RAM, KVM storage or OCI boot, read Guest RAM and VirtioFS performance. Keep RAM and KVM slot offsets aligned to 2 MiB and request transparent huge pages through capsem_foundation::unix::guest_memory::GuestRam. A regular 4-KiB-backed mapping once made kernel startup take 1.1 seconds and a 352-MB EROFS scan wait 1.5 seconds in reads. The allocation and slot regression is guest_ram_and_kvm_slot_offsets_preserve_huge_page_alignment in hypervisor/kvm/memory/tests.rs; alignment alone is insufficient without the per-mapping huge-page hint.
Bidirectional I/O -- thread per direction
When bridging two blocking file descriptors bidirectionally (e.g., TCP socket to vsock in net_proxy.rs, or master PTY to vsock in capsem-pty-agent), doing both reads and writes in a single thread using poll(2) causes deadlocks. If both outgoing buffers fill simultaneously, a single thread blocks on writing and stops reading, creating mutual lockup. Always spawn a dedicated thread for at least one direction (std::thread::spawn for fd_b -> fd_a while the main thread handles fd_a -> fd_b).
Serde -- avoid serde_json::Value on LLM payloads
The MITM proxy and ai_traffic parsers handle massive HTTP payloads (megabytes of tool calls, histories, images). Parsing these into serde_json::Value does full DOM allocation, which is inefficient and risks memory exhaustion.
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files. Certified 16 Jun 2026.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/dev-rust-patterns/SKILL.md
Popularity
- Repository stars
- 56
- Repository forks
- 8
- 7-day trend score
- 20
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/google/capsem/dev-rust-patterns)