@sinkaroid/rust-shapeshift 1.0.8 → 1.0.11

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.
package/README.md CHANGED
@@ -1,21 +1,21 @@
1
1
  # Rust Shapeshift
2
2
 
3
- `@sinkaroid/rust-shapeshift` is an AI agent skill specialized in **extreme memory and runtime efficiency** for Rust backend architectures. It enforces deterministic resource containment, zero-allocation data paths, and allocator-level memory reclamation across long-running production workloads.
3
+ `@sinkaroid/rust-shapeshift` is memory and runtime efficiency skills that guides AI coding agents in building memory- and runtime-efficient Rust backend services. It establishes conventions for bounded, predictable resource usage, allocation-free hot paths, and allocator-level memory reclamation, targeting long-running production workloads where steady-state footprint and latency stability matter.
4
4
 
5
- Universally compatible with all AI agent runtimes.
5
+ The skill is runtime-agnostic and can be loaded by any agent environment that supports skill or instruction files.
6
6
 
7
7
  ---
8
8
 
9
- ## Dual Operating Modes & Architectural Archetypes
9
+ ## Dual Operating Modes & Archetypes
10
10
 
11
11
  Before selecting libraries, AI agents must determine both the operating mode and the workload archetype:
12
12
 
13
13
  ### 1. Operating Modes
14
14
 
15
15
  1. **The Shapeshifter (Migration & Modernization Mode)**:
16
- Translates backend services from any runtime (Go, Python, Java, Node.js/TypeScript) into idiomatic Rust without carrying over garbage collection habits, DOM retention leaks, unbounded maps, or per-request connection allocations.
16
+ Translates backend services from any runtime (JavaScript/TypeScript, Python, Java, etc.) into idiomatic Rust without carrying over garbage collection habits, DOM retention leaks, unbounded maps, or per-request connection allocations.
17
17
  2. **The Native Architect (Greenfield Mode)**:
18
- Architects native Rust services from scratch targeting modern Rust 1.80+ / 2024 Edition with baseline memory consumption (<50MB RSS), stack inlining (`compact_str`), bounded buffers, zero-copy parsing, and deterministic resource lifecycles.
18
+ Architects native Rust services from scratch targeting baseline memory consumption (<50MB RSS), stack inlining (`compact_str`), bounded buffers, zero-copy parsing, and deterministic resource lifecycles.
19
19
 
20
20
  ### 2. Workload Archetypes & Framework Adaptability
21
21
 
@@ -28,7 +28,7 @@ Before selecting libraries, AI agents must determine both the operating mode and
28
28
 
29
29
  > [!IMPORTANT]
30
30
  > **The Real-World Testing & Anti-Hallucination Mandate**:
31
- > AI agents consistently fail in production by authoring synthetic, hallucinated unit tests (`<div class="item">Card 1</div>`) that pass 100% green while proving nothing and masking critical bugs.
31
+ > AI agents consistently fail in production by authoring synthetic, hallucinated unit. Agents commonly generate tests that are disconnected from the code's actual behavior: invented inputs (e.g. `<div class="item">Card 1</div>`), assertions that merely restate the implementation, and cases that never exercise real data. These tests pass reliably yet verify nothing, and defects in real-world data handling go undetected until production.
32
32
  > **All ingestion, scraping, and parsing code MUST be validated using real production fixtures and dual-assertion invariants.** Consult [`real_world_testing_and_dom_fixtures.md`](skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md) as the mandatory primary testing specification.
33
33
  >
34
34
  > Before blindly reaching for `tokio` or `axum`, evaluate your workload archetype. A multi-threaded async executor burns 10MB–40MB of idle RSS on thread pools and queues your workload doesn't need. For low-QPS daemons, monitoring sidecars, or CLI utilities, adopt [The Koburi Pattern](skills/rust-shapeshift/resources/zero_runtime_and_minimalist_daemons.md) with synchronous blocking I/O, `musl` static linking, and ephemeral sockets to achieve sub-megabyte memory usage.
