@sinkaroid/rust-shapeshift 1.0.11 → 1.0.13

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 (57) hide show
  1. package/README.md +8 -8
  2. package/package.json +6 -6
  3. package/skills/rust-shapeshift/SKILL.md +46 -33
  4. package/skills/rust-shapeshift/resources/adaptive_concurrency_and_load_shedding.md +9 -0
  5. package/skills/rust-shapeshift/resources/anti_bot_and_cookie_challenges.md +9 -0
  6. package/skills/rust-shapeshift/resources/async_cancellation_safety_and_task_drainage.md +9 -0
  7. package/skills/rust-shapeshift/resources/axum_and_tower_architecture.md +21 -5
  8. package/skills/rust-shapeshift/resources/bounded_caching_and_pooling.md +15 -5
  9. package/skills/rust-shapeshift/resources/bounded_streaming_and_payload_guards.md +9 -0
  10. package/skills/rust-shapeshift/resources/bounds_check_elimination_and_zero_cost_memory.md +9 -0
  11. package/skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md +9 -0
  12. package/skills/rust-shapeshift/resources/collection_reuse_and_capacity_retention.md +9 -0
  13. package/skills/rust-shapeshift/resources/compiler_niche_optimizations_and_size_assertions.md +9 -0
  14. package/skills/rust-shapeshift/resources/concurrency_model_checking_and_resource_budgets.md +9 -0
  15. package/skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md +9 -0
  16. package/skills/rust-shapeshift/resources/docker_slimming_and_build_hygiene.md +14 -18
  17. package/skills/rust-shapeshift/resources/dom_and_scraper_pruning.md +41 -14
  18. package/skills/rust-shapeshift/resources/enum_variant_boxing_and_stack_squashing.md +8 -0
  19. package/skills/rust-shapeshift/resources/graphql_memory_and_query_containment.md +20 -1
  20. package/skills/rust-shapeshift/resources/grpc_tonic_and_http2_memory_tuning.md +9 -0
  21. package/skills/rust-shapeshift/resources/hidden_drop_offload_and_wcet_contracts.md +9 -0
  22. package/skills/rust-shapeshift/resources/hot_path_string_and_zero_cost_helpers.md +31 -18
  23. package/skills/rust-shapeshift/resources/instruction_cache_and_cold_path_outlining.md +9 -0
  24. package/skills/rust-shapeshift/resources/io_uring_and_zero_syscall_networking.md +8 -0
  25. package/skills/rust-shapeshift/resources/jemalloc_profiling_and_allocator_switch.md +9 -0
  26. package/skills/rust-shapeshift/resources/kubernetes_runtime_and_resource_containment.md +41 -29
  27. package/skills/rust-shapeshift/resources/lock_free_ring_buffers_and_disruptor.md +8 -0
  28. package/skills/rust-shapeshift/resources/memory_allocator_tuning.md +58 -33
  29. package/skills/rust-shapeshift/resources/memory_mapped_files_and_zero_copy_paging.md +8 -0
  30. package/skills/rust-shapeshift/resources/message_queue_and_stream_backpressure.md +8 -0
  31. package/skills/rust-shapeshift/resources/numa_architecture_and_hugepages.md +8 -0
  32. package/skills/rust-shapeshift/resources/numeric_safety_and_saturating_arithmetic.md +8 -0
  33. package/skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md +8 -0
  34. package/skills/rust-shapeshift/resources/profile_guided_optimization_and_fast_hashing.md +9 -0
  35. package/skills/rust-shapeshift/resources/rate_limiting_and_state.md +8 -0
  36. package/skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md +16 -7
  37. package/skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md +8 -0
  38. package/skills/rust-shapeshift/resources/redis_connection_and_caching_pitfalls.md +8 -0
  39. package/skills/rust-shapeshift/resources/reqwest_client_and_connection_pooling.md +22 -17
  40. package/skills/rust-shapeshift/resources/simd_vectorization_and_hardware_acceleration.md +8 -0
  41. package/skills/rust-shapeshift/resources/sqlx_and_database_pool_memory.md +8 -0
  42. package/skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md +8 -0
  43. package/skills/rust-shapeshift/resources/streaming_file_io_and_compression.md +8 -0
  44. package/skills/rust-shapeshift/resources/telemetry_and_metrics.md +15 -6
  45. package/skills/rust-shapeshift/resources/thread_per_core_and_shared_nothing.md +8 -0
  46. package/skills/rust-shapeshift/resources/tokio_thread_starvation_and_cpu_offload.md +11 -2
  47. package/skills/rust-shapeshift/resources/typestate_domain_proofs_and_buffer_recycling.md +8 -0
  48. package/skills/rust-shapeshift/resources/wasm_runtime_and_memory_sandboxing.md +8 -0
  49. package/skills/rust-shapeshift/resources/zero_allocation_error_architecture.md +8 -0
  50. package/skills/rust-shapeshift/resources/zero_copy_ipc_and_shared_memory.md +8 -0
  51. package/skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md +9 -0
  52. package/skills/rust-shapeshift/resources/zero_copy_zero_alloc_serialization_rkyv.md +8 -0
  53. package/skills/rust-shapeshift/resources/zero_cost_iterators_and_pipeline_inlining.md +8 -0
  54. package/skills/rust-shapeshift/resources/zero_cost_state_machines_and_enum_dispatch.md +8 -0
  55. package/skills/rust-shapeshift/resources/zero_overhead_distributed_tracing.md +8 -0
  56. package/skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md +8 -0
  57. package/skills/rust-shapeshift/resources/zero_runtime_and_minimalist_daemons.md +8 -0
