@sinkaroid/rust-shapeshift 1.0.12 → 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
@@ -6,9 +6,14 @@ This reference guide demonstrates the exact patterns used to achieve sub-50MB RS
6
6
 
7
7
  ---
8
8
 
9
- ## 1. Pattern A: Pre-Parse HTML Slicing
9
+ ## 1. Pattern A: Zero-DOM Extraction First, Then Guarded Pre-Parse HTML Slicing
10
10
 
11
- Never pass a full 5MB–10MB HTML page to `Html::parse_document` when target data is only in the first 20% of the page. Slicing the raw text string *before* parsing prevents the parser from generating thousands of unnecessary DOM nodes.
11
+ Before parsing HTML into a DOM tree, check whether the required 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 and yields the largest CPU and RSS win.
12
+
13
+ When DOM parsing is required, never pass a full multi-megabyte HTML page to `Html::parse_document` if heavy trailing bloat follows the main content. However, you **MUST** avoid two common pruning regressions:
14
+ 1. **Fragile Substring Matches**: Loose markers like `.find("id=\"related\"")` or `.find("class=\"pagination\"")` can match inside `<head>`, inline JS, comments, or fail on single-quoted attributes (`class='pagination'`). Anchor strictly to verified container/footer signatures from live markup.
15
+ 2. **Unguarded Double-Parse Fallback**: Always guard full-document fallback with `pruned.len() < html_str.len()`. Without that check, 404 pages, empty search results, and pages lacking markers will parse the entire HTML **twice**.
16
+ 3. **Redundant `/random` HTTP Round-Trips**: Never call `scrape_get` after already fetching `/random` HTML if the full gallery markup is already in hand—share a `parse_gallery_document` / `build_gallery_response` helper instead.
12
17
 
13
18
  ### Detail View vs Search / Related Pruning Strategies
14
19
 
@@ -21,12 +26,24 @@ static SEL_SEARCH_WRAP: LazyLock<Selector> =
21
26
  static SEL_SEARCH_TITLE: LazyLock<Selector> =
22
27
  LazyLock::new(|| Selector::parse("a[title]").unwrap());
23
28
 
