@sinkaroid/rust-shapeshift 1.0.8 → 1.0.10
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,19 +1,19 @@
|
|
|
1
1
|
# Rust Shapeshift
|
|
2
2
|
|
|
3
|
-
`@sinkaroid/rust-shapeshift` is
|
|
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
|
-
|
|
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 &
|
|
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 (
|
|
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
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.
|
|
19
19
|
|
|
@@ -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
|
|
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.
|
|
@@ -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.
|
|
30
|
-
"@sinkaroid/rust-shapeshift-darwin-x64": "1.0.
|
|
31
|
-
"@sinkaroid/rust-shapeshift-linux-arm64": "1.0.
|
|
32
|
-
"@sinkaroid/rust-shapeshift-linux-x64": "1.0.
|
|
33
|
-
"@sinkaroid/rust-shapeshift-win32-x64": "1.0.
|
|
29
|
+
"@sinkaroid/rust-shapeshift-darwin-arm64": "1.0.10",
|
|
30
|
+
"@sinkaroid/rust-shapeshift-darwin-x64": "1.0.10",
|
|
31
|
+
"@sinkaroid/rust-shapeshift-linux-arm64": "1.0.10",
|
|
32
|
+
"@sinkaroid/rust-shapeshift-linux-x64": "1.0.10",
|
|
33
|
+
"@sinkaroid/rust-shapeshift-win32-x64": "1.0.10"
|
|
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.
|
|
46
|
+
"version": "1.0.10"
|
|
47
47
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: rust-shapeshift
|
|
3
3
|
author: "@sinkaroid"
|
|
4
|
-
version: "1.0.
|
|
4
|
+
version: "1.0.10"
|
|
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:
|
|
@@ -115,6 +115,11 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
|
|
|
115
115
|
- `check_cancellation_safety`: Scans async code and `tokio::select!` branches for drop-hazard operations (`read_exact`, partial writes, lock starvation across cancellation).
|
|
116
116
|
- `optimize_serde_zero_copy`: Transforms owned serde payloads (`String`, `Vec<u8>`) into zero-copy borrowed structs (`&'a str`, `Cow<'a, str>`, `#[serde(borrow)]`) to eliminate deserialization heap churn.
|
|
117
117
|
- `generate_hardened_docker`: Generates hardened multi-stage Dockerfiles (<65MB) with Debian Bookworm C-ABI parity, symbol stripping, and `MALLOC_ARENA_MAX=2` memory guarding.
|
|
118
|
+
- `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.
|
|
119
|
+
- `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`).
|
|
120
|
+
- `generate_k8s_manifest`: Generates hardened Kubernetes Deployment YAML with Guaranteed QoS, Downward API `TOKIO_WORKER_THREADS`, `preStop: sleep 3` hook, and probe isolation.
|
|
121
|
+
- `detect_lock_await`: Scans async Rust source files for synchronous Mutex/RwLock guards held across `.await` points causing reactor thread starvation and deadlocks.
|
|
122
|
+
- `scaffold_benchmark_profile`: Scaffolds Criterion throughput benchmarks, DHAT heap allocation profiling, or live jemalloc runtime statistics harnesses.
|
|
118
123
|
|
|
119
124
|
### 1. Real-World Testing & Anti-Hallucination Standards
|
|
120
125
|
|
|
@@ -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.
|
|
4
|
-
3.
|
|
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
|
-
#
|
|
65
|
-
# 1.
|
|
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.
|
|
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
|
-
##
|
|
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
|
|