package/README.md CHANGED
@@ -41,7 +41,7 @@ All 58 deep-dive reference guides are located in [`skills/rust-shapeshift/resour
41
41
 
42
42
  ### Memory, Stack & Allocator Optimization
43
43
 
44
- - [`Memory Allocator Tuning`](skills/rust-shapeshift/resources/memory_allocator_tuning.md): Glibc arena containment (`MALLOC_ARENA_MAX=2`) and `libc::malloc_trim(0)`.
44
+ - [`Memory Allocator Tuning`](skills/rust-shapeshift/resources/memory_allocator_tuning.md): Preserving native defaults out-of-the-box, deploy-time opt-in `MALLOC_*`/`TOKIO_WORKER_THREADS` tuning, and `spawn_blocking`-offloaded `libc::malloc_trim(0)`.
45
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
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`).
47
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.
@@ -71,7 +71,7 @@ All 58 deep-dive reference guides are located in [`skills/rust-shapeshift/resour
71
71
 
72
72
  - [`Real-Time WebSocket & Connection Scaling`](skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md): Scaling 50k–500k connections, tuned 4KB buffers, single-task event loops, and zero-copy broadcasting.
73
73
  - [`gRPC, Tonic & HTTP/2 Memory Tuning`](skills/rust-shapeshift/resources/grpc_tonic_and_http2_memory_tuning.md): HTTP/2 stream/conn window bounding (64KB/512KB), streaming RPC backpressure, and zero-copy `Bytes`.
74
- - [`Reqwest Client & Socket Pooling`](skills/rust-shapeshift/resources/reqwest_client_and_connection_pooling.md): Singleton pool in `Arc<AppState>`, tiered timeouts, and selective `/random` non-caching.
74
+ - [`Reqwest Client & Socket Pooling`](skills/rust-shapeshift/resources/reqwest_client_and_connection_pooling.md): Singleton pool in `Arc<AppState>`, TCP keepalive, tiered timeouts, and `/random` cache-lookup bypass.
75
75
  - [`Bounded Streaming & Payload Guards`](skills/rust-shapeshift/resources/bounded_streaming_and_payload_guards.md): Bounded HTTP streaming, `take(MAX_BYTES)` limits, memory bomb defense, and zero-copy proxying.
76
76
  - [`Zero-Copy IPC & Shared Memory`](skills/rust-shapeshift/resources/zero_copy_ipc_and_shared_memory.md): Unix Domain Sockets (UDS) vs TCP loopback, and `memmap2` shared memory ring buffers.
77
77
 
@@ -121,7 +121,7 @@ All 58 deep-dive reference guides are located in [`skills/rust-shapeshift/resour
121
121
 
122
122
  ## Installation & Usage
123
123
 
124
- ### 🚀 npx
124
+ ### npx
125
125
 
126
126
  Run inside your current project directory:
127
127
 
@@ -144,7 +144,7 @@ Automatically primes:
144
144
 
145
145
  ---
146
146
 
147
- ### 🚀 ask your AI agent
147
+ ### Ask your AI agent
148
148
 
149
149
  ```sh
150
150
  Install and follow this skill from https://github.com/sinkaroid/rust-shapeshift
@@ -195,17 +195,17 @@ Or using native binary:
195
195
 
196
196
  #### Available MCP Tools
197
197
 
198
- - `audit_memory_antipatterns`: Scans current workspace for memory bloat, missing `MALLOC_ARENA_MAX`, unoptimized release profile, locks across `.await`, and synthetic test fixtures.
198
+ - `audit_memory_antipatterns`: Scans current workspace for regression traps (hardcoded Dockerfile/Tokio tuning, per-request/unoffloaded `malloc_trim`, unguarded DOM double-parse fallbacks, locks across `.await`, and synthetic test fixtures).
199
199
  - `inspect_struct_layout`: Computes exact field alignment, wasted padding bytes, optimal reordering, and cache-line false sharing hazards.
200
200
  - `calculate_hardware_budget`: Computes worst-case RSS and maximum safe concurrent connections without triggering Linux OOMKilled (Exit Code 137).
201
- - `explain_recipe`: Retrieves targeted zero-cost implementation snippets and principles from the 58 production guides on-demand.
201
+ - `explain_recipe`: Retrieves targeted zero-cost implementation snippets, principles, and Pros/Cons trade-offs from the 58 production guides on-demand.
202
202
  - `scaffold_archetype`: Generates verified boilerplates for minimal daemons (`koburi_daemon`), Axum gateways (`axum_gateway`), or zero-copy pipelines (`zero_copy_pipeline`).
203
203
  - `verify_test_fixtures`: Audits test suites and fixtures against the Anti-Hallucination Real DOM Standard, detecting synthetic placeholders and missing dual assertions.
204
204
  - `profile_future_size`: Analyzes enum variants and future frames, detecting oversized variants (>128B) and generating `Box<T>` stack-squashing recommendations with compile-time assertions.
205
205
  - `check_cancellation_safety`: Scans async code and `tokio::select!` branches for drop-hazard operations (`read_exact`, partial writes, lock contention across await).
206
206
  - `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.
207
- - `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.
208
- - `tune_allocator_env`: Generates tuned allocator environment variables (`MALLOC_ARENA_MAX`, `MALLOC_MMAP_THRESHOLD_`, `TOKIO_WORKER_THREADS`, or `MALLOC_CONF`) with detailed trade-off analysis.
207
+ - `generate_hardened_docker`: Generates hardened, non-root multi-stage Dockerfiles (<65MB) with Debian Bookworm C-ABI parity, symbol stripping, and native runtime defaults (opt-in allocator tuning via `docker run -e`).
208
+ - `tune_allocator_env`: Evaluates workload, hardware/libc, SLA priority, and public vs private scope to surface diagnostic questions, Pros & Cons, and opt-in deploy-time (`docker run -e` / K8s) allocator & Tokio flags.
209
209
  - `analyze_collection_overhead`: Scans Rust code for heavy collections (`String`, `Vec<T>`, `HashMap`) and recommends zero-cost drop-in alternatives (`CompactString`, `Box<[T]>`, `AHashMap`, `SmallVec`).
210
210
  - `generate_k8s_manifest`: Generates hardened Kubernetes Deployment YAML with Guaranteed QoS, Downward API `TOKIO_WORKER_THREADS`, `preStop: sleep 3` hook, and probe isolation.
211
211
  - `detect_lock_await`: Scans async Rust source files for synchronous Mutex/RwLock guards held across `.await` points causing reactor thread starvation and deadlocks.
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.11",
30
- "@sinkaroid/rust-shapeshift-darwin-x64": "1.0.11",
31
- "@sinkaroid/rust-shapeshift-linux-arm64": "1.0.11",
32
- "@sinkaroid/rust-shapeshift-linux-x64": "1.0.11",
33
- "@sinkaroid/rust-shapeshift-win32-x64": "1.0.11"
29
+ "@sinkaroid/rust-shapeshift-darwin-arm64": "1.0.13",
30
+ "@sinkaroid/rust-shapeshift-darwin-x64": "1.0.13",
31
+ "@sinkaroid/rust-shapeshift-linux-arm64": "1.0.13",
32
+ "@sinkaroid/rust-shapeshift-linux-x64": "1.0.13",
33
+ "@sinkaroid/rust-shapeshift-win32-x64": "1.0.13"
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.11"
46
+ "version": "1.0.13"
47
47
  }
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: rust-shapeshift
3
3
  author: "@sinkaroid"
4
- version: "1.0.11"
4
+ version: "1.0.13"
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:
@@ -12,8 +12,8 @@ metadata:
12
12
  # Rust Shapeshift: Extreme Memory & Runtime Systems Engineering
13
13
 
14
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.
15
+ > **Mandatory Real-World Testing & Privacy 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 DOM/JSON structures with dual-assertion invariants (positive extraction of runtime types via static selectors + negative severance of memory bloat). Prefer **compact, trimmed inline real snippets** in `#[cfg(test)]` over committing bloated `.html` fixture files into the repository unless external fixtures are explicitly requested. **NEVER** commit private API domains, internal endpoints, real proxy IPs/credentials, or `.env` values into tests, fixtures, `README.md`, or `.env.schema`—always sanitize with `example.com` and RFC 5737 test IPs (`203.0.113.0/24`). When optimizations face boundary edge-cases, agents **MUST NEVER** propose reverting optimizations; agents must engineer zero-downgrade adaptive self-healing fallbacks.
17
17
  > **Primary Testing Specification**: [`real_world_testing_and_dom_fixtures.md`](skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md)
18
18
 
19
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.
@@ -53,7 +53,7 @@ To eliminate architectural confusion and ensure consistent agent behavior across
53
53
 
54
54
  Over 70% of this skill focuses on hardware-, kernel-, allocator-, and compiler-level optimizations that apply to **every Rust codebase**, regardless of the web framework chosen:
55
55
 
56
- - **Linux Allocator Hygiene**: `MALLOC_ARENA_MAX=2`, `libc::malloc_trim(0)`, musl vs glibc trade-offs, and Docker C-ABI pairing.
56
+ - **Linux Allocator Hygiene (Opt-In First)**: Preserving native Tokio (`available_parallelism()`) and glibc defaults out-of-the-box; exposing `MALLOC_ARENA_MAX`, `MALLOC_MMAP_THRESHOLD_`, `TOKIO_WORKER_THREADS`, `DISABLE_THP`, and `spawn_blocking`-offloaded `libc::malloc_trim(0)` strictly as **opt-in deploy-time tuning** (`docker run -e ...` / K8s env), musl vs glibc trade-offs, and Docker C-ABI pairing.
57
57
  - **Data Layout & Zero Churn**: Stack inlining (`compact_str`), capacity trimming (`Box<str>`, `Box<[T]>`), enum boxing, struct alignment (`#[repr(align(64))]`), and arena allocation (`bumpalo`).
58
58
  - **Low-Level Throughput**: Bounds Check Elimination (BCE), SIMD vector parsing, Profile-Guided Optimization (PGO), `io_uring`, and NUMA HugePages.
59
59
  - **Concurrency & Reactor Safety**: Loom deterministic model checking, async cancellation safety, lock-free atomics, and bounded channel backpressure.
@@ -83,19 +83,29 @@ When project constraints or user requirements dictate an alternative framework b
83
83
 
84
84
  ## Instructions
85
85
 
86
- 1. **Enforce Real-World Testing & Production Fixtures (Zero Synthetic Mocks)**:
86
+ 1. **Plan-First & Multi-Dimensional Context Gate (Ask Before Mutating Code)**:
87
+ Before editing source code, `Dockerfile`, runtime configs, or dependencies, **NEVER** jump straight into edits or apply one-size-fits-all presets. Inspect the codebase, identify which context dimensions are relevant and unknown, **ask the user / present choices with Pros & Cons**, and present an **Implementation Plan** for approval first (unless the user explicitly asks for immediate execution on an unambiguous change). Evaluate all relevant dimensions dynamically without bias:
88
+ - **Workload & Archetype**: Stateless REST/GraphQL, WebSocket hub (50k–500k idle conns), gRPC stream, Queue consumer (Kafka/RabbitMQ/SQS), CPU/SIMD parser, Scraper/Proxy, Minimalist Daemon (Koburi `std::net`), or Wasm sandbox host.
89
+ - **SLA Priority**: `p99`/`p99.99` tail latency (WCET) vs maximum throughput vs strict RSS ceiling vs binary size / cold-start.
90
+ - **Hardware, OS & Kernel Topology**: Dedicated bare-metal vs burstable/shared vCPU vs cgroup/CFS quota; `x86_64` (AVX2) vs `ARM64` (NEON); NUMA; `glibc` vs static `musl` (no `malloc_trim`) vs `tikv-jemallocator` / `mimalloc`; kernel support (`io_uring` / HugePages / seccomp).
91
+ - **Traffic & Payload Shape**: Steady vs spiky/bursty vs low-QPS; payload size distribution (<4 KB JSON vs >100 KB HTML/blobs); cache hit-ratio; short-lived HTTP vs long-lived streams.
92
+ - **Co-Tenancy & Ops**: Standalone dedicated vs sharing host RAM/CPU with Redis/DB/proxy; profiling needs (`jemalloc-ctl`, DHAT); compile-time vs binary constraints (`lto = "thin"` vs `"fat"`, PGO/BOLT).
93
+ - **Repository Scope & Blast Radius (Public OSS vs Private Internal)**:
94
+ - **Public Open-Source Repo / Published Image / Crate (`ghcr.io`, `crates.io`, `npm`)**: Consumed by unknown users/contributors across diverse hardware (4-core laptops to 64-core cloud servers). **NEVER** hardcode host-specific throttles (`MALLOC_ARENA_MAX=2`, `MALLOC_MMAP_THRESHOLD_`, `MALLOC_TRIM_THRESHOLD_`, `MALLOC_TOP_PAD_`, `TOKIO_WORKER_THREADS=2`, `PR_SET_THP_DISABLE`, or default `malloc_trim`) into `Dockerfile` or `main.rs`—preserve safe native defaults and expose tuning strictly as documented opt-in runtime flags (`docker run -e` / `.env.schema`).
95
+ - **Private / Single-Tenant Deployment**: Host-specific tuning may be considered *only* after user confirmation and weighing trade-offs.
96
+ 2. **Enforce Real-World Testing & Production Fixtures (Zero Synthetic Mocks)**:
87
97
  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.
88
- 2. **Classify Operating Mode**:
98
+ 3. **Classify Operating Mode**:
89
99
  - **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).
