@sinkaroid/rust-shapeshift 1.0.4 → 1.0.7
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 +61 -5
- package/package.json +6 -6
- package/skills/rust-shapeshift/SKILL.md +24 -4
- 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 +3 -3
- 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/hot_path_string_and_zero_cost_helpers.md +3 -3
- 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/realtime_websocket_and_connection_scaling.md +1 -1
- package/skills/rust-shapeshift/resources/redis_connection_and_caching_pitfalls.md +1 -1
- package/skills/rust-shapeshift/resources/reqwest_client_and_connection_pooling.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 +2 -2
- 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,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.
|
|
@@ -4,7 +4,7 @@ In real-time communication systems (chat gateways, live sports feeds, financial
|
|
|
4
4
|
|
|
5
5
|
A naive WebSocket server consumes **100KB to 200KB of RAM per idle connection**—meaning 50,000 idle connections exhaust 5GB to 10GB of memory before processing a single payload.
|
|
6
6
|
|
|
7
|
-
This
|
|
7
|
+
This reference guide documents the architecture required to achieve **< 4KB RSS per concurrent connection** and sub-millisecond zero-copy broadcast fan-out.
|
|
8
8
|
|
|
9
9
|
---
|
|
10
10
|
|
|
@@ -37,7 +37,7 @@ Connecting to Redis in asynchronous Rust (via `redis` and `deadpool-redis`) oper
|
|
|
37
37
|
|
|
38
38
|
---
|
|
39
39
|
|
|
40
|
-
## 2. The Production-Tested Hybrid Cache Pattern
|
|
40
|
+
## 2. The Production-Tested Hybrid Cache Pattern
|
|
41
41
|
|
|
42
42
|
```rust
|
|
43
43
|
use deadpool_redis::{Config as RedisConfig, Pool, Runtime};
|
|
@@ -42,7 +42,7 @@ pub fn create_shared_http_client(user_agent: &str) -> reqwest::Client {
|
|
|
42
42
|
|
|
43
43
|
A common mistake is using the same 15-second timeout for everything. If an ancillary request (like GeoIP lookup or third-party status probe) hangs, it pins the Tokio worker thread context for 15 seconds.
|
|
44
44
|
|
|
45
|
-
### The
|
|
45
|
+
### The Fast-Fail Ancillary Pattern:
|
|
46
46
|
Override timeouts on ancillary requests so they fail fast without impacting core traffic:
|
|
47
47
|
|
|
48
48
|
```rust
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
In high-throughput services and scrapers, indiscriminate use of `String` and `Vec<T>` inside Data Transfer Objects (DTOs), ASTs, and cache models causes thousands of tiny heap allocations and deallocations per second. This triggers CPU L1/L2 cache misses, increases glibc arena fragmentation, and unnecessarily inflates process RSS.
|
|
4
4
|
|
|
5
|
-
This
|
|
5
|
+
This reference guide establishes the **Zero-Allocation Type Discipline** required for sub-50MB RSS baseline operations.
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Many Rust applications pull in bloated telemetry crates (`prometheus`, `opentelemetry`) that add megabytes to binary size and create subtle memory leaks through unconstrained label dimensions.
|
|
4
4
|
|
|
5
|
-
This
|
|
5
|
+
This reference guide provides a **lightweight, zero-dependency Prometheus metrics exporter** that tracks OS process memory, Tokio scheduler health, event loop lag, and HTTP requests with strict cardinality containment.
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -96,7 +96,7 @@ pub async fn telemetry_middleware(req: Request<Body>, next: Next) -> Response {
|
|
|
96
96
|
return next.run(req).await;
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
-
// STRICT route normalization: Only record matched templates (e.g. /
|
|
99
|
+
// STRICT route normalization: Only record matched templates (e.g. /api/v1/items/:id),
|
|
100
100
|
// NEVER raw path or query params (?id=..., ?key=...) to prevent cardinality explosion.
|
|
101
101
|
let matched_path = req
|
|
102
102
|
.extensions()
|
|
@@ -4,7 +4,7 @@ In high-throughput services, error handling is frequently overlooked as a source
|
|
|
4
4
|
1. **The `Result<T, E>` Stack Bloat**: The memory size of `Result<T, E>` is determined by `max(sizeof(T), sizeof(E)) + alignment`. A bloated error enum forces every single function call returning `Result` to allocate massive stack frames, even when the `Ok` branch is taken 99.9% of the time.
|
|
5
5
|
2. **Hot-Path Error Heap Churn**: Creating error instances using `format!` or `String::from` triggers heap allocations on every validation failure, rate limit breach, or missing parameter. Under high traffic or bot fuzzing, error generation alone degrades allocator performance.
|
|
6
6
|
|
|
7
|
-
This
|
|
7
|
+
This reference guide documents how to construct lean, zero-allocation error hierarchies.
|
|
8
8
|
|
|
9
9
|
---
|
|
10
10
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
In web APIs, microservices, and scraper pipelines, JSON serialization and deserialization is the single largest consumer of CPU cycles and allocator bandwidth. The default pattern of deserializing into owned `String` fields forces thousands of tiny heap allocations per request, completely defeating the zero-cost promise of Rust.
|
|
4
4
|
|
|
5
|
-
This
|
|
5
|
+
This reference guide documents how to eliminate allocation churn during serialization and achieve zero-copy JSON parsing.
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# Zero-Allocation and Zero-Copy Serialization with rkyv & zerocopy
|
|
2
|
+
|
|
3
|
+
Standard serialization frameworks (such as `serde_json`, `bincode`, or `rmp-serde`) decode serialized data by traversing buffers, validating individual fields, and allocating concrete Rust structs in stack/heap memory. Even with `#[serde(borrow)]`, pointers must be reconstructed and collection capacities allocated.
|
|
4
|
+
|
|
5
|
+
In ultra-low-latency gateways, telemetry pipelines, and memory-constrained microservices, deserialization overhead can be eliminated entirely using **zero-copy in-place serialization**:
|
|
6
|
+
- **`rkyv`**: Serializes Rust data into a format that can be accessed in-place with **zero decoding time ($0\text{ns}$)** and **zero heap allocation**.
|
|
7
|
+
- **`zerocopy`**: Converts raw byte buffers to and from plain-old-data (POD) structs with compile-time layout and alignment guarantees.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## 1. Serialization Performance Comparison
|
|
12
|
+
|
|
13
|
+
| Serialization Framework | Deserialization Speed | Heap Allocations During Read | Schema Flexibility | Zero-Copy Capability |
|
|
14
|
+
|---|---|---|---|---|
|
|
15
|
+
| **`serde_json`** | Baseline (~50–200 MB/s) | High (Strings, Vecs, Maps) | Dynamic JSON | Slices only with `&'a str` |
|
|
16
|
+
| **`bincode`** | Fast (~400–800 MB/s) | Medium (Allocates collections) | Strict Binary | Partial |
|
|
17
|
+
| **`rkyv`** | **Instant ($0\text{ns}$ / In-place)** | **0 bytes** | Complex Nested Structs | **100% In-Place Borrowing** |
|
|
18
|
+
| **`zerocopy`** | **Instant ($0\text{ns}$ / Transmute)** | **0 bytes** | Flat POD Structs only | **100% Direct Cast** |
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## 2. In-Place Deserialization with `rkyv`
|
|
23
|
+
|
|
24
|
+
Add `rkyv` to `Cargo.toml`:
|
|
25
|
+
```toml
|
|
26
|
+
[dependencies]
|
|
27
|
+
rkyv = { version = "0.8", default-features = false, features = ["std", "alloc"] }
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### Serializing and In-Place Accessing Structs
|
|
31
|
+
|
|
32
|
+
```rust
|
|
33
|
+
use rkyv::{
|
|
34
|
+
access,
|
|
35
|
+
rancor::Error,
|
|
36
|
+
to_bytes,
|
|
37
|
+
Archive,
|
|
38
|
+
Deserialize,
|
|
39
|
+
Serialize,
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
#[derive(Archive, Serialize, Deserialize, Debug, PartialEq)]
|
|
43
|
+
#[rkyv(as = Self)]
|
|
44
|
+
pub struct PacketTelemetry {
|
|
45
|
+
pub session_id: u64,
|
|
46
|
+
pub timestamp_epoch_ms: u64,
|
|
47
|
+
pub error_flags: u32,
|
|
48
|
+
pub payload_name: String,
|
|
49
|
+
pub sensor_readings: Vec<f32>,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
pub fn serialize_telemetry_payload(packet: &PacketTelemetry) -> Result<Vec<u8>, Error> {
|
|
53
|
+
// Serializes directly into contiguous byte buffer
|
|
54
|
+
let bytes = to_bytes::<Error>(packet)?;
|
|
55
|
+
Ok(bytes.into_vec())
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
pub fn inspect_telemetry_in_place(buffer: &[u8]) -> Result<(), Error> {
|
|
59
|
+
// ZERO ALLOCATION: Validates boundaries and accesses the archived struct directly
|
|
60
|
+
// in-place inside the raw byte buffer.
|
|
61
|
+
let archived = access::<PacketTelemetry, Error>(buffer)?;
|
|
62
|
+
|
|
63
|
+
// Fields can be read directly without unpacking
|
|
64
|
+
assert_eq!(archived.session_id, 1024);
|
|
65
|
+
|
|
66
|
+
// String and slice data are borrowed directly from buffer pointers:
|
|
67
|
+
let name: &str = &archived.payload_name;
|
|
68
|
+
let readings: &[f32] = &archived.sensor_readings;
|
|
69
|
+
|
|
70
|
+
println!("Inspected session {} payload '{}' with {} readings",
|
|
71
|
+
archived.session_id, name, readings.len());
|
|
72
|
+
|
|
73
|
+
Ok(())
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## 3. High-Throughput POD Framing with `zerocopy`
|
|
80
|
+
|
|
81
|
+
For high-density networking protocols (e.g. TCP packet framing, binary IPC headers, or hardware sensor packets), structs with fixed layouts can be safely cast directly from raw bytes using `zerocopy`.
|
|
82
|
+
|
|
83
|
+
Add `zerocopy` to `Cargo.toml`:
|
|
84
|
+
```toml
|
|
85
|
+
[dependencies]
|
|
86
|
+
zerocopy = { version = "0.8", features = ["derive"] }
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Zero-Allocation Header Parsing
|
|
90
|
+
|
|
91
|
+
```rust
|
|
92
|
+
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, NetworkEndian, U16, U32, U64};
|
|
93
|
+
|
|
94
|
+
#[derive(FromBytes, IntoBytes, KnownLayout, Immutable, Debug, Clone, Copy)]
|
|
95
|
+
#[repr(C, packed)]
|
|
96
|
+
pub struct BinaryFrameHeader {
|
|
97
|
+
pub magic: [u8; 4], // "SHPF"
|
|
98
|
+
pub version: u8, // Protocol version
|
|
99
|
+
pub flags: u8, // Control flags
|
|
100
|
+
pub sequence_id: U64<NetworkEndian>,
|
|
101
|
+
pub payload_length: U32<NetworkEndian>,
|
|
102
|
+
pub checksum: U16<NetworkEndian>,
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
impl BinaryFrameHeader {
|
|
106
|
+
pub const MAGIC: [u8; 4] = *b"SHPF";
|
|
107
|
+
|
|
108
|
+
#[inline(always)]
|
|
109
|
+
pub fn parse_from_buffer(buffer: &[u8]) -> Option<(&Self, &[u8])> {
|
|
110
|
+
let (header, payload) = Self::ref_from_prefix(buffer).ok()?;
|
|
111
|
+
|
|
112
|
+
if header.magic != Self::MAGIC {
|
|
113
|
+
return None;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
let expected_len = header.payload_length.get() as usize;
|
|
117
|
+
if payload.len() < expected_len {
|
|
118
|
+
return None; // Incomplete packet
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
Some((header, &payload[..expected_len]))
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## 4. Architectural Rules for Zero-Copy Data Pipelines
|
|
129
|
+
|
|
130
|
+
1. **Alignment Verification**:
|
|
131
|
+
- `rkyv` and `zerocopy` require proper memory alignment. When reading byte buffers from network sockets or disk, use aligned buffers (`rkyv::util::AlignedVec`) or enforce `#[repr(C, packed)]` / `#[repr(C, align(N))]`.
|
|
132
|
+
2. **Untrusted Input Boundaries**:
|
|
133
|
+
- Always run validation (`rkyv::access` or `zerocopy::FromBytes::ref_from_prefix`) before reading archived structs to ensure buffer bounds and alignment invariants hold. Never use unchecked transmutes.
|
|
134
|
+
3. **Cache Storage**:
|
|
135
|
+
- For high-concurrency Redis or RocksDB caches, store byte payloads encoded with `rkyv`. Workers retrieve the bytes and inspect cached structs with **zero deserialization CPU cost and zero heap memory duplication**.
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# Zero-Cost Iterators & Pipeline Inlining
|
|
2
|
+
|
|
3
|
+
In high-throughput Rust services, data transformation loops (filtering HTTP headers, parsing delimiter streams, normalizing metrics) frequently fall victim to **intermediate allocation bloat**.
|
|
4
|
+
|
|
5
|
+
Developers migrating from languages like Python, JavaScript, or Java commonly chain `.collect::<Vec<_>>()` at intermediate stages of a pipeline. Each `.collect()` forces a heap allocation, dynamic vector resizing, and redundant cache-line churn before the next transformation even begins.
|
|
6
|
+
|
|
7
|
+
This reference guide documents how to construct purely lazy, zero-allocation iterator pipelines that LLVM compiles down to single-pass vectorized machine loops.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## 1. The Intermediate `.collect()` Anti-Pattern
|
|
12
|
+
|
|
13
|
+
### Naive Implementation (Multiple Allocations & Cache Misses)
|
|
14
|
+
```rust
|
|
15
|
+
// ANTI-PATTERN: Allocates 2 heap vectors for a simple pipeline!
|
|
16
|
+
pub fn process_metrics_naive(raw: &[i64]) -> Vec<i64> {
|
|
17
|
+
// Allocation #1: intermediate filtered vector
|
|
18
|
+
let positive: Vec<i64> = raw.iter().copied().filter(|&x| x > 0).collect();
|
|
19
|
+
|
|
20
|
+
// Allocation #2: final mapped vector
|
|
21
|
+
let doubled: Vec<i64> = positive.into_iter().map(|x| x * 2).collect();
|
|
22
|
+
|
|
23
|
+
doubled
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
### Zero-Allocation Lazy Inlining (Zero Heap Overhead)
|
|
28
|
+
```rust
|
|
29
|
+
// ZERO-COST: Evaluated in a single pass directly into the final container
|
|
30
|
+
pub fn process_metrics_optimal(raw: &[i64]) -> Vec<i64> {
|
|
31
|
+
raw.iter()
|
|
32
|
+
.copied()
|
|
33
|
+
.filter(|&x| x > 0)
|
|
34
|
+
.map(|x| x * 2)
|
|
35
|
+
.collect() // Exactly ONE allocation with pre-sized capacity when possible
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
In the optimal version, Rust's iterator combinators (`filter`, `map`, `take`) are zero-sized types (ZSTs) or small stack wrappers. LLVM fuses them together and inlines the entire pipeline into a single assembly loop, eliminating all intermediate heap allocations.
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## 2. In-Place Allocation Recycling with `.drain()`
|
|
44
|
+
|
|
45
|
+
When processing queues or batches inside worker loops, dropping and recreating a `Vec` causes continuous allocator churn. Use `.drain(..)` to consume elements while **preserving the underlying allocated capacity**:
|
|
46
|
+
|
|
47
|
+
```rust
|
|
48
|
+
pub struct BatchWorker {
|
|
49
|
+
buffer: Vec<String>,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
impl BatchWorker {
|
|
53
|
+
pub fn new(capacity: usize) -> Self {
|
|
54
|
+
Self {
|
|
55
|
+
buffer: Vec::with_capacity(capacity),
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/// Processes items using an iterator and leaves `self.buffer` empty
|
|
60
|
+
/// with zero deallocations.
|
|
61
|
+
pub fn flush_and_process<F>(&mut self, mut processor: F)
|
|
62
|
+
where
|
|
63
|
+
F: FnMut(&str),
|
|
64
|
+
{
|
|
65
|
+
// .drain(..) produces an iterator that moves elements out of the buffer
|
|
66
|
+
// and restores len to 0 while keeping capacity intact!
|
|
67
|
+
for item in self.buffer.drain(..) {
|
|
68
|
+
processor(&item);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Buffer capacity remains completely intact for the next request cycle!
|
|
72
|
+
debug_assert_eq!(self.buffer.len(), 0);
|
|
73
|
+
debug_assert!(self.buffer.capacity() > 0);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## 3. Monomorphized `impl Iterator` vs `Box<dyn Iterator>`
|
|
81
|
+
|
|
82
|
+
When returning an iterator from a function or struct method, avoid dynamic trait objects (`Box<dyn Iterator>`), which introduce heap allocation and vtable indirect call penalties:
|
|
83
|
+
|
|
84
|
+
```rust
|
|
85
|
+
// BAD: Triggers heap allocation for the Box + dynamic vtable dispatch on every .next()
|
|
86
|
+
pub fn active_tokens_dyn<'a>(tokens: &'a [str]) -> Box<dyn Iterator<Item = &'a str> + 'a> {
|
|
87
|
+
Box::new(tokens.iter().copied().filter(|s| !s.is_empty()))
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// GOOD: Zero heap allocation, fully inlined by LLVM at the call site
|
|
91
|
+
pub fn active_tokens_impl<'a>(tokens: &'a [str]) -> impl Iterator<Item = &'a str> + 'a {
|
|
92
|
+
tokens.iter().copied().filter(|s| !s.is_empty())
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
| Trait Form | Heap Allocations | Function Call Overhead | LLVM Inlining |
|
|
97
|
+
|---|---|---|---|
|
|
98
|
+
| `Box<dyn Iterator>` | 1 heap allocation (`Box`) | Indirect pointer jump | Prevented (virtual call) |
|
|
99
|
+
| `impl Iterator` | **0 heap allocations** | **0 overhead** | **Fully inlined & vectorized** |
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## 4. Batch Ingestion with `Extend` and Pre-Sizing
|
|
104
|
+
|
|
105
|
+
When appending multiple elements to an existing collection, avoid repeated `.push()` calls in a loop. Use `.extend()`, which leverages `Iterator::size_hint()` to pre-allocate capacity in a single resize:
|
|
106
|
+
|
|
107
|
+
```rust
|
|
108
|
+
pub fn ingest_records(target: &mut Vec<u32>, source: impl IntoIterator<Item = u32>) {
|
|
109
|
+
// Leverages TrustedLen specialization in stdlib for single-reallocation growth
|
|
110
|
+
target.extend(source);
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## 5. Architectural Checklist for Iterators
|
|
117
|
+
|
|
118
|
+
1. Never chain `.collect()` in the middle of a processing pipeline. Keep iterators lazy until the terminal consumer.
|
|
119
|
+
2. In hot worker loops, use `buffer.drain(..)` or `buffer.clear()` to reuse pre-allocated capacity.
|
|
120
|
+
3. Return `impl Iterator<Item = T>` instead of `Box<dyn Iterator<Item = T>>`.
|
|
121
|
+
4. Prefer iterators over manual indexing (`for i in 0..slice.len()`) to automatically eliminate bounds checks (`BCE`).
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# Zero-Cost State Machines and Enum Dispatch Architecture
|
|
2
|
+
|
|
3
|
+
In object-oriented and dynamically-typed runtimes, polymorphic dispatch and state machines are typically implemented via runtime interfaces, virtual method tables (vtables), or dynamic subclassing.
|
|
4
|
+
|
|
5
|
+
In Rust, using dynamic trait objects (`Box<dyn Trait>` or `&dyn Trait`):
|
|
6
|
+
1. **Requires Heap Allocation**: Storing heterogeneous implementations in collections requires `Box<dyn Trait>`, adding heap allocation and pointer indirection.
|
|
7
|
+
2. **Inhibits Compiler Inlining**: Calls through vtables cannot be inlined by LLVM, disabling loop unrolling and dead-code elimination.
|
|
8
|
+
3. **Breaks SIMD Vectorization**: The CPU cannot vectorize operations across unpredictable indirect function pointers.
|
|
9
|
+
|
|
10
|
+
Using **Compile-Time Enum Dispatch** (`enum_dispatch`) and **Type-State Pattern State Machines**, polymorphic behavior achieves **zero heap allocation, zero pointer chasing, and full LLVM inlining**.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## 1. Dynamic Dispatch (`dyn Trait`) vs. Static Enum Dispatch
|
|
15
|
+
|
|
16
|
+
| Architectural Feature | Dynamic Dispatch (`Box<dyn Trait>`) | Static Enum Dispatch (`enum_dispatch`) |
|
|
17
|
+
|---|---|---|
|
|
18
|
+
| **Memory Allocation** | Heap (`Box<T>`) | **Stack (Inline discriminated union)** |
|
|
19
|
+
| **Pointer Indirection** | 2-word fat pointer (data ptr + vtable ptr) | **1 enum discriminant byte + data** |
|
|
20
|
+
| **LLVM Inlining** | No (indirect branch) | **Full inlining permitted** |
|
|
21
|
+
| **Branch Prediction** | Indirect call misprediction hazard | **Direct jump table / match statement** |
|
|
22
|
+
| **SIMD Auto-Vectorization** | Blocked | **Fully enabled** |
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## 2. Zero-Allocation Polymorphism with `enum_dispatch`
|
|
27
|
+
|
|
28
|
+
Add `enum_dispatch` to `Cargo.toml`:
|
|
29
|
+
```toml
|
|
30
|
+
[dependencies]
|
|
31
|
+
enum_dispatch = "0.3"
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Eliminating Dynamic Vtables
|
|
35
|
+
|
|
36
|
+
```rust
|
|
37
|
+
use enum_dispatch::enum_dispatch;
|
|
38
|
+
|
|
39
|
+
// Define the common trait
|
|
40
|
+
#[enum_dispatch]
|
|
41
|
+
pub trait StreamCodec {
|
|
42
|
+
fn encode(&self, payload: &[u8], output: &mut Vec<u8>);
|
|
43
|
+
fn is_compressed(&self) -> bool;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Concrete Implementations
|
|
47
|
+
pub struct RawCodec;
|
|
48
|
+
impl StreamCodec for RawCodec {
|
|
49
|
+
#[inline(always)]
|
|
50
|
+
fn encode(&self, payload: &[u8], output: &mut Vec<u8>) {
|
|
51
|
+
output.extend_from_slice(payload);
|
|
52
|
+
}
|
|
53
|
+
#[inline(always)]
|
|
54
|
+
fn is_compressed(&self) -> bool { false }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
pub struct ZstdCodec {
|
|
58
|
+
pub compression_level: i32,
|
|
59
|
+
}
|
|
60
|
+
impl StreamCodec for ZstdCodec {
|
|
61
|
+
#[inline(always)]
|
|
62
|
+
fn encode(&self, payload: &[u8], output: &mut Vec<u8>) {
|
|
63
|
+
// Zstd streaming compression logic...
|
|
64
|
+
output.extend_from_slice(payload);
|
|
65
|
+
}
|
|
66
|
+
#[inline(always)]
|
|
67
|
+
fn is_compressed(&self) -> bool { true }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Enum Dispatch replaces Box<dyn StreamCodec>
|
|
71
|
+
#[enum_dispatch(StreamCodec)]
|
|
72
|
+
pub enum PipelineCodec {
|
|
73
|
+
Raw(RawCodec),
|
|
74
|
+
Zstd(ZstdCodec),
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
pub fn execute_pipeline_stream(codecs: &[PipelineCodec], data: &[u8]) -> Vec<u8> {
|
|
78
|
+
let mut buffer = Vec::with_capacity(data.len());
|
|
79
|
+
|
|
80
|
+
// ZERO HEAP INDIRECTION: Dispatches via direct compiler-generated match.
|
|
81
|
+
// Inlines completely under LTO release builds.
|
|
82
|
+
for codec in codecs {
|
|
83
|
+
codec.encode(data, &mut buffer);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
buffer
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## 3. The Typestate Pattern: Zero-Cost Lifecycle State Machines
|
|
93
|
+
|
|
94
|
+
To prevent illegal lifecycle transitions (e.g. attempting to send data over an unauthenticated or disconnected socket), encode states as **Zero-Sized Types (ZSTs)** into the type system:
|
|
95
|
+
|
|
96
|
+
```rust
|
|
97
|
+
use std::marker::PhantomData;
|
|
98
|
+
|
|
99
|
+
// Lifecycle States (Zero-Sized Types - consume 0 bytes of memory)
|
|
100
|
+
pub struct Disconnected;
|
|
101
|
+
pub struct Connecting;
|
|
102
|
+
pub struct Authenticated;
|
|
103
|
+
|
|
104
|
+
pub struct SecureGatewayConnection<State> {
|
|
105
|
+
socket_fd: i32,
|
|
106
|
+
session_token: Option<String>,
|
|
107
|
+
_state: PhantomData<State>,
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
impl SecureGatewayConnection<Disconnected> {
|
|
111
|
+
pub fn new(fd: i32) -> Self {
|
|
112
|
+
Self {
|
|
113
|
+
socket_fd: fd,
|
|
114
|
+
session_token: None,
|
|
115
|
+
_state: PhantomData,
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
pub fn connect(self) -> SecureGatewayConnection<Connecting> {
|
|
120
|
+
// Socket connection logic...
|
|
121
|
+
SecureGatewayConnection {
|
|
122
|
+
socket_fd: self.socket_fd,
|
|
123
|
+
session_token: None,
|
|
124
|
+
_state: PhantomData,
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
impl SecureGatewayConnection<Connecting> {
|
|
130
|
+
pub fn authenticate(self, token: String) -> Result<SecureGatewayConnection<Authenticated>, Self> {
|
|
131
|
+
if !token.is_empty() {
|
|
132
|
+
Ok(SecureGatewayConnection {
|
|
133
|
+
socket_fd: self.socket_fd,
|
|
134
|
+
session_token: Some(token),
|
|
135
|
+
_state: PhantomData,
|
|
136
|
+
})
|
|
137
|
+
} else {
|
|
138
|
+
Err(self) // Return connection in Connecting state on auth failure
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
impl SecureGatewayConnection<Authenticated> {
|
|
144
|
+
// This method physically CANNOT be called on Disconnected or Connecting states!
|
|
145
|
+
// Enforced at compile-time with 0 runtime checks.
|
|
146
|
+
pub fn send_secure_payload(&self, payload: &[u8]) -> Result<(), std::io::Error> {
|
|
147
|
+
println!("Sending {} bytes on socket {}", payload.len(), self.socket_fd);
|
|
148
|
+
Ok(())
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
---
|
|
154
|
+
|
|
155
|
+
## 4. Architectural Rules for Zero-Cost State Machines
|
|
156
|
+
|
|
157
|
+
1. **Replace `Box<dyn Trait>` with `enum_dispatch`**:
|
|
158
|
+
- Whenever the set of polymorphic types is known within the crate/service boundary, use `enum_dispatch` or a manual enum match instead of `Box<dyn Trait>`.
|
|
159
|
+
2. **Use ZSTs (`PhantomData`) for State Tracking**:
|
|
160
|
+
- Never use runtime flags like `is_authenticated: bool` or `state: u8` when states can be modeled statically via typestates. Compile-time states have **zero runtime memory footprint and zero branch misprediction penalty**.
|
|
161
|
+
3. **Static Size Verification**:
|
|
162
|
+
- Verify that enum variants are balanced using `static_assertions::assert_type_size!`. If one variant is significantly larger (>128 bytes), box only that rare variant to keep the main enum discriminant compact on the stack.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
In high-throughput services, an unhandled panic on a Tokio worker thread drops the task, risks corrupting thread-local state, orphans synchronization locks, and degrades long-term process throughput. A robust production service must be mathematically panic-free at compile time.
|
|
4
4
|
|
|
5
|
-
This
|
|
5
|
+
This reference guide documents the **Zero-Panic Policy**, router recursion management, and correct middleware layer ordering used in high-efficiency production services.
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|