@sinkaroid/rust-shapeshift 0.0.0-stage → 1.0.3
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/LICENSE +21 -0
- package/README.md +145 -2
- package/bin/rust-shapeshift.js +29 -0
- package/package.json +45 -4
- package/skills/rust-shapeshift/SKILL.md +282 -0
- package/skills/rust-shapeshift/resources/adaptive_concurrency_and_load_shedding.md +122 -0
- package/skills/rust-shapeshift/resources/anti_bot_and_cookie_challenges.md +139 -0
- package/skills/rust-shapeshift/resources/arena_allocation_and_bump_memory.md +83 -0
- package/skills/rust-shapeshift/resources/async_cancellation_safety_and_task_drainage.md +158 -0
- package/skills/rust-shapeshift/resources/axum_and_tower_architecture.md +145 -0
- package/skills/rust-shapeshift/resources/bounded_caching_and_pooling.md +105 -0
- package/skills/rust-shapeshift/resources/bounded_streaming_and_payload_guards.md +147 -0
- package/skills/rust-shapeshift/resources/bounds_check_elimination_and_zero_cost_memory.md +122 -0
- package/skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md +121 -0
- package/skills/rust-shapeshift/resources/compiler_niche_optimizations_and_size_assertions.md +126 -0
- package/skills/rust-shapeshift/resources/concurrency_model_checking_and_resource_budgets.md +170 -0
- package/skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md +158 -0
- package/skills/rust-shapeshift/resources/docker_slimming_and_build_hygiene.md +115 -0
- package/skills/rust-shapeshift/resources/dom_and_scraper_pruning.md +157 -0
- package/skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md +143 -0
- package/skills/rust-shapeshift/resources/graphql_memory_and_query_containment.md +192 -0
- package/skills/rust-shapeshift/resources/grpc_tonic_and_http2_memory_tuning.md +117 -0
- package/skills/rust-shapeshift/resources/hidden_drop_offload_and_wcet_contracts.md +255 -0
- package/skills/rust-shapeshift/resources/hot_path_string_and_zero_cost_helpers.md +113 -0
- package/skills/rust-shapeshift/resources/instruction_cache_and_cold_path_outlining.md +135 -0
- package/skills/rust-shapeshift/resources/io_uring_and_zero_syscall_networking.md +146 -0
- package/skills/rust-shapeshift/resources/jemalloc_profiling_and_allocator_switch.md +145 -0
- package/skills/rust-shapeshift/resources/kubernetes_runtime_and_resource_containment.md +207 -0
- package/skills/rust-shapeshift/resources/memory_allocator_tuning.md +125 -0
- package/skills/rust-shapeshift/resources/message_queue_and_stream_backpressure.md +125 -0
- package/skills/rust-shapeshift/resources/numa_architecture_and_hugepages.md +169 -0
- package/skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md +253 -0
- package/skills/rust-shapeshift/resources/profile_guided_optimization_and_fast_hashing.md +94 -0
- package/skills/rust-shapeshift/resources/rate_limiting_and_state.md +140 -0
- package/skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md +251 -0
- package/skills/rust-shapeshift/resources/redis_connection_and_caching_pitfalls.md +230 -0
- package/skills/rust-shapeshift/resources/reqwest_client_and_connection_pooling.md +130 -0
- package/skills/rust-shapeshift/resources/simd_vectorization_and_hardware_acceleration.md +108 -0
- package/skills/rust-shapeshift/resources/sqlx_and_database_pool_memory.md +156 -0
- package/skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md +134 -0
- package/skills/rust-shapeshift/resources/streaming_file_io_and_compression.md +97 -0
- package/skills/rust-shapeshift/resources/telemetry_and_metrics.md +170 -0
- package/skills/rust-shapeshift/resources/thread_per_core_and_shared_nothing.md +149 -0
- package/skills/rust-shapeshift/resources/tokio_thread_starvation_and_cpu_offload.md +124 -0
- package/skills/rust-shapeshift/resources/typestate_domain_proofs_and_buffer_recycling.md +254 -0
- package/skills/rust-shapeshift/resources/wasm_runtime_and_memory_sandboxing.md +114 -0
- package/skills/rust-shapeshift/resources/zero_allocation_error_architecture.md +130 -0
- package/skills/rust-shapeshift/resources/zero_copy_ipc_and_shared_memory.md +99 -0
- package/skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md +159 -0
- package/skills/rust-shapeshift/resources/zero_overhead_distributed_tracing.md +109 -0
- package/skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md +104 -0
- package/skills/rust-shapeshift/resources/zero_runtime_and_minimalist_daemons.md +156 -0
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
# Predictable Tail Latency, WCET Contracts & Offloaded Destructors
|
|
2
|
+
|
|
3
|
+
## The Problem: Latency Spikes in Garbage-Free Rust
|
|
4
|
+
|
|
5
|
+
A pervasive myth in backend engineering is that eliminating a tracing Garbage Collector automatically guarantees low, predictable latency. In production Rust services, tail latency spikes (p99/p99.99) and jitter frequently occur due to four subtle runtime hazards:
|
|
6
|
+
|
|
7
|
+
1. **Hidden `Drop` Deallocation Cascades**: Dropping large or deeply nested heap structures (`Vec<T>`, large DOMs, JSON abstract syntax trees, nested `Arc<T>`) causes the current worker thread to synchronously walk thousands of pointers and execute memory deallocations, halting request handling for milliseconds.
|
|
8
|
+
2. **Unbounded Compare-And-Swap (CAS) Loops**: Naive lock-free atomic loops spin indefinitely under high CPU concurrency and cache-line contention, starving CPU pipelines.
|
|
9
|
+
3. **Async Task Worker Starvation**: Tight polling loops in Tokio tasks consume full executor time slices without yielding, delaying subsequent scheduled tasks.
|
|
10
|
+
4. **Hot-Path String Formatting & Logging Allocations**: Macros like `format!`, `println!`, and dynamic tracing spans perform heap allocations and acquire global OS stdout mutexes in the critical execution path.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## 1. Path Classification & Worst-Case Execution Time (WCET) Contracts
|
|
15
|
+
|
|
16
|
+
Strict real-time and low-jitter guidelines must only be applied to latency-critical paths. Segregate components explicitly into execution zones:
|
|
17
|
+
|
|
18
|
+
```text
|
|
19
|
+
Hot / Latency-Critical Path:
|
|
20
|
+
- Packet Rx/Tx, WebSocket message loop, HTTP stream decode, driver rings.
|
|
21
|
+
- Zero heap allocation, zero blocking locks, zero formatting/logging.
|
|
22
|
+
- Constant or bounded iterations (O(1) or O(bounded_N)).
|
|
23
|
+
|
|
24
|
+
Deferred / Non-Critical Path:
|
|
25
|
+
- Config parsing, metrics exposition, startup initialization, cleanup drain.
|
|
26
|
+
- Dynamic heap allocation allowed, standard HashMaps permitted.
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### Documenting Formal WCET Contracts
|
|
30
|
+
|
|
31
|
+
For every latency-sensitive function, declare an explicit WCET contract in rustdoc:
|
|
32
|
+
|
|
33
|
+
```rust
|
|
34
|
+
/// WCET Contract:
|
|
35
|
+
/// - Maximum time complexity: O(MAX_BATCH), where MAX_BATCH <= 128.
|
|
36
|
+
/// - Allocations: 0 heap allocations during steady-state processing.
|
|
37
|
+
/// - Synchronization: Lock-free atomic load/store only; no Mutex or OS syscalls.
|
|
38
|
+
/// - Panics: Panic-free. All slice accesses guarded via checked slices.
|
|
39
|
+
/// - Logging: Zero format string evaluations or I/O calls.
|
|
40
|
+
pub fn process_event_batch<const MAX_BATCH: usize>(
|
|
41
|
+
events: &[RawEvent; MAX_BATCH],
|
|
42
|
+
count: usize,
|
|
43
|
+
) -> Result<usize, ProcessingError> {
|
|
44
|
+
let active_slice = events.get(..count).ok_or(ProcessingError::OutOfBounds)?;
|
|
45
|
+
let mut processed = 0;
|
|
46
|
+
|
|
47
|
+
for event in active_slice {
|
|
48
|
+
// Deterministic, bounded inner operations
|
|
49
|
+
processed += 1;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
Ok(processed)
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## 2. Offloading Destructors: The Background Cleaner Pattern
|
|
59
|
+
|
|
60
|
+
When a worker thread finishes parsing or manipulating a large data structure (e.g., thousands of scraped records or large gRPC message buffers), dropping it in-place triggers immediate heap deallocation overhead.
|
|
61
|
+
|
|
62
|
+
Transfer ownership to a dedicated background cleaner channel:
|
|
63
|
+
|
|
64
|
+
```rust
|
|
65
|
+
use tokio::sync::mpsc;
|
|
66
|
+
use std::thread;
|
|
67
|
+
|
|
68
|
+
pub struct AsyncCleaner<T: Send + 'static> {
|
|
69
|
+
tx: mpsc::Sender<T>,
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
impl<T: Send + 'static> AsyncCleaner<T> {
|
|
73
|
+
pub fn new(capacity: usize) -> Self {
|
|
74
|
+
let (tx, mut rx) = mpsc::channel::<T>(capacity);
|
|
75
|
+
|
|
76
|
+
// Spawn a dedicated, low-priority background OS thread for deallocations
|
|
77
|
+
thread::Builder::new()
|
|
78
|
+
.name("heap-cleaner".to_string())
|
|
79
|
+
.spawn(move || {
|
|
80
|
+
while let Some(garbage) = rx.blocking_recv() {
|
|
81
|
+
drop(garbage); // Explicit drop occurs off the worker thread
|
|
82
|
+
}
|
|
83
|
+
})
|
|
84
|
+
.expect("failed to spawn cleaner thread");
|
|
85
|
+
|
|
86
|
+
Self { tx }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/// Non-blocking handoff. If cleaner channel is saturated, falls back to in-place drop.
|
|
90
|
+
pub fn offload(&self, item: T) {
|
|
91
|
+
if let Err(mpsc::error::TrySendError::Full(overflow)) = self.tx.try_send(item) {
|
|
92
|
+
// Saturated cleaner queue: drop in place as backpressure valve
|
|
93
|
+
drop(overflow);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Usage in High-Concurrency Request Handlers
|
|
100
|
+
|
|
101
|
+
```rust
|
|
102
|
+
pub async fn handle_batch_request(
|
|
103
|
+
cleaner: &AsyncCleaner<Vec<LargeRecord>>,
|
|
104
|
+
payload: Vec<u8>,
|
|
105
|
+
) -> Result<(), AppError> {
|
|
106
|
+
// Heavy transformation produces heap-allocated structure
|
|
107
|
+
let records: Vec<LargeRecord> = parse_and_process(&payload)?;
|
|
108
|
+
|
|
109
|
+
// Hot path completes here. Hand off deallocation to the background worker:
|
|
110
|
+
cleaner.offload(records);
|
|
111
|
+
|
|
112
|
+
Ok(())
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## 3. Bounded CAS Retry Loops vs. Spin Contention
|
|
119
|
+
|
|
120
|
+
Unbounded atomic loops create pathological latency spikes under high multicore contention due to cache-coherency ping-ponging.
|
|
121
|
+
|
|
122
|
+
### Anti-Pattern: Unbounded Compare-And-Swap Loop
|
|
123
|
+
|
|
124
|
+
```rust
|
|
125
|
+
use std::sync::atomic::{AtomicU64, Ordering};
|
|
126
|
+
|
|
127
|
+
// BAD: Can spin millions of times under lock contention
|
|
128
|
+
pub fn increment_counter_unbounded(counter: &AtomicU64) {
|
|
129
|
+
let mut current = counter.load(Ordering::Relaxed);
|
|
130
|
+
loop {
|
|
131
|
+
match counter.compare_exchange_weak(
|
|
132
|
+
current,
|
|
133
|
+
current + 1,
|
|
134
|
+
Ordering::AcqRel,
|
|
135
|
+
Ordering::Relaxed,
|
|
136
|
+
) {
|
|
137
|
+
Ok(_) => break,
|
|
138
|
+
Err(actual) => current = actual,
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### Production Pattern: Bounded Retry with Hardware Pause
|
|
145
|
+
|
|
146
|
+
```rust
|
|
147
|
+
use std::sync::atomic::{AtomicU64, Ordering};
|
|
148
|
+
use std::hint::spin_loop;
|
|
149
|
+
|
|
150
|
+
pub const MAX_CAS_RETRIES: usize = 32;
|
|
151
|
+
|
|
152
|
+
#[derive(Debug, thiserror::Error)]
|
|
153
|
+
pub enum AtomicContentionError {
|
|
154
|
+
#[error("Exceeded maximum CAS retries due to thread contention")]
|
|
155
|
+
Saturated,
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
pub fn increment_counter_bounded(counter: &AtomicU64) -> Result<(), AtomicContentionError> {
|
|
159
|
+
let mut current = counter.load(Ordering::Relaxed);
|
|
160
|
+
|
|
161
|
+
for _ in 0..MAX_CAS_RETRIES {
|
|
162
|
+
match counter.compare_exchange_weak(
|
|
163
|
+
current,
|
|
164
|
+
current.saturating_add(1),
|
|
165
|
+
Ordering::AcqRel,
|
|
166
|
+
Ordering::Relaxed,
|
|
167
|
+
) {
|
|
168
|
+
Ok(_) => return Ok(()),
|
|
169
|
+
Err(actual) => {
|
|
170
|
+
current = actual;
|
|
171
|
+
spin_loop(); // Emits PAUSE instruction on x86_64 to reduce power & pipeline contention
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
Err(AtomicContentionError::Saturated)
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
---
|
|
181
|
+
|
|
182
|
+
## 4. Async Cooperative Poll Bounds (Preventing Task Starvation)
|
|
183
|
+
|
|
184
|
+
Tokio uses cooperative scheduling, but tasks draining queues via `while let Some(...)` loops can consume excessive runtime time slices without yielding.
|
|
185
|
+
|
|
186
|
+
### Anti-Pattern: Monopolizing Worker Thread
|
|
187
|
+
|
|
188
|
+
```rust
|
|
189
|
+
// BAD: Runs indefinitely if queue is populated faster than drained
|
|
190
|
+
async fn process_inbound_stream(mut rx: tokio::sync::mpsc::Receiver<Frame>) {
|
|
191
|
+
while let Some(frame) = rx.recv().await {
|
|
192
|
+
handle_frame(frame);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
### Production Pattern: Bounded Iteration with Explicit Yield
|
|
198
|
+
|
|
199
|
+
```rust
|
|
200
|
+
use tokio::task::yield_now;
|
|
201
|
+
|
|
202
|
+
pub const MAX_DRAIN_PER_POLL: usize = 64;
|
|
203
|
+
|
|
204
|
+
pub async fn process_inbound_stream_bounded(mut rx: tokio::sync::mpsc::Receiver<Frame>) {
|
|
205
|
+
'outer: loop {
|
|
206
|
+
for _ in 0..MAX_DRAIN_PER_POLL {
|
|
207
|
+
match rx.try_recv() {
|
|
208
|
+
Ok(frame) => handle_frame(frame),
|
|
209
|
+
Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {
|
|
210
|
+
// Await next item asynchronously
|
|
211
|
+
match rx.recv().await {
|
|
212
|
+
Some(frame) => handle_frame(frame),
|
|
213
|
+
None => break 'outer,
|
|
214
|
+
}
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
217
|
+
Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => break 'outer,
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Voluntarily yield current task back to executor run-queue
|
|
222
|
+
yield_now().await;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
---
|
|
228
|
+
|
|
229
|
+
## 5. Hot-Path Ring Buffer Logging (Deferred Formatting)
|
|
230
|
+
|
|
231
|
+
Dynamic log formatting (`format!("{}: {}", id, msg)`) allocates temporary strings and takes file descriptor write locks. Replace hot-path logging with lock-free, fixed-capacity event enums.
|
|
232
|
+
|
|
233
|
+
```rust
|
|
234
|
+
#[derive(Clone, Copy, Debug)]
|
|
235
|
+
pub enum FastEvent {
|
|
236
|
+
RequestReceived { id: u64, timestamp_ns: u64 },
|
|
237
|
+
CacheHit { id: u64 },
|
|
238
|
+
RateLimited { client_ip: [u8; 4] },
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/// Fixed-capacity, lock-free SPSC ring buffer for telemetry
|
|
242
|
+
pub struct EventRecorder<const CAP: usize> {
|
|
243
|
+
queue: rtrb::Producer<FastEvent>,
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
impl<const CAP: usize> EventRecorder<CAP> {
|
|
247
|
+
#[inline(always)]
|
|
248
|
+
pub fn record(&mut self, event: FastEvent) {
|
|
249
|
+
// Non-blocking, zero-allocation write. Drops oldest if full.
|
|
250
|
+
let _ = self.queue.push(event);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
```
|
|
254
|
+
|
|
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.
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# Hot-Path String Optimization & Zero-Cost Helpers
|
|
2
|
+
|
|
3
|
+
In dynamic languages (JavaScript / Python), developers habitually call regex replacements (`str.replace(/\s+/g, ' ')`), date libraries (Moment/Dayjs), or dynamic validators (Zod/Joi) inside request loops. In Rust, applying dynamic regex or heavy parsing in hot paths introduces significant CPU overhead and micro-allocations.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Zero-Regex Whitespace Squeezing (Single-Pass Iterator)
|
|
8
|
+
|
|
9
|
+
In `jandapress/src/scraper/pururin.rs`, collapsing newlines and multiple spaces into a single space is executed on every parsed tag.
|
|
10
|
+
|
|
11
|
+
Instead of running a regex engine, this single-pass character iterator performs zero regex compilation and minimal allocations:
|
|
12
|
+
|
|
13
|
+
```rust
|
|
14
|
+
pub fn squeeze_whitespace(value: &str) -> String {
|
|
15
|
+
let mut result = String::with_capacity(value.len());
|
|
16
|
+
let mut last_was_space = false;
|
|
17
|
+
|
|
18
|
+
for c in value.chars() {
|
|
19
|
+
if c.is_whitespace() {
|
|
20
|
+
if !last_was_space {
|
|
21
|
+
result.push(' ');
|
|
22
|
+
last_was_space = true;
|
|
23
|
+
}
|
|
24
|
+
} else {
|
|
25
|
+
result.push(c);
|
|
26
|
+
last_was_space = false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
result.trim().to_string()
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## 2. Integer Arithmetic Over Heavy Date/Time Crates
|
|
37
|
+
|
|
38
|
+
In `lustpress/src/util.rs`, converting video duration in seconds into `"{m}min, {s}sec"` format is called on hundreds of items per search request.
|
|
39
|
+
|
|
40
|
+
Instead of creating DateTime objects or calling heavy formatting libraries, use native CPU integer division and modulo:
|
|
41
|
+
|
|
42
|
+
```rust
|
|
43
|
+
#[inline]
|
|
44
|
+
pub fn second_to_minute(seconds: u64) -> String {
|
|
45
|
+
let m = seconds / 60;
|
|
46
|
+
let s = seconds % 60;
|
|
47
|
+
format!("{m}min, {s}sec")
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## 3. Safe URL Query Encoding (`form_urlencoded`)
|
|
54
|
+
|
|
55
|
+
In legacy JavaScript, query spacers and URL replacements (`val.replace(/ /g, '+')`) easily introduce injection vulnerabilities or malformed URLs.
|
|
56
|
+
|
|
57
|
+
Use `form_urlencoded::byte_serialize` from the `url` crate for zero-cost, standard-compliant query encoding:
|
|
58
|
+
|
|
59
|
+
```rust
|
|
60
|
+
use url::form_urlencoded;
|
|
61
|
+
|
|
62
|
+
#[inline]
|
|
63
|
+
pub fn encode_query(val: &str) -> String {
|
|
64
|
+
form_urlencoded::byte_serialize(val.as_bytes()).collect()
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
## 4. Static Regex Compilation with `LazyLock<Regex>`
|
|
71
|
+
|
|
72
|
+
When regular expressions are strictly required (such as mathematical challenge extraction in `lustpress/src/fetch.rs`), **NEVER** construct `Regex::new(...)` inside function bodies.
|
|
73
|
+
|
|
74
|
+
Always compile regex patterns once into static memory:
|
|
75
|
+
|
|
76
|
+
```rust
|
|
77
|
+
use regex::Regex;
|
|
78
|
+
use std::sync::LazyLock;
|
|
79
|
+
|
|
80
|
+
static RE_CHALLENGE_P: LazyLock<Regex> =
|
|
81
|
+
LazyLock::new(|| Regex::new(r"var\s+p\s*=\s*(-?\d+)").unwrap());
|
|
82
|
+
static RE_CHALLENGE_S: LazyLock<Regex> =
|
|
83
|
+
LazyLock::new(|| Regex::new(r"var\s+s\s*=\s*(-?\d+)").unwrap());
|
|
84
|
+
static RE_IFELSE: LazyLock<Regex> =
|
|
85
|
+
LazyLock::new(|| Regex::new(r"if\(\(s>>(\d+)\)&1\)\{p([+-])=(\d+)\*(\d+);\}else\{p([+-])=(\d+)\*(\d+);\}").unwrap());
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## 5. Zero-Cost Query Validation (`validator` Derive)
|
|
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:
|
|
95
|
+
|
|
96
|
+
```rust
|
|
97
|
+
use axum::extract::Query;
|
|
98
|
+
use validator::Validate;
|
|
99
|
+
|
|
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,
|
|
104
|
+
|
|
105
|
+
#[validate(range(min = 1, max = 500, message = "Page out of bounds"))]
|
|
106
|
+
pub page: Option<u32>,
|
|
107
|
+
}
|
|
108
|
+
|
|
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
|
+
```
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# Instruction Cache (I-Cache) Saturation & Cold Path Outlining
|
|
2
|
+
|
|
3
|
+
## The Problem: The 32 KB L1 Instruction Cache Wall
|
|
4
|
+
|
|
5
|
+
Modern CPU performance optimization frequently obsesses over data cache locality (L1D/L2D), completely ignoring **Instruction Cache (L1I) locality**:
|
|
6
|
+
|
|
7
|
+
1. **The 32 KB Hardware Limit**: A physical CPU core typically possesses only **32 KB of L1 Instruction Cache**. When CPU instruction fetch pipelines miss L1I, the core stalls while fetching machine instructions from slower L2/L3 caches or system RAM.
|
|
8
|
+
2. **Monomorphization Bloat**: Rust's generic dispatch (`fn process<T: Handler>(h: T)`) duplicates entire machine-code blocks for every concrete type instantiation. A binary with hundreds of monomorphized functions swells to dozens of megabytes, ejecting hot execution loops from the 32 KB L1I cache (*I-Cache Thrashing*).
|
|
9
|
+
3. **Interleaved Cold Assembly**: Without explicit compiler directives, LLVM interleaves code for error handling, panic unwinding, and debug logging directly alongside the hot execution path in memory, polluting I-cache lines with rarely executed instructions.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 1. Cold Path Outlining (`#[cold]` & `#[inline(never)]`)
|
|
14
|
+
|
|
15
|
+
Every branch dedicated to error validation, logging, or exceptional recovery should be outlined into a separate cold function.
|
|
16
|
+
|
|
17
|
+
Applying `#[cold]` tells LLVM that the branch is statistically improbable, prompting the compiler to:
|
|
18
|
+
- Move the cold assembly instructions to a separate memory page at the end of the executable section (`.text.unlikely`).
|
|
19
|
+
- Keep the hot loop compact, contiguous, and aligned, fitting entirely within a few 64-byte cache lines.
|
|
20
|
+
|
|
21
|
+
### Anti-Pattern: Inlined Error Handling Pollutes I-Cache
|
|
22
|
+
|
|
23
|
+
```rust
|
|
24
|
+
// BAD: Error string formatting and validation assembly sits directly inside the hot loop!
|
|
25
|
+
pub fn process_packet_polluted(header: &[u8], payload: &[u8]) -> Result<(), Error> {
|
|
26
|
+
if header.len() < 16 {
|
|
27
|
+
// This format string and error construction code is fetched into L1I cache on every packet!
|
|
28
|
+
let msg = format!("Invalid packet header length: {} (expected >= 16)", header.len());
|
|
29
|
+
tracing::error!("{}", msg);
|
|
30
|
+
return Err(Error::HeaderTooShort(msg));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Hot execution path...
|
|
34
|
+
Ok(())
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### Production Pattern: Outlined Cold Error Handler
|
|
39
|
+
|
|
40
|
+
```rust
|
|
41
|
+
pub fn process_packet_clean(header: &[u8], payload: &[u8]) -> Result<(), Error> {
|
|
42
|
+
// Branch predictor treats this as unlikely; hot path stays straight-line assembly
|
|
43
|
+
if header.len() < 16 {
|
|
44
|
+
return handle_header_error(header.len());
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// HOT PATH: Kept contiguous in memory. Zero cold instructions in L1I!
|
|
48
|
+
unsafe { process_packet_hot(header, payload) }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
#[cold]
|
|
52
|
+
#[inline(never)]
|
|
53
|
+
fn handle_header_error(actual_len: usize) -> Result<(), Error> {
|
|
54
|
+
let msg = format!("Invalid packet header length: {} (expected >= 16)", actual_len);
|
|
55
|
+
tracing::error!("{}", msg);
|
|
56
|
+
Err(Error::HeaderTooShort(msg))
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## 2. Dynamic Dispatch (`dyn Trait`) as an I-Cache Optimization
|
|
63
|
+
|
|
64
|
+
A dogmatic avoidance of `dyn Trait` in favor of generics often degrades runtime performance when dozens of types are involved.
|
|
65
|
+
|
|
66
|
+
### When Monomorphization Hurts
|
|
67
|
+
|
|
68
|
+
```rust
|
|
69
|
+
// If called with 30 different Request types, LLVM emits 30 copies of this 4KB function.
|
|
70
|
+
// Total code size = 120 KB (Instantly blows out the 32 KB L1 Instruction Cache!)
|
|
71
|
+
pub fn execute_pipeline<R: RequestHandler>(handler: &R, req: &[u8]) {
|
|
72
|
+
// 400 lines of complex pipeline logic...
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### When Dynamic Dispatch Wins
|
|
77
|
+
|
|
78
|
+
Using a trait object (`&dyn RequestHandler`) emits **exactly one copy of the function** (4 KB total). The single vtable lookup indirection (1–2 ns) is orders of magnitude faster than a CPU pipeline stall caused by continuous L1I cache misses:
|
|
79
|
+
|
|
80
|
+
```rust
|
|
81
|
+
// Exactly ONE copy in the binary (.text). Sits permanently in L1I cache!
|
|
82
|
+
pub fn execute_pipeline(handler: &dyn RequestHandler, req: &[u8]) {
|
|
83
|
+
// 400 lines of complex pipeline logic...
|
|
84
|
+
handler.handle(req);
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### Decision Matrix: Generics vs. Trait Objects
|
|
89
|
+
|
|
90
|
+
| Scenario | Recommended Dispatch | Justification |
|
|
91
|
+
| :--- | :--- | :--- |
|
|
92
|
+
| **Tight inner loop (<50 lines)** | Generics / Monomorphization | Allows compiler inlining, auto-vectorization (SIMD), and constant folding. |
|
|
93
|
+
| **Large method (>200 lines)** | Dynamic Dispatch (`dyn Trait`) | Prevents multi-kilobyte code bloat and preserves L1I cache locality. |
|
|
94
|
+
| **Control Plane / Request Router** | Dynamic Dispatch (`Box<dyn T>`) | Avoids explosive router monomorphization and reduces compile times. |
|
|
95
|
+
| **Hot Packet Parser** | Static Enum Dispatch | Exhaustive enum matching without dynamic heap or code duplication. |
|
|
96
|
+
|
|
97
|
+
---
|
|
98
|
+
|
|
99
|
+
## 3. Likely and Unlikely Branch Hints (Hardware Pre-Fetching)
|
|
100
|
+
|
|
101
|
+
On x86_64 and ARM64, the CPU Branch Prediction Unit (BPU) prefetches instructions along the predicted path. Ensure predictable branches align with hardware expectations:
|
|
102
|
+
|
|
103
|
+
```rust
|
|
104
|
+
use std::hint;
|
|
105
|
+
|
|
106
|
+
pub fn route_frame(frame: &[u8]) -> Result<(), AppError> {
|
|
107
|
+
// Inform the compiler that valid frames are the 99.999% expected path
|
|
108
|
+
if hint::unlikely(frame.is_empty()) {
|
|
109
|
+
return cold_empty_frame_handler();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Primary instruction stream executes without branch penalty
|
|
113
|
+
execute_frame(frame)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
#[cold]
|
|
117
|
+
#[inline(never)]
|
|
118
|
+
fn cold_empty_frame_handler() -> Result<(), AppError> {
|
|
119
|
+
Err(AppError::EmptyFrame)
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## 4. Measuring Instruction Cache Misses with Linux `perf`
|
|
126
|
+
|
|
127
|
+
Verify that your hot loop fits snugly in the 32 KB L1I cache using Linux hardware performance counters:
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
perf stat -e L1-icache-load-misses,L1-icache-loads,instructions,cycles ./target/release/my_service
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### Target Production Ratios
|
|
134
|
+
* **L1I Miss Rate**: $\frac{\text{L1-icache-load-misses}}{\text{L1-icache-loads}} < \mathbf{0.5\%}$ (Ideal: $<0.1\%$).
|
|
135
|
+
* **Instructions Per Cycle (IPC)**: $\frac{\text{instructions}}{\text{cycles}} > \mathbf{2.5}$ on modern x86_64 / Apple Silicon.
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# Zero-Syscall I/O & Kernel Bypass with io_uring
|
|
2
|
+
|
|
3
|
+
## The Problem: The Syscall and Context-Switch Wall
|
|
4
|
+
|
|
5
|
+
High-concurrency network servers utilizing `epoll` (standard Linux Tokio / Mio) face an inescapable hardware performance ceiling under extreme throughput (100k–500k+ packets/sec). Every network read, write, or socket registration requires:
|
|
6
|
+
|
|
7
|
+
1. **User-to-Kernel Mode Transitions**: Switching CPU privilege levels via the `syscall` instruction forces CPU pipeline flushes and invalidates Translation Lookaside Buffer (TLB) entries.
|
|
8
|
+
2. **KPTI (Kernel Page Table Isolation) Overhead**: Hardware mitigations for Spectre and Meltdown dramatically increase the cost of entering and exiting the Linux kernel.
|
|
9
|
+
3. **Repeated Buffer Pinning & Page Faults**: The kernel must validate, pin into RAM, and unpin userspace memory buffers on every single `read()` and `write()` call, triggering continuous memory controller bus traffic.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 1. The io_uring Architectural Paradigm
|
|
14
|
+
|
|
15
|
+
Unlike `epoll` (which is a readiness notification mechanism), `io_uring` is a **true asynchronous completion queue** operating over two lock-free ring buffers shared directly between userspace and kernel memory:
|
|
16
|
+
|
|
17
|
+
```text
|
|
18
|
+
Userspace Memory ◄══════════════ Shared Ring Buffers ══════════════► Kernel Memory
|
|
19
|
+
│ │
|
|
20
|
+
├──► [Submission Queue (SQ)] ──(Pushes I/O Requests: Read/Write)───────►┤
|
|
21
|
+
│ │
|
|
22
|
+
└──◄ [Completion Queue (CQ)] ◄─(Pops Completed Results with status)─────┤
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Because both queues reside in shared memory (`mmap`), submitting requests and harvesting completions requires **zero system calls** during steady state.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## 2. Kernel Polling: Zero-Syscall I/O (`IORING_SETUP_SQPOLL`)
|
|
30
|
+
|
|
31
|
+
By configuring the kernel ring with `IORING_SETUP_SQPOLL`, the Linux kernel spawns a dedicated kernel thread that continuously polls the Submission Queue. The application simply writes descriptors to the ring; the kernel consumes them without any userspace interrupt or syscall.
|
|
32
|
+
|
|
33
|
+
### Production Setup using `io-uring` Crate
|
|
34
|
+
|
|
35
|
+
```rust
|
|
36
|
+
use io_uring::{opcode, types, IoUring};
|
|
37
|
+
use std::os::unix::io::AsRawFd;
|
|
38
|
+
|
|
39
|
+
pub struct ZeroSyscallEngine {
|
|
40
|
+
ring: IoUring,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
impl ZeroSyscallEngine {
|
|
44
|
+
pub fn new(entries: u32) -> Result<Self, std::io::Error> {
|
|
45
|
+
// Configure kernel polling thread (SQPOLL)
|
|
46
|
+
let ring = IoUring::builder()
|
|
47
|
+
.setup_sqpoll(2000) // Kernel thread sleeps after 2000ms idle
|
|
48
|
+
.build(entries)?;
|
|
49
|
+
|
|
50
|
+
Ok(Self { ring })
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/// Submit an asynchronous socket read with ZERO syscalls
|
|
54
|
+
pub unsafe fn submit_read(
|
|
55
|
+
&mut self,
|
|
56
|
+
fd: &std::net::TcpStream,
|
|
57
|
+
buf: &mut [u8],
|
|
58
|
+
user_data: u64,
|
|
59
|
+
) -> Result<(), std::io::Error> {
|
|
60
|
+
let read_e = opcode::Read::new(
|
|
61
|
+
types::Fd(fd.as_raw_fd()),
|
|
62
|
+
buf.as_mut_ptr(),
|
|
63
|
+
buf.len() as _,
|
|
64
|
+
)
|
|
65
|
+
.build()
|
|
66
|
+
.user_data(user_data);
|
|
67
|
+
|
|
68
|
+
// Push directly into shared userspace-kernel ring
|
|
69
|
+
let mut sq = self.ring.submission();
|
|
70
|
+
sq.push(&read_e).map_err(|_| std::io::Error::new(
|
|
71
|
+
std::io::ErrorKind::WouldBlock,
|
|
72
|
+
"Submission queue is full",
|
|
73
|
+
))?;
|
|
74
|
+
sq.sync(); // Memory barrier to publish to kernel SQPOLL thread
|
|
75
|
+
|
|
76
|
+
Ok(())
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/// Harvest completed events without blocking
|
|
80
|
+
pub fn reap_completions<F>(&mut self, mut callback: F)
|
|
81
|
+
where
|
|
82
|
+
F: FnMut(u64, i32), // user_data, result
|
|
83
|
+
{
|
|
84
|
+
let cq = self.ring.completion();
|
|
85
|
+
for cqe in cq {
|
|
86
|
+
callback(cqe.user_data(), cqe.result());
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## 3. Pre-Registered Fixed Buffers (`io_uring_register_buffers`)
|
|
95
|
+
|
|
96
|
+
When buffers are registered upfront with the kernel via `io_uring_register_buffers`, the kernel maps the virtual pages into its page tables once at startup. Subsequent read/write operations bypass address translation, page pinning, and unpinning entirely.
|
|
97
|
+
|
|
98
|
+
```rust
|
|
99
|
+
use io_uring::IoUring;
|
|
100
|
+
use libc::iovec;
|
|
101
|
+
|
|
102
|
+
pub struct RegisteredMemoryPool {
|
|
103
|
+
raw_memory: Vec<u8>,
|
|
104
|
+
iovecs: Vec<iovec>,
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
impl RegisteredMemoryPool {
|
|
108
|
+
pub fn new(ring: &mut IoUring, chunk_count: usize, chunk_size: usize) -> std::io::Result<Self> {
|
|
109
|
+
let total_size = chunk_count * chunk_size;
|
|
110
|
+
let mut raw_memory = vec![0u8; total_size];
|
|
111
|
+
|
|
112
|
+
let mut iovecs = Vec::with_capacity(chunk_count);
|
|
113
|
+
for i in 0..chunk_count {
|
|
114
|
+
iovecs.push(iovec {
|
|
115
|
+
iov_base: unsafe { raw_memory.as_mut_ptr().add(i * chunk_size) as *mut _ },
|
|
116
|
+
iov_len: chunk_size,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Register buffers permanently with kernel
|
|
121
|
+
ring.submitter().register_buffers(&iovecs)?;
|
|
122
|
+
|
|
123
|
+
Ok(Self { raw_memory, iovecs })
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## 4. Architectural Selection Matrix: Tokio Epoll vs. io_uring
|
|
131
|
+
|
|
132
|
+
| Workload Dimension | Standard Tokio (`epoll`) | `io_uring` (`monoio` / `tokio-uring`) |
|
|
133
|
+
| :--- | :--- | :--- |
|
|
134
|
+
| **QPS Threshold** | Ideal for <100k QPS | Essential for >150k QPS per node |
|
|
135
|
+
| **Kernel Overhead** | 15%–25% CPU time in syscall/KPTI | <2% CPU time in kernel transitions |
|
|
136
|
+
| **Buffer Ownership** | Borrows slices (`&mut [u8]`) | Requires owned buffers (`Vec<u8>`) across submission/completion |
|
|
137
|
+
| **Portability** | Universal (Linux, macOS, Windows) | Strict Linux modern kernel (5.10+, ideally 6.x+) |
|
|
138
|
+
| **Disk Storage I/O** | Requires `spawn_blocking` thread pool | True non-blocking asynchronous direct disk I/O (`O_DIRECT`) |
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
## 5. Production Rules for io_uring in Rust
|
|
143
|
+
|
|
144
|
+
1. **Kernel Version Guard**: Always assert kernel version $\ge$ 5.10 at runtime; older kernels contained security bugs in SQPOLL privilege escalation.
|
|
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
|
+
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`.
|