90
100
  - **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.
91
- 3. **Classify Project Archetype & Framework Decision**:
101
+ 4. **Classify Project Archetype & Framework Decision**:
92
102
  - **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.
93
103
  - **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)**.
94
- 4. **Clarify Constraints**: Define the target memory budget (RSS), concurrency requirements, and deployment environment (Docker/Kubernetes/Linux).
95
- 5. **Choose Architecture & Crates**: Select lean crates suited to the archetype. Never pull in Tokio or connection pools for simple polling daemons.
96
- 6. **Configure Release Profiles**: Ensure `Cargo.toml` specifies `lto = "fat"`, `panic = "abort"`, `codegen-units = 1`, and `strip = "symbols"`.
97
- 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.
98
- 8. **Verify & Profile**: Write unit tests with real fixtures, run `cargo clippy -- -D warnings`, and verify zero-cost properties.
104
+ 5. **Clarify Constraints**: Define the target memory budget (RSS), traffic profile (heavy public vs private low-consume), concurrency requirements, and deployment environment (Docker/Kubernetes/Linux).
105
+ 6. **Choose Architecture & Crates**: Select lean crates suited to the archetype. Never pull in Tokio or connection pools for simple polling daemons.
106
+ 7. **Configure Release Profiles**: Ensure `Cargo.toml` specifies `lto = "thin"` (fast CI/dev) or `lto = "fat"` (minimal binary size), `panic = "abort"`, `codegen-units = 1`, and `strip = true`.
107
+ 8. **Implement with Memory & Concurrency Guards**: Apply zero-DOM fast paths first, pre-parse DOM slicing with guarded `pruned.len() < html.len()` fallbacks, conditional opt-in allocator/Tokio tuning (preserving native defaults when unset), bounded state, and cancellation-safe async branches.
108
+ 9. **Verify & Profile**: Write unit tests with real fixtures, run `cargo clippy -- -D warnings`, and verify zero-cost properties.
99
109
 
100
110
  ---
101
111
 
@@ -111,7 +121,7 @@ Master modern Rust (1.80+ / 2024 Edition) features, advanced type system mechani
111
121
 
112
122
  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:
113
123
 
114
- - `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.
124
+ - `audit_memory_antipatterns`: Automatically scans workspace files for hardcoded Dockerfile/runtime allocator traps, unoffloaded `malloc_trim`/sync locks across `.await`, unguarded DOM double-parse fallbacks, unoptimized release profiles, and synthetic test fixtures.
115
125
  - `inspect_struct_layout`: Computes struct padding bytes, alignment boundaries, field reordering, and cache-line false-sharing hazards.
116
126
  - `calculate_hardware_budget`: Computes worst-case RSS ceilings and safe per-connection buffers to prevent Linux OOMKilled (Exit Code 137).
117
127
  - `explain_recipe`: Queries the 58 production engineering references on-demand, returning targeted snippets without bloating context window.
@@ -120,8 +130,8 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
120
130
  - `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.
121
131
  - `check_cancellation_safety`: Scans async code and `tokio::select!` branches for drop-hazard operations (`read_exact`, partial writes, lock starvation across cancellation).
