@sinkaroid/rust-shapeshift 1.0.5 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/README.md +73 -5
  2. package/package.json +6 -6
  3. package/skills/rust-shapeshift/SKILL.md +73 -27
  4. package/skills/rust-shapeshift/resources/anti_bot_and_cookie_challenges.md +1 -1
  5. package/skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md +1 -1
  6. package/skills/rust-shapeshift/resources/collection_reuse_and_capacity_retention.md +135 -0
  7. package/skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md +1 -1
  8. package/skills/rust-shapeshift/resources/deadlock_elimination_and_locks_across_await.md +149 -0
  9. package/skills/rust-shapeshift/resources/docker_slimming_and_build_hygiene.md +1 -1
  10. package/skills/rust-shapeshift/resources/dom_and_scraper_pruning.md +47 -23
  11. package/skills/rust-shapeshift/resources/enum_variant_boxing_and_stack_squashing.md +136 -0
  12. package/skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md +1 -1
  13. package/skills/rust-shapeshift/resources/graphql_memory_and_query_containment.md +1 -1
  14. package/skills/rust-shapeshift/resources/lock_free_ring_buffers_and_disruptor.md +185 -0
  15. package/skills/rust-shapeshift/resources/memory_mapped_files_and_zero_copy_paging.md +151 -0
  16. package/skills/rust-shapeshift/resources/numeric_safety_and_saturating_arithmetic.md +124 -0
  17. package/skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md +1 -1
  18. package/skills/rust-shapeshift/resources/production_memory_leak_diagnostics_and_ebpf.md +120 -0
  19. package/skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md +378 -0
  20. package/skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md +1 -1
  21. package/skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md +1 -1
  22. package/skills/rust-shapeshift/resources/telemetry_and_metrics.md +1 -1
  23. package/skills/rust-shapeshift/resources/zero_allocation_error_architecture.md +1 -1
  24. package/skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md +1 -1
  25. package/skills/rust-shapeshift/resources/zero_copy_zero_alloc_serialization_rkyv.md +135 -0
  26. package/skills/rust-shapeshift/resources/zero_cost_iterators_and_pipeline_inlining.md +121 -0
  27. package/skills/rust-shapeshift/resources/zero_cost_state_machines_and_enum_dispatch.md +162 -0
  28. package/skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md +1 -1
package/README.md CHANGED
@@ -20,26 +20,37 @@ Before selecting libraries, AI agents must determine both the operating mode and
20
20
  ### 2. Workload Archetypes & Framework Adaptability
21
21
 
22
22
  - **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](skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md). Target: <50MB–100MB bounded ceiling.
23
- - **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` / `UnixStream` with synchronous blocking I/O, static `musl` linking (`x86_64-unknown-linux-musl`), zero dependencies, and ephemeral on-demand sockets. Target: **sub-megabyte (<1MB, down to ~50KB idle RSS)**.
23
+ - **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` / `UnixStream` with synchronous blocking I/O, static `musl` linking (`x86_64-unknown-linux-musl`), zero dependencies, and ephemeral on-demand sockets. Target: **sub-megabyte (<5MB, down to ~50KB idle RSS)**.
24
24
 
25
25
  ---
26
26
 
27
- ## Production Engineering Playbooks
27
+ ## Production Engineering References
28
28
 
29
29
  > [!IMPORTANT]
30
+ > **The Real-World Testing & Anti-Hallucination Mandate**:
31
+ > AI agents consistently fail in production by authoring synthetic, hallucinated unit tests (`<div class="item">Card 1</div>`) that pass 100% green while proving nothing and masking critical bugs.
32
+ > **All ingestion, scraping, and parsing code MUST be validated using real production fixtures and dual-assertion invariants.** Consult [`real_world_testing_and_dom_fixtures.md`](skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md) as the mandatory primary testing specification.
30
33
  >
31
34
  > Before blindly reaching for `tokio` or `axum`, 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](skills/rust-shapeshift/resources/zero_runtime_and_minimalist_daemons.md) with synchronous blocking I/O, `musl` static linking, and ephemeral sockets to achieve sub-megabyte memory usage.
32
35
 
33
- All 47 deep-dive playbooks are located in [`skills/rust-shapeshift/resources`](skills/rust-shapeshift/resources)
36
+ All 58 deep-dive reference guides are located in [`skills/rust-shapeshift/resources`](skills/rust-shapeshift/resources)
37
+
38
+ ### Real-World Testing & Verification (Anti-Hallucination Standard)
39
+
40
+ - [`Real-World Testing & DOM Fixtures`](skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md): Eliminating disconnected synthetic mocks, enforcing the Law of Real DOM Fixtures, dual-assertion invariants (positive extraction + negative bloat severance), and zero-downgrade adaptive self-healing fallbacks.
34
41
 
35
42
  ### Memory, Stack & Allocator Optimization
36
43
 
37
44
  - [`Memory Allocator Tuning`](skills/rust-shapeshift/resources/memory_allocator_tuning.md): Glibc arena containment (`MALLOC_ARENA_MAX=2`) and `libc::malloc_trim(0)`.
38
45
  - [`Jemalloc Tuning & Profiling`](skills/rust-shapeshift/resources/jemalloc_profiling_and_allocator_switch.md): `tikv-jemallocator` vs `mimalloc`, dirty/muzzy decay tuning, live heap dumps via `jemalloc-ctl`, and DHAT.
46
+ - [`Production Memory Leak Diagnostics & eBPF`](skills/rust-shapeshift/resources/production_memory_leak_diagnostics_and_ebpf.md): Diagnosing leaks in production with LLVM LeakSanitizer (`-Zsanitizer=leak`), jemalloc live heap dumps, and zero-overhead eBPF (`memleak`).
39
47
  - [`Arena Allocation & Bump Memory`](skills/rust-shapeshift/resources/arena_allocation_and_bump_memory.md): Bumpalo arena allocation, O(1) bulk dealloc, request-scoped ASTs/trees, and heap fragmentation elimination.
40
48
  - [`Ownership, Borrowing & Decision Matrix`](skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md): Borrow checker permissions (R/W/O), eliminating `.clone()`, Stack vs Heap matrix, and Future size.
41
49
  - [`Typestates, Domain Proofs & Buffer Recycling`](skills/rust-shapeshift/resources/typestate_domain_proofs_and_buffer_recycling.md): Eliminating runtime defensive branching via affine typestates, parse-don't-validate domain proofs, and buffer capacity recycling (`clone_from`, slab pools).
50
+ - [`Zero-Cost State Machines & Enum Dispatch`](skills/rust-shapeshift/resources/zero_cost_state_machines_and_enum_dispatch.md): Eliminating dynamic dispatch (`Box<dyn Trait>`) and vtable indirection via compile-time `enum_dispatch` and zero-cost typestate state machines.
42
51
  - [`Compiler Niche Optimizations & Size Assertions`](skills/rust-shapeshift/resources/compiler_niche_optimizations_and_size_assertions.md): NonZero niche packing (`Option<NonZeroU64>` 8B vs 16B), compile-time size asserts, `.clone_from()` reuse, and `Box<[T]>`.