29
+ fn extract_titles(doc: &Html) -> Vec<String> {
30
+ let mut titles = Vec::new();
31
+ for el in doc.select(&SEL_SEARCH_WRAP) {
32
+ if let Some(title_el) = el.select(&SEL_SEARCH_TITLE).next()
33
+ && let Some(title) = title_el.value().attr("title")
34
+ {
35
+ titles.push(title.to_string());
36
+ }
37
+ }
38
+ titles
39
+ }
40
+
24
41
  pub fn parse_search_optimized(body: &[u8], url: &str) -> Result<Vec<String>, String> {
25
42
  let html_str = String::from_utf8_lossy(body);
26
43
  let is_related = url.contains("view_video.php");
27
44
 
28
45
  // CRITICAL PRUNING BOUNDARIES:
29
- // For search listings: prune at pagination or footer.
46
+ // For search listings: prune at verified pagination or footer wrapper.
30
47
  // For related videos: do not prune at pagination if comment pagination precedes the related video block.
31
48
  let end_pos = if is_related {
32
49
  html_str
@@ -37,24 +54,25 @@ pub fn parse_search_optimized(body: &[u8], url: &str) -> Result<Vec<String>, Str
37
54
  html_str
38
55
  .find("class=\"page_numbers\"")
39
56
  .or_else(|| html_str.find("class=\"pagination\""))
57
+ .or_else(|| html_str.find("class='pagination'"))
40
58
  .or_else(|| html_str.find("<footer"))
41
59
  .or_else(|| html_str.find("class=\"footer-wrap\""))
42
60
  .unwrap_or(html_str.len())
43
61
  };
44
62
 
45
- // Parse ONLY the sliced substring:
46
- let document = Html::parse_document(&html_str[..end_pos]);
47
-
48
- let mut titles = Vec::new();
49
- for el in document.select(&SEL_SEARCH_WRAP) {
50
- if let Some(title_el) = el.select(&SEL_SEARCH_TITLE).next() {
51
- if let Some(title) = title_el.value().attr("title") {
52
- titles.push(title.to_string());
53
- }
54
- }
63
+ // Fast path: parse ONLY the sliced substring
64
+ let pruned = &html_str[..end_pos];
65
+ let mut titles = {
66
+ let document = Html::parse_document(pruned);
67
+ extract_titles(&document)
68
+ }; // `document` drops immediately here, freeing all DOM tree nodes from RAM.
69
+
70
+ // Adaptive fallback ONLY when slicing actually truncated the document
71
+ if titles.is_empty() && pruned.len() < html_str.len() {
72
+ let full_doc = Html::parse_document(&html_str);
73
+ titles = extract_titles(&full_doc);
55
74
  }
56
75
 
57
- // `document` drops immediately here, freeing all DOM tree nodes from RAM.
58
76
  Ok(titles)
59
77
  }
60
78
  ```
@@ -179,3 +197,12 @@ mod tests {
179
197
  }
180
198
  }
181
199
  ```
200
+
201
+ ---
202
+
203
+ ## Trade-Offs: Pros, Cons & When to Skip
204
+
205
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
206
+ | :--- | :--- | :--- | :--- |
207
+ | **Zero-DOM Slice Extraction (`__NEXT_DATA__`, `g_th`, `gdata`)** | Skips `html5ever` completely—largest CPU and RAM win | Breaks if upstream changes JS variable/script serialization format | Always check & prefer first when structured JSON/script exists; pair with DOM fallback if needed |
208
+ | **Guarded Pre-Parse HTML Slicing (`&html[..end_pos]`)** | Cuts 70%–90% of DOM AST allocations when trailing bloat is large | Loose markers match `<head>`/JS early; **unguarded fallback double-parses 404s & empty searches** | Use when heavy trailing bloat exists; **always** guard fallback with `pruned.len() < html.len()` and never call `scrape_get` twice on `/random` |
@@ -134,3 +134,11 @@ const _: () = assert!(
134
134
  2. If the size difference between the smallest and largest variant exceeds **128 bytes**, box the largest variant.
135
135
  3. For recursive data structures (trees, ASTs, JSON representations), always box child enum nodes.
136
136
  4. Enforce `const _: () = assert!(size_of::<MyEnum>() <= BUDGET);` for core protocol types.
137
+
138
+ ---
139
+
140
+ ## Trade-Offs: Pros, Cons & When to Skip
141
+
142
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
143
+ | :--- | :--- | :--- | :--- |
144
+ | **Boxing Oversized Enum Variants (`Box<T>`)** | Prevents `Future` / stack-frame multiplication across all async tasks | Adds 1 heap allocation when the rare large variant is constructed | Box rare variants >128B (especially inside async state machines); skip if the large variant is the hot path |
@@ -183,10 +183,29 @@ pub fn configure_graphql_routes(schema: AppSchema) -> Router {
183
183
 
184
184
  ---
185
185
 
186
- ## 5. GraphQL Security & Memory Checklist
186
+ ## 5. REST ↔ GraphQL Parity & Protocol Support
187
+
188
+ When exposing both REST and GraphQL over the same domain services, enforce strict parity so GraphQL resolvers never drift into broken URLs or missing fields:
189
+ 1. **Shared Service Helpers & Validation**: GraphQL resolvers and REST handlers MUST call the exact same URL builders, ID validators (`is_valid_id`), and `fetch_*` service functions—never re-implement upstream URL construction or skip validation inside GraphQL resolvers.
190
+ 2. **Exact Schema Parity**: Keep GraphQL output structs (`#[derive(SimpleObject, Deserialize)]`) strictly aligned with the fields serialized by REST parity structs; test deserialization from real scraper outputs in `#[cfg(test)]`.
191
+ 3. **Full HTTP Transport Support**: Support `GET /graphql?query=...` (executing queries when `?query=` is provided and serving GraphiQL HTML only when empty) and `POST /graphql` for both `application/json` and `application/graphql`.
192
+
193
+ ---
194
+
195
+ ## 6. GraphQL Security & Memory Checklist
187
196
 
188
197
  1. Is `limit_depth` configured (recommended: 5–7 levels maximum)?
189
198
  2. Is `limit_complexity` applied to constrain expensive multiply-nested lists?
190
199
  3. Is schema introspection disabled in production via `.disable_introspection()`?
191
200
  4. Are recursive relational lookups batched via `DataLoader` to eliminate N+1 allocations?
192
201
  5. Are all query list limits (`limit: Option<usize>`) clamped to a strict maximum (e.g., `.min(50)`)?
202
+ 6. Do REST and GraphQL share identical URL builders, validation helpers, and output field parity?
203
+
204
+ ---
205
+
206
+ ## Trade-Offs: Pros, Cons & When to Skip
207
+
208
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
209
+ | :--- | :--- | :--- | :--- |
210
+ | **`limit_depth` + `limit_complexity` + `DataLoader`** | Blocks nested AST memory bombs and eliminates N+1 upstream calls | Overly tight depth/complexity caps reject legitimate deeply-nested client queries | Always enforce on public GraphQL endpoints; tune limits against real client query shapes |
211
+ | **Shared REST ↔ GraphQL Helpers & `GET /graphql`** | Prevents URL/validation/schema divergence bugs between REST and GraphQL | Requires keeping parity structs synchronized when scrapers evolve | Always share service fetchers, validators (`is_valid_id`), and test GraphQL deserialization against parity structs |
@@ -115,3 +115,12 @@ pub async fn create_optimized_channel(dst: &'static str) -> Result<Channel, toni
115
115
  - [ ] Bounded streaming MPSC channels to low numbers (e.g. 16–64) for backpressure propagation.
116
116
  - [ ] Protobuf messages use `bytes::Bytes` rather than `Vec<u8>` for binary data payloads.
117
117
  - [ ] Tonic client channels are created as shared singletons inside `Arc<AppState>`.
118
+
119
+ ---
120
+
121
+ ## Trade-Offs: Pros, Cons & When to Skip
122
+
123
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
124
+ | :--- | :--- | :--- | :--- |
125
+ | **Bounded HTTP/2 Flow-Control Windows (64KB/512KB)** | Prevents multi-GB per-connection buffer bloat across many streams | Caps max single-stream throughput over high-BDP (high-latency, high-bandwidth) WAN links | Use on multi-tenant / tight-RAM gRPC servers; increase windows for high-BDP single-stream bulk transfers |
126
+ | **`bytes::Bytes` Zero-Copy Protobuf Payloads** | Eliminates `Vec<u8>` buffer copies across streaming channels | Refcounted slice keeps backing allocation alive until last `Bytes` drops | Use for large binary payloads; skip if payloads are tiny (<64B) |
@@ -253,3 +253,12 @@ impl<const CAP: usize> EventRecorder<CAP> {
253
253
  ```
254
254
 
255
255
  Formatting and serialization to JSON or text logs are performed solely by an asynchronous consumer reading from the consumer end (`rtrb::Consumer`), keeping the hot path entirely allocation-free.
256
+
257
+ ---
258
+
259
+ ## Trade-Offs: Pros, Cons & When to Skip
260
+
261
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
262
+ | :--- | :--- | :--- | :--- |
263
+ | **Offloaded Destructors + Ring-Buffer Logging** | Eliminates `p99.99` tail-latency spikes from massive `HashMap`/`Vec` drops on hot paths | Background cleaner thread lags under sustained drop storms if queue isn't bounded | Use for strict sub-millisecond WCET/tail-latency systems; skip for ordinary CRUD/scraper services |
264
+ | **Bounded CAS Retries** | Guarantees deterministic worst-case loop latency under contention | Needs fallback path when retry bound hits | Use in lock-free hot paths with strict SLA; skip where standard mutex/channel suffices |
@@ -87,27 +87,40 @@ static RE_IFELSE: LazyLock<Regex> =
87
87
 
88
88
  ---
89
89
 
90
- ## 5. Zero-Cost Query Validation (`validator` Derive)
90
+ ## 5. Zero-Dependency Inline Query & ID Validation (Avoiding `validator` Bloat)
91
91
 
92
- Instead of runtime validation libraries (like Zod) that build heap schemas on each request, use `validator::Validate` derive macros.
93
-
94
- Validation executes as inline compile-time generated boolean checks with zero heap allocation when valid:
92
+ Avoid pulling in `validator` + `validator_derive` just for simple query parameter checks—it adds macro compile overhead and triggers `proc-macro-error2` future-incompatibility warnings in modern Rust toolchains. Instead, write small, zero-allocation inline validators that match real upstream ID formats without breaking valid slugs (for example, allowing single `.` in IDs like `video.abc123/slug` while rejecting path traversal `..`, `./`, `/.`, leading/trailing `.`, and query/fragment injection characters):
95
93
 
96
94
  ```rust
97
- use axum::extract::Query;
98
- use validator::Validate;
95
+ pub fn is_valid_id(id: &str) -> bool {
96
+ let clean = id.trim();
97
+ if clean.is_empty() || clean.len() > 256 {
98
+ return false;
99
+ }
100
+ if clean.starts_with('.')
101
+ || clean.ends_with('.')
102
+ || clean.contains("..")
103
+ || clean.contains("./")
104
+ || clean.contains("/.")
105
+ || clean.contains('&')
106
+ || clean.contains('?')
107
+ || clean.contains('#')
108
+ || clean.contains('\\')
109
+ || clean.contains(' ')
110
+ {
111
+ return false;
112
+ }
113
+ clean
114
+ .chars()
115
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '/' | '.'))
116
+ }
117
+ ```
99
118
 
100
- #[derive(serde::Deserialize, Validate)]
101
- pub struct SearchParams {
102
- #[validate(length(min = 1, max = 100, message = "Query cannot be empty"))]
103
- pub q: String,
119
+ ---
104
120
 
105
- #[validate(range(min = 1, max = 500, message = "Page out of bounds"))]
106
- pub page: Option<u32>,
107
- }
121
+ ## Trade-Offs: Pros, Cons & When to Skip
108
122
 
109
- pub async fn search_handler(Query(params): Query<SearchParams>) -> Result<(), AppError> {
110
- params.validate().map_err(|e| AppError::Validation(e.to_string()))?;
111
- Ok(())
112
- }
113
- ```
123
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
124
+ | :--- | :--- | :--- | :--- |
125
+ | **Single-Pass Helpers & `LazyLock<Regex>`** | Removes dynamic regex compilation and date-crate bloat from hot loops | Hand-rolled string scans need thorough edge-case unit tests (UTF-8, whitespace) | Use everywhere in parsers & formatters; keep `Regex` only when pattern logic truly needs it |
126
+ | **Inline Zero-Dep Validators (vs `validator` Crate)** | Zero macro bloat, avoids `proc-macro-error2` future-incompat warnings | Must carefully match real provider ID formats (e.g. single `.` in `video.id/slug`) | Always prefer inline helpers for query/ID validation; audit both REST and GraphQL callers |
@@ -133,3 +133,12 @@ perf stat -e L1-icache-load-misses,L1-icache-loads,instructions,cycles ./target/
133
133
  ### Target Production Ratios
134
134
  * **L1I Miss Rate**: $\frac{\text{L1-icache-load-misses}}{\text{L1-icache-loads}} < \mathbf{0.5\%}$ (Ideal: $<0.1\%$).
135
135
  * **Instructions Per Cycle (IPC)**: $\frac{\text{instructions}}{\text{cycles}} > \mathbf{2.5}$ on modern x86_64 / Apple Silicon.
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
+ | **`#[cold]` / `#[inline(never)]` Outlining** | Keeps 32KB L1 I-cache hot for happy paths; reduces monomorphization bloat | Extra `call` instruction on error paths; premature `#[inline(never)]` hurts tiny helpers | Use on rare error/formatting branches inside hot loops; verify with `perf stat` L1I misses |
144
+ | **`dyn Trait` vs Heavy Monomorphization** | Shrinks binary code size when 10+ concrete implementations exist | Adds vtable pointer indirection and blocks cross-call inlining | Use for cold/coarse plugin boundaries; keep generics/`enum_dispatch` on tight per-item loops |
@@ -144,3 +144,11 @@ impl RegisteredMemoryPool {
144
144
  1. **Kernel Version Guard**: Always assert kernel version $\ge$ 5.10 at runtime; older kernels contained security bugs in SQPOLL privilege escalation.
145
145
  2. **Buffer Pinning Discipline**: Since the kernel accesses memory asynchronously via pointers in the SQ, buffers submitted to `io_uring` must **never be moved, resized, or dropped** until the matching Completion Queue Entry (CQE) is reaped. Use pinned types or pool-allocated owned buffers.
146
146
  3. **Graceful SQPOLL Fallback**: If the host environment forbids unprivileged `CAP_SYS_ADMIN` or `CAP_SYS_NICE`, catch the initialization error and fall back to normal `io_uring_enter()` submission or standard `epoll`.
147
+
148
+ ---
149
+
150
+ ## Trade-Offs: Pros, Cons & When to Skip
151
+
152
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
153
+ | :--- | :--- | :--- | :--- |
154
+ | **`io_uring` + `SQPOLL` + Registered Buffers** | Eliminates syscall/context-switch walls at extreme IOPS/PPS | Requires Linux >= 5.10, often blocked by default Docker/K8s seccomp profiles, requires pinned buffer lifetimes, `SQPOLL` burns a kernel CPU core | Use on dedicated Linux bare-metal/VM I/O engines; **skip** in standard Docker/K8s or portable cross-platform apps (use standard Tokio `epoll`) |
@@ -143,3 +143,12 @@ static GLOBAL: MiMalloc = MiMalloc;
143
143
  - [ ] Injected `MALLOC_CONF="background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:1000"` in Docker container.
144
144
  - [ ] Added live diagnostic heap dump endpoint protected by administrative authorization.
145
145
  - [ ] Added DHAT heap assertion tests on latency-critical hot paths.
146
+
147
+ ---
148
+
149
+ ## Trade-Offs: Pros, Cons & When to Skip
150
+
151
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
152
+ | :--- | :--- | :--- | :--- |
153
+ | **`tikv-jemallocator` (`dirty_decay_ms:1000`)** | Better multi-core scaling than `MALLOC_ARENA_MAX=2` while automatically purging unused pages asynchronously | Adds C build dependency, slightly larger binary, complicates `musl`/Windows cross-builds | Best upgrade when high-traffic glibc services leak RSS via arena fragmentation; skip on minimalist Koburi daemons or simple low-QPS apps |
154
+ | **Live `jemalloc-ctl` Profiling + DHAT** | Pinpoints exact allocation call sites in production/CI | Small runtime profiling overhead when `prof_active:true` | Keep `prof_active:false` at rest and toggle on-demand behind admin auth |
@@ -14,39 +14,36 @@ By default, `tokio::runtime::Builder::new_multi_thread()` or `#[tokio::main]` ca
14
14
  2. Catastrophic context-switching thrashing.
15
15
  3. Severe CFS bandwidth throttling, driving latency from milliseconds into seconds.
16
16
 
17
- ### The Solution: Quota-Aware Runtime Sizing
18
- Explicitly cap Tokio worker threads based on container CPU limits or environment variables:
17
+ ### The Solution: Quota-Aware Runtime Sizing (Opt-In Env Override, Native Default)
18
+ Allow `TOKIO_WORKER_THREADS` to be injected via Kubernetes manifest `env:` when a pod has a strict fractional CPU limit (`limits.cpu: "1"` or `"2"`). **Never hardcode a `.unwrap_or(2)` or `.clamp(1, 4)` cap in Rust code** when `TOKIO_WORKER_THREADS` is unset—preserve `#[tokio::main]` / `available_parallelism()` native defaults so multi-core hosts aren't throttled to 2 threads accidentally:
19
19
 
20
20
  ```rust
21
21
  use std::env;
22
22
 
23
- fn build_optimized_runtime() -> tokio::runtime::Runtime {
24
- // Read from K8s downward API env (e.g., CONTAINER_CPU_LIMIT=2) or fallback
25
- let worker_threads = env::var("TOKIO_WORKER_THREADS")
23
+ fn build_optimized_runtime() -> std::io::Result<tokio::runtime::Runtime> {
24
+ let mut builder = tokio::runtime::Builder::new_multi_thread();
25
+ builder.enable_all();
26
+
27
+ // Only override worker threads when explicitly configured via container/K8s env
28
+ if let Some(threads) = env::var("TOKIO_WORKER_THREADS")
26
29
  .ok()
27
30
  .and_then(|v| v.parse::<usize>().ok())
28
- .unwrap_or_else(|| {
29
- // Alternatively clamp available_parallelism to realistic container quota
30
- std::thread::available_parallelism()
31
- .map(|p| p.get().clamp(1, 4)) // Never spawn unbounded threads on host
32
- .unwrap_or(2)
33
- });
34
-
35
- tokio::runtime::Builder::new_multi_thread()
36
- .worker_threads(worker_threads)
37
- .max_blocking_threads(16) // Prevent unbounded blocking pool
38
- .enable_all()
39
- .build()
40
- .expect("Failed to initialize Tokio runtime")
31
+ .filter(|&n| n > 0)
32
+ {
33
+ builder.worker_threads(threads);
34
+ }
35
+
36
+ builder.build()
41
37
  }
42
38
 
43
- fn main() {
44
- let rt = build_optimized_runtime();
45
- rt.block_on(async_main());
39
+ fn main() -> Result<(), Box<dyn std::error::Error>> {
40
+ let rt = build_optimized_runtime()?;
41
+ rt.block_on(async_main())
46
42
  }
47
43
 
48
- async fn async_main() {
44
+ async fn async_main() -> Result<(), Box<dyn std::error::Error>> {
49
45
  // Application logic here
46
+ Ok(())
50
47
  }
51
48
  ```
52
49
 
@@ -76,7 +73,7 @@ When a container exceeds `resources.limits.memory`, the Linux kernel cgroups OOM
76
73
 
77
74
  ### Best Practice: Guaranteed QoS & Threshold Trimming
78
75
  1. **Match Requests and Limits (Guaranteed QoS)**: In memory-critical services, set `requests.memory == limits.memory`. This prevents the K8s node from overcommitting memory and evicting your pod when other noisy neighbor pods spike.
79
- 2. **Internal High-Watermark Trim**: If running with `glibc`, trigger `libc::malloc_trim(0)` when memory reaches 80% of container limits. If running with `tikv-jemallocator`, ensure `dirty_decay_ms:1000,muzzy_decay_ms:1000` is active.
76
+ 2. **Internal High-Watermark Trim (Opt-In + `spawn_blocking` Only)**: If running with `glibc` under tight memory caps, gate `libc::malloc_trim(0)` behind an opt-in flag (`MALLOC_TRIM=true`) and offload it to `tokio::task::spawn_blocking` (never per-request). If running with `tikv-jemallocator`, configure `dirty_decay_ms:1000,muzzy_decay_ms:1000`.
80
77
 
81
78
  ```yaml
82
79
  resources:
@@ -115,16 +112,22 @@ use tokio::signal::unix::{signal, SignalKind};
115
112
 
116
113
  pub async fn shutdown_signal() {
117
114
  let ctrl_c = async {
118
- tokio::signal::ctrl_c()
119
- .await
120
- .expect("Failed to listen for Ctrl+C");
115
+ if let Err(err) = tokio::signal::ctrl_c().await {
116
+ tracing::warn!("Failed to listen for Ctrl+C: {err}");
117
+ }
121
118
  };
122
119
 
123
120
  #[cfg(unix)]
124
121
  let terminate = async {
125
- let mut sigterm = signal(SignalKind::terminate())
126
- .expect("Failed to listen for SIGTERM");
127
- sigterm.recv().await;
122
+ match signal(SignalKind::terminate()) {
123
+ Ok(mut sigterm) => {
124
+ sigterm.recv().await;
125
+ }
126
+ Err(err) => {
127
+ tracing::warn!("Failed to listen for SIGTERM: {err}");
128
+ std::future::pending::<()>().await;
129
+ }
130
+ }
128
131
  };
129
132
 
130
133
  #[cfg(not(unix))]
@@ -205,3 +208,12 @@ securityContext:
205
208
  - [ ] Liveness probe isolated from database/cache dependencies.
206
209
  - [ ] Readiness probe fails gracefully (`503 Service Unavailable`) without triggering pod restarts.
207
210
  - [ ] Binary runs as non-root with `readOnlyRootFilesystem: true`.
211
+
212
+ ---
213
+
214
+ ## Trade-Offs: Pros, Cons & When to Skip
215
+
216
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
217
+ | :--- | :--- | :--- | :--- |
218
+ | **K8s `TOKIO_WORKER_THREADS` Matching CPU Limit** | Prevents 64/128-thread explosion inside fractional-CPU CFS pods | Hard-caps concurrency if pod CPU limits are raised without updating env; **never** hardcode fallback `.unwrap_or(2)` in Rust code | Set in K8s YAML only when pod has strict CPU limits; leave unset on bare-metal/dedicated VMs |
219
+ | **Guaranteed QoS + `preStop: sleep 3` + Isolated Probes** | Prevents noisy-neighbor OOM eviction, 502 deploy races, and DB-outage crash loops | Guaranteed QoS reserves full memory upfront; `sleep 3` adds 3s per rolling pod stop | Standard best practice for production K8s HTTP services; skip for standalone Docker/CLI tools |
@@ -183,3 +183,11 @@ impl TrueDisruptorRing {
183
183
  - **Exponential Backoff** (`std::hint::spin_loop` ➔ `thread::yield_now` ➔ async sleep).
184
184
  3. **Batch Draining**:
185
185
  - Consumers should drain items in batches (e.g. 64–256 items at a time) to amortize atomic synchronization overhead and optimize CPU L1 cache throughput.
186
+
187
+ ---
188
+
189
+ ## Trade-Offs: Pros, Cons & When to Skip
190
+
191
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
192
+ | :--- | :--- | :--- | :--- |
193
+ | **Bounded `rtrb` (SPSC) / `ArrayQueue` (MPMC)** | Zero heap allocation per message and predictable cache-line latency | Fixed capacity drops/rejects under backpressure; busy-spin consumes 100% core | Use for high-frequency telemetry/audio/order pipelines; use `tokio::sync::mpsc` for normal async I/O |
@@ -1,8 +1,8 @@
1
1
  # Linux Memory Allocator Tuning & Low-Level Libc ABI Hardening
2
- 1. How to tame glibc memory fragmentation (`MALLOC_ARENA_MAX=2` and `malloc_trim`).
3
- 2. Optional runtime environment tuning (`MALLOC_MMAP_THRESHOLD_`, `MALLOC_TRIM_THRESHOLD_`, `MALLOC_TOP_PAD_`, `TOKIO_WORKER_THREADS`) & detailed trade-offs.
2
+ 1. Why native glibc and Tokio defaults must be preserved out-of-the-box (opt-in deploy-time tuning only).
3
+ 2. Opt-in runtime environment tuning (`MALLOC_ARENA_MAX`, `MALLOC_MMAP_THRESHOLD_`, `MALLOC_TRIM_THRESHOLD_`, `MALLOC_TOP_PAD_`, `TOKIO_WORKER_THREADS`, `MALLOC_TRIM`) & throughput vs RSS trade-offs.
4
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
+ 4. Why `malloc_trim` fails on Alpine (musl vs glibc target environments) and why per-request/reactor-thread `malloc_trim` causes regressions.
6
6
 
7
7
  ---
8
8
 
@@ -23,13 +23,34 @@ When a Rust binary links to C libraries (such as `libc`, `libssl`, `libcrypto`),
23
23
 
24
24
  ---
25
25
 
26
- ## 2. Hardened Production Dockerfile (Bulletproof Glibc ABI)
26
+ ## 2. Multi-Dimensional Decision Gate: Assess Context & Ask First!
27
27
 
28
- To guarantee 100% binary-ABI compatibility and zero `libc.so` errors:
28
+ Before recommending or setting any allocator/Tokio environment variables, evaluate **all relevant dimensions** with the user (do not rely on a single "busy vs idle" rule):
29
+
30
+ 1. **Repository Scope & Blast Radius (Public OSS vs Private Internal)**:
31
+ - For **public OSS repos, published Docker images (`ghcr.io`), or crates (`crates.io`)**: **NEVER** hardcode `MALLOC_ARENA_MAX=2`, `MALLOC_MMAP_THRESHOLD_`, `MALLOC_TRIM_THRESHOLD_`, `MALLOC_TOP_PAD_`, `TOKIO_WORKER_THREADS=2`, or default `malloc_trim` into `Dockerfile` or `main.rs`. Downstream users run on unpredictable hardware; public artifacts must preserve safe native defaults and expose tuning strictly as documented opt-in (`docker run -e`).
32
+ 2. **Hardware, Cgroup & Co-Tenancy**:
33
+ - Dedicated 8 vCPU / 16 GB server (even if low traffic) → keep native Tokio & glibc defaults; clamping `TOKIO_WORKER_THREADS=2` or forcing `mmap` syscalls wastes hardware capacity.
34
+ - Tight container/VPS (e.g. `1–2 vCPU`, `256–512 MB` RAM, or sharing host RAM with Redis/Postgres) → inspect whether CFS CPU quota or memory ceiling warrants opt-in tuning.
35
+ 3. **SLA Priority & Traffic Shape**:
36
+ - Latency-sensitive / high-QPS (`p99` priority) → avoid low `MALLOC_MMAP_THRESHOLD_` (`mmap`/`munmap` + TLB churn) and avoid per-request `malloc_trim`; consider `tikv-jemallocator` if RSS fragments.
37
+ - Private / low-QPS / tight-RSS container → opt-in deploy-time `MALLOC_ARENA_MAX=2`, `MALLOC_MMAP_THRESHOLD_=131072`, `MALLOC_TRIM_THRESHOLD_=131072`, `MALLOC_TOP_PAD_=65536` (and optionally `TOKIO_WORKER_THREADS` matching vCPU + `MALLOC_TRIM=true` via `spawn_blocking`).
38
+
39
+ | Scenario | Recommended Action | Why |
40
+ | :--- | :--- | :--- |
41
+ | **Public OSS / Published Image / Multi-Core Server / Latency-First** | Keep `TOKIO_WORKER_THREADS`, `MALLOC_*`, and `MALLOC_TRIM` **unset** by default. Document as opt-in only. | Protects downstream users from silent throughput/latency regressions; avoids arena lock contention and kernel syscall overhead. |
42
+ | **Private / Tight-RSS Container (`≤512 MB` or shared host) + Low/Moderate QPS** | Suggest opt-in deploy-time env (`docker run -e` / K8s):<br>`MALLOC_ARENA_MAX=2`<br>`MALLOC_MMAP_THRESHOLD_=131072`<br>`MALLOC_TRIM_THRESHOLD_=131072`<br>`MALLOC_TOP_PAD_=65536`<br>*(Optional: `TOKIO_WORKER_THREADS` = vCPU, `MALLOC_TRIM=true` via `spawn_blocking`)* | Immediate `munmap` and bounded arenas prevent OOMKilled on small RAM budgets while low QPS keeps syscall overhead negligible. |
43
+ | **High-Concurrency Service with Confirmed Glibc Arena Bloat** | Evaluate `tikv-jemallocator` (`dirty_decay_ms:1000,background_thread:true`) rather than throttling glibc with `MALLOC_MMAP_THRESHOLD_`. | Reclaims memory asynchronously without forcing `mmap` syscalls on every >128KB allocation. |
44
+
45
+ ---
46
+
47
+ ## 3. Hardened Production Dockerfile (Bulletproof Glibc ABI)
48
+
49
+ To guarantee 100% binary-ABI compatibility and zero `libc.so` errors without imposing throughput regressions by default:
29
50
  - Pin the **exact same Debian codename** for both Builder and Runtime (e.g. `bookworm` and `bookworm-slim`).
30
51
  - Install `ca-certificates` and `libssl3` 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.
52
+ - Keep `Dockerfile` free of hardcoded `TOKIO_WORKER_THREADS` and `MALLOC_*` overrides so Tokio (`available_parallelism()`) and glibc keep native throughput defaults when deployed normally.
53
+ - Pass memory-containment variables at deploy time (`docker run -e ...` or K8s manifest) only when running under strict RSS budgets.
33
54
 
34
55
  ```dockerfile
35
56
  # ========================================================
@@ -63,24 +84,19 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
63
84
  WORKDIR /app
64
85
  COPY --from=builder /usr/src/app/target/release/app_binary /app/app_binary
65
86
 
66
- # BASELINE MEMORY & RUNTIME GUARD:
67
- # 1. Caps glibc multi-thread memory arenas (stops multi-thread RSS fragmentation)
68
- ENV MALLOC_ARENA_MAX=2
87
+ # Keep native runtime/allocator defaults in Dockerfile; tune via `docker run -e` when needed:
69
88
  ENV PORT=3000
70
89
 
71
90
  # --------------------------------------------------------
72
- # OPTIONAL SITUATIONAL KNOBS (NON-MANDATORY)
73
- # Uncomment only after evaluating the trade-offs in Section 3:
91
+ # OPTIONAL DEPLOY-TIME TUNING (Pass via `docker run -e` ONLY for private/low-traffic/tight-RSS workloads!)
92
+ # Do NOT enable on heavy-traffic public APIs unless profiling confirms RSS bloat.
74
93
  # --------------------------------------------------------
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
94
+ # -e MALLOC_ARENA_MAX=2
95
+ # -e MALLOC_MMAP_THRESHOLD_=131072
96
+ # -e MALLOC_TRIM_THRESHOLD_=131072
97
+ # -e MALLOC_TOP_PAD_=65536
98
+ # -e TOKIO_WORKER_THREADS=2
99
+ # -e MALLOC_TRIM=true (Opt-in background spawn_blocking malloc_trim(0))
84
100
 
85
101
  EXPOSE 3000
86
102
 
@@ -90,9 +106,9 @@ CMD ["/app/app_binary"]
90
106
 
91
107
  ---
92
108
 
93
- ## 3. Deep Dive: Optional Runtime Environment Knobs (Non-Mandatory)
109
+ ## 4. Deep Dive: Opt-In Deploy-Time Environment Knobs (Conditional by Traffic)
94
110
 
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.
111
+ Hardcoding `TOKIO_WORKER_THREADS=2` or aggressive `MALLOC_*` variables in `Dockerfile` or `main.rs` degrades multi-core throughput, causes allocator lock contention, and forces repeated `mmap`/`munmap` syscalls and page faults on HTML/JSON buffers. **Keep all of these unset by default** so native Tokio (`available_parallelism()`) and glibc behavior apply on busy APIs, and **only suggest them** when the user confirms a private, low-traffic, or strict-RSS deployment.
96
112
 
97
113
  ### 1. `TOKIO_WORKER_THREADS`
98
114
  - **What it does**: Manually defines the number of worker threads in Tokio's multi-threaded work-stealing scheduler (`tokio::runtime::Runtime`).
@@ -111,7 +127,7 @@ While `MALLOC_ARENA_MAX=2` is the recommended universal baseline for multi-threa
111
127
  - **Trade-offs**:
112
128
  - **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
129
  - **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.
130
+ - **Recommendation**: **Opt-In for Low-Traffic / Tight-RSS Only**. Suggest `131072` (or `65536`) when the user confirms a private/low-consume workload with tight RAM limits. For high-traffic, latency-sensitive services, **do not set this**—keep the glibc default.
115
131
 
116
132
  ---
117
133
 
@@ -122,7 +138,7 @@ While `MALLOC_ARENA_MAX=2` is the recommended universal baseline for multi-threa
122
138
  - **Trade-offs**:
123
139
  - **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
140
  - **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`.
141
+ - **Recommendation**: **Opt-In for Low-Traffic / Tight-RSS Only**. Recommended values when the user opts into low-memory tuning: `MALLOC_TRIM_THRESHOLD_=131072` and `MALLOC_TOP_PAD_=65536`. For busy APIs, keep unset.
126
142
 
127
143
  ---
128
144
 
@@ -130,15 +146,18 @@ While `MALLOC_ARENA_MAX=2` is the recommended universal baseline for multi-threa
130
146
 
131
147
  | Environment Variable | Glibc / Tokio Default | Tuned Value | Primary Benefit (RSS / Stability) | Trade-Off / Risk (Throughput / CPU) | When to Use |
132
148
  | :--- | :--- | :--- | :--- | :--- | :--- |
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). |
149
+ | `MALLOC_ARENA_MAX` | `8 × CPU_CORES` | `2` | Eliminates multi-thread arena memory multiplication. | Lock contention across threads during concurrent small allocations (`html5ever`/`serde_json`). | **Opt-In** via `docker run -e` for RSS-constrained multi-threaded services. |
134
150
  | `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
151
  | `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. |
152
+ | `MALLOC_TRIM_THRESHOLD_` | Dynamic / 128KB | `131072` (128KB) | Auto-trims top of heap without manual `malloc_trim(0)`. | More frequent `sbrk` kernel calls during rapid allocation bursts. | Private / low-traffic services needing fast memory reclamation. |
137
153
  | `MALLOC_TOP_PAD_` | 0 or 128KB | `65536` (64KB) | Tighter heap expansion padding. | Slightly more frequent heap expansion calls. | Paired with `MALLOC_TRIM_THRESHOLD_`. |
138
154
 
139
155
  ---
140
156
 
141
- ## 4. Safe Rust Code Guard for `malloc_trim`
157
+ ## 5. Safe Opt-In & Offloaded Rust Code for `malloc_trim`
158
+
159
+ > [!CAUTION]
160
+ > **Never call `libc::malloc_trim(0)` synchronously on Tokio async worker threads or in per-request HTTP middleware!** Calling `malloc_trim(0)` acquires arena locks across the heap and forces kernel `madvise` page decommitment + re-faults on subsequent requests, severely degrading p99 latency under traffic. Always gate it behind an opt-in config flag (`MALLOC_TRIM=true`, default `false`) and execute it inside `tokio::task::spawn_blocking`.
142
161
 
143
162
  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:
144
163
 
@@ -148,10 +167,11 @@ Because `malloc_trim` is GNU glibc specific, protect it in your Rust source code
148
167
  libc = "0.2"
149
168
  ```
150
169
 
151
- ### `src/util.rs`
170
+ ### `src/util.rs` & Background Task
152
171
  ```rust
153
172
  /// Release unused glibc allocator heap pages back to the Linux kernel.
154
173
  /// Guarded with `target_env = "gnu"` so it compiles safely and won't panic on musl/macOS/Windows.
174
+ /// IMPORTANT: Only invoke inside `tokio::task::spawn_blocking` when opt-in `MALLOC_TRIM=true` is enabled.
155
175
  #[inline]
156
176
  pub fn trim_memory() {
157
177
  #[cfg(all(target_os = "linux", target_env = "gnu"))]
@@ -159,11 +179,16 @@ pub fn trim_memory() {
159
179
  libc::malloc_trim(0);
160
180
  }
161
181
  }
182
+
183
+ // Inside background telemetry loop (ONLY when config.malloc_trim == true):
184
+ // if malloc_trim_enabled {
185
+ // let _ = tokio::task::spawn_blocking(crate::util::trim_memory).await;
186
+ // }
162
187
  ```
163
188
 
164
189
  ---
165
190
 
166
- ## 5. Why Glibc (`x86_64-unknown-linux-gnu`) is the Primary Backend Target
191
+ ## 6. Why Glibc (`x86_64-unknown-linux-gnu`) is the Primary Backend Target
167
192
 
168
193
  Both production reference projects strictly target **`x86_64-unknown-linux-gnu`** (Debian Bookworm) rather than Alpine/musl:
169
194
 
@@ -174,9 +199,9 @@ Both production reference projects strictly target **`x86_64-unknown-linux-gnu`*
174
199
 
175
200
  2. **The Glibc Arena Tradeoff (And How It's Solved)**:
176
201
  - Glibc provides raw multi-threaded throughput, but introduces aggressive arena creation (`8 * CPU_CORES`), causing RSS phantom bloat.
177
- - This skill applies the two-part containment recipe:
178
- - `ENV MALLOC_ARENA_MAX=2` to limit arena fragmentation.
179
- - `libc::malloc_trim(0)` to actively return idle pages to the Linux kernel.
202
+ - Opt-in deployment containment recipe (only when strict RSS caps demand it):
203
+ - `-e MALLOC_ARENA_MAX=2` via `docker run` / K8s env to limit arena fragmentation.
204
+ - Opt-in `MALLOC_TRIM=true` calling `libc::malloc_trim(0)` offloaded via `tokio::task::spawn_blocking`.
180
205
 
181
206
  3. **Strict Docker Base Image Pairing (Preventing `libc.so` Crashes)**:
182
207
  - Dynamic linking requires that the runner image glibc version is identical to the builder image.
@@ -149,3 +149,11 @@ pub async fn serve_mmap_asset(
149
149
  2. **Writable Memory Maps (`MmapMut`)**:
150
150
  - For Write-Ahead Logs (WAL) or shared ring buffers, use `MmapMut::map_mut(&file)`.
151
151
  - Call `mmap.flush_async()?` or `mmap.flush()?` to persist dirty pages deterministically without blocking the Tokio reactor loop.
152
+
153
+ ---
154
+
155
+ ## Trade-Offs: Pros, Cons & When to Skip
156
+
157
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
158
+ | :--- | :--- | :--- | :--- |
159
+ | **`memmap2` + `madvise` Zero-Copy Paging** | Delegates caching to kernel page cache with near-zero heap RSS | Requires `unsafe` (`SIGBUS` risk if another process truncates the file while mapped!); network filesystems (`NFS`) stall | Use for immutable/controlled local static indexes/assets; **skip** on untrusted/concurrently truncated files or slow network mounts |
@@ -123,3 +123,11 @@ pub fn create_kafka_consumer_config() -> ClientConfig {
123
123
  - [ ] Configured `queued.max.messages.kbytes` on Kafka consumers to prevent GBs of buffered records.
124
124
  - [ ] Offloaded heavy CPU decoding/parsing to `rayon` or `spawn_blocking` to avoid stalling the message ACK loop.
125
125
  - [ ] Ensured offset commits only happen after processing has completed, preventing silent message loss during task drainage.
126
+
127
+ ---
128
+
129
+ ## Trade-Offs: Pros, Cons & When to Skip
130
+
131
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
132
+ | :--- | :--- | :--- | :--- |
133
+ | **Bounded Broker Prefetch + `mpsc` Pipeline** | Prevents consumers from buffering GBs of unacked messages into RAM | Setting prefetch too low (`1`) bottlenecks high-latency networks | Always tune prefetch (`basic_qos` / `queued.max.messages.kbytes`) + offload heavy decode to `spawn_blocking`/`rayon` before committing offsets |
@@ -167,3 +167,11 @@ pub fn lock_process_memory() -> Result<(), std::io::Error> {
167
167
  1. **NUMA Binding with Thread Affinity**: Pair every `core_affinity::set_for_current` call with NUMA-local memory allocation (`MPOL_BIND`). Never allow a worker thread on Socket 1 to allocate buffers on Socket 0.
168
168
  2. **Pre-Fault Buffers at Startup**: Always write a single byte to every 2 MB page during the initialization phase (`ptr.write_volatile(0)`) to trigger kernel page allocation upfront, ensuring zero fault overhead during runtime.
169
169
  3. **Verify via Linux Procfs**: Inspect `/proc/<pid>/numa_maps` to ensure zero pages are mapped on remote NUMA nodes.
170
+
171
+ ---
172
+
173
+ ## Trade-Offs: Pros, Cons & When to Skip
174
+
175
+ | Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
176
+ | :--- | :--- | :--- | :--- |
177
+ | **NUMA `MPOL_BIND` + 2MB/1GB HugePages (`madvise`)** | Eliminates remote memory-bus latency and TLB misses on multi-GB datasets | Requires multi-socket NUMA hardware + kernel/privileged setup; `THP` can actually *bloat* small-object RSS in normal web containers | Use only on dedicated multi-socket bare-metal/high-frequency servers; **skip** on single-socket VMs/containers (where `DISABLE_THP` may even be preferred for small RSS) |