122
132
  - `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.
123
- - `generate_hardened_docker`: Generates hardened multi-stage Dockerfiles (<65MB) with Debian Bookworm C-ABI parity, symbol stripping, and `MALLOC_ARENA_MAX=2` memory guarding.
124
- - `tune_allocator_env`: Generates tuned allocator environment variables (`MALLOC_ARENA_MAX`, `MALLOC_MMAP_THRESHOLD_`, `TOKIO_WORKER_THREADS`, or `MALLOC_CONF`) with detailed trade-off analysis.
133
+ - `generate_hardened_docker`: Generates hardened multi-stage Dockerfiles (<65MB) with Debian Bookworm C-ABI parity, symbol stripping, and deploy-time opt-in allocator/Tokio env documentation (keeping native runtime defaults out-of-the-box).
134
+ - `tune_allocator_env`: Generates deploy-time (`docker run -e` / K8s) allocator & Tokio environment variables (`MALLOC_ARENA_MAX`, `MALLOC_MMAP_THRESHOLD_`, `TOKIO_WORKER_THREADS`, or `MALLOC_CONF`) with explicit throughput vs RSS trade-off analysis.
125
135
  - `analyze_collection_overhead`: Scans Rust code for heavy collections (`String`, `Vec<T>`, `HashMap`) and recommends zero-cost drop-in alternatives (`CompactString`, `Box<[T]>`, `AHashMap`, `SmallVec`).
126
136
  - `generate_k8s_manifest`: Generates hardened Kubernetes Deployment YAML with Guaranteed QoS, Downward API `TOKIO_WORKER_THREADS`, `preStop: sleep 3` hook, and probe isolation.
127
137
  - `detect_lock_await`: Scans async Rust source files for synchronous Mutex/RwLock guards held across `.await` points causing reactor thread starvation and deadlocks.
@@ -157,8 +167,8 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
157
167
  ### 4. Linux Memory Allocator Tuning & Docker Slimming
158
168
 
159
169
  - **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.
160
- - **Glibc Arena Containment**: Configuring `ENV MALLOC_ARENA_MAX=2` in Dockerfiles to prevent multi-threaded Tokio worker arena fragmentation.
161
- - **Active Heap Trimming**: Integrating `libc::malloc_trim(0)` inside telemetry loops and post-request middleware, safely guarded by `#[cfg(all(target_os = "linux", target_env = "gnu"))]`.
170
+ - **Preserve Native Defaults (Opt-In Deploy-Time Tuning Only)**: **NEVER** hardcode `ENV TOKIO_WORKER_THREADS=2`, `ENV MALLOC_ARENA_MAX=2`, `ENV MALLOC_MMAP_THRESHOLD_`, `ENV MALLOC_TRIM_THRESHOLD_`, `ENV MALLOC_TOP_PAD_`, or `PR_SET_THP_DISABLE` in `Dockerfile` or `main.rs` fallback code (do not `.unwrap_or(2)` worker threads in Rust!). Leave Tokio (`available_parallelism()`) and glibc at their native defaults unless explicitly overridden at deploy time (`docker run -e ...` or K8s env) for tight-RSS environments.
171
+ - **Opt-In Offloaded Heap Trimming**: **NEVER** call `libc::malloc_trim(0)` in per-request HTTP middleware or synchronously inside Tokio worker tasks (it locks heap arenas and forces constant page re-faults under concurrency). When periodic trimming is needed for strict RSS limits, gate it behind an opt-in flag (`MALLOC_TRIM=true`, default `false`), guard with `#[cfg(all(target_os = "linux", target_env = "gnu"))]`, and offload to `tokio::task::spawn_blocking`.
162
172
  - **Docker C-ABI Safety**: Strictly pairing builder and runner stage base images (`rust:1.xx-slim-bookworm` ➔ `debian:bookworm-slim`) and installing `ca-certificates` and `libssl3` to eliminate `/lib/x86_64-linux-gnu/libc.so.6: version GLIBC_xxx not found`.
163
173
  - **Sub-80MB Docker Multi-Stage Slimming**:
164
174
  - Isolating build tools (`cargo`, `rustc`, `gcc`, `libssl-dev`) to the builder stage.
@@ -171,9 +181,11 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
171
181
 
172
182
  ### 5. High-Efficiency Scraping & DOM Pruning
173
183
 
174
- - **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.
175
- - **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.
176
- - **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.
184
+ - **The Law of Real DOM Fixtures (No Synthetic Mocks & No Repo Bloat)**: Strictly prohibiting hallucinatory, synthetic DOM placeholders (`<div class="item">Card 1</div>`). Verify scrapers against authentic production DOM snippets containing real tag hierarchies, class signatures, and attributes — preferably as compact trimmed inline literals in `#[cfg(test)]` (never dump bloated raw `.html` files into the repository unless requested, and never leak private domains or credentials).
185
+ - **Zero-DOM Extraction First**: Before parsing HTML into a DOM tree, check if target data already exists in embedded JSON/script blocks (`__NEXT_DATA__`, `gdata`, `g_th`, `self.__next_f.push`). Direct string/byte slicing + `serde_json::from_slice` skips `html5ever` completely.
186
+ - **Pre-Parse HTML Slicing & Safe Boundary Anchors**: Truncating raw HTML text strings (`&html[..end_pos]`) _before_ passing them to `Html::parse_document` when heavy trailing bloat follows the main content. Anchor markers strictly to real production wrapper/footer signatures (avoid loose substrings like `id="related"` or `class="pagination"` that can match inside `<head>`, inline scripts, or single-quoted attributes).
187
+ - **Zero-Downgrade Adaptive Self-Healing Fallback (With Length Guard)**: Always guard full-document fallback with `if extracted_is_empty && pruned.len() < full_html.len()`. Without the `pruned.len() < full_html.len()` guard, 404s, empty searches, and pages lacking markers double-parse the entire HTML!
188
+ - **Single-Fetch `/random` Parity**: Extract a shared `parse_gallery_document` / `build_gallery_response` helper so `/random` endpoints that already receive the full gallery HTML parse it directly in one HTTP request instead of issuing a redundant second `scrape_get` HTTP round-trip.
177
189
  - **Static Selectors (`LazyLock`)**: Compiling CSS selectors once at startup using `static SEL: LazyLock<Selector>` instead of recompiling selector ASTs inside request loops.
178
190
  - **Direct Byte Slice Deserialization**: Parsing undocumented internal JSON APIs directly from byte buffers using `serde_json::from_slice(bytes)` without creating intermediate `String` instances.
179
191
  - **Scope-Confined DOM Lifecycle**: Extracting values immediately into small typed structs and instantly dropping the `Html` document out of scope.
@@ -181,7 +193,7 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
181
193
 
182
194
  ### 6. Async Concurrency & Tokio Reactor Safety
183
195
 
