@sinkaroid/rust-shapeshift 1.0.4 → 1.0.7

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 (30) hide show
  1. package/README.md +61 -5
  2. package/package.json +6 -6
  3. package/skills/rust-shapeshift/SKILL.md +24 -4
  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 +3 -3
  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/hot_path_string_and_zero_cost_helpers.md +3 -3
  15. package/skills/rust-shapeshift/resources/lock_free_ring_buffers_and_disruptor.md +185 -0
  16. package/skills/rust-shapeshift/resources/memory_mapped_files_and_zero_copy_paging.md +151 -0
  17. package/skills/rust-shapeshift/resources/numeric_safety_and_saturating_arithmetic.md +124 -0
  18. package/skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md +1 -1
  19. package/skills/rust-shapeshift/resources/production_memory_leak_diagnostics_and_ebpf.md +120 -0
  20. package/skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md +1 -1
  21. package/skills/rust-shapeshift/resources/redis_connection_and_caching_pitfalls.md +1 -1
  22. package/skills/rust-shapeshift/resources/reqwest_client_and_connection_pooling.md +1 -1
  23. package/skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md +1 -1
  24. package/skills/rust-shapeshift/resources/telemetry_and_metrics.md +2 -2
  25. package/skills/rust-shapeshift/resources/zero_allocation_error_architecture.md +1 -1
  26. package/skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md +1 -1
  27. package/skills/rust-shapeshift/resources/zero_copy_zero_alloc_serialization_rkyv.md +135 -0
  28. package/skills/rust-shapeshift/resources/zero_cost_iterators_and_pipeline_inlining.md +121 -0
  29. package/skills/rust-shapeshift/resources/zero_cost_state_machines_and_enum_dispatch.md +162 -0
  30. package/skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md +1 -1
package/README.md CHANGED
@@ -20,26 +20,30 @@ 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
30
  >
31
31
  > 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
32
 
33
- All 47 deep-dive playbooks are located in [`skills/rust-shapeshift/resources`](skills/rust-shapeshift/resources)
33
+ All 57 deep-dive reference guides are located in [`skills/rust-shapeshift/resources`](skills/rust-shapeshift/resources)
34
34
 
35
35
  ### Memory, Stack & Allocator Optimization
36
36
 
37
37
  - [`Memory Allocator Tuning`](skills/rust-shapeshift/resources/memory_allocator_tuning.md): Glibc arena containment (`MALLOC_ARENA_MAX=2`) and `libc::malloc_trim(0)`.