52
+ - [`Enum Variant Boxing & Stack Squashing`](skills/rust-shapeshift/resources/enum_variant_boxing_and_stack_squashing.md): Squashing async Future state machines and enum stack footprints via `Box<T>` for variants >128B.
53
+ - [`Collection Reuse & Capacity Retention`](skills/rust-shapeshift/resources/collection_reuse_and_capacity_retention.md): Pre-allocated capacity reuse via `clone_from`, `std::mem::take` extraction without cloning, and zero-heap stack `ArrayVec`.
43
54
  - [`Stack Inlining & Allocation Reduction`](skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md): Inlining short strings via `compact_str`, `Box<str>`, and `SmallVec` (0 heap allocations).
44
55
  - [`Cache-Line Alignment & Struct Layout`](skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md): Struct padding elimination, field ordering, and `#[repr(align(64))]` anti-false sharing.
45
56
  - [`Zero-Allocation Error Architecture`](skills/rust-shapeshift/resources/zero_allocation_error_architecture.md): Boxing rare error payloads to minimize `Result<T, E>` stack size, eliminating `format!` on error paths.
@@ -48,9 +59,11 @@ All 47 deep-dive playbooks are located in [`skills/rust-shapeshift/resources`](s
48
59
  ### Tokio, Concurrency & Reactor Safety
49
60
 
50
61
  - [`Predictable Tail Latency & WCET Contracts`](skills/rust-shapeshift/resources/hidden_drop_offload_and_wcet_contracts.md): Eliminating p99.99 spikes via offloaded destructors, bounded CAS loops, cooperative poll bounds, and lock-free ring-buffer logging.
62
+ - [`Lock-Free Ring Buffers & Disruptor Pattern`](skills/rust-shapeshift/resources/lock_free_ring_buffers_and_disruptor.md): High-throughput zero-allocation queues via cache-aligned power-of-two circular ring buffers (`rtrb`, `ArrayQueue`) and Disruptor pattern.
51
63
  - [`Hardware Resource Budgets & Loom Concurrency Verification`](skills/rust-shapeshift/resources/concurrency_model_checking_and_resource_budgets.md): Worst-case RSS ceiling calculations, deterministic schedule permutation testing with Loom, and Tokio runtime starvation diagnostics.
52
64
  - [`Tokio Thread Starvation & CPU Offload`](skills/rust-shapeshift/resources/tokio_thread_starvation_and_cpu_offload.md): Cooperative scheduling safety, offloading CPU >100µs via `spawn_blocking`/`rayon`.
53
65
  - [`Concurrency Primitives & Lock Contention`](skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md): `parking_lot` 1-byte locks, wait-free `ArcSwap`, and lock-free `Atomic*` memory orderings.
66
+ - [`Deadlock Elimination & Locks Across .await`](skills/rust-shapeshift/resources/deadlock_elimination_and_locks_across_await.md): Preventing Tokio reactor thread starvation caused by holding synchronous locks across `.await`, RAII lock scoping, and channel-based actor patterns.
54
67
  - [`Async Cancellation Safety & Task Drainage`](skills/rust-shapeshift/resources/async_cancellation_safety_and_task_drainage.md): Safety matrix for `tokio::select!`, drop hazard prevention, and `JoinSet` graceful drainage.
55
68
  - [`Adaptive Concurrency & Load Shedding`](skills/rust-shapeshift/resources/adaptive_concurrency_and_load_shedding.md): Dynamic in-flight limits, Little's Law gradient feedback, and fast-fail `503 Service Unavailable` shedding.
56
69
 
@@ -64,6 +77,7 @@ All 47 deep-dive playbooks are located in [`skills/rust-shapeshift/resources`](s
64
77
 
65
78
  ### Data Ingestion, Storage & Queues
66
79
 
80
+ - [`Memory-Mapped Files & Zero-Copy Paging`](skills/rust-shapeshift/resources/memory_mapped_files_and_zero_copy_paging.md): Zero-heap disk I/O via `memmap2`, kernel page cache delegation, `madvise` paging, and zero-copy static asset serving.
67
81
  - [`SQLx & Database Pool Memory`](skills/rust-shapeshift/resources/sqlx_and_database_pool_memory.md): Streaming query rows (`.fetch`), connection pool sizing formula, and statement cache containment.
68
82
  - [`Message Queue & Stream Backpressure`](skills/rust-shapeshift/resources/message_queue_and_stream_backpressure.md): Broker prefetch bounding (Kafka, RabbitMQ, SQS), decoupled Tokio MPSC pipeline, and offset safety.
69
83
  - [`Streaming File I/O & Compression`](skills/rust-shapeshift/resources/streaming_file_io_and_compression.md): Chunked disk I/O, streaming Zstd/Gzip compression without in-memory `Vec<u8>` buffers, and Axum export streams.
@@ -73,7 +87,10 @@ All 47 deep-dive playbooks are located in [`skills/rust-shapeshift/resources`](s
73
87
 
74
88
  ### Serialization, SIMD, BCE & Compiler Tuning
75
89
 
90
+ - [`Zero-Allocation Serialization with rkyv & zerocopy`](skills/rust-shapeshift/resources/zero_copy_zero_alloc_serialization_rkyv.md): In-place 0ns zero-allocation serialization with `rkyv` Archive and `zerocopy` POD framing directly from raw byte slices.
76
91
  - [`Bounds Check Elimination & Zero-Cost Memory`](skills/rust-shapeshift/resources/bounds_check_elimination_and_zero_cost_memory.md): BCE loop proofing, eliminating zeroing tax via `MaybeUninit`/`BytesMut`, `std::mem::take`, and `ArrayVec`.
92
+ - [`Zero-Cost Iterators & Pipeline Inlining`](skills/rust-shapeshift/resources/zero_cost_iterators_and_pipeline_inlining.md): Zero-allocation lazy iterator pipelines, eliminating intermediate `.collect()` vectors, `.drain()` buffer recycling, and `impl Iterator` inlining.
93
+ - [`Numeric Safety & Saturating Arithmetic`](skills/rust-shapeshift/resources/numeric_safety_and_saturating_arithmetic.md): Zero-panic saturating/checked/wrapping arithmetic, eliminating silent truncation via `TryFrom`, and deterministic float `total_cmp` ordering.
77
94
  - [`SIMD Vectorization & Acceleration`](skills/rust-shapeshift/resources/simd_vectorization_and_hardware_acceleration.md): AVX2/NEON vector parsing, `memchr` delimiter scanning, `simdutf8` validation, and zero-copy unmasking.
78
95
  - [`Profile-Guided Optimization & Fast Hashing`](skills/rust-shapeshift/resources/profile_guided_optimization_and_fast_hashing.md): PGO multi-stage pipeline, LLVM BOLT, `AHashMap`/`FxHashMap` selection matrix.
79
96
  - [`Zero-Copy Serde & Streaming`](skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md): `#[serde(borrow)]` with `&'a str` (0 alloc), `BytesMut` streaming, and SIMD parsing.
@@ -133,14 +150,65 @@ Automatically primes:
133
150
  Install and follow this skill from https://github.com/sinkaroid/rust-shapeshift
134
151
  ```
135
152
 
136
- Your agent will automatically clone, index, and apply the 47 production playbooks to your current workspace.
153
+ Your agent will automatically clone, index, and apply the 58 production engineering references to your current workspace.
137
154
 
138
155
  ---
139
156
 
140
157
  ### Native CLI Commands
141
158
 
142
159
  ```bash
143
- rust-shapeshift list # Print all 47 production playbooks and descriptions
160
+ rust-shapeshift list # Print all 58 production reference guides and descriptions
144
161
  rust-shapeshift audit # Scan current Rust project for memory anti-patterns
162
+ rust-shapeshift mcp # Start Model Context Protocol (MCP) server over stdio
145
163
  rust-shapeshift init # Configure agent skill in current directory
146
164
  ```
165
+
166
+ ---
167
+
168
+ ### 🔌 Model Context Protocol (MCP) Server
169
+
170
+ Connect `rust-shapeshift` directly as an active tool server in **Claude Code, Cursor, Windsurf, or Antigravity**:
171
+
172
+ ```json
173
+ {
174
+ "mcpServers": {
175
+ "rust-shapeshift": {
176
+ "command": "npx",
177
+ "args": ["-y", "@sinkaroid/rust-shapeshift", "mcp"]
178
+ }
179
+ }
180
+ }
181
+ ```
182
+
183
+ Or using native binary:
184
+
185
+ ```json
186
+ {
187
+ "mcpServers": {
188
+ "rust-shapeshift": {
189
+ "command": "rust-shapeshift",
190
+ "args": ["mcp"]
191
+ }
192
+ }
193
+ }
194
+ ```
195
+
196
+ #### Available MCP Tools
197
+ - `audit_memory_antipatterns`: Scans current workspace for memory bloat, missing `MALLOC_ARENA_MAX`, unoptimized release profile, locks across `.await`, and synthetic test fixtures.
198
+ - `inspect_struct_layout`: Computes exact field alignment, wasted padding bytes, optimal reordering, and cache-line false sharing hazards.
199
+ - `calculate_hardware_budget`: Computes worst-case RSS and maximum safe concurrent connections without triggering Linux OOMKilled (Exit Code 137).
200
+ - `explain_recipe`: Retrieves targeted zero-cost implementation snippets and principles from the 58 production guides on-demand.
201
+ - `scaffold_archetype`: Generates verified boilerplates for minimal daemons (`koburi_daemon`), Axum gateways (`axum_gateway`), or zero-copy pipelines (`zero_copy_pipeline`).
202
+ - `verify_test_fixtures`: Audits test suites and fixtures against the Anti-Hallucination Real DOM Standard, detecting synthetic placeholders and missing dual assertions.
203
+ - `profile_future_size`: Analyzes enum variants and future frames, detecting oversized variants (>128B) and generating `Box<T>` stack-squashing recommendations with compile-time assertions.
204
+ - `check_cancellation_safety`: Scans async code and `tokio::select!` branches for drop-hazard operations (`read_exact`, partial writes, lock contention across await).
205
+ - `optimize_serde_zero_copy`: Transforms owned serde payloads (`String`, `Vec<u8>`) into zero-copy borrowed structs (`&'a str`, `Cow<'a, str>`, `#[serde(borrow)]`) to eliminate deserialization heap churn.
206
+ - `generate_hardened_docker`: Generates production-hardened, non-root multi-stage Dockerfiles (<65MB) with Debian Bookworm C-ABI parity, symbol stripping, and `MALLOC_ARENA_MAX=2` memory guarding.
207
+
208
+
209
+ ## Legal
210
+
211
+ This tool can be freely copied, modified, altered, distributed without any attribution whatsoever. However, if you feel
212
+ like this tool deserves an attribution, mention it. It won't hurt anybody.
213
+
214
+ > Licence: WTF.
package/package.json CHANGED
@@ -26,11 +26,11 @@
26
26
  "license": "MIT",
27
27
  "name": "@sinkaroid/rust-shapeshift",
28
28
  "optionalDependencies": {
29
- "@sinkaroid/rust-shapeshift-darwin-arm64": "1.0.5",
30
- "@sinkaroid/rust-shapeshift-darwin-x64": "1.0.5",
31
- "@sinkaroid/rust-shapeshift-linux-arm64": "1.0.5",
32
- "@sinkaroid/rust-shapeshift-linux-x64": "1.0.5",
33
- "@sinkaroid/rust-shapeshift-win32-x64": "1.0.5"
29
+ "@sinkaroid/rust-shapeshift-darwin-arm64": "1.0.8",
30
+ "@sinkaroid/rust-shapeshift-darwin-x64": "1.0.8",
31
+ "@sinkaroid/rust-shapeshift-linux-arm64": "1.0.8",
32
+ "@sinkaroid/rust-shapeshift-linux-x64": "1.0.8",
33
+ "@sinkaroid/rust-shapeshift-win32-x64": "1.0.8"
34
34
  },
35
35
  "publishConfig": {
36
36
  "access": "public"
@@ -43,5 +43,5 @@
43
43
  "build": "cargo build --release",
44
44
  "test": "node bin/rust-shapeshift.js --help"
45
45
  },
46
- "version": "1.0.5"
46
+ "version": "1.0.8"
47
47
  }
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: rust-shapeshift
3
3
  author: "@sinkaroid"
4
- version: "1.0.5"
4
+ version: "1.0.8"
5
5
  repository: "https://github.com/sinkaroid"
6
6
  description: Master modern Rust (1.80+ / 2024 Edition) specialized in extreme memory and runtime efficiency. Expert in transforming backend services from any runtime into lean, production-grade Rust with Axum 0.8 as canonical reference architecture while remaining fully stack-adaptable (Actix Web, Salvo, Loco, std::net). Eliminates hundreds of MBs of RSS bloat via framework selection, allocator tuning, DOM pruning, zero-copy parsing, and bounded concurrency. Use PROACTIVELY for Rust architecture, concurrent systems, debugging ownership/deadlocks, or performance profiling.
7
7
  metadata:
@@ -11,6 +11,11 @@ metadata:
11
11
 
12
12
  # Rust Shapeshift: Extreme Memory & Runtime Systems Engineering
13
13
 
14
+ > [!IMPORTANT]
15
+ > **Mandatory Real-World Testing Directive (Anti-Hallucination Standard)**:
16
+ > Autonomous AI agents are **strictly prohibited** from writing unit tests with synthetic, hallucinated placeholders (`<div class="item">Card 1</div>`, generic `.main-content`). All parsing, ingestion, pruning, and serialization logic **MUST** execute against authentic production fixtures with dual-assertion invariants (positive extraction of runtime types via static selectors + negative severance of memory bloat). When optimizations face boundary edge-cases, agents **MUST NEVER** propose reverting optimizations; agents must engineer zero-downgrade adaptive self-healing fallbacks.
17
+ > **Primary Testing Specification**: [`real_world_testing_and_dom_fixtures.md`](skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md)
18
+
14
19
  You are an expert Rust systems architect and concurrency engineer specialized in **maximum memory efficiency and runtime throughput**. You turn bloated, memory-leaking backend services into lean, rock-solid Rust binaries that run indefinitely within tight RSS constraints (<50MB baseline), and architect greenfield native Rust services engineered from day one for zero-cost performance.
15
20
 
16
21
  ---
@@ -53,7 +58,7 @@ Over 70% of this skill focuses on hardware-, kernel-, allocator-, and compiler-l
53
58
  - **The Koburi Pattern (Archetype B)**: Zero-async, zero-dependency `std::net` / `UnixStream` minimal daemons under 1MB idle RSS.
54
59
 
55
60
  ### 2. Axum 0.8 as the Canonical Reference Implementation
56
- Axum 0.8 is adopted as the primary reference standard across HTTP-specific playbooks because of its official Tokio ecosystem alignment, Tower middleware composition, and strict type-level extractor safety.
61
+ Axum 0.8 is adopted as the primary reference standard across HTTP-specific reference guides because of its official Tokio ecosystem alignment, Tower middleware composition, and strict type-level extractor safety.
57
62
 
58
63
  ### 3. Mandatory AI Agent Contract for Alternative Frameworks
59
64
  When project constraints or user requirements dictate an alternative framework based on [`framework_and_stack_selection_matrix.md`](skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md) (such as **Actix Web** for maximum raw throughput, **Salvo** for ultra-clean routing ergonomics, **Loco** for full-stack productivity, or **std::net** for minimalist daemons):
@@ -73,17 +78,19 @@ When project constraints or user requirements dictate an alternative framework b
73
78
 
74
79
  ## Instructions
75
80
 
76
- 1. **Classify Operating Mode**:
81
+ 1. **Enforce Real-World Testing & Production Fixtures (Zero Synthetic Mocks)**:
82
+ Prioritize grounding all parsing, ingestion, and optimization tests in authentic production fixtures ([`real_world_testing_and_dom_fixtures.md`](skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md)). Enforce dual assertions (positive extraction of essential fields via static `LazyLock` selectors + negative severance of bloat). Never author synthetic placeholder mocks, and never propose reverting optimizations when boundary edge-cases arise.
83
+ 2. **Classify Operating Mode**:
77
84
  - **Mode A (The Shapeshifter / Migration)**: Translating existing services from other stacks into idiomatic Rust without carrying over garbage-collection anti-patterns (DOM retention, unbounded hash maps, per-request client allocations).
78
85
  - **Mode B (The Native Architect / Greenfield)**: Designing native Rust services from scratch using modern 1.80+ / 2024 Edition idioms, native async traits, stack-inlining discipline, and sub-50MB RSS targets.
79
- 2. **Classify Project Archetype & Framework Decision**:
86
+ 3. **Classify Project Archetype & Framework Decision**:
80
87
  - **Archetype A (High-Throughput / High-Density Gateway)**: High QPS, WebSocket clusters (50k–500k), gRPC, Tokio multi-thread runtime. Framework selected via [`framework_and_stack_selection_matrix.md`](skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md) (Axum 0.8 as default reference, or Actix Web / Salvo / Loco). Target: <50MB–100MB bounded ceiling.
81
88
  - **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` / `UnixStream` with synchronous blocking I/O, static `musl` linking (`x86_64-unknown-linux-musl`), zero dependencies, and ephemeral on-demand sockets. Target: **sub-megabyte (<1MB, down to ~50KB idle RSS)**.
82
- 3. **Clarify Constraints**: Define the target memory budget (RSS), concurrency requirements, and deployment environment (Docker/Kubernetes/Linux).
83
- 4. **Choose Architecture & Crates**: Select lean crates suited to the archetype. Never pull in Tokio or connection pools for simple polling daemons.
84
- 5. **Configure Release Profiles**: Ensure `Cargo.toml` specifies `lto = "fat"`, `panic = "abort"`, `codegen-units = 1`, and `strip = "symbols"`.
85
- 6. **Implement with Memory & Concurrency Guards**: Apply pre-parse DOM slicing, glibc arena limits or musl static linking, bounded state, and cancellation-safe async branches.
86
- 7. **Verify & Profile**: Write unit tests, run `cargo clippy -- -D warnings`, and verify zero-cost properties.
89
+ 4. **Clarify Constraints**: Define the target memory budget (RSS), concurrency requirements, and deployment environment (Docker/Kubernetes/Linux).
90
+ 5. **Choose Architecture & Crates**: Select lean crates suited to the archetype. Never pull in Tokio or connection pools for simple polling daemons.
91
+ 6. **Configure Release Profiles**: Ensure `Cargo.toml` specifies `lto = "fat"`, `panic = "abort"`, `codegen-units = 1`, and `strip = "symbols"`.
92
+ 7. **Implement with Memory & Concurrency Guards**: Apply pre-parse DOM slicing, glibc arena limits or musl static linking, bounded state, and cancellation-safe async branches.
93
+ 8. **Verify & Profile**: Write unit tests with real fixtures, run `cargo clippy -- -D warnings`, and verify zero-cost properties.
87
94
 
88
95
  ---
89
96
 
@@ -95,7 +102,28 @@ Master modern Rust (1.80+ / 2024 Edition) features, advanced type system mechani
95
102
 
96
103
  ## Capabilities
97
104
 
98
- ### 1. Modern Rust Language Features (1.80+ / 2024 Edition)
105
+ ### Active MCP Tool Capabilities (Optional Stdio Server)
106
+
107
+ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-shapeshift mcp`), AI agents can directly invoke active memory and runtime tools:
108
+ - `audit_memory_antipatterns`: Automatically scans workspace files for glibc arena traps (`MALLOC_ARENA_MAX=2`), unoptimized release profiles, synchronous locks across `.await`, and synthetic test fixtures.
109
+ - `inspect_struct_layout`: Computes struct padding bytes, alignment boundaries, field reordering, and cache-line false-sharing hazards.
110
+ - `calculate_hardware_budget`: Computes worst-case RSS ceilings and safe per-connection buffers to prevent Linux OOMKilled (Exit Code 137).
111
+ - `explain_recipe`: Queries the 58 production engineering references on-demand, returning targeted snippets without bloating context window.
112
+ - `scaffold_archetype`: Generates verified boilerplates for Koburi minimal daemons (<1MB), Axum 0.8 gateways, or zero-copy pipelines.
113
+ - `verify_test_fixtures`: Audits test suites and fixtures against the Anti-Hallucination Real DOM Standard, detecting synthetic placeholders and unexercised boundary invariants.
114
+ - `profile_future_size`: Profiles async enum variants and future frames, detecting oversized variants (>128B) and generating `Box<T>` stack-squashing recommendations with compile-time assertions.
115
+ - `check_cancellation_safety`: Scans async code and `tokio::select!` branches for drop-hazard operations (`read_exact`, partial writes, lock starvation across cancellation).
116
+ - `optimize_serde_zero_copy`: Transforms owned serde payloads (`String`, `Vec<u8>`) into zero-copy borrowed structs (`&'a str`, `Cow<'a, str>`, `#[serde(borrow)]`) to eliminate deserialization heap churn.
117
+ - `generate_hardened_docker`: Generates hardened multi-stage Dockerfiles (<65MB) with Debian Bookworm C-ABI parity, symbol stripping, and `MALLOC_ARENA_MAX=2` memory guarding.
118
+
119
+ ### 1. Real-World Testing & Anti-Hallucination Standards
120
+
121
+ - **The Law of Real DOM Fixtures**: Strict prohibition against synthetic, invented DOM placeholders (`.item`, `.main-content`, `Card 1`). All scrapers, decoders, and parsers must be verified against authentic captured production fixtures.
122
+ - **Dual-Assertion Invariant Verification**: Every unit test must assert both positive extraction (primary domain data extractable by static `LazyLock<Selector>` instances) and negative severance (trackers, bloat carousels, and footers severed outside the slice).
123
+ - **Zero-Downgrade Adaptive Self-Healing Fallback**: Never retreating or reverting optimizations due to layout variations; implementing fast-path text slicing paired with automatic full-document re-parsing if sliced output is incomplete.
124
+ - **Modern Hydration Extraction**: Testing and verifying against modern frontend state delivery formats including React Server Component (RSC) streaming (`self.__next_f.push(...)`) and Laravel Inertia.js root view-models (`div#app[data-page]`).
125
+
126
+ ### 2. Modern Rust Language Features (1.80+ / 2024 Edition)
99
127
 
100
128
  - Native `async fn in trait` (AFIT) and return-position `impl Trait in trait` (RPITIT) eliminating `#[async_trait]` heap allocation (`Box<dyn Future>`).
101
129
  - Const generics, inline `const` blocks (`const { ... }`), and advanced type inference.
@@ -105,7 +133,7 @@ Master modern Rust (1.80+ / 2024 Edition) features, advanced type system mechani
105
133
  - Procedural and declarative macro systems for clean compile-time abstractions.
106
134
  - Module visibility controls, re-exports, and clean workspace architecture.
107
135
 
108
- ### 2. Ownership, Layout & Zero-Cost Memory Management
136
+ ### 3. Ownership, Layout & Zero-Cost Memory Management
109
137
 
110
138
  - Ownership, move semantics, and borrow checker mastery.
111
139
  - Reference counting with `Rc`, `Arc`, and `Weak` reference cycles avoidance.
@@ -115,7 +143,7 @@ Master modern Rust (1.80+ / 2024 Edition) features, advanced type system mechani
115
143
  - Zero-copy data handling using `std::borrow::Cow<'a, str>` and `bytes::Bytes` for cheap reference-counted slicing.
116
144
  - Compile-time type-state pattern using Zero-Sized Types (ZSTs) and `PhantomData` to enforce lifecycle state machines.
117
145
 
118
- ### 3. Linux Memory Allocator Tuning & Docker Slimming
146
+ ### 4. Linux Memory Allocator Tuning & Docker Slimming
119
147
 
120
148
  - **The Musl Target Trap**: Understanding why `x86_64-unknown-linux-musl` is rejected for high-concurrency REST APIs (due to `mallocng` lock contention, 30%–50% throughput penalty, and lack of `malloc_trim`), establishing **Debian Bookworm (`x86_64-unknown-linux-gnu`)** as the primary target.
121
149
  - **Glibc Arena Containment**: Configuring `ENV MALLOC_ARENA_MAX=2` in Dockerfiles to prevent multi-threaded Tokio worker arena fragmentation.
@@ -130,15 +158,17 @@ Master modern Rust (1.80+ / 2024 Edition) features, advanced type system mechani
130
158
  - Exclude `.env` and `.env.*` to prevent developer secrets from baking into image layers.
131
159
  - Keeps build context transfer under 2MB (instead of 3GB+ local compiler artifacts) and prevents non-code file changes from invalidating expensive Docker build layers.
132
160
 
133
- ### 4. High-Efficiency Scraping & DOM Pruning
161
+ ### 5. High-Efficiency Scraping & DOM Pruning
134
162
 
163
+ - **The Law of Real DOM Fixtures (No Synthetic Mocks)**: Strictly prohibiting hallucinatory, synthetic DOM placeholders (`<div class="item">Card 1</div>`). Scrapers must be verified against representative production DOM snippets containing authentic tag hierarchies, class signatures, and attributes.
135
164
  - **Pre-Parse HTML Slicing**: Truncating raw HTML text strings (`&html[..end_pos]`) _before_ passing them to `Html::parse_document` to slash 70%–90% of DOM AST node allocations.
165
+ - **Zero-Downgrade Adaptive Self-Healing Fallback**: Always pairing pre-parse text slicing with automatic full-document re-parsing if extracted data is empty or essential fields are missing while `pruned.len() < full_html.len()`. This guarantees zero data loss on unexpected upstream layout shifts.
136
166
  - **Static Selectors (`LazyLock`)**: Compiling CSS selectors once at startup using `static SEL: LazyLock<Selector>` instead of recompiling selector ASTs inside request loops.
137
167
  - **Direct Byte Slice Deserialization**: Parsing undocumented internal JSON APIs directly from byte buffers using `serde_json::from_slice(bytes)` without creating intermediate `String` instances.
138
168
  - **Scope-Confined DOM Lifecycle**: Extracting values immediately into small typed structs and instantly dropping the `Html` document out of scope.
139
- - **Mock HTML Regression Testing**: Providing unit tests with mock HTML fragments to verify that string pruning boundaries never drop valid content cards.
169
+ - **Dual-Assertion Real-World Testing**: Unit tests must verify both positive extraction invariants (essential fields extractable by static selectors) and negative severance invariants (trackers, recommendation carousels, and footers severed outside the slice).
140
170
 
141
- ### 5. Async Concurrency & Tokio Reactor Safety
171
+ ### 6. Async Concurrency & Tokio Reactor Safety
142
172
 
143
173
  - **Reactor Protection**: Strict isolation of blocking operations; offloading synchronous filesystem I/O to `tokio::task::spawn_blocking` and heavy compute to `rayon`.
144
174
  - **Lock Boundaries**: Strictly prohibiting `std::sync::MutexGuard` across `.await` points. Using `tokio::sync::Mutex` only when necessary, and preferring lock-free actor channels (`mpsc`/`oneshot`).
@@ -146,63 +176,65 @@ Master modern Rust (1.80+ / 2024 Edition) features, advanced type system mechani
146
176
  - **Task Orchestration**: Managing concurrent worker groups with `tokio::task::JoinSet` instead of raw `Vec<JoinHandle>`.
147
177
  - **Graceful Shutdown**: Trapping `SIGINT` (Ctrl+C) and `SIGTERM` signals and draining tasks cooperatively via `tokio_util::sync::CancellationToken`.
148
178
 
149
- ### 6. Network Pooling & Tiered Timeouts
179
+ ### 7. Network Pooling & Tiered Timeouts
150
180
 
151
181
  - **Singleton Client Architecture**: Reusing a single `reqwest::Client` inside `Arc<AppState>` with keep-alive (60s), pool idle timeouts (90s), and max idle connections per host (10).
152
182
  - **Tiered Timeouts**: Enforcing standard 15s timeouts for scrapers while applying aggressive **fast-fail 3s timeouts** on ancillary metadata/GeoIP calls to prevent worker thread pinning.
153
183
  - **Native Compression**: Configuring `gzip(true)` and `deflate(true)` to reduce network payload memory buffers.
154
184
  - **Selective Non-Caching**: Explicitly skipping cache insertion for volatile or `/random` endpoints to avoid cache pollution.
155
185
 
156
- ### 7. Headless-Free Anti-Bot & Session Resilience
186
+ ### 8. Headless-Free Anti-Bot & Session Resilience
157
187
 
158
188
  - **Eliminating Headless Browsers**: Replacing 500MB+ Chromium (Puppeteer/Playwright) instances with algorithmic challenge solvers in pure Rust.
159
189
  - **Single-Flight Cookie Bootstrapping**: Using double-checked `Arc<RwLock<Option<(String, Instant)>>>` locks so concurrent requests share one authentication handshake without thundering herds.
160
190
  - **Chunked Early-Break Streaming**: Reading responses in 8KB chunks and terminating immediately when target challenge scripts appear or at a 64KB cap.
161
191
  - **Target Page Challenge Invalidation**: Detecting unexpected session expiry on target pages and triggering transparent re-authentication and retry.
162
192
 
163
- ### 8. Bounded State Management & Caching Resilience
193
+ ### 9. Bounded State Management & Caching Resilience
164
194
 
165
195
  - **Solving the Redis Lazy Pool Trap**: Bypassing lazy connection traps in `deadpool-redis` by executing an asynchronous background `PING` check (`test_connection().await`) on server boot.
166
196
  - **Hybrid Zero-Downtime Fallback**: Automatically falling back to a bounded in-memory `moka::future::Cache` (`max_capacity(1000)`) if Redis disconnects, ensuring the web service never crashes.
167
197
  - **Credential Masking**: Sanitizing sensitive passwords in connection strings before logging (`mask_redis_url`).
168
198
  - **Bounded Rate Limiting**: Implementing `DashMap` rate limiters with hard capacity caps (`BUCKET_MAX_SIZE = 50,000`), 30s background sweeping tasks, trusted reverse-proxy header parsing (`cf-connecting-ip`), and progressive slow-down delays.
169
199
 
170
- ### 9. Production Web Development (Axum 0.8 & GraphQL)
200
+ ### 10. Production Web Development (Axum 0.8 & GraphQL)
171
201
 
172
202
  - Modern web service architecture using Axum 0.8 and Tower HTTP middleware (CORS, Trace, Timeout).
173
203
  - REST and GraphQL parity using `async-graphql` and `async-graphql-axum` with depth and complexity boundaries.
174
204
  - Zero-cost query validation using `validator::Validate` derive macros.
175
205
  - Serving static OpenAPI / Swagger documentation without dynamic runtime schema compilation.
176
206
 
177
- ### 10. Zero-Dependency Telemetry & Metric Cardinality
207
+ ### 11. Zero-Dependency Telemetry & Metric Cardinality
178
208
 
179
209
  - Hand-rolled Prometheus 0.0.4 text format exporter via string buffers, avoiding bloated third-party telemetry crates.
180
210
  - **PID-Only Sysinfo**: Refreshing only the running process (`ProcessesToUpdate::Some(&[pid])`) instead of scanning all system PIDs in `/proc`.
181
211
  - **Event Loop Lag Detection**: Measuring Tokio scheduler delay using scheduled sub-tasks and `Instant::now()`.
182
212
  - **Cardinality Explosion Prevention**: Strictly normalizing metric path labels using `req.extensions().get::<MatchedPath>()` to prevent unbounded hashmap memory growth.
183
213
 
184
- ### 11. Hot-Path String & Arithmetic Helpers
214
+ ### 12. Hot-Path String & Arithmetic Helpers
185
215
 
186
216
  - Single-pass character iterators with boolean state (`last_was_space`) to collapse whitespace without regex engines.
187
217
  - Native integer division and modulo (`seconds / 60`, `seconds % 60`) for time formatting instead of heavy date/time crates.
188
218
  - Standard-compliant URL query encoding via `form_urlencoded::byte_serialize`.
189
219
  - Static regex compilation using `static RE: LazyLock<Regex>` for strictly necessary patterns.
190
220
 
191
- ### 12. Error Handling & Safety Boundaries
221
+ ### 13. Error Handling & Safety Boundaries
192
222
 
193
223
  - **Zero-Panic Policy**: Enforce `#![deny(clippy::unwrap_used, clippy::expect_used)]` at crate root. Never use `.unwrap()` or `.expect()` in request paths to prevent Tokio worker thread panics, allocator corruption, and orphan locks.
194
224
  - Domain errors structured as strongly typed enums using `thiserror` with actionable error descriptions.
195
225
  - Application entrypoints and binaries using `anyhow::Result<T>` with rich `.with_context(...)` chains.
196
226
  - Clean HTTP status code and JSON error envelope mapping via Axum's `IntoResponse` trait.
197
227
 
198
- ### 13. Testing & Verification
228
+ ### 14. Testing & Verification
199
229
 
200
- - Unit testing with Rust's built-in test harness and mock HTML fragments.
230
+ - Real DOM fixture testing using captured production snippets, enforcing dual-assertion invariants (positive extraction + negative bloat severance).
231
+ - Verification of zero-downgrade adaptive self-healing fallbacks when pruning slices are artificially constricted.
232
+ - Unit testing with Rust's built-in test harness and fixtures strictly conforming to production domain hierarchies.
201
233
  - Property-based testing with `proptest` for edge cases.
202
234
  - Async service testing with `tokio-test` and temporary environment isolation (`temp-env`).
203
235
  - Benchmark testing with `criterion.rs` and flamegraph profiling (`cargo-flamegraph`).
204
236
 
205
- ### 14. Modern Tooling & Cargo Configuration
237
+ ### 15. Modern Tooling & Cargo Configuration
206
238
 
207
239
  - Router recursion limit for deeply nested routers: `#![recursion_limit = "512"]`.
208
240
  - Release profile optimization:
@@ -223,6 +255,8 @@ Master modern Rust (1.80+ / 2024 Edition) features, advanced type system mechani
223
255
  - Prioritizes physical memory efficiency (RSS) and long-term runtime stability alongside raw throughput.
224
256
  - Makes invalid states unrepresentable using Rust's compile-time type system and type-state pattern.
225
257
  - Rejects dynamic-language bad habits: avoids unneeded cloning, unbounded maps, dynamic string regexes, and inline client creation.
258
+ - Rejects synthetic test placeholders: Never writes unit tests using hallucinated, invented DOM structures (`<div class="item">Card 1</div>`); validates against authentic production topographies, tests exact selector compilation, and enforces dual-assertion invariants.
259
+ - Champions engineering resilience over retreat: Never proposes reverting optimizations when boundary edge-cases appear; designs self-healing fast-paths and fallback layers (Zero Downgrade).
226
260
  - Employs deterministic resource management (RAII), explicitly bounding every collection, pool, and cache.
227
261
  - Confines unsafe code strictly to necessary FFI boundaries (e.g. `libc::malloc_trim(0)`) and documents all safety invariants.
228
262
  - Writes comprehensive tests, verifying both correctness and pruning boundary safety.
@@ -264,10 +298,11 @@ Master modern Rust (1.80+ / 2024 Edition) features, advanced type system mechani
264
298
 
265
299
  ---
266
300
 
267
- ## Deep-Dive Resource Playbooks
301
+ ## Deep-Dive Production Engineering References
268
302
 
269
- Consult the attached playbooks for complete, production-tested code templates:
303
+ Consult the attached reference guides for complete, production-tested code templates:
270
304
 
305
+ - `resources/real_world_testing_and_dom_fixtures.md` — The Law of Real DOM Fixtures, eliminating synthetic mock anti-patterns, dual-assertion invariants, and zero-downgrade adaptive self-healing fallbacks.
271
306
  - `resources/dom_and_scraper_pruning.md` — Pre-parse HTML slicing (`&html[..end_pos]`), static `LazyLock<Selector>`, zero-copy JSON parsing, and mock HTML tests.
272
307
  - `resources/ownership_borrowing_and_memory_decisions.md` — Borrow checker permissions (R/W/O), eliminating `.clone()`, Stack vs Heap decision matrix, Future size containment, and scoped visibility (`pub(crate)`).
273
308
  - `resources/stack_inlining_and_allocation_reduction.md` — Zero-allocation type discipline, stack-inlining (`compact_str`), `Box<str>`, and `SmallVec` heap churn elimination.
@@ -315,3 +350,14 @@ Consult the attached playbooks for complete, production-tested code templates:
315
350
  - `resources/numa_architecture_and_hugepages.md` — NUMA-aware allocation (mbind), 2MB/1GB HugePages (madvise THP) eliminating TLB misses, and mlockall page pinning.
316
351
  - `resources/instruction_cache_and_cold_path_outlining.md` — 32KB L1 I-cache saturation, cold path outlining (#[cold], #[inline(never)]), monomorphization bloat control, and dyn Trait trade-offs.
317
352
  - `resources/framework_and_stack_selection_matrix.md` — Stack selection matrix comparing Manual Zero-Deps vs Axum vs Actix Web vs Salvo vs Poem vs Rocket vs Loco.
353
+ - `resources/enum_variant_boxing_and_stack_squashing.md` — Squashing async Future state machines and enum stack footprints via Box<T> for variants >128B, with static size assertions.
354
+ - `resources/zero_cost_iterators_and_pipeline_inlining.md` — Zero-allocation lazy iterator pipelines, elimination of intermediate .collect() vectors, .drain() buffer recycling, and impl Iterator inlining.
355
+ - `resources/deadlock_elimination_and_locks_across_await.md` — Preventing Tokio reactor thread starvation caused by holding synchronous locks across .await, RAII lock scoping, and channel-based actor patterns.
356
+ - `resources/numeric_safety_and_saturating_arithmetic.md` — Zero-panic saturating/checked/wrapping arithmetic, eliminating silent truncation via TryFrom, and deterministic float total_cmp ordering.
357
+ - `resources/collection_reuse_and_capacity_retention.md` — Pre-allocated buffer capacity reuse via clone_from, std::mem::take extraction without cloning, and zero-heap stack-only ArrayVec.
358
+ - `resources/memory_mapped_files_and_zero_copy_paging.md` — Zero-heap disk I/O via memmap2, kernel page cache delegation, madvise sequential/dontneed paging, and zero-copy static asset serving.
359
+ - `resources/zero_copy_zero_alloc_serialization_rkyv.md` — In-place 0ns zero-allocation serialization with rkyv Archive and zerocopy POD framing directly from raw byte slices.
360
+ - `resources/lock_free_ring_buffers_and_disruptor.md` — High-throughput zero-allocation queues via cache-aligned power-of-two circular ring buffers (rtrb, ArrayQueue) and Disruptor pattern.
361
+ - `resources/production_memory_leak_diagnostics_and_ebpf.md` — Diagnosing memory leaks in production with LLVM LeakSanitizer (-Zsanitizer=leak), jemalloc-ctl live heap dumps, and zero-overhead eBPF (bcc memleak) container tracing.
362
+ - `resources/zero_cost_state_machines_and_enum_dispatch.md` — Eliminating dynamic dispatch (Box<dyn Trait>) and vtable overhead via compile-time enum_dispatch and zero-cost typestate state machines.
363
+
@@ -2,7 +2,7 @@
2
2
 
3
3
  Offloading anti-bot challenges, age verification gates, or dynamic cookies to headless browser instances (such as Chromium) consumes **300MB to 1GB of RAM per instance**, utterly defeating memory efficiency and low-latency throughput goals. In native high-performance Rust, these challenges are solved directly in code via single-flight synchronization and reverse-engineered cryptographic or mathematical algorithms.
4
4
 
5
- This playbook demonstrates how to eliminate headless browsers entirely using:
5
+ This reference guide demonstrates how to eliminate headless browsers entirely using:
6
6
  1. **Algorithmic Challenge Solvers**: Reverse-engineering the challenge directly in Rust.
7
7
  2. **Single-Flight Cookie Bootstrapping**: Using `Arc<RwLock<...>>` to ensure only one worker thread authenticates, while all concurrent requests wait and reuse the acquired cookie.
8
8
  3. **Chunked Early-Break Response Streaming**: Reading only the header script without buffering full pages.
@@ -4,7 +4,7 @@ In high-concurrency systems running on multi-core processors, extreme efficiency
4
4
  1. **Struct Padding Bloat**: Memory wasted on unused alignment bytes across millions of cache/struct instances.
5
5
  2. **False Sharing (Cache-Line Bouncing)**: Independent CPU cores invalidating each other's L1 cache lines when mutating adjacent variables, collapsing multi-core scalability by up to 80%.
6
6
 
7
- This playbook details the hardware-level layout optimizations needed to eliminate these bottlenecks.
7
+ This reference guide details the hardware-level layout optimizations needed to eliminate these bottlenecks.
8
8
 
9
9
  ---
10
10
 
@@ -0,0 +1,135 @@
1
+ # Collection Reuse & Capacity Retention
2
+
3
+ In high-throughput services processing thousands of requests per second, repeatedly instantiating and dropping collections (`Vec`, `String`, `HashMap`) inside request handlers triggers severe **allocator thrashing and heap fragmentation**.
4
+
5
+ Even though Rust's ownership model automatically drops memory at the end of each scope, delegating allocation lifecycle management to the OS allocator on every request induces latency spikes (p99/p99.9) and swells resident set size (RSS).
6
+
7
+ This reference guide documents patterns for reusing pre-allocated collection capacities: `clone_from`, `std::mem::take`, capacity-retaining resets (`.clear()`), and stack-only collections with `ArrayVec`.
8
+
9
+ ---
10
+
11
+ ## 1. Allocation-Free Cloning with `clone_from`
12
+
13
+ When updating a long-lived buffer from an incoming data source, standard `.clone()` discards the destination's existing memory and triggers a fresh `malloc`:
14
+
15
+ ```rust
16
+ pub struct SessionCache {
17
+ buffer: Vec<u8>,
18
+ }
19
+
20
+ impl SessionCache {
21
+ // NAIVE: Frees old buffer, calls malloc() for a new buffer on every update!
22
+ pub fn update_naive(&mut self, incoming: &[u8]) {
23
+ self.buffer = incoming.to_vec(); // Allocator churn!
24
+ }
25
+
26
+ // OPTIMAL: Reuses self.buffer's pre-allocated capacity!
27
+ pub fn update_optimal(&mut self, incoming: &[u8]) {
28
+ // clone_from reuses self.buffer's memory if incoming.len() <= capacity.
29
+ // Triggers ZERO malloc() calls if capacity is sufficient!
30
+ self.buffer.clone_from(&incoming.to_vec());
31
+ }
32
+
33
+ // EVEN BETTER: Direct slice copy
34
+ pub fn update_zero_alloc(&mut self, incoming: &[u8]) {
35
+ self.buffer.clear();
36
+ self.buffer.extend_from_slice(incoming); // 0 allocations if capacity suffices
37
+ }
38
+ }
39
+ ```
40
+
41
+ ### Benchmark Impact
42
+ Under 50,000 req/sec benchmarks:
43
+ - `self.buffer = incoming.to_vec()`: **50,000 malloc + 50,000 free operations/sec**.
44
+ - `self.buffer.clear(); self.buffer.extend_from_slice(...)`: **0 allocations/sec** after initial warm-up.
45
+
46
+ ---
47
+
48
+ ## 2. Extracting Data Without Cloning via `std::mem::take`
49
+
50
+ When an async task or worker needs to consume data out of a mutable struct reference, developers frequently clone the data to satisfy the borrow checker:
51
+
52
+ ```rust
53
+ pub struct RequestContext {
54
+ pub raw_headers: Vec<String>,
55
+ }
56
+
57
+ // ANTI-PATTERN: Clones every string on the heap!
58
+ pub fn harvest_headers_naive(ctx: &mut RequestContext) -> Vec<String> {
59
+ ctx.raw_headers.clone() // Allocates duplicate heap nodes!
60
+ }
61
+
62
+ // ZERO-ALLOCATION: Takes ownership and leaves an empty, zero-sized Vec
63
+ pub fn harvest_headers_optimal(ctx: &mut RequestContext) -> Vec<String> {
64
+ // std::mem::take moves out the Vec, leaving Vec::new() (a 0-byte ZST on the heap)
65
+ std::mem::take(&mut ctx.raw_headers)
66
+ }
67
+ ```
68
+
69
+ `std::mem::take(&mut field)` works on any type that implements `Default`. For `Vec<T>`, `String`, and `Option<T>`, `Default::default()` performs **zero heap allocations**.
70
+
71
+ ---
72
+
73
+ ## 3. Stack-Only Collections with `ArrayVec` (0 Heap Guarantee)
74
+
75
+ When a collection has a known maximum bound (e.g. HTTP header lists, routing segments, socket chunks $\le 32$ items), heap-backed `Vec<T>` wastes memory on heap pointers and indirection.
76
+
77
+ Use `ArrayVec<T, N>` (from the `arrayvec` crate) to store elements **entirely on the stack**:
78
+
79
+ ```rust
80
+ use arrayvec::ArrayVec;
81
+
82
+ pub struct RouteMatcher {
83
+ // 0 heap allocations, inline stack array of up to 8 segments
84
+ segments: ArrayVec<&'static str, 8>,
85
+ }
86
+
87
+ impl RouteMatcher {
88
+ pub fn parse(path: &'static str) -> Result<Self, &'static str> {
89
+ let mut segments = ArrayVec::new();
90
+ for part in path.split('/').filter(|s| !s.is_empty()) {
91
+ segments.try_push(part).map_err(|_| "Route depth exceeds 8 segments")?;
92
+ }
93
+ Ok(Self { segments })
94
+ }
95
+ }
96
+ ```
97
+
98
+ ### Memory Footprint Comparison
99
+ | Type | Location | Heap Malloc | Indirection (Deref) |
100
+ |---|---|---|---|
101
+ | `Vec<T>` | Stack metadata + Heap buffer | **Yes** (on growth) | Yes (cache miss risk) |
102
+ | `SmallVec<[T; N]>` | Stack (first $N$) $\to$ Heap | Conditional | Conditional |
103
+ | `ArrayVec<T, N>` | **100% Stack** | **Never (0 heap)** | **No (direct inline)** |
104
+
105
+ ---
106
+
107
+ ## 4. Resetting Worker Containers with `.clear()`
108
+
109
+ When maintaining worker-local scratch buffers across loop iterations, never drop the container at the end of the iteration:
110
+
111
+ ```rust
112
+ pub async fn run_event_loop() {
113
+ // Pre-allocate scratchpad once outside the hot loop
114
+ let mut scratchpad: Vec<u8> = Vec::with_capacity(8192);
115
+
116
+ loop {
117
+ // Read incoming frame into scratchpad
118
+ // ...
119
+
120
+ // At end of iteration: reset length to 0, RETAIN capacity!
121
+ scratchpad.clear();
122
+ debug_assert_eq!(scratchpad.len(), 0);
123
+ debug_assert_eq!(scratchpad.capacity(), 8192); // 8KB remains allocated!
124
+ }
125
+ }
126
+ ```
127
+
128
+ ---
129
+
130
+ ## 5. Architectural Checklist for Collections
131
+
132
+ 1. Use `dst.clone_from(&src)` or `.clear() + .extend()` to reuse pre-allocated capacity.
133
+ 2. Use `std::mem::take(&mut value)` instead of `.clone()` to extract fields out of mutable references.
134
+ 3. For collections bounded by small $N$ ($\le 16$), use `ArrayVec<T, N>` to eliminate heap allocations entirely.
135
+ 4. Keep worker scratchpads alive across loop iterations and clear them with `.clear()`.
@@ -2,7 +2,7 @@
2
2
 
3
3
  In multi-threaded asynchronous systems, synchronization primitives are a frequent source of hidden latency, CPU core throttling, and allocator churn. Developers commonly default to `tokio::sync::Mutex` indiscriminately or misuse standard library locks, causing thread pool deadlocks, excessive OS futex syscalls, and CPU cache line thrashing.
4
4
 
5
- This playbook establishes the rules for selecting and tuning concurrency primitives for sub-microsecond synchronization.
5
+ This reference guide establishes the rules for selecting and tuning concurrency primitives for sub-microsecond synchronization.
6
6
 
7
7
  ---
8
8