184
- - **Reactor Protection**: Strict isolation of blocking operations; offloading synchronous filesystem I/O to `tokio::task::spawn_blocking` and heavy compute to `rayon`.
196
+ - **Reactor Protection**: Strict isolation of blocking operations; offloading synchronous filesystem I/O, synchronous compression/decompression (`flate2`/`zstd` above small thresholds), and optional `libc::malloc_trim(0)` to `tokio::task::spawn_blocking`, and heavy compute to `rayon`.
185
197
  - **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`).
186
198
  - **Cancellation Safety**: Auditing all `tokio::select!` branches against drop hazards; decoupling uninterruptible actions into background `JoinSet` tasks.
187
199
  - **Task Orchestration**: Managing concurrent worker groups with `tokio::task::JoinSet` instead of raw `Vec<JoinHandle>`.
@@ -189,10 +201,10 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
189
201
 
190
202
  ### 7. Network Pooling & Tiered Timeouts
191
203
 
192
- - **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).
193
- - **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.
194
- - **Native Compression**: Configuring `gzip(true)` and `deflate(true)` to reduce network payload memory buffers.
195
- - **Selective Non-Caching**: Explicitly skipping cache insertion for volatile or `/random` endpoints to avoid cache pollution.
204
+ - **Singleton Client Architecture**: Reusing a single `reqwest::Client` inside `Arc<AppState>` with `.tcp_keepalive(60s)` (preserving `reqwest`'s native `pool_max_idle_per_host` default unless host/FD caps specifically require bounding, avoiding artificial caps like `10` that force repeated TCP+TLS handshakes under burst concurrency).
205
+ - **Tiered Timeouts**: Enforcing standard 15s timeouts for scrapers while applying aggressive **fast-fail 3s–5s timeouts** on ancillary metadata/GeoIP calls to prevent worker thread pinning.
206
+ - **Selective Non-Caching (Bypass Lookup Before Query)**: Explicitly skipping both cache lookup (`get`) and cache insertion (`set`) for volatile or `/random` endpoints so `/random` never wastes a Redis/Moka round-trip.
207
+ - **Optional Proxy Routing**: When supporting `PROXY_URL`, accept a single standard RFC URL (`http://`, `https://`, `socks5://`, `socks5h://`) instead of biased split IP/port/user/pass env vars, and sanitize credentials in logs.
196
208
 
197
209
  ### 8. Headless-Free Anti-Bot & Session Resilience
198
210
 
@@ -204,15 +216,15 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
204
216
  ### 9. Bounded State Management & Caching Resilience
205
217
 
206
218
  - **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.
207
- - **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.
208
- - **Credential Masking**: Sanitizing sensitive passwords in connection strings before logging (`mask_redis_url`).
219
+ - **Hybrid Zero-Downtime Fallback**: Automatically falling back to a bounded in-memory `moka::future::Cache` (bounded by byte weight or entry count) if Redis disconnects, ensuring the web service never crashes. Any payload compression (`CACHE_COMPRESS`) must be opt-in (`false` by default) and offloaded to `spawn_blocking` above small thresholds (e.g. >16 KiB).
220
+ - **Credential Masking**: Sanitizing sensitive passwords in all connection/proxy strings before logging (`sanitize_url_credentials` for both `REDIS_URL` and `PROXY_URL`).
209
221
  - **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.
210
222
 
211
223
  ### 10. Production Web Development (Axum 0.8 & GraphQL)
212
224
 
213
225
  - Modern web service architecture using Axum 0.8 and Tower HTTP middleware (CORS, Trace, Timeout).