38
38
  - [`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.
39
+ - [`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
40
  - [`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
41
  - [`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
42
  - [`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).
43
+ - [`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
44
  - [`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]>`.
45
+ - [`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.
46
+ - [`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
47
  - [`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
48
  - [`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
49
  - [`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 +52,11 @@ All 47 deep-dive playbooks are located in [`skills/rust-shapeshift/resources`](s
48
52
  ### Tokio, Concurrency & Reactor Safety
49
53
 
50
54
  - [`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.
55
+ - [`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
56
  - [`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
57
  - [`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
58
  - [`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.
59
+ - [`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
60
  - [`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
61
  - [`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
62
 
@@ -64,6 +70,7 @@ All 47 deep-dive playbooks are located in [`skills/rust-shapeshift/resources`](s
64
70
 
65
71
  ### Data Ingestion, Storage & Queues
66
72
 
73
+ - [`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
74
  - [`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
75
  - [`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
76
  - [`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 +80,10 @@ All 47 deep-dive playbooks are located in [`skills/rust-shapeshift/resources`](s
73
80
 
74
81
  ### Serialization, SIMD, BCE & Compiler Tuning
75
82
 
83
+ - [`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
84
  - [`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`.
85
+ - [`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.
86
+ - [`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
87
  - [`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
88
  - [`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
89
  - [`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 +143,60 @@ Automatically primes:
133
143
  Install and follow this skill from https://github.com/sinkaroid/rust-shapeshift
134
144
  ```
135
145
 
136
- Your agent will automatically clone, index, and apply the 47 production playbooks to your current workspace.
146
+ Your agent will automatically clone, index, and apply the 57 production engineering references to your current workspace.
137
147
 
138
148
  ---
139
149
 
140
150
  ### Native CLI Commands
141
151
 
142
152
  ```bash
143
- rust-shapeshift list # Print all 47 production playbooks and descriptions
153
+ rust-shapeshift list # Print all 57 production reference guides and descriptions
144
154
  rust-shapeshift audit # Scan current Rust project for memory anti-patterns
155
+ rust-shapeshift mcp # Start Model Context Protocol (MCP) server over stdio
145
156
  rust-shapeshift init # Configure agent skill in current directory
146
157
  ```
158
+
159
+ ---
160
+
161
+ ### 🔌 Model Context Protocol (MCP) Server
162
+
163
+ Connect `rust-shapeshift` directly as an active tool server in **Claude Code, Cursor, Windsurf, or Antigravity**:
164
+
165
+ ```json
166
+ {
167
+ "mcpServers": {
168
+ "rust-shapeshift": {
169
+ "command": "npx",
170
+ "args": ["-y", "@sinkaroid/rust-shapeshift", "mcp"]
171
+ }
172
+ }
173
+ }
174
+ ```
175
+
176
+ Or using native binary:
177
+
178
+ ```json
179
+ {
180
+ "mcpServers": {
181
+ "rust-shapeshift": {
182
+ "command": "rust-shapeshift",
183
+ "args": ["mcp"]
184
+ }
185
+ }
186
+ }
187
+ ```
188
+
189
+ #### Available MCP Tools
190
+ - `audit_memory_antipatterns`: Scans current workspace for memory bloat, missing `MALLOC_ARENA_MAX`, unoptimized release profile, and locks across `.await`.
191
+ - `inspect_struct_layout`: Computes exact field alignment, wasted padding bytes, optimal reordering, and cache-line false sharing hazards.
192
+ - `calculate_hardware_budget`: Computes worst-case RSS and maximum safe concurrent connections without triggering Linux OOMKilled (Exit Code 137).
193
+ - `explain_recipe`: Retrieves targeted zero-cost implementation snippets and principles from the 57 production guides on-demand.
194
+ - `scaffold_archetype`: Generates verified boilerplates for minimal daemons (`koburi_daemon`), Axum gateways (`axum_gateway`), or zero-copy pipelines (`zero_copy_pipeline`).
195
+
196
+
197
+ ## Legal
198
+
199
+ This tool can be freely copied, modified, altered, distributed without any attribution whatsoever. However, if you feel
200
+ like this tool deserves an attribution, mention it. It won't hurt anybody.
201
+
202
+ > 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.4",
30
- "@sinkaroid/rust-shapeshift-darwin-x64": "1.0.4",
31
- "@sinkaroid/rust-shapeshift-linux-arm64": "1.0.4",
32
- "@sinkaroid/rust-shapeshift-linux-x64": "1.0.4",
33
- "@sinkaroid/rust-shapeshift-win32-x64": "1.0.4"
29
+ "@sinkaroid/rust-shapeshift-darwin-arm64": "1.0.7",
30
+ "@sinkaroid/rust-shapeshift-darwin-x64": "1.0.7",
31
+ "@sinkaroid/rust-shapeshift-linux-arm64": "1.0.7",
32
+ "@sinkaroid/rust-shapeshift-linux-x64": "1.0.7",
33
+ "@sinkaroid/rust-shapeshift-win32-x64": "1.0.7"
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.4"
46
+ "version": "1.0.7"
47
47
  }
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: rust-shapeshift
3
3
  author: "@sinkaroid"
4
- version: "1.0.4"
4
+ version: "1.0.7"
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:
@@ -53,7 +53,7 @@ Over 70% of this skill focuses on hardware-, kernel-, allocator-, and compiler-l
53
53
  - **The Koburi Pattern (Archetype B)**: Zero-async, zero-dependency `std::net` / `UnixStream` minimal daemons under 1MB idle RSS.
54
54
 
55
55
  ### 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.
56
+ 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
57
 
58
58
  ### 3. Mandatory AI Agent Contract for Alternative Frameworks
59
59
  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):
@@ -95,6 +95,15 @@ Master modern Rust (1.80+ / 2024 Edition) features, advanced type system mechani
95
95
 
96
96
  ## Capabilities
97
97
 
98
+ ### Active MCP Tool Capabilities (Optional Stdio Server)
99
+
100
+ 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:
101
+ - `audit_memory_antipatterns`: Automatically scans workspace files for glibc arena traps (`MALLOC_ARENA_MAX=2`), unoptimized release profiles, and synchronous locks across `.await`.
102
+ - `inspect_struct_layout`: Computes struct padding bytes, alignment boundaries, field reordering, and cache-line false-sharing hazards.
103
+ - `calculate_hardware_budget`: Computes worst-case RSS ceilings and safe per-connection buffers to prevent Linux OOMKilled (Exit Code 137).
104
+ - `explain_recipe`: Queries the 57 production engineering references on-demand, returning targeted snippets without bloating context window.
105
+ - `scaffold_archetype`: Generates verified boilerplates for Koburi minimal daemons (<1MB), Axum 0.8 gateways, or zero-copy pipelines.
106
+
98
107
  ### 1. Modern Rust Language Features (1.80+ / 2024 Edition)
99
108
 
100
109
  - Native `async fn in trait` (AFIT) and return-position `impl Trait in trait` (RPITIT) eliminating `#[async_trait]` heap allocation (`Box<dyn Future>`).
@@ -264,9 +273,9 @@ Master modern Rust (1.80+ / 2024 Edition) features, advanced type system mechani
264
273
 
265
274
  ---
266
275
 
267
- ## Deep-Dive Resource Playbooks
276
+ ## Deep-Dive Production Engineering References
268
277
 
269
- Consult the attached playbooks for complete, production-tested code templates:
278
+ Consult the attached reference guides for complete, production-tested code templates:
270
279
 
271
280
  - `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
281
  - `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)`).
@@ -315,3 +324,14 @@ Consult the attached playbooks for complete, production-tested code templates:
315
324
  - `resources/numa_architecture_and_hugepages.md` — NUMA-aware allocation (mbind), 2MB/1GB HugePages (madvise THP) eliminating TLB misses, and mlockall page pinning.
316
325
  - `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
326
  - `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.
327
+ - `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.
328
+ - `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.
329
+ - `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.
330
+ - `resources/numeric_safety_and_saturating_arithmetic.md` — Zero-panic saturating/checked/wrapping arithmetic, eliminating silent truncation via TryFrom, and deterministic float total_cmp ordering.
331
+ - `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.
332
+ - `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.
333
+ - `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.
334
+ - `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.
335
+ - `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.
336
+ - `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.
337
+
@@ -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
 
@@ -0,0 +1,149 @@
1
+ # Deadlock Elimination & Lock Safety Across `.await` Points
2
+
3
+ In multi-threaded asynchronous systems powered by Tokio, holding a synchronous lock (`std::sync::Mutex` or `parking_lot::Mutex`) across an `.await` boundary is one of the most destructive architectural bugs in production Rust.
4
+
5
+ It triggers **Tokio worker thread starvation**, completely stalling the asynchronous reactor and freezing all incoming HTTP/gRPC requests without producing a single panic or error log.
6
+
7
+ This reference guide documents the mechanics of the `.await` lock hazard, RAII block scoping disciplines, when to use `tokio::sync::Mutex`, and how to replace lock contention with zero-cost channel-based actor patterns.
8
+
9
+ ---
10
+
11
+ ## 1. The Anatomy of an Async Lock Freeze
12
+
13
+ ### The Anti-Pattern (Total Reactor Deadlock)
14
+ ```rust
15
+ use std::sync::Mutex;
16
+
17
+ pub struct SharedState {
18
+ counter: u64,
19
+ }
20
+
21
+ // HAZARD: Holding a synchronous MutexGuard across an .await point!
22
+ pub async fn increment_and_notify_hazard(state: &Mutex<SharedState>) {
23
+ let mut guard = state.lock().unwrap();
24
+ guard.counter += 1;
25
+
26
+ // The current OS worker thread is suspended here waiting for network I/O.
27
+ // The synchronous MutexGuard is NOT released!
28
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
29
+
30
+ println!("Counter: {}", guard.counter);
31
+ // guard dropped here
32
+ }
33
+ ```
34
+
35
+ ### Why This Freezes Tokio
36
+ 1. **Worker Thread Exhaustion**: Tokio runtimes typically allocate 1 OS thread per CPU core (e.g. 4 or 8 threads).
37
+ 2. **Cascading Block**:
38
+ - Task 1 acquires the synchronous lock on Thread A, then hits `.await` and yields.
39
+ - Task 2 runs on Thread B and attempts to acquire `state.lock()`. Because it is a synchronous lock, Thread B **physically blocks the OS thread via a kernel futex syscall**.
40
+ - As more tasks hit the lock, all 4 or 8 Tokio worker threads become physically blocked waiting on the lock.
41
+ - Now, Task 1's timer or network read cannot wake up because **no worker threads are free to run the Tokio scheduler**.
42
+ - The process enters a **permanent, unrecoverable deadlock**.
43
+
44
+ ---
45
+
46
+ ## 2. Pattern A: RAII Block Scoping (Synchronous Work)
47
+
48
+ If the critical section only involves in-memory data manipulation and requires no async I/O, **confine the lock guard to an explicit synchronous scope** that drops before `.await`:
49
+
50
+ ```rust
51
+ use parking_lot::Mutex;
52
+
53
+ pub struct SharedState {
54
+ counter: u64,
55
+ }
56
+
57
+ pub async fn increment_and_notify_safe(state: &Mutex<SharedState>) {
58
+ // 1. Enter isolated synchronous block
59
+ let new_val = {
60
+ let mut guard = state.lock();
61
+ guard.counter += 1;
62
+ guard.counter // Copy out primitive or clone small data
63
+ }; // <-- guard is GUARANTEED to be dropped here!
64
+
65
+ // 2. Perform async operation safely with ZERO locks held
66
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
67
+
68
+ println!("Counter updated to: {}", new_val);
69
+ }
70
+ ```
71
+
72
+ By constraining `guard` to the inner block, the synchronous lock duration is measured in **nanoseconds**, completely eliminating thread starvation.
73
+
74
+ ---
75
+
76
+ ## 3. Pattern B: When to Use `tokio::sync::Mutex`
77
+
78
+ If you **must** hold a lock across an `.await` point (e.g. exclusive transactional access to an async socket or stream):
79
+
80
+ ```rust
81
+ use tokio::sync::Mutex;
82
+
83
+ pub struct SocketSession {
84
+ stream: tokio::net::TcpStream,
85
+ }
86
+
87
+ // SAFE: tokio::sync::Mutex yields cooperatively to the reactor
88
+ pub async fn send_exclusive_packet(session: &Mutex<SocketSession>, data: &[u8]) {
89
+ // .lock().await yields the task if contended, freeing the OS worker thread!
90
+ let mut guard = session.lock().await;
91
+
92
+ // Safe to hold across async I/O
93
+ use tokio::io::AsyncWriteExt;
94
+ let _ = guard.stream.write_all(data).await;
95
+
96
+ // Lock released automatically when guard drops
97
+ }
98
+ ```
99
+
100
+ ### Selection Matrix: `parking_lot::Mutex` vs `tokio::sync::Mutex`
101
+ | Dimension | `parking_lot::Mutex` | `tokio::sync::Mutex` |
102
+ |---|---|---|
103
+ | **Memory Footprint** | **1 byte** | **64–88 bytes** |
104
+ | **Uncontended Lock Speed** | **~10 ns** (CPU atomic) | **~50–80 ns** (async machinery) |
105
+ | **Cross-`.await` Safety** | **DEADLOCK HAZARD** | **100% Safe** |
106
+ | **Best Production Use Case** | In-memory structs, fast state updates, cache maps | Shared network streams, exclusive async transactions |
107
+
108
+ ---
109
+
110
+ ## 4. Pattern C: Zero-Lock Architecture via Actor Channels
111
+
112
+ For high-throughput systems, the cleanest way to eliminate locks entirely is **single-writer message passing**:
113
+
114
+ ```rust
115
+ use tokio::sync::mpsc;
116
+
117
+ pub enum StateMsg {
118
+ Increment { respond_to: tokio::sync::oneshot::Sender<u64> },
119
+ }
120
+
121
+ pub struct StateActor {
122
+ counter: u64,
123
+ receiver: mpsc::Receiver<StateMsg>,
124
+ }
125
+
126
+ impl StateActor {
127
+ pub async fn run(mut self) {
128
+ while let Some(msg) = self.receiver.recv().await {
129
+ match msg {
130
+ StateMsg::Increment { respond_to } => {
131
+ self.counter += 1;
132
+ let _ = respond_to.send(self.counter);
133
+ }
134
+ }
135
+ }
136
+ }
137
+ }
138
+ ```
139
+
140
+ Only one task owns the state. All other tasks send messages via bounded channels with zero lock contention.
141
+
142
+ ---
143
+
144
+ ## 5. Architectural Checklist for Lock Safety
145
+
146
+ 1. Enforce `#![deny(clippy::await_holding_lock)]` in `src/lib.rs` and `src/main.rs`.
147
+ 2. Never call `std::sync::Mutex::lock()` inside an `async fn` without explicit RAII block scoping.
148
+ 3. Use `parking_lot::Mutex` for sub-microsecond in-memory state updates; never hold it across `.await`.
149
+ 4. Use `tokio::sync::Mutex` only when exclusive state must be preserved across async I/O boundaries.
@@ -2,7 +2,7 @@
2
2
 
3
3
  Achieving production efficiency requires minimizing **both runtime memory consumption (RSS) and physical Docker image size**. A bloated Docker image wastes registry bandwidth, slows CI/CD deployments, expands vulnerability attack surfaces, and invalidates build caches needlessly.
4
4
 
5
- This playbook documents the exact multi-stage container recipe and `.dockerignore` discipline used in **Jandapress** and **Lustpress** to achieve **sub-80MB Debian runtime images** and instant build context transfers.
5
+ This reference guide documents the exact multi-stage container recipe and `.dockerignore` discipline used in high-throughput production services to achieve **sub-80MB Debian runtime images** and instant build context transfers.
6
6
 
7
7
  ---
8
8
 
@@ -1,8 +1,8 @@
1
- # Scraper & DOM Optimization Playbook: Cutting 80% Memory Bloat
1
+ # Scraper & DOM Optimization Reference: Cutting 80% Memory Bloat
2
2
 
3
3
  Parsing full, unconstrained HTML documents (containing thousands of script tags, ads, comments, and footers) into an in-memory DOM tree allocates millions of transient AST nodes, severely stressing the memory allocator and bloating process RSS.
4
4
 
5
- This playbook demonstrates the exact patterns used to achieve sub-50MB RSS memory baselines by pruning raw text strings before AST instantiation.
5
+ This reference guide demonstrates the exact patterns used to achieve sub-50MB RSS memory baselines by pruning raw text strings before AST instantiation.
6
6
 
7
7
  ---
8
8
 
@@ -86,7 +86,7 @@ static SEL_VIEWS: LazyLock<Selector> =
86
86
 
87
87
  ## 3. Pattern C: Zero-Allocation Byte Slice Parsing for JSON APIs
88
88
 
89
- When scraping providers that offer undocumented or internal JSON endpoints (such as Eporner or Txxx in `lustpress`), **never** allocate an intermediate `String` from the network response.
89
+ When scraping upstream providers that offer undocumented or internal JSON endpoints, **never** allocate an intermediate `String` from the network response.
90
90
 
91
91
  Deserialize directly from `&[u8]` using `serde_json::from_slice`:
92
92