@sinkaroid/rust-shapeshift 1.0.5 → 1.0.8
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 +73 -5
- package/package.json +6 -6
- package/skills/rust-shapeshift/SKILL.md +73 -27
- package/skills/rust-shapeshift/resources/anti_bot_and_cookie_challenges.md +1 -1
- package/skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md +1 -1
- package/skills/rust-shapeshift/resources/collection_reuse_and_capacity_retention.md +135 -0
- package/skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md +1 -1
- package/skills/rust-shapeshift/resources/deadlock_elimination_and_locks_across_await.md +149 -0
- package/skills/rust-shapeshift/resources/docker_slimming_and_build_hygiene.md +1 -1
- package/skills/rust-shapeshift/resources/dom_and_scraper_pruning.md +47 -23
- package/skills/rust-shapeshift/resources/enum_variant_boxing_and_stack_squashing.md +136 -0
- package/skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md +1 -1
- package/skills/rust-shapeshift/resources/graphql_memory_and_query_containment.md +1 -1
- package/skills/rust-shapeshift/resources/lock_free_ring_buffers_and_disruptor.md +185 -0
- package/skills/rust-shapeshift/resources/memory_mapped_files_and_zero_copy_paging.md +151 -0
- package/skills/rust-shapeshift/resources/numeric_safety_and_saturating_arithmetic.md +124 -0
- package/skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md +1 -1
- package/skills/rust-shapeshift/resources/production_memory_leak_diagnostics_and_ebpf.md +120 -0
- package/skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md +378 -0
- package/skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md +1 -1
- package/skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md +1 -1
- package/skills/rust-shapeshift/resources/telemetry_and_metrics.md +1 -1
- package/skills/rust-shapeshift/resources/zero_allocation_error_architecture.md +1 -1
- package/skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md +1 -1
- package/skills/rust-shapeshift/resources/zero_copy_zero_alloc_serialization_rkyv.md +135 -0
- package/skills/rust-shapeshift/resources/zero_cost_iterators_and_pipeline_inlining.md +121 -0
- package/skills/rust-shapeshift/resources/zero_cost_state_machines_and_enum_dispatch.md +162 -0
- package/skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md +1 -1
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
# Memory-Mapped Files and Zero-Copy Paging Architecture
|
|
2
|
+
|
|
3
|
+
When applications process large binary datasets, disk caches, persistent logs, or static web assets, using standard filesystem APIs like `tokio::fs::read` or `std::fs::File::read_to_end` forces the OS to copy entire files into userspace heap buffers (`Vec<u8>`). This spikes process Resident Set Size (RSS), strains the allocator, and risks triggering Linux OOMKilled (Exit Code 137).
|
|
4
|
+
|
|
5
|
+
Memory-mapped file I/O delegates paging to the Linux Virtual Memory Subsystem and Page Cache, achieving **sub-megabyte memory footprints** even when processing multi-gigabyte files.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. How Memory Mapping Prevents RSS Bloat
|
|
10
|
+
|
|
11
|
+
Standard read vs. memory-mapped I/O:
|
|
12
|
+
|
|
13
|
+
| Metric / Behavior | Standard `File::read_to_end` | Memory Mapping (`memmap2`) |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| **Userspace Heap Allocation** | Full file size allocated in heap `Vec<u8>` | **0 bytes** allocated on heap |
|
|
16
|
+
| **OS Page Cache Duplication** | 2x (Kernel page cache + userspace buffer) | **1x** (Userspace directly maps page cache) |
|
|
17
|
+
| **Memory Eviction Under Pressure** | None (OS cannot free userspace heap) | **Automatic** (Kernel drops clean pages) |
|
|
18
|
+
| **Paging Granularity** | Eager bulk copy | **On-demand** (4KB page faults as touched) |
|
|
19
|
+
| **OOM Risk** | High for files > available RAM | **Zero** (Pages flushed/evicted dynamically) |
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## 2. Zero-Copy File Inspection with `memmap2`
|
|
24
|
+
|
|
25
|
+
Add `memmap2` to `Cargo.toml`:
|
|
26
|
+
```toml
|
|
27
|
+
[dependencies]
|
|
28
|
+
memmap2 = "0.9"
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### Read-Only Zero-Copy Memory Map with Kernel Advice
|
|
32
|
+
|
|
33
|
+
```rust
|
|
34
|
+
use memmap2::{Mmap, MmapOptions, Advice};
|
|
35
|
+
use std::fs::File;
|
|
36
|
+
use std::path::Path;
|
|
37
|
+
use std::io::{Result, Error, ErrorKind};
|
|
38
|
+
|
|
39
|
+
pub struct PagedFileStorage {
|
|
40
|
+
file: File,
|
|
41
|
+
mmap: Mmap,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
impl PagedFileStorage {
|
|
45
|
+
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
|
|
46
|
+
let file = File::open(path)?;
|
|
47
|
+
let metadata = file.metadata()?;
|
|
48
|
+
|
|
49
|
+
if metadata.len() == 0 {
|
|
50
|
+
return Err(Error::new(ErrorKind::InvalidData, "Cannot mmap zero-length file"));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Safety: File is opened read-only and no concurrent writes are made
|
|
54
|
+
// by this process. Underlying file descriptor must not be truncated externally.
|
|
55
|
+
let mmap = unsafe { MmapOptions::new().map(&file)? };
|
|
56
|
+
|
|
57
|
+
// Kernel hint: Sequential reading optimization
|
|
58
|
+
#[cfg(target_os = "linux")]
|
|
59
|
+
let _ = mmap.advise(Advice::Sequential);
|
|
60
|
+
|
|
61
|
+
Ok(Self { file, mmap })
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/// Read a subslice with zero heap allocation
|
|
65
|
+
#[inline(always)]
|
|
66
|
+
pub fn read_slice(&self, offset: usize, length: usize) -> Option<&[u8]> {
|
|
67
|
+
self.mmap.get(offset..offset + length)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/// Advise kernel that a memory range is no longer needed in physical RAM
|
|
71
|
+
pub fn release_range_from_ram(&self, offset: usize, length: usize) {
|
|
72
|
+
#[cfg(target_os = "linux")]
|
|
73
|
+
let _ = self.mmap.advise_range(Advice::DontNeed, offset, length);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
pub fn total_bytes(&self) -> usize {
|
|
77
|
+
self.mmap.len()
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
## 3. High-Performance Zero-Copy Static Asset Serving (Axum 0.8)
|
|
85
|
+
|
|
86
|
+
In web services, serving static files via `tokio::fs::read` loads file contents into per-request heap buffers. Under high concurrent traffic, 100 concurrent requests for a 10MB file consume 1GB of RSS.
|
|
87
|
+
|
|
88
|
+
Using `memmap2` allows hundreds of concurrent requests to borrow directly from the same shared kernel page cache:
|
|
89
|
+
|
|
90
|
+
```rust
|
|
91
|
+
use axum::{
|
|
92
|
+
extract::{Path as AxumPath, State},
|
|
93
|
+
http::{header, HeaderMap, StatusCode},
|
|
94
|
+
response::IntoResponse,
|
|
95
|
+
routing::get,
|
|
96
|
+
Router,
|
|
97
|
+
};
|
|
98
|
+
use memmap2::Mmap;
|
|
99
|
+
use std::collections::HashMap;
|
|
100
|
+
use std::fs::File;
|
|
101
|
+
use std::sync::Arc;
|
|
102
|
+
|
|
103
|
+
pub struct SharedAssetCache {
|
|
104
|
+
mapped_assets: HashMap<String, Arc<Mmap>>,
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
impl SharedAssetCache {
|
|
108
|
+
pub fn new() -> Self {
|
|
109
|
+
Self {
|
|
110
|
+
mapped_assets: HashMap::new(),
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
pub fn preload_asset(&mut self, route_key: &str, file_path: &str) -> std::io::Result<()> {
|
|
115
|
+
let file = File::open(file_path)?;
|
|
116
|
+
// Safety: Read-only memory map for immutable server assets
|
|
117
|
+
let mmap = unsafe { Mmap::map(&file)? };
|
|
118
|
+
self.mapped_assets.insert(route_key.to_string(), Arc::new(mmap));
|
|
119
|
+
Ok(())
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
pub async fn serve_mmap_asset(
|
|
124
|
+
AxumPath(asset_name): AxumPath<String>,
|
|
125
|
+
State(cache): State<Arc<SharedAssetCache>>,
|
|
126
|
+
) -> Result<impl IntoResponse, StatusCode> {
|
|
127
|
+
let mmap = cache.mapped_assets.get(&asset_name).ok_or(StatusCode::NOT_FOUND)?;
|
|
128
|
+
|
|
129
|
+
// Zero userspace copying: bytes are streamed directly from shared OS pages
|
|
130
|
+
let bytes = mmap.as_ref();
|
|
131
|
+
let body_slice = bytes.to_vec(); // Or wrap in bytes::Bytes::from_static if static lifetime
|
|
132
|
+
|
|
133
|
+
let mut headers = HeaderMap::new();
|
|
134
|
+
headers.insert(header::CONTENT_TYPE, "application/octet-stream".parse().unwrap());
|
|
135
|
+
headers.insert(header::CONTENT_LENGTH, mmap.len().into());
|
|
136
|
+
|
|
137
|
+
Ok((headers, body_slice))
|
|
138
|
+
}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
---
|
|
142
|
+
|
|
143
|
+
## 4. Safety Invariants & Mitigation
|
|
144
|
+
|
|
145
|
+
1. **External File Truncation (SIGBUS Defense)**:
|
|
146
|
+
- If another process on Linux truncates an open mapped file while your service reads beyond the new EOF, the kernel generates a `SIGBUS` signal.
|
|
147
|
+
- **Mitigation**: Exclusively map files owned by the service process, enforce read-only filesystem permissions, or verify file size via `file.metadata()?.len()`.
|
|
148
|
+
|
|
149
|
+
2. **Writable Memory Maps (`MmapMut`)**:
|
|
150
|
+
- For Write-Ahead Logs (WAL) or shared ring buffers, use `MmapMut::map_mut(&file)`.
|
|
151
|
+
- Call `mmap.flush_async()?` or `mmap.flush()?` to persist dirty pages deterministically without blocking the Tokio reactor loop.
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# Numeric Safety & Saturating Arithmetic
|
|
2
|
+
|
|
3
|
+
In production services, integer overflow, uncontrolled bit truncation via `as` casts, and IEEE 754 floating-point comparisons represent critical runtime hazards.
|
|
4
|
+
|
|
5
|
+
In debug builds, unhandled integer overflow triggers a process panic. In release builds, integer overflow wraps silently via two's complement. In high-frequency metrics pipelines, financial engines, and token-bucket rate limiters, unhandled numeric edge cases lead to negative balances, infinite rate-limit allowances, or unexpected process aborts.
|
|
6
|
+
|
|
7
|
+
This reference guide documents zero-cost numeric disciplines: explicit overflow handling (`saturating_*`, `checked_*`, `wrapping_*`), safe narrowing via `TryFrom`, and deterministic floating-point ordering.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## 1. The Four Arithmetic Intents
|
|
12
|
+
|
|
13
|
+
Instead of relying on ambiguous operators (`+`, `-`, `*`), production services must declare explicit mathematical intent:
|
|
14
|
+
|
|
15
|
+
| Method | Behavior on Overflow | Best Production Use Case |
|
|
16
|
+
|---|---|---|
|
|
17
|
+
| **`saturating_*`** | Clamps at `MAX` or `MIN` (never overflows) | **Rate limiters, metrics counters, gauge tracking** |
|
|
18
|
+
| **`checked_*`** | Returns `None` on overflow | **Financial ledgers, memory buffer pre-sizing** |
|
|
19
|
+
| **`wrapping_*`** | Explicitly wraps modulo $2^N$ | **Hash algorithms, ring buffers, sequence numbers** |
|
|
20
|
+
| **`overflowing_*`** | Returns `(value, has_overflowed)` | **Low-level crypto primitives, multi-word math** |
|
|
21
|
+
|
|
22
|
+
### Code Example: Production Token Bucket
|
|
23
|
+
```rust
|
|
24
|
+
pub struct TokenBucket {
|
|
25
|
+
pub available_tokens: u64,
|
|
26
|
+
pub max_capacity: u64,
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
impl TokenBucket {
|
|
30
|
+
pub fn refill(&mut self, added: u64) {
|
|
31
|
+
// ZERO-PANIC: Automatically caps at max_capacity without overflow risk
|
|
32
|
+
self.available_tokens = self
|
|
33
|
+
.available_tokens
|
|
34
|
+
.saturating_add(added)
|
|
35
|
+
.min(self.max_capacity);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
pub fn try_consume(&mut self, cost: u64) -> bool {
|
|
39
|
+
// ZERO-PANIC: Returns None if cost > available_tokens
|
|
40
|
+
if let Some(remaining) = self.available_tokens.checked_sub(cost) {
|
|
41
|
+
self.available_tokens = remaining;
|
|
42
|
+
true
|
|
43
|
+
} else {
|
|
44
|
+
false
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Hardware Efficiency of Saturating Arithmetic
|
|
51
|
+
Modern x86_64 and ARM64 CPUs implement hardware saturation instructions. Rust's `saturating_add` and `saturating_sub` compile down to **1–2 machine instructions** (e.g. `add` + conditional move on x86, or native saturating instructions on ARM), with **zero conditional panic branches** in the generated assembly.
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## 2. Eliminating the Silent Truncation Trap of `as`
|
|
56
|
+
|
|
57
|
+
Using `as` for narrowing numeric conversions silently drops the upper bits, creating severe data corruption bugs:
|
|
58
|
+
|
|
59
|
+
```rust
|
|
60
|
+
// HAZARD: 65,537 exceeds u16::MAX (65,535)
|
|
61
|
+
let large_port: u32 = 65_537;
|
|
62
|
+
let port: u16 = large_port as u16; // SILENT TRUNCATION! port is now 1!
|
|
63
|
+
assert_eq!(port, 1);
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### The Solution: Safe Narrowing with `TryFrom`
|
|
67
|
+
Use `TryFrom` / `TryInto` to detect narrowing failures at runtime without panicking:
|
|
68
|
+
|
|
69
|
+
```rust
|
|
70
|
+
use std::convert::TryFrom;
|
|
71
|
+
|
|
72
|
+
pub fn parse_port(val: u32) -> Result<u16, &'static str> {
|
|
73
|
+
u16::try_from(val).map_err(|_| "Port number exceeds 65535 boundary")
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
assert!(parse_port(65_537).is_err());
|
|
77
|
+
assert_eq!(parse_port(8080).unwrap(), 8080);
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
For widening conversions (e.g. `u16` to `u32`), always use `u32::from(val)`, which is guaranteed to be lossless and verified at compile time.
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
## 3. Floating-Point Comparisons & Ordering
|
|
85
|
+
|
|
86
|
+
Because IEEE 754 floating-point numbers include `NaN` (Not a Number) and negative zero (`-0.0`), floats do not implement `Eq` or `Ord`:
|
|
87
|
+
|
|
88
|
+
```rust
|
|
89
|
+
let x = f64::NAN;
|
|
90
|
+
assert!(!(x == x)); // NaN is not equal to itself!
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### Safe Equality Check with Epsilon
|
|
94
|
+
Never compare floating-point numbers with `==`. Compare within an acceptable tolerance:
|
|
95
|
+
|
|
96
|
+
```rust
|
|
97
|
+
pub fn approx_equal(a: f64, b: f64, epsilon: f64) -> bool {
|
|
98
|
+
(a - b).abs() < epsilon
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
assert!(approx_equal(0.1 + 0.2, 0.3, 1e-10));
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Safe Sorting with `f64::total_cmp`
|
|
105
|
+
Calling standard `.sort()` on `Vec<f64>` fails to compile because floats do not implement `Ord`. Using naive `.partial_cmp().unwrap()` panics in production if a slice contains `NaN`.
|
|
106
|
+
|
|
107
|
+
Use `f64::total_cmp`, which enforces a total ordering across all IEEE 754 values (including `NaN` and `-0.0`):
|
|
108
|
+
|
|
109
|
+
```rust
|
|
110
|
+
pub fn sort_latencies(latencies: &mut [f64]) {
|
|
111
|
+
// ZERO-PANIC: total_cmp handles NaN and infinities predictably
|
|
112
|
+
latencies.sort_by(|a, b| a.total_cmp(b));
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## 4. Architectural Checklist for Numeric Safety
|
|
119
|
+
|
|
120
|
+
1. Enforce `#![warn(clippy::cast_possible_truncation, clippy::cast_sign_loss)]` to catch unsafe `as` casts.
|
|
121
|
+
2. Use `saturating_*` for token buckets, rate limiters, gauges, and queue counters.
|
|
122
|
+
3. Use `checked_*` for monetary balances, slice indexing math, and memory allocations.
|
|
123
|
+
4. Always use `TryFrom` for narrowing integer casts.
|
|
124
|
+
5. Sort floating-point metrics using `.sort_by(f64::total_cmp)`.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
In Rust systems architecture, memory safety and extreme runtime efficiency are direct consequences of the **Ownership and Borrow Checker Permission Model**. Novice developers and unguided AI agents frequently resort to `.clone()` as a crutch to bypass compiler borrow errors, introducing unnecessary heap churn, latency spikes, and CPU cache misses.
|
|
4
4
|
|
|
5
|
-
This
|
|
5
|
+
This reference guide provides the authoritative **Decision Matrix** for placing data on the Stack vs Heap, mastering the Borrow Checker's permission mechanics, and applying strict visibility encapsulation.
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# Production Memory Leak Diagnostics and eBPF Profiling
|
|
2
|
+
|
|
3
|
+
A common misconception among developers transitioning to Rust is that the borrow checker makes memory leaks impossible. In reality, the Rust compiler guarantees **memory safety** (preventing data races, double-frees, and use-after-free), but **not the absence of memory leaks**.
|
|
4
|
+
|
|
5
|
+
Services running in long-term production can leak memory through:
|
|
6
|
+
1. **Reference Cycles**: `Rc<RefCell<T>>` or `Arc<Mutex<T>>` cycles that never drop their refcount to zero.
|
|
7
|
+
2. **Unbounded Collections**: HashMaps, DashMaps, or unbounded queues that continuously insert keys without eviction policies.
|
|
8
|
+
3. **Leaked Allocations**: Deliberate or accidental `Box::leak`, `std::mem::forget`, or unreleased arena pages.
|
|
9
|
+
4. **FFI Allocation Boundaries**: C libraries (`libssl`, `librdkafka`, `sqlite3`) failing to free buffers across FFI boundaries.
|
|
10
|
+
5. **Glibc Arena Fragmentation**: Unreturned memory chunks kept in glibc thread arenas.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## 1. Diagnostics Tooling Matrix
|
|
15
|
+
|
|
16
|
+
| Tool | When to Use | Performance Overhead | Production Safe? |
|
|
17
|
+
|---|---|---|---|
|
|
18
|
+
| **AddressSanitizer / LSan** | CI / Local testing | ~2x CPU, ~2x RAM | No (requires custom compiler flag) |
|
|
19
|
+
| **Valgrind Massif** | Local reproduction of heap peaks | 10x–20x slowdown | No (local only) |
|
|
20
|
+
| **`tikv-jemalloc-ctl`** | Live heap snapshot dumps on demand | Negligible (<1%) | **Yes (Safe for production)** |
|
|
21
|
+
| **eBPF (`bcc memleak`)** | Kernel-level leak tracing on running PIDs | Minimal (~1%–2%) | **Yes (Zero binary changes needed)** |
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## 2. CI & Local Leak Detection: LLVM LeakSanitizer (LSan)
|
|
26
|
+
|
|
27
|
+
Compile the binary with LeakSanitizer enabled using nightly Rust:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
# Enable address and leak sanitizers
|
|
31
|
+
RUSTFLAGS="-Zsanitizer=leak" cargo +nightly test --target x86_64-unknown-linux-gnu
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
If memory is allocated and orphaned without being reclaimed before process exit, LSan prints the exact backtrace:
|
|
35
|
+
|
|
36
|
+
```text
|
|
37
|
+
=================================================================
|
|
38
|
+
==12345==ERROR: LeakSanitizer: detected memory leaks
|
|
39
|
+
Direct leak of 1048576 byte(s) in 1 object(s) allocated from:
|
|
40
|
+
#0 0x55d7f1 in malloc
|
|
41
|
+
#1 0x55df2a in alloc::alloc::alloc
|
|
42
|
+
#2 0x55e100 in my_service::cache::leak_buffer
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## 3. Production Heap Profiling with `jemalloc-ctl`
|
|
48
|
+
|
|
49
|
+
When running in Kubernetes or bare-metal Linux with `tikv-jemallocator`, configure jemalloc profiling at compile and runtime to dump live heap snapshots without restarting the service.
|
|
50
|
+
|
|
51
|
+
Add `tikv-jemalloc-ctl` to `Cargo.toml`:
|
|
52
|
+
```toml
|
|
53
|
+
[dependencies]
|
|
54
|
+
tikv-jemalloc-ctl = "0.6"
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Configure `_MALLOC_CONF` in the Dockerfile:
|
|
58
|
+
```dockerfile
|
|
59
|
+
ENV MALLOC_CONF="prof:true,prof_active:true,prof_prefix:jeprof.out"
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### In-Process Trigger for Memory Heap Dumps
|
|
63
|
+
|
|
64
|
+
Expose an internal administrative endpoint or listen for `SIGUSR1` to dump an allocation profile:
|
|
65
|
+
|
|
66
|
+
```rust
|
|
67
|
+
use tikv_jemalloc_ctl::{epoch, stats};
|
|
68
|
+
use std::ffi::CString;
|
|
69
|
+
|
|
70
|
+
pub fn trigger_heap_dump(filename: &str) -> Result<(), String> {
|
|
71
|
+
let c_str = CString::new(filename).map_err(|e| e.to_string())?;
|
|
72
|
+
|
|
73
|
+
unsafe {
|
|
74
|
+
// Advance jemalloc internal epoch to refresh metrics
|
|
75
|
+
epoch::advance().map_err(|e| format!("Epoch advance failed: {e:?}"))?;
|
|
76
|
+
|
|
77
|
+
// Write heap profile to disk
|
|
78
|
+
tikv_jemalloc_ctl::raw::write(
|
|
79
|
+
b"prof.dump\0",
|
|
80
|
+
c_str.as_ptr() as *const std::ffi::c_void,
|
|
81
|
+
).map_err(|e| format!("Heap dump failed: {e:?}"))?;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
Ok(())
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
pub fn read_process_allocated_bytes() -> usize {
|
|
88
|
+
let _ = epoch::advance();
|
|
89
|
+
stats::allocated::read().unwrap_or(0)
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Inspect the generated profile locally using `jeprof`:
|
|
94
|
+
```bash
|
|
95
|
+
jeprof --show_bytes --pdf ./target/release/my_service jeprof.out.1234.0.mheap > leak_report.pdf
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## 4. Zero-Overhead Live Production Tracing with eBPF (`memleak`)
|
|
101
|
+
|
|
102
|
+
In production environments where binaries cannot be recompiled or restarted, attach the BCC / bpftrace `memleak` tool directly to the container's PID via the host Linux kernel:
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
# Trace outstanding allocations for PID 4512 larger than 1MB over 30 seconds
|
|
106
|
+
sudo /usr/share/bcc/tools/memleak -p 4512 --older 30000 --top 10
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Output: Stack Traces with Unfreed Allocations
|
|
110
|
+
|
|
111
|
+
```text
|
|
112
|
+
Attaching to malloc/free syscalls for PID 4512...
|
|
113
|
+
[09:42:15] Top 2 stacks with outstanding allocations:
|
|
114
|
+
8388608 bytes in 1 allocations from stack
|
|
115
|
+
my_service::state::unbounded_cache_insert+0x42 [my_service]
|
|
116
|
+
my_service::handlers::process_request+0x18a [my_service]
|
|
117
|
+
tokio::runtime::task::core::run+0x85 [my_service]
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
This immediately pinpoints the exact function responsible for unbounded memory retention without touching application code.
|