214
- - REST and GraphQL parity using `async-graphql` and `async-graphql-axum` with depth and complexity boundaries.
215
- - Zero-cost query validation using `validator::Validate` derive macros.
226
+ - REST and GraphQL parity using `async-graphql` and `async-graphql-axum` with depth and complexity boundaries: share exact service helpers, URL builders, ID validators, and output models between REST and GraphQL (never duplicate endpoint URL logic or diverge schema fields), and handle `GET /graphql?query=...` alongside `POST` (`application/json` & `application/graphql`).
227
+ - Zero-cost inline input validation (preferring explicit helpers over `validator` crate which drags in `proc-macro-error2` future-incompat warnings). Ensure ID validators accept valid provider characters (e.g. single `.` in `video.abc/slug`) while rejecting path traversal (`..`, `./`, `/.`) and query/fragment injection (`&`, `?`, `#`, `\`).
216
228
  - Serving static OpenAPI / Swagger documentation without dynamic runtime schema compilation.
217
229
 
218
230
  ### 11. Zero-Dependency Telemetry & Metric Cardinality
@@ -263,6 +275,7 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
263
275
 
264
276
  ## Behavioral Traits
265
277
 
278
+ - **Plan-First & Multi-Dimensional Decision-Making (Never One-Size-Fits-All)**: Always presents an implementation plan and asks the user about relevant dimensions (workload archetype, SLA priority, hardware/cgroup/libc constraints, co-located services, and public OSS vs private blast radius) before mutating code or prescribing opt-in tuning.
266
279
  - Prioritizes physical memory efficiency (RSS) and long-term runtime stability alongside raw throughput.
267
280
  - Makes invalid states unrepresentable using Rust's compile-time type system and type-state pattern.
268
281
  - Rejects dynamic-language bad habits: avoids unneeded cloning, unbounded maps, dynamic string regexes, and inline client creation.
@@ -290,10 +303,10 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
290
303
 
291
304
  ## Response Approach
292
305
 
293
- 1. **Analyze Constraints & Operating Mode**: Identify if the task is a rewrite from dynamic code (Mode A) or greenfield native design (Mode B). Establish memory and throughput constraints.
306
+ 1. **Assess Context & Present Plan First**: Identify Mode A vs Mode B, evaluate the 6 context dimensions (archetype, SLA priority, hardware/libc, traffic/payload, co-tenancy, and public OSS vs private blast radius), ask the user about missing critical factors, and present an implementation plan with Pros/Cons before modifying files.
294
307
  2. **Design Data Models & Boundaries**: Define strongly typed structs, avoiding premature cloning through borrowing (`&str`, `&[T]`) or `Cow<'a, str>`. Define explicit error types with `thiserror`.
295
308
  3. **Structure Asynchronous Pipelines**: Implement singleton connection pooling, bounded caching (`moka`), and cancellation-safe Tokio primitives.
296
- 4. **Enforce Memory & Allocator Containment**: Apply pre-parse HTML pruning, static compiled selectors (`LazyLock`), glibc arena controls (`MALLOC_ARENA_MAX=2`), and `malloc_trim`.
309
+ 4. **Enforce Memory & Allocator Containment**: Apply zero-DOM slicing first, guarded pre-parse HTML pruning (`pruned.len() < full_html.len()`), static compiled selectors (`LazyLock`), and deploy-time opt-in allocator/Tokio tuning (keeping native defaults unless configured via env).
297
310
  5. **Verify & Validate**: Include unit tests (or mock HTML parsing tests), verify Clippy clean status, and confirm absence of unbounded resource growth.
298
311
 
299
312
  ---
@@ -324,7 +337,7 @@ Consult the attached reference guides for complete, production-tested code templ
324
337
  - `resources/zero_allocation_error_architecture.md` — Boxing rare error payloads, `Result<T, E>` stack minimization, and eliminating dynamic `format!` on error paths.
325
338
  - `resources/tokio_thread_starvation_and_cpu_offload.md` — Cooperative scheduling safety, offloading CPU-bound tasks (>100µs) via `spawn_blocking`/`rayon`, and event loop lag monitoring.
326
339
  - `resources/bounded_streaming_and_payload_guards.md` — Bounded HTTP streaming, memory bomb defense, early-break chunk accumulation, and zero-copy proxying.
327
- - `resources/memory_allocator_tuning.md` — Glibc arena containment (`MALLOC_ARENA_MAX=2`), safe `libc::malloc_trim(0)`, and Dockerfile ABI hardening.
340
+ - `resources/memory_allocator_tuning.md` — Native default preservation, deploy-time opt-in glibc/Tokio tuning, `spawn_blocking`-offloaded `libc::malloc_trim(0)`, and Dockerfile ABI hardening.
328
341
  - `resources/docker_slimming_and_build_hygiene.md` — Sub-80MB multi-stage builds, `.dockerignore` discipline, cache protection, and APT cleanup.
329
342
  - `resources/reqwest_client_and_connection_pooling.md` — Singleton client pooling, idle timeouts, tiered timeouts, and selective non-caching of `/random`.
330
343
  - `resources/redis_connection_and_caching_pitfalls.md` — Solving lazy connection traps, feature flag requirements (`tokio-comp`), URL auth formatting, PING verification, and hybrid fallback.
@@ -332,7 +345,7 @@ Consult the attached reference guides for complete, production-tested code templ
332
345
  - `resources/rate_limiting_and_state.md` — Bounded `DashMap` rate limiter (`BUCKET_MAX_SIZE`), background 30s cleaner tasks, proxy IP extraction, and progressive throttling.
333
346
  - `resources/telemetry_and_metrics.md` — Zero-dependency Prometheus exporter, PID-filtered `sysinfo`, Tokio event loop lag measurement, and `MatchedPath` cardinality protection.
334
347
  - `resources/anti_bot_and_cookie_challenges.md` — Headless browser elimination, single-flight `RwLock` cookie bootstrapping, and early-break chunk streaming.
335
- - `resources/hot_path_string_and_zero_cost_helpers.md` — Zero-regex single-pass whitespace squeezing, native integer time conversions, static `LazyLock<Regex>`, and `validator` derive.
348
+ - `resources/hot_path_string_and_zero_cost_helpers.md` — Zero-regex single-pass whitespace squeezing, native integer time conversions, static `LazyLock<Regex>`, and zero-dep inline validation.
336
349
  - `resources/zero_panic_and_router_architecture.md` — Zero-panic enforcement (`deny(clippy::unwrap_used)`), macro recursion limits, and middleware execution order.
337
350
  - `resources/axum_and_tower_architecture.md` — Production Axum 0.8 backend template, Tower middleware, GraphQL parity, domain error mapping, and graceful shutdown.
338
351
  - `resources/realtime_websocket_and_connection_scaling.md` — 50k–500k WebSocket connections, tuned 4KB buffers, single-task event loops, zero-copy broadcast fan-out, and slow consumer isolation.
@@ -120,3 +120,12 @@ pub fn is_sheddable_route(path: &str) -> bool {
120
120
  - [ ] Configured fast-fail `503 Service Unavailable` with `Retry-After` header before parsing bodies.
121
121
  - [ ] Priority routes (checkout, health probes) bypass shedding guards.
122
122
  - [ ] Drop guard ensures in-flight counters decrement even on unexpected panic or cancellation.
123
+
124
+ ---
125
+
126
+ ## Trade-Offs: Pros, Cons & When to Skip
127
+
128
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
129
+ | :--- | :--- | :--- | :--- |
130
+ | **Little's Law Dynamic Concurrency Limit** | Prevents queue pileup, OOM, and latency collapse under traffic spikes | Over-aggressive gradient feedback can throttle valid bursts or reject healthy slow upstreams | Use on public/shared services facing bursty load; skip on low-QPS internal tools or single-consumer queue workers |
131
+ | **Fast-Fail `503` Load Shedding** | Protects p99 latency and keeps health probes responsive before parsing bodies | Returns `503` to excess callers instead of queuing | Use when downstream capacity is saturated; skip for background batch jobs where queuing/retry is preferred |
@@ -137,3 +137,12 @@ impl AuthService {
137
137
  }
138
138
  }
139
139
  ```
140
+
141
+ ---
142
+
143
+ ## Trade-Offs: Pros, Cons & When to Skip
144
+
145
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
146
+ | :--- | :--- | :--- | :--- |
147
+ | **Headless-Free Algorithmic Solver** | Eliminates 500MB+ Chromium RSS and browser spawn latency | Breaks immediately if upstream obfuscates or rotates challenge JS | Use for deterministic JS/cookie challenges; skip if target uses behavioral CAPTCHA/TLS fingerprinting requiring residential proxy or user action |
148
+ | **Single-Flight `RwLock` Cookie Cache + 64KB Early Break** | Prevents thundering-herd auth handshakes and avoids downloading full HTML twice | Stale cached cookie causes one retry round-trip on expiry | Use whenever multiple concurrent requests share upstream session cookies; skip for stateless public APIs |
@@ -156,3 +156,12 @@ impl WorkerPool {
156
156
  2. Are `read_exact` and `write_all` operations shielded from arbitrary drop cancellations?
157
157
  3. Are background tasks tracked inside a `JoinSet` rather than detached `tokio::spawn` calls?
158
158
  4. Does the shutdown handler broadcast a `CancellationToken` and drain background tasks cleanly before exit?
159
+
160
+ ---
161
+
162
+ ## Trade-Offs: Pros, Cons & When to Skip
163
+
164
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
165
+ | :--- | :--- | :--- | :--- |
166
+ | **Cancellation-Safe `select!` + `JoinSet` Drainage** | Prevents silent partial-read/write data loss and dropped in-flight tasks on shutdown | Adds task tracking/channel plumbing and slightly higher code complexity | Use on all long-lived async servers, streaming pipelines, and stateful `tokio::select!` loops; skip on trivial single-shot CLI scripts |
167
+ | **Decoupled Worker + `CancellationToken`** | Uninterruptible I/O finishes cleanly during rolling deploys | Delays process exit until active tasks drain (must stay within K8s `terminationGracePeriodSeconds`) | Use for graceful shutdown in HTTP/gRPC/queue services; skip for stateless ephemeral tasks |
@@ -66,15 +66,22 @@ async fn main() -> anyhow::Result<()> {
66
66
 
67
67
  async fn shutdown_signal() {
68
68
  let ctrl_c = async {
69
- signal::ctrl_c().await.expect("Failed to install Ctrl+C handler");
69
+ if let Err(err) = signal::ctrl_c().await {
70
+ tracing::warn!("Failed to install Ctrl+C handler: {err}");
71
+ }
70
72
  };
71
73
 
72
74
  #[cfg(unix)]
73
75
  let terminate = async {
74
- signal::unix::signal(signal::unix::SignalKind::terminate())
75
- .expect("Failed to install SIGTERM handler")
76
- .recv()
77
- .await;
76
+ match signal::unix::signal(signal::unix::SignalKind::terminate()) {
77
+ Ok(mut sig) => {
78
+ sig.recv().await;
79
+ }
80
+ Err(err) => {
81
+ tracing::warn!("Failed to install SIGTERM handler: {err}");
82
+ std::future::pending::<()>().await;
83
+ }
84
+ }
78
85
  };
79
86
 
80
87
  #[cfg(not(unix))]
@@ -143,3 +150,12 @@ impl IntoResponse for AppError {
143
150
  }
144
151
  }
145
152
  ```
153
+
154
+ ---
155
+
156
+ ## Trade-Offs: Pros, Cons & When to Skip
157
+
158
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
159
+ | :--- | :--- | :--- | :--- |
160
+ | **Axum 0.8 + `Arc<AppState>` + Tower Layers** | Strong type-safe extractors, zero-copy state sharing, ecosystem alignment | Multi-threaded Tokio runtime burns ~10–30MB baseline RSS; overkill for simple polling | Use for Archetype A web APIs/gateways; skip in favor of Koburi `std::net` for sub-5MB sidecars |
161
+ | **Trimmed `tower-http` Features + `thiserror` Mapping** | Keeps compile times fast and prevents unused middleware overhead | Changing middleware layer order alters timeout/CORS behavior on errors | Always trim unused features (`cors` only if trace/timeout unneeded); audit layer order carefully |
@@ -40,6 +40,11 @@ impl CacheService {
40
40
  self.cache.insert(key.to_string(), val).await;
41
41
  }
42
42
  }
43
+
44
+ // NOTE on Payload Compression (CACHE_COMPRESS):
45
+ // Do NOT enable synchronous gzip/zstd compression by default on every cache hit/miss.
46
+ // Running synchronous compression directly on Tokio worker threads burns CPU and increases p99 latency.
47
+ // Keep CACHE_COMPRESS=false (opt-in), and if enabled, offload payloads > 16 KiB to tokio::task::spawn_blocking.
43
48
  ```
44
49
 
45
50
  ---
@@ -58,14 +63,10 @@ pub fn build_http_client(user_agent: &str) -> reqwest::Client {
58
63
 
59
64
  reqwest::Client::builder()
60
65
  .default_headers(headers)
61
- .pool_idle_timeout(Duration::from_secs(90))
62
- .pool_max_idle_per_host(10)
63
66
  .tcp_keepalive(Duration::from_secs(60))
64
67
  .timeout(Duration::from_secs(15))
65
- .gzip(true)
66
- .deflate(true)
67
68
  .build()
68
- .expect("Failed to build HTTP client")
69
+ .unwrap_or_default()
69
70
  }
70
71
  ```
71
72
 
@@ -103,3 +104,12 @@ pub async fn telemetry_middleware(req: Request<Body>, next: Next) -> Response {
103
104
  next.run(req).await
104
105
  }
105
106
  ```
107
+
108
+ ---
109
+
110
+ ## Trade-Offs: Pros, Cons & When to Skip
111
+
112
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
113
+ | :--- | :--- | :--- | :--- |
114
+ | **Bounded `moka` Cache (`max_capacity` / byte weight)** | Hard memory ceiling prevents OOM while serving hot hits in nanoseconds | Evicts entries under small budgets; opt-in `CACHE_COMPRESS` burns CPU if not offloaded to `spawn_blocking` | Use for deterministic read-heavy responses; skip/bypass lookup on `/random` or volatile endpoints |
115
+ | **Singleton `reqwest::Client` (Default Pool)** | Reuses TCP/TLS connections across handlers without socket exhaustion | Capping `pool_max_idle_per_host` too low (e.g. `10`) causes handshake churn under burst load | Always share one client in `AppState`; leave `pool_max_idle_per_host` at `reqwest` default unless FD limits demand a cap |
@@ -145,3 +145,12 @@ pub async fn proxy_asset_handler(
145
145
  2. Are all third-party HTTP streams guarded with a byte accumulator ceiling?
146
146
  3. Does proxying use `Body::from_stream` rather than buffering in a `Vec<u8>`?
147
147
  4. Are oversized responses aborted immediately at the TCP stream level without downloading remainder bytes?
148
+
149
+ ---
150
+
151
+ ## Trade-Offs: Pros, Cons & When to Skip
152
+
153
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
154
+ | :--- | :--- | :--- | :--- |
155
+ | **Chunked `take()` / Byte-Ceiling Guards** | Neutralizes memory bombs and truncates oversized upstream payloads early | Rejects/cuts legitimate payloads if `MAX_BYTES` is set too conservatively | Always enforce on untrusted inbound bodies and upstream fetches; calibrate `MAX_BYTES` to real max document size |
156
+ | **Zero-Copy `Body::from_stream` Proxying** | Constant O(1) memory per proxied media stream regardless of file size | Cannot inspect or rewrite full response body mid-flight | Use for image/video/file proxies (e.g. CDN relays); skip only when full-body transformation is mandatory |
@@ -120,3 +120,12 @@ pub fn collect_local_headers() -> ArrayVec<&'static str, 8> {
120
120
  - [ ] Eliminated zero-fill buffers (`vec![0; N]`) on network/file read targets.
121
121
  - [ ] Used `std::mem::take` or `std::mem::replace` to avoid cloning during struct state shifts.
122
122
  - [ ] Substituted small fixed-bound heap vectors with stack-allocated `ArrayVec`.
123
+
124
+ ---
125
+
126
+ ## Trade-Offs: Pros, Cons & When to Skip
127
+
128
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
129
+ | :--- | :--- | :--- | :--- |
130
+ | **Iterator / `.chunks_exact()` BCE** | Eliminates panic branches and unlocks LLVM auto-vectorization with 100% safe Rust | Slightly less obvious for complex random-access algorithms | Always prefer on hot byte/slice loops; use `get_unchecked` only with proven benchmarks |
131
+ | **`MaybeUninit` / `std::mem::take`** | Removes `vec![0; N]` zeroing tax and avoids cloning when moving fields | `MaybeUninit` requires `unsafe` soundness discipline (`assume_init` after exact write) | Use `std::mem::take` everywhere; restrict `MaybeUninit` to verified I/O/ring-buffer hot paths |
@@ -119,3 +119,12 @@ impl WorkerStats {
119
119
  2. Has `std::mem::size_of::<T>()` been audited against theoretical minimum field sizes?
120
120
  3. Are multi-threaded hot atomic counters padded to 64 bytes using `#[repr(align(64))]`?
121
121
  4. Are `Newtype` wrappers marked with `#[repr(transparent)]`?