@@ -154,18 +154,18 @@ Your agent will automatically clone, index, and apply the 58 production engineer
154
154
 
155
155
  ---
156
156
 
157
- ### Native CLI Commands
157
+ ### Commands
158
158
 
159
159
  ```bash
160
- rust-shapeshift list # Print all 58 production reference guides and descriptions
161
- rust-shapeshift audit # Scan current Rust project for memory anti-patterns
162
- rust-shapeshift mcp # Start Model Context Protocol (MCP) server over stdio
163
- rust-shapeshift init # Configure agent skill in current directory
160
+ rust-shapeshift list
161
+ rust-shapeshift audit
162
+ rust-shapeshift mcp
163
+ rust-shapeshift init
164
164
  ```
165
165
 
166
166
  ---
167
167
 
168
- ### 🔌 Model Context Protocol (MCP) Server
168
+ ### MCP
169
169
 
170
170
  Connect `rust-shapeshift` directly as an active tool server in **Claude Code, Cursor, Windsurf, or Antigravity**:
171
171
 
@@ -194,6 +194,7 @@ Or using native binary:
194
194
  ```
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
199
  - `inspect_struct_layout`: Computes exact field alignment, wasted padding bytes, optimal reordering, and cache-line false sharing hazards.
199
200
  - `calculate_hardware_budget`: Computes worst-case RSS and maximum safe concurrent connections without triggering Linux OOMKilled (Exit Code 137).
@@ -204,7 +205,11 @@ Or using native binary:
204
205
  - `check_cancellation_safety`: Scans async code and `tokio::select!` branches for drop-hazard operations (`read_exact`, partial writes, lock contention across await).
205
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.
206
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.
207
-
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.
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
+ - `generate_k8s_manifest`: Generates hardened Kubernetes Deployment YAML with Guaranteed QoS, Downward API `TOKIO_WORKER_THREADS`, `preStop: sleep 3` hook, and probe isolation.
211
+ - `detect_lock_await`: Scans async Rust source files for synchronous Mutex/RwLock guards held across `.await` points causing reactor thread starvation and deadlocks.
212
+ - `scaffold_benchmark_profile`: Scaffolds Criterion throughput benchmarks, DHAT heap allocation profiling, or live jemalloc runtime statistics harnesses.
208
213
 
209
214
  ## Legal
210
215
 
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.8",
30
- "@sinkaroid/rust-shapeshift-darwin-x64": "1.0.8",
31
- "@sinkaroid/rust-shapeshift-linux-arm64": "1.0.8",
32
- "@sinkaroid/rust-shapeshift-linux-x64": "1.0.8",
33
- "@sinkaroid/rust-shapeshift-win32-x64": "1.0.8"
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"
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.8"
46
+ "version": "1.0.11"
47
47
  }
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: rust-shapeshift
3
3
  author: "@sinkaroid"
4
- version: "1.0.8"
4
+ version: "1.0.11"
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:
@@ -50,7 +50,9 @@ You are an expert Rust systems architect and concurrency engineer specialized in
50
50
  To eliminate architectural confusion and ensure consistent agent behavior across different project stacks, this skill enforces a strict separation between **Universal Memory/Systems Foundations** and **HTTP Transport Layering**:
51
51
 
52
52
  ### 1. The Systems & Memory Core is 100% Framework-Agnostic
53
+
53
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
+
54
56
  - **Linux Allocator Hygiene**: `MALLOC_ARENA_MAX=2`, `libc::malloc_trim(0)`, musl vs glibc trade-offs, and Docker C-ABI pairing.
55
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`).
56
58
  - **Low-Level Throughput**: Bounds Check Elimination (BCE), SIMD vector parsing, Profile-Guided Optimization (PGO), `io_uring`, and NUMA HugePages.
@@ -58,21 +60,24 @@ Over 70% of this skill focuses on hardware-, kernel-, allocator-, and compiler-l
58
60
  - **The Koburi Pattern (Archetype B)**: Zero-async, zero-dependency `std::net` / `UnixStream` minimal daemons under 1MB idle RSS.
59
61
 
