@sinkaroid/rust-shapeshift
v1.0.7
Published
Rust agent skill for extreme memory and runtime efficiency
Maintainers
Readme
Rust Shapeshift
@sinkaroid/rust-shapeshift is an AI agent skill specialized in extreme memory and runtime efficiency for Rust backend architectures. It enforces deterministic resource containment, zero-allocation data paths, and allocator-level memory reclamation across long-running production workloads.
Universally compatible with all AI agent runtimes.
Dual Operating Modes & Architectural Archetypes
Before selecting libraries, AI agents must determine both the operating mode and the workload archetype:
1. Operating Modes
- The Shapeshifter (Migration & Modernization Mode): Translates backend services from any runtime (Go, Python, Java, Node.js/TypeScript) into idiomatic Rust without carrying over garbage collection habits, DOM retention leaks, unbounded maps, or per-request connection allocations.
- The Native Architect (Greenfield Mode):
Architects native Rust services from scratch targeting modern Rust 1.80+ / 2024 Edition with baseline memory consumption (<50MB RSS), stack inlining (
compact_str), bounded buffers, zero-copy parsing, and deterministic resource lifecycles.
2. Workload Archetypes & Framework Adaptability
- Archetype A (High-Throughput / High-Density Gateway): High QPS, WebSocket clusters (50k–500k), gRPC, Tokio multi-thread runtime, bounded Moka caches, connection pooling. Axum 0.8 is adopted as the canonical reference architecture, while remaining fully adaptable to Actix Web, Salvo, or Loco via the Framework & Stack Selection Matrix. Target: <50MB–100MB bounded ceiling.
- Archetype B (Sub-Megabyte Minimalist Daemon / Sidecar - The Koburi Pattern): Low QPS, polling intervals, container monitors, CLI sidecars. DO NOT use Tokio, Axum, or async executors. Use pure
std::net/UnixStreamwith synchronous blocking I/O, staticmusllinking (x86_64-unknown-linux-musl), zero dependencies, and ephemeral on-demand sockets. Target: sub-megabyte (<5MB, down to ~50KB idle RSS).
Production Engineering References
[!IMPORTANT]
Before blindly reaching for
tokiooraxum, evaluate your workload archetype. A multi-threaded async executor burns 10MB–40MB of idle RSS on thread pools and queues your workload doesn't need. For low-QPS daemons, monitoring sidecars, or CLI utilities, adopt The Koburi Pattern with synchronous blocking I/O,muslstatic linking, and ephemeral sockets to achieve sub-megabyte memory usage.
All 57 deep-dive reference guides are located in skills/rust-shapeshift/resources
Memory, Stack & Allocator Optimization
Memory Allocator Tuning: Glibc arena containment (MALLOC_ARENA_MAX=2) andlibc::malloc_trim(0).Jemalloc Tuning & Profiling:tikv-jemallocatorvsmimalloc, dirty/muzzy decay tuning, live heap dumps viajemalloc-ctl, and DHAT.Production Memory Leak Diagnostics & eBPF: Diagnosing leaks in production with LLVM LeakSanitizer (-Zsanitizer=leak), jemalloc live heap dumps, and zero-overhead eBPF (memleak).Arena Allocation & Bump Memory: Bumpalo arena allocation, O(1) bulk dealloc, request-scoped ASTs/trees, and heap fragmentation elimination.Ownership, Borrowing & Decision Matrix: Borrow checker permissions (R/W/O), eliminating.clone(), Stack vs Heap matrix, and Future size.Typestates, Domain Proofs & Buffer Recycling: Eliminating runtime defensive branching via affine typestates, parse-don't-validate domain proofs, and buffer capacity recycling (clone_from, slab pools).Zero-Cost State Machines & Enum Dispatch: Eliminating dynamic dispatch (Box<dyn Trait>) and vtable indirection via compile-timeenum_dispatchand zero-cost typestate state machines.Compiler Niche Optimizations & Size Assertions: NonZero niche packing (Option<NonZeroU64>8B vs 16B), compile-time size asserts,.clone_from()reuse, andBox<[T]>.Enum Variant Boxing & Stack Squashing: Squashing async Future state machines and enum stack footprints viaBox<T>for variants >128B.Collection Reuse & Capacity Retention: Pre-allocated capacity reuse viaclone_from,std::mem::takeextraction without cloning, and zero-heap stackArrayVec.Stack Inlining & Allocation Reduction: Inlining short strings viacompact_str,Box<str>, andSmallVec(0 heap allocations).Cache-Line Alignment & Struct Layout: Struct padding elimination, field ordering, and#[repr(align(64))]anti-false sharing.Zero-Allocation Error Architecture: Boxing rare error payloads to minimizeResult<T, E>stack size, eliminatingformat!on error paths.Hot-Path String & Zero-Cost Helpers: Zero-regex single-pass whitespace collapsing and native integer time formatting.
Tokio, Concurrency & Reactor Safety
Predictable Tail Latency & WCET Contracts: Eliminating p99.99 spikes via offloaded destructors, bounded CAS loops, cooperative poll bounds, and lock-free ring-buffer logging.Lock-Free Ring Buffers & Disruptor Pattern: High-throughput zero-allocation queues via cache-aligned power-of-two circular ring buffers (rtrb,ArrayQueue) and Disruptor pattern.Hardware Resource Budgets & Loom Concurrency Verification: Worst-case RSS ceiling calculations, deterministic schedule permutation testing with Loom, and Tokio runtime starvation diagnostics.Tokio Thread Starvation & CPU Offload: Cooperative scheduling safety, offloading CPU >100µs viaspawn_blocking/rayon.Concurrency Primitives & Lock Contention:parking_lot1-byte locks, wait-freeArcSwap, and lock-freeAtomic*memory orderings.Deadlock Elimination & Locks Across .await: Preventing Tokio reactor thread starvation caused by holding synchronous locks across.await, RAII lock scoping, and channel-based actor patterns.Async Cancellation Safety & Task Drainage: Safety matrix fortokio::select!, drop hazard prevention, andJoinSetgraceful drainage.Adaptive Concurrency & Load Shedding: Dynamic in-flight limits, Little's Law gradient feedback, and fast-fail503 Service Unavailableshedding.
Network, Real-Time & Microservices
Real-Time WebSocket & Connection Scaling: Scaling 50k–500k connections, tuned 4KB buffers, single-task event loops, and zero-copy broadcasting.gRPC, Tonic & HTTP/2 Memory Tuning: HTTP/2 stream/conn window bounding (64KB/512KB), streaming RPC backpressure, and zero-copyBytes.Reqwest Client & Socket Pooling: Singleton pool inArc<AppState>, tiered timeouts, and selective/randomnon-caching.Bounded Streaming & Payload Guards: Bounded HTTP streaming,take(MAX_BYTES)limits, memory bomb defense, and zero-copy proxying.Zero-Copy IPC & Shared Memory: Unix Domain Sockets (UDS) vs TCP loopback, andmemmap2shared memory ring buffers.
Data Ingestion, Storage & Queues
Memory-Mapped Files & Zero-Copy Paging: Zero-heap disk I/O viamemmap2, kernel page cache delegation,madvisepaging, and zero-copy static asset serving.SQLx & Database Pool Memory: Streaming query rows (.fetch), connection pool sizing formula, and statement cache containment.Message Queue & Stream Backpressure: Broker prefetch bounding (Kafka, RabbitMQ, SQS), decoupled Tokio MPSC pipeline, and offset safety.Streaming File I/O & Compression: Chunked disk I/O, streaming Zstd/Gzip compression without in-memoryVec<u8>buffers, and Axum export streams.Redis Connection & Pooling Pitfalls: Solving lazy connection traps,tokio-comprequirements, startup asyncPING, and credential masking.Bounded Caching & Pooling: Hybridmokain-memory cache (bounded 1,000) withdeadpool-redisfallback.Rate Limiting & State Management: Hard capacity ceilingDashMap, 30s background cleaner tasks, and proxy IP extraction.
Serialization, SIMD, BCE & Compiler Tuning
Zero-Allocation Serialization with rkyv & zerocopy: In-place 0ns zero-allocation serialization withrkyvArchive andzerocopyPOD framing directly from raw byte slices.Bounds Check Elimination & Zero-Cost Memory: BCE loop proofing, eliminating zeroing tax viaMaybeUninit/BytesMut,std::mem::take, andArrayVec.Zero-Cost Iterators & Pipeline Inlining: Zero-allocation lazy iterator pipelines, eliminating intermediate.collect()vectors,.drain()buffer recycling, andimpl Iteratorinlining.Numeric Safety & Saturating Arithmetic: Zero-panic saturating/checked/wrapping arithmetic, eliminating silent truncation viaTryFrom, and deterministic floattotal_cmpordering.SIMD Vectorization & Acceleration: AVX2/NEON vector parsing,memchrdelimiter scanning,simdutf8validation, and zero-copy unmasking.Profile-Guided Optimization & Fast Hashing: PGO multi-stage pipeline, LLVM BOLT,AHashMap/FxHashMapselection matrix.Zero-Copy Serde & Streaming:#[serde(borrow)]with&'a str(0 alloc),BytesMutstreaming, and SIMD parsing.GraphQL Memory & Query Containment: Hard query depth & complexity limits,DataLoaderN+1 elimination, and Axum 0.8 integration.DOM & Scraper Pruning: Pre-parse HTML slicing (&html[..end_pos]) slashing 80% of DOM AST node allocations.Headless-Free Anti-Bot Solvers: Eliminating 500MB+ Chromium instances with reverse-engineered algorithmic solvers & single-flightRwLock.
Minimalist Daemons, Container Ops & Wasm
Zero-Runtime Minimalist Daemons: The Koburi Pattern: sub-5MB idle RSS, zero-async blocking architecture, musl static linking, std-only streams, and ephemeral sockets.Axum 0.8 & Tower Middleware: Production Axum 0.8 template, Tower middleware ordering, and dual graceful shutdown signals.Zero-Panic & Router Architecture:#![deny(clippy::unwrap_used)], safe fallback idioms, and router recursion limits.Zero-Overhead Distributed Tracing: Compile-time static level filtering, non-blockingtracing-appender, and zero-allocation span fields.Telemetry & Metric Cardinality: Hand-rolled zero-dependency Prometheus exporter, PID-filtered sysinfo, and route cardinality protection.Docker Slimming & Build Hygiene: Sub-80MB Debian multi-stage builds,.dockerignorediscipline, and C-ABI version locking.Kubernetes Runtime & Resource Containment: CFS CPU quota threads, OOMKilled exit 137 defense, preStop 502 drain race, and safe probe architectures.WebAssembly Sandboxing & Memory Limits: WasmtimeResourceLimiterlinear memory caps, epoch interruption, and zero-copy guest memory slices.Framework & Stack Selection Matrix: Manual Zero-Deps vs Axum vs Actix Web vs Salvo vs Poem vs Rocket vs Loco decision trees.
Silicon, Kernel Bedrock & Hardware Topography
Zero-Syscall I/O & io_uring: Zero-syscall I/O via io_uring, kernel SQPOLL threads, pre-registered fixed buffers, and memory-mapped completion rings.Thread-Per-Core & Shared-Nothing Architecture: Pinned CPU cores (core_affinity),SO_REUSEPORTlisteners, and eliminating cross-core work-stealing cache thrashing.NUMA Architecture & HugePages: NUMA node memory binding (mbind), 2MB/1GB HugePages (madviseTHP) eliminating TLB misses, andmlockallpage pinning.Instruction Cache (I-Cache) & Cold Path Outlining: 32KB L1 I-cache saturation, cold path outlining (#[cold],#[inline(never)]), monomorphization bloat control, anddyn Traittrade-offs.
Installation & Usage
🚀 npx
Run inside your current project directory:
npx @sinkaroid/rust-shapeshiftInstalls the canonical skill directly into .agents/skills/rust-shapeshift.
To make the skill available globally across all projects on your machine:
npx @sinkaroid/rust-shapeshift install --globalAutomatically primes:
- Google Antigravity Global:
~/.gemini/config/skills/rust-shapeshift - Claude Code Global:
~/.claude/skills/rust-shapeshift
🚀 ask your AI agent
Install and follow this skill from https://github.com/sinkaroid/rust-shapeshiftYour agent will automatically clone, index, and apply the 57 production engineering references to your current workspace.
Native CLI Commands
rust-shapeshift list # Print all 57 production reference guides and descriptions
rust-shapeshift audit # Scan current Rust project for memory anti-patterns
rust-shapeshift mcp # Start Model Context Protocol (MCP) server over stdio
rust-shapeshift init # Configure agent skill in current directory🔌 Model Context Protocol (MCP) Server
Connect rust-shapeshift directly as an active tool server in Claude Code, Cursor, Windsurf, or Antigravity:
{
"mcpServers": {
"rust-shapeshift": {
"command": "npx",
"args": ["-y", "@sinkaroid/rust-shapeshift", "mcp"]
}
}
}Or using native binary:
{
"mcpServers": {
"rust-shapeshift": {
"command": "rust-shapeshift",
"args": ["mcp"]
}
}
}Available MCP Tools
audit_memory_antipatterns: Scans current workspace for memory bloat, missingMALLOC_ARENA_MAX, unoptimized release profile, and locks across.await.inspect_struct_layout: Computes exact field alignment, wasted padding bytes, optimal reordering, and cache-line false sharing hazards.calculate_hardware_budget: Computes worst-case RSS and maximum safe concurrent connections without triggering Linux OOMKilled (Exit Code 137).explain_recipe: Retrieves targeted zero-cost implementation snippets and principles from the 57 production guides on-demand.scaffold_archetype: Generates verified boilerplates for minimal daemons (koburi_daemon), Axum gateways (axum_gateway), or zero-copy pipelines (zero_copy_pipeline).
Legal
This tool can be freely copied, modified, altered, distributed without any attribution whatsoever. However, if you feel like this tool deserves an attribution, mention it. It won't hurt anybody.
Licence: WTF.