122
+
123
+ ---
124
+
125
+ ## Trade-Offs: Pros, Cons & When to Skip
126
+
127
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
128
+ | :--- | :--- | :--- | :--- |
129
+ | **Field Reordering (8B -> 1B)** | Eliminates silent padding bytes at zero runtime cost | Makes field grouping slightly less domain-ordered visually | Always apply to structs stored in large arrays/caches (`Vec<T>`, `Moka`) |
130
+ | **`#[repr(align(64))]` Padding** | Eliminates multi-core false sharing on hot atomic counters | Inflates each struct to >=64 bytes (wasteful if stored in huge arrays) | Use only on contended per-core/shared atomics; skip on cold config structs or large dense collections |
@@ -133,3 +133,12 @@ pub async fn run_event_loop() {
133
133
  2. Use `std::mem::take(&mut value)` instead of `.clone()` to extract fields out of mutable references.
134
134
  3. For collections bounded by small $N$ ($\le 16$), use `ArrayVec<T, N>` to eliminate heap allocations entirely.
135
135
  4. Keep worker scratchpads alive across loop iterations and clear them with `.clear()`.
136
+
137
+ ---
138
+
139
+ ## Trade-Offs: Pros, Cons & When to Skip
140
+
141
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
142
+ | :--- | :--- | :--- | :--- |
143
+ | **`.clone_from()` / `.clear()` Buffer Reuse** | Eliminates repeated `malloc`/`free` churn in loops | Retains peak buffer capacity (`shrink_to` needed if rare huge spikes occur) | Use inside tight request/parser loops; pair with max-capacity cap if spikes vary wildly |
144
+ | **Stack-Only `ArrayVec<T, N>`** | Zero heap allocations for small fixed-bound lists | Increases stack frame / `Future` size; panics or errors if `N` exceeded | Use for small bounded items (`N <= 16`) outside huge async state machines; skip for unbounded inputs |
@@ -124,3 +124,12 @@ fn handle_unlikely_reconnection_error(err: std::io::Error) {
124
124
  - [ ] Switched loop assignments to `.clone_from()` to prevent allocator thrashing.
125
125
  - [ ] Converted immutable vectors and strings to `Box<[T]>` and `Box<str>`.
126
126
  - [ ] Tagged rare error recovery routines with `#[cold]`.
127
+
128
+ ---
129
+
130
+ ## Trade-Offs: Pros, Cons & When to Skip
131
+
132
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
133
+ | :--- | :--- | :--- | :--- |
134
+ | **`NonZero*` Niches & `Box<[T]>`** | Shrinks `Option<T>` / fixed slices (24B -> 16B) with zero runtime overhead | `Box<[T]>` cannot grow in-place without reallocating into `Vec` | Use `NonZero*` for IDs/ports/counts and `Box<[T]>` for immutable collections; skip if frequent `.push()` needed |
135
+ | **Compile-Time `assert!(size_of::<T>() <= N)`** | Catches accidental stack/enum bloat immediately at compile time | Can break cross-platform builds (`32-bit` vs `64-bit`) if asserted for exact `usize` bytes | Use on hot cache/protocol structs; assert `<=` or guard pointer-width assumptions |
@@ -168,3 +168,12 @@ Watch for:
168
168
  1. **Long Poll Times**: Tasks showing poll durations > 1ms. Identify the offending function and offload it to `tokio::task::spawn_blocking` or `rayon`.
169
169
  2. **High Busy/Idle Ratio**: Indicates that workers are saturated with computation rather than waiting on non-blocking I/O.
170
170
  3. **Woken Without Progress**: Tasks scheduled frequently by poorly configured timers or channels without actual work ready.
171
+
172
+ ---
173
+
174
+ ## Trade-Offs: Pros, Cons & When to Skip
175
+
176
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
177
+ | :--- | :--- | :--- | :--- |
178
+ | **Upfront Physical RSS Budget Math** | Prevents Linux `OOMKilled` (Exit 137) before production deploy | Conservative estimates may under-utilize available RAM if buffers are rarely full | Always calculate for strict-RAM pods/VPS (`<=512MB`) or high-connection WebSockets |
179
+ | **Loom Deterministic Model Checking** | Exhaustively catches subtle atomic ordering & deadlock bugs | Exponential state explosion limits Loom to small isolated concurrency primitives | Use on custom lock-free structures/atomics; skip on high-level Axum handlers |
@@ -156,3 +156,12 @@ impl TelemetryCounters {
156
156
  3. Are read-heavy configurations ($>95\%$ reads) decoupled using `ArcSwap`?
157
157
  4. Are concurrent metrics using `Atomic*` with `Ordering::Relaxed`?
158
158
  5. Has Clippy verified that no synchronous mutex guard crosses an `.await` boundary?
159
+
160
+ ---
161
+
162
+ ## Trade-Offs: Pros, Cons & When to Skip
163
+
164
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
165
+ | :--- | :--- | :--- | :--- |
166
+ | **`parking_lot` / `ArcSwap` / `Atomic*`** | 1-byte locks and wait-free reads crush lock contention on read-heavy state | Sync locks (`parking_lot`/`std`) held across `.await` still freeze Tokio worker threads | Use `ArcSwap` for rare-write config, `parking_lot` for short sync critical sections; never hold across `.await` |
167
+ | **Actor Channels (`mpsc`) vs `tokio::sync::Mutex`** | Eliminates shared lock contention and guarantees cancellation-safe ownership | Channel hop adds slight latency & heap/bounded queue overhead vs uncontended atomics | Use `mpsc` actors for stateful I/O resources; skip for simple counters (use `AtomicU64`) |
@@ -93,24 +93,20 @@ WORKDIR /app
93
93
  # Copy ONLY the compiled binary from builder stage
94
94
  COPY --from=builder /usr/src/app/target/release/app_binary /app/app_binary
95
95
 
96
- # CRITICAL RUNTIME CONFIGURATION:
97
- # 1. Baseline Mandatory: Bounded glibc arenas to eliminate multi-threaded RSS fragmentation
98
- ENV MALLOC_ARENA_MAX=2
96
+ # Keep native Tokio & glibc defaults in Dockerfile; pass tuning via `docker run -e` when needed:
99
97
  ENV PORT=3000
100
98
 
101
99
  # --------------------------------------------------------
102
- # OPTIONAL SITUATIONAL KNOBS (NON-MANDATORY):
103
- # (See resources/memory_allocator_tuning.md for detailed trade-offs)
100
+ # OPTIONAL DEPLOY-TIME TUNING (Ask user if workload is private/low-traffic vs busy public API):
101
+ # (See resources/memory_allocator_tuning.md for conditional decision guide)
104
102
  # --------------------------------------------------------
105
- # Clamp Tokio runtime to match container CPU quotas:
106
- # ENV TOKIO_WORKER_THREADS=2
107
- #
108
- # Direct kernel munmap for large buffers >= 128KB (note trailing underscore):
109
- # ENV MALLOC_MMAP_THRESHOLD_=131072
110
- #
111
- # Aggressive auto-trim for heap top (note trailing underscores):
112
- # ENV MALLOC_TRIM_THRESHOLD_=65536
113
- # ENV MALLOC_TOP_PAD_=65536
103
+ # Only pass these via `docker run -e` for private / low-traffic / tight-RSS containers:
104
+ # -e MALLOC_ARENA_MAX=2
105
+ # -e MALLOC_MMAP_THRESHOLD_=131072
106
+ # -e MALLOC_TRIM_THRESHOLD_=131072
107
+ # -e MALLOC_TOP_PAD_=65536
108
+ # -e TOKIO_WORKER_THREADS=2
109
+ # -e MALLOC_TRIM=true (Opt-in offloaded malloc_trim(0))
114
110
 
115
111
  EXPOSE 3000
116
112
 
@@ -130,9 +126,9 @@ CMD ["/app/app_binary"]
130
126
 
131
127
  ---
132
128
 
133
- ## 4. Allocator & Concurrency Knobs: Baseline vs Non-Mandatory Tuning
129
+ ## 4. Allocator & Concurrency Knobs: Conditional Opt-In & Blast Radius
134
130
 
135
131
  > [!NOTE]
136
- > **Tuning Discipline: Never Blindly Add Every Variable**
137
- > - **Mandatory Baseline**: `ENV MALLOC_ARENA_MAX=2` should be present in virtually every containerized multi-threaded Rust service targeting Linux glibc to avoid 8x arena fragmentation.
138
- > - **Non-Mandatory Situational Knobs**: `MALLOC_MMAP_THRESHOLD_`, `MALLOC_TRIM_THRESHOLD_`, `MALLOC_TOP_PAD_`, and `TOKIO_WORKER_THREADS` are **optional**. They represent conscious trade-offs between physical RSS reduction and kernel syscall overhead (`mmap`/`munmap`/`sbrk`). Consult [`memory_allocator_tuning.md`](memory_allocator_tuning.md) before enabling them.
132
+ > **Smart Decision Rule: Check Repo Scope, Hardware & SLA Before Tuning**
133
+ > - **Default Image (Especially Public OSS / Published Images)**: Keep `Dockerfile` free of hardcoded `MALLOC_*` and `TOKIO_WORKER_THREADS` overrides so downstream users on varied hardware keep native multi-core Tokio scaling and user-space heap reuse without extra `mmap`/`munmap` syscalls.
134
+ > - **Opt-In via `docker run -e` (Private / Tight-RSS / Cgroup-Constrained)**: Only suggest `MALLOC_ARENA_MAX=2`, `MALLOC_MMAP_THRESHOLD_=131072`, `MALLOC_TRIM_THRESHOLD_=131072`, `MALLOC_TOP_PAD_=65536` (and optionally `TOKIO_WORKER_THREADS` matched to container vCPU or `MALLOC_TRIM=true`) after confirming hardware limits, co-located services, and latency tolerance with the user. Consult [`memory_allocator_tuning.md`](memory_allocator_tuning.md) for full Pros & Cons.