60
62
  ### 2. Axum 0.8 as the Canonical Reference Implementation
63
+
61
64
  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.
62
65
 
63
66
  ### 3. Mandatory AI Agent Contract for Alternative Frameworks
67
+
64
68
  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):
69
+
65
70
  > **MANDATORY DIRECTIVE**: The AI agent **MUST NOT** force Axum onto the workspace. Instead, the agent **MUST adapt** the core zero-cost memory and safety principles into the target framework using the **Framework Adaptation Rosetta Stone** below:
66
71
 
67
- | Architectural Primitive | Axum 0.8 (Canonical Reference) | Actix Web | Salvo | Minimal std::net (Koburi) |
68
- |---|---|---|---|---|
69
- | **Zero-Allocation Error Envelope** | `impl IntoResponse for AppError` | `impl ResponseError for AppError` | `#[salvo::async_trait] impl Writer for AppError` | Custom byte serializer over `TcpStream::write_all` |
70
- | **Normalized Metric Routing (Cardinality Safe)** | `req.extensions().get::<MatchedPath>()` | `req.match_pattern()` | `req.params()` | Static route enum matching |
71
- | **Shared Application State** | `axum::extract::State(Arc<AppState>)` | `actix_web::web::Data<AppState>` | `depot.obtain::<Arc<AppState>>()` | Passed by borrowed reference `&AppState` |
72
- | **Zero-Downtime Rate Limiting Middleware** | `axum::middleware::from_fn_with_state` | `actix_web::dev::Transform` / `wrap_fn` | `#[handler] fn rate_limit(...)` | Inline bucket check before connection accept |
73
- | **Low-Memory WebSocket Upgrades** | `axum::extract::ws::{WebSocket, Message}` (4KB tuned buffer) | `actix-ws` with session framing | `salvo::websocket::WebSocket` | Custom lightweight framing over raw TCP |
74
- | **Chunked Streaming Response** | `axum::body::Body::from_stream` | `HttpResponse::Ok().streaming(stream)` | `Response::streaming(stream)` | Sequential `std::io::copy` to socket buffer |
75
- | **Graceful Shutdown Signal** | `axum::serve().with_graceful_shutdown()` | `actix_web::HttpServer::stop()` | `salvo::Server::stop()` | Polling atomic flag / SIGINT listener |
72
+ | Architectural Primitive | Axum 0.8 (Canonical Reference) | Actix Web | Salvo | Minimal std::net (Koburi) |
73
+ | ------------------------------------------------ | ------------------------------------------------------------ | --------------------------------------- | ------------------------------------------------ | -------------------------------------------------- |
74
+ | **Zero-Allocation Error Envelope** | `impl IntoResponse for AppError` | `impl ResponseError for AppError` | `#[salvo::async_trait] impl Writer for AppError` | Custom byte serializer over `TcpStream::write_all` |
75
+ | **Normalized Metric Routing (Cardinality Safe)** | `req.extensions().get::<MatchedPath>()` | `req.match_pattern()` | `req.params()` | Static route enum matching |
76
+ | **Shared Application State** | `axum::extract::State(Arc<AppState>)` | `actix_web::web::Data<AppState>` | `depot.obtain::<Arc<AppState>>()` | Passed by borrowed reference `&AppState` |
77
+ | **Zero-Downtime Rate Limiting Middleware** | `axum::middleware::from_fn_with_state` | `actix_web::dev::Transform` / `wrap_fn` | `#[handler] fn rate_limit(...)` | Inline bucket check before connection accept |
78
+ | **Low-Memory WebSocket Upgrades** | `axum::extract::ws::{WebSocket, Message}` (4KB tuned buffer) | `actix-ws` with session framing | `salvo::websocket::WebSocket` | Custom lightweight framing over raw TCP |
79
+ | **Chunked Streaming Response** | `axum::body::Body::from_stream` | `HttpResponse::Ok().streaming(stream)` | `Response::streaming(stream)` | Sequential `std::io::copy` to socket buffer |
80
+ | **Graceful Shutdown Signal** | `axum::serve().with_graceful_shutdown()` | `actix_web::HttpServer::stop()` | `salvo::Server::stop()` | Polling atomic flag / SIGINT listener |
76
81
 
77
82
  ---
78
83
 
@@ -105,6 +110,7 @@ Master modern Rust (1.80+ / 2024 Edition) features, advanced type system mechani
105
110
  ### Active MCP Tool Capabilities (Optional Stdio Server)
106
111
 
107
112
  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
+
108
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.
109
115
  - `inspect_struct_layout`: Computes struct padding bytes, alignment boundaries, field reordering, and cache-line false-sharing hazards.
110
116
  - `calculate_hardware_budget`: Computes worst-case RSS ceilings and safe per-connection buffers to prevent Linux OOMKilled (Exit Code 137).
@@ -115,6 +121,11 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
115
121
  - `check_cancellation_safety`: Scans async code and `tokio::select!` branches for drop-hazard operations (`read_exact`, partial writes, lock starvation across cancellation).
116
122
  - `optimize_serde_zero_copy`: Transforms owned serde payloads (`String`, `Vec<u8>`) into zero-copy borrowed structs (`&'a str`, `Cow<'a, str>`, `#[serde(borrow)]`) to eliminate deserialization heap churn.
117
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.
125
+ - `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
+ - `generate_k8s_manifest`: Generates hardened Kubernetes Deployment YAML with Guaranteed QoS, Downward API `TOKIO_WORKER_THREADS`, `preStop: sleep 3` hook, and probe isolation.
127
+ - `detect_lock_await`: Scans async Rust source files for synchronous Mutex/RwLock guards held across `.await` points causing reactor thread starvation and deadlocks.
128
+ - `scaffold_benchmark_profile`: Scaffolds Criterion throughput benchmarks, DHAT heap allocation profiling, or live jemalloc runtime statistics harnesses.
118
129
 
119
130
  ### 1. Real-World Testing & Anti-Hallucination Standards
120
131
 
@@ -360,4 +371,3 @@ Consult the attached reference guides for complete, production-tested code templ
360
371
  - `resources/lock_free_ring_buffers_and_disruptor.md` — High-throughput zero-allocation queues via cache-aligned power-of-two circular ring buffers (rtrb, ArrayQueue) and Disruptor pattern.
361
372
  - `resources/production_memory_leak_diagnostics_and_ebpf.md` — Diagnosing memory leaks in production with LLVM LeakSanitizer (-Zsanitizer=leak), jemalloc-ctl live heap dumps, and zero-overhead eBPF (bcc memleak) container tracing.
362
373
  - `resources/zero_cost_state_machines_and_enum_dispatch.md` — Eliminating dynamic dispatch (Box<dyn Trait>) and vtable overhead via compile-time enum_dispatch and zero-cost typestate state machines.
363
-
@@ -94,10 +94,24 @@ WORKDIR /app
94
94
  COPY --from=builder /usr/src/app/target/release/app_binary /app/app_binary
95
95
 
96
96
  # CRITICAL RUNTIME CONFIGURATION:
97
- # 1. Bounded glibc arenas to eliminate multi-threaded RSS fragmentation
97
+ # 1. Baseline Mandatory: Bounded glibc arenas to eliminate multi-threaded RSS fragmentation
98
98
  ENV MALLOC_ARENA_MAX=2
99
99
  ENV PORT=3000
100
100
 
101
+ # --------------------------------------------------------
102
+ # OPTIONAL SITUATIONAL KNOBS (NON-MANDATORY):
103
+ # (See resources/memory_allocator_tuning.md for detailed trade-offs)
104
+ # --------------------------------------------------------
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
114
+
101
115
  EXPOSE 3000
102
116
 
103
117
  CMD ["/app/app_binary"]
@@ -113,3 +127,12 @@ CMD ["/app/app_binary"]
113
127
  | **2. Clean APT Package Lists** | `rm -rf /var/lib/apt/lists/*` on every `apt-get` layer | Saves 30MB–50MB of cached package metadata in image layers. |
114
128
  | **3. Avoid Recommended Packages** | `--no-install-recommends` on `apt-get install` | Prevents Debian from pulling in hundreds of megabytes of documentation, man pages, and optional daemons. |
115
129
  | **4. Strict Codename Pairing** | `rust:1.xx-slim-bookworm` ➔ `debian:bookworm-slim` | Guarantees identical glibc 2.36 dynamic ABI without missing symbols or version mismatch crashes. |
130
+
131
+ ---
132
+
133
+ ## 4. Allocator & Concurrency Knobs: Baseline vs Non-Mandatory Tuning
134
+
135
+ > [!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.
@@ -1,7 +1,8 @@
1
1
  # Linux Memory Allocator Tuning & Low-Level Libc ABI Hardening
2
2
  1. How to tame glibc memory fragmentation (`MALLOC_ARENA_MAX=2` and `malloc_trim`).
3
- 2. How to avoid the **`libc.so` / GLIBC version mismatch** disaster in Docker multi-stage builds.
4
- 3. Why `malloc_trim` fails on Alpine (musl vs glibc target environments).
3
+ 2. Optional runtime environment tuning (`MALLOC_MMAP_THRESHOLD_`, `MALLOC_TRIM_THRESHOLD_`, `MALLOC_TOP_PAD_`, `TOKIO_WORKER_THREADS`) & detailed trade-offs.
4
+ 3. How to avoid the **`libc.so` / GLIBC version mismatch** disaster in Docker multi-stage builds.
5
+ 4. Why `malloc_trim` fails on Alpine (musl vs glibc target environments).
5
6
 
6
7
  ---
7
8
 
@@ -27,7 +28,8 @@ When a Rust binary links to C libraries (such as `libc`, `libssl`, `libcrypto`),
27
28
  To guarantee 100% binary-ABI compatibility and zero `libc.so` errors:
28
29
  - Pin the **exact same Debian codename** for both Builder and Runtime (e.g. `bookworm` and `bookworm-slim`).
29
30
  - Install `ca-certificates` and `libssl3` in the runtime layer.
30
- - Set `MALLOC_ARENA_MAX=2` directly in the runtime layer.
31
+ - Set `MALLOC_ARENA_MAX=2` directly in the runtime layer as the baseline memory guard.
32
+ - Optionally add fine-grained runtime environment knobs depending on workload memory constraints.
31
33
 
32
34
  ```dockerfile
33
35
  # ========================================================
@@ -61,11 +63,25 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
61
63
  WORKDIR /app
62
64
  COPY --from=builder /usr/src/app/target/release/app_binary /app/app_binary
63
65
 
64
- # CRITICAL MEMORY & RUNTIME TUNING:
65
- # 1. Restricts glibc multi-thread memory arenas (stops multi-thread RSS fragmentation)
66
+ # BASELINE MEMORY & RUNTIME GUARD:
67
+ # 1. Caps glibc multi-thread memory arenas (stops multi-thread RSS fragmentation)
66
68
  ENV MALLOC_ARENA_MAX=2
67
69
  ENV PORT=3000
68
70
 
71
+ # --------------------------------------------------------
72
+ # OPTIONAL SITUATIONAL KNOBS (NON-MANDATORY)
73
+ # Uncomment only after evaluating the trade-offs in Section 3:
74
+ # --------------------------------------------------------
75
+ # Clamp Tokio runtime to match container CPU quotas:
76
+ # ENV TOKIO_WORKER_THREADS=2
77
+ #
78
+ # Bypass arena for buffers >= 128KB (immediate munmap back to kernel OS):
79
+ # ENV MALLOC_MMAP_THRESHOLD_=131072
80
+ #
81
+ # Eagerly auto-trim free memory from the top of the heap:
82
+ # ENV MALLOC_TRIM_THRESHOLD_=65536
83
+ # ENV MALLOC_TOP_PAD_=65536
84
+
69
85
  EXPOSE 3000
70
86
 
71
87
  # Run binary
@@ -74,7 +90,55 @@ CMD ["/app/app_binary"]
74
90
 
75
91
  ---
76
92
 
77
- ## 3. Safe Rust Code Guard for `malloc_trim`
93
+ ## 3. Deep Dive: Optional Runtime Environment Knobs (Non-Mandatory)
94
+
95
+ While `MALLOC_ARENA_MAX=2` is the recommended universal baseline for multi-threaded glibc services, the following environment variables provide granular control over memory vs CPU behavior. **They are strictly non-mandatory**—applying them blindly without understanding their trade-offs can introduce unnecessary syscall overhead or constrain throughput.
96
+
97
+ ### 1. `TOKIO_WORKER_THREADS`
98
+ - **What it does**: Manually defines the number of worker threads in Tokio's multi-threaded work-stealing scheduler (`tokio::runtime::Runtime`).
99
+ - **When to consider**: Container environments (Kubernetes, Docker with CFS CPU limits like `cpus: "1"` or `resources.limits.cpu: "1"`). By default, `std::thread::available_parallelism()` may inspect the host node's physical CPU cores (e.g. 64 or 128 cores), spawning dozens of idle worker threads inside a fractional-core container.
100
+ - **Trade-offs**:
101
+ - **Pros (Memory & Latency)**: Prevents thread explosion, reduces OS thread stack allocation (~2MB per thread reserved virtual memory), and eliminates catastrophic context-switching contention under CFS CPU bandwidth limits.
102
+ - **Cons (Throughput Ceiling)**: If the container CPU limit is increased dynamically or runs compute-bound Rayon tasks, hardcoding this value caps parallelism unless updated.
103
+ - **Recommendation**: Set in Kubernetes deployment manifests or container environment to match allotted CPU cores (e.g. `2`). Keep unset for bare-metal or dedicated VM deployments where Tokio should scale across all available physical cores.
104
+
105
+ ---
106
+
107
+ ### 2. `MALLOC_MMAP_THRESHOLD_` *(Note the trailing underscore!)*
108
+ - **What it does**: Specifies the allocation size threshold (in bytes) above which glibc allocates memory directly via the `mmap()` syscall instead of sub-allocating from the heap arena (`brk`/`sbrk`). When memory allocated via `mmap()` is freed (`drop`), glibc immediately invokes `munmap()`, instantly returning the physical pages back to the Linux kernel.
109
+ - **The glibc Trap (Dynamic Thresholding)**: By default, glibc dynamically increases `mmap_threshold` up to **32MB** on 64-bit systems. When transient large allocations occur (e.g. Serde JSON parsing, scraper DOM trees, database bulk fetches), glibc stretches the threshold and retains large buffers inside arena heaps, leaving physical RSS elevated indefinitely.
110
+ - **The Syntax Trap**: Glibc environment variables for `mallopt` parameters **strictly require a trailing underscore** (`MALLOC_MMAP_THRESHOLD_`). Writing `MALLOC_MMAP_THRESHOLD=131072` (without underscore) is silently ignored by glibc.
111
+ - **Trade-offs**:
112
+ - **Pros (RSS Containment)**: Any temporary buffer $\ge$ the threshold (e.g. `131072` / 128KB or `65536` / 64KB) is guaranteed to be returned to the OS kernel immediately upon deallocation. This stops the notorious "sawtooth" memory creep in microservices handling large request payloads.
113
+ - **Cons (Throughput & CPU Syscalls)**: `mmap()` and `munmap()` are kernel syscalls requiring page table manipulation, kernel lock acquisition, and TLB invalidation. If a hot loop frequently allocates and frees buffers around this size threshold (e.g. 50,000 req/sec allocating 150KB buffers), CPU utilization will increase by 5%–15% and tail latency (p99) may degrade.
114
+ - **Recommendation**: **Non-mandatory**. Apply only when running within tight RSS budgets (<100MB) or when diagnosing services that retain memory after handling sporadic large payloads. For pure high-frequency, micro-allocation throughput services, keep the glibc default.
115
+
116
+ ---
117
+
118
+ ### 3. `MALLOC_TRIM_THRESHOLD_` & `MALLOC_TOP_PAD_` *(Trailing underscores required)*
119
+ - **What they do**:
120
+ - `MALLOC_TRIM_THRESHOLD_`: Controls the amount of contiguous free memory kept at the top of the heap before glibc automatically calls `sbrk()` negative to return pages to the OS. Default is typically 128KB or dynamically adjusted.
121
+ - `MALLOC_TOP_PAD_`: Determines how much padding is added when expanding the heap via `sbrk`, and how much cushion is preserved when trimming.
122
+ - **Trade-offs**:
123
+ - **Pros (Automated Trimming)**: Eagerly releases free memory from the heap top back to the operating system without having to implement periodic application-level `libc::malloc_trim(0)` loops in Rust code.
124
+ - **Cons (Syscall Churn)**: Frequent expansion and contraction of the heap top triggers repeated `brk`/`sbrk` syscalls, introducing mild CPU overhead under fluctuating workloads.
125
+ - **Recommendation**: **Non-mandatory**. Useful in batch or fluctuating microservices where RSS must contract quickly after load spikes. Recommended values if enabled: `MALLOC_TRIM_THRESHOLD_=65536` and `MALLOC_TOP_PAD_=65536`.
126
+
127
+ ---
128
+
129
+ ### 4. Trade-Off Comparison Matrix
130
+
131
+ | Environment Variable | Glibc / Tokio Default | Tuned Value | Primary Benefit (RSS / Stability) | Trade-Off / Risk (Throughput / CPU) | When to Use |
132
+ | :--- | :--- | :--- | :--- | :--- | :--- |
133
+ | `MALLOC_ARENA_MAX` | `8 × CPU_CORES` | `2` | Eliminates multi-thread arena memory multiplication. | Minimal; slight allocation lock contention under >32 concurrent OS threads. | **Universal Baseline** (Recommended for all containerized Rust services). |
134
+ | `TOKIO_WORKER_THREADS` | `available_parallelism()` | `2`–`4` | Prevents thread explosion inside CFS-limited containers. | Hard-caps Tokio parallelism if container CPU quota is increased. | Containers with CPU limits (`requests.cpu` / `limits.cpu`). |
135
+ | `MALLOC_MMAP_THRESHOLD_` | Dynamic (up to 32MB) | `131072` (128KB) | Immediate kernel page release (`munmap`) for large buffers. | Kernel syscall overhead (`mmap`/`munmap`) & TLB shootdowns under high allocation churn. | Strict RSS ceilings (<100MB) or memory-leaking payload endpoints. |
136
+ | `MALLOC_TRIM_THRESHOLD_` | Dynamic / 128KB | `65536` (64KB) | Auto-trims top of heap without manual `malloc_trim(0)`. | More frequent `sbrk` kernel calls during rapid allocation bursts. | Fluctuating load or batch services needing fast memory reclamation. |
137
+ | `MALLOC_TOP_PAD_` | 0 or 128KB | `65536` (64KB) | Tighter heap expansion padding. | Slightly more frequent heap expansion calls. | Paired with `MALLOC_TRIM_THRESHOLD_`. |
138
+
139
+ ---
140
+
141
+ ## 4. Safe Rust Code Guard for `malloc_trim`
78
142
 
79
143
  Because `malloc_trim` is GNU glibc specific, protect it in your Rust source code so that it only compiles when targeting GNU Linux. This ensures your code doesn't break if someone builds on macOS, Windows, or an Alpine musl target:
80
144
 
@@ -99,7 +163,7 @@ pub fn trim_memory() {
99
163
 
100
164
  ---
101
165
 
102
- ## 4. Why Glibc (`x86_64-unknown-linux-gnu`) is the Primary Backend Target
166
+ ## 5. Why Glibc (`x86_64-unknown-linux-gnu`) is the Primary Backend Target
103
167
 
104
168
  Both production reference projects strictly target **`x86_64-unknown-linux-gnu`** (Debian Bookworm) rather than Alpine/musl:
105
169