@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.
Files changed (28) hide show
  1. package/README.md +73 -5
  2. package/package.json +6 -6
  3. package/skills/rust-shapeshift/SKILL.md +73 -27
  4. package/skills/rust-shapeshift/resources/anti_bot_and_cookie_challenges.md +1 -1
  5. package/skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md +1 -1
  6. package/skills/rust-shapeshift/resources/collection_reuse_and_capacity_retention.md +135 -0
  7. package/skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md +1 -1
  8. package/skills/rust-shapeshift/resources/deadlock_elimination_and_locks_across_await.md +149 -0
  9. package/skills/rust-shapeshift/resources/docker_slimming_and_build_hygiene.md +1 -1
  10. package/skills/rust-shapeshift/resources/dom_and_scraper_pruning.md +47 -23
  11. package/skills/rust-shapeshift/resources/enum_variant_boxing_and_stack_squashing.md +136 -0
  12. package/skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md +1 -1
  13. package/skills/rust-shapeshift/resources/graphql_memory_and_query_containment.md +1 -1
  14. package/skills/rust-shapeshift/resources/lock_free_ring_buffers_and_disruptor.md +185 -0
  15. package/skills/rust-shapeshift/resources/memory_mapped_files_and_zero_copy_paging.md +151 -0
  16. package/skills/rust-shapeshift/resources/numeric_safety_and_saturating_arithmetic.md +124 -0
  17. package/skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md +1 -1
  18. package/skills/rust-shapeshift/resources/production_memory_leak_diagnostics_and_ebpf.md +120 -0
  19. package/skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md +378 -0
  20. package/skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md +1 -1
  21. package/skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md +1 -1
  22. package/skills/rust-shapeshift/resources/telemetry_and_metrics.md +1 -1
  23. package/skills/rust-shapeshift/resources/zero_allocation_error_architecture.md +1 -1
  24. package/skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md +1 -1
  25. package/skills/rust-shapeshift/resources/zero_copy_zero_alloc_serialization_rkyv.md +135 -0
  26. package/skills/rust-shapeshift/resources/zero_cost_iterators_and_pipeline_inlining.md +121 -0
  27. package/skills/rust-shapeshift/resources/zero_cost_state_machines_and_enum_dispatch.md +162 -0
  28. package/skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md +1 -1
@@ -0,0 +1,149 @@
1
+ # Deadlock Elimination & Lock Safety Across `.await` Points
2
+
3
+ In multi-threaded asynchronous systems powered by Tokio, holding a synchronous lock (`std::sync::Mutex` or `parking_lot::Mutex`) across an `.await` boundary is one of the most destructive architectural bugs in production Rust.
4
+
5
+ It triggers **Tokio worker thread starvation**, completely stalling the asynchronous reactor and freezing all incoming HTTP/gRPC requests without producing a single panic or error log.
6
+
7
+ This reference guide documents the mechanics of the `.await` lock hazard, RAII block scoping disciplines, when to use `tokio::sync::Mutex`, and how to replace lock contention with zero-cost channel-based actor patterns.
8
+
9
+ ---
10
+
11
+ ## 1. The Anatomy of an Async Lock Freeze
12
+
13
+ ### The Anti-Pattern (Total Reactor Deadlock)
14
+ ```rust
15
+ use std::sync::Mutex;
16
+
17
+ pub struct SharedState {
18
+ counter: u64,
19
+ }
20
+
21
+ // HAZARD: Holding a synchronous MutexGuard across an .await point!
22
+ pub async fn increment_and_notify_hazard(state: &Mutex<SharedState>) {
23
+ let mut guard = state.lock().unwrap();
24
+ guard.counter += 1;
25
+
26
+ // The current OS worker thread is suspended here waiting for network I/O.
27
+ // The synchronous MutexGuard is NOT released!
28
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
29
+
30
+ println!("Counter: {}", guard.counter);
31
+ // guard dropped here
32
+ }
33
+ ```
34
+
35
+ ### Why This Freezes Tokio
36
+ 1. **Worker Thread Exhaustion**: Tokio runtimes typically allocate 1 OS thread per CPU core (e.g. 4 or 8 threads).
37
+ 2. **Cascading Block**:
38
+ - Task 1 acquires the synchronous lock on Thread A, then hits `.await` and yields.
39
+ - Task 2 runs on Thread B and attempts to acquire `state.lock()`. Because it is a synchronous lock, Thread B **physically blocks the OS thread via a kernel futex syscall**.
40
+ - As more tasks hit the lock, all 4 or 8 Tokio worker threads become physically blocked waiting on the lock.
41
+ - Now, Task 1's timer or network read cannot wake up because **no worker threads are free to run the Tokio scheduler**.
42
+ - The process enters a **permanent, unrecoverable deadlock**.
43
+
44
+ ---
45
+
46
+ ## 2. Pattern A: RAII Block Scoping (Synchronous Work)
47
+
48
+ If the critical section only involves in-memory data manipulation and requires no async I/O, **confine the lock guard to an explicit synchronous scope** that drops before `.await`:
49
+
50
+ ```rust
51
+ use parking_lot::Mutex;
52
+
53
+ pub struct SharedState {
54
+ counter: u64,
55
+ }
56
+
57
+ pub async fn increment_and_notify_safe(state: &Mutex<SharedState>) {
58
+ // 1. Enter isolated synchronous block
59
+ let new_val = {
60
+ let mut guard = state.lock();
61
+ guard.counter += 1;
62
+ guard.counter // Copy out primitive or clone small data
63
+ }; // <-- guard is GUARANTEED to be dropped here!
64
+
65
+ // 2. Perform async operation safely with ZERO locks held
66
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
67
+
68
+ println!("Counter updated to: {}", new_val);
69
+ }
70
+ ```
71
+
72
+ By constraining `guard` to the inner block, the synchronous lock duration is measured in **nanoseconds**, completely eliminating thread starvation.
73
+
74
+ ---
75
+
76
+ ## 3. Pattern B: When to Use `tokio::sync::Mutex`
77
+
78
+ If you **must** hold a lock across an `.await` point (e.g. exclusive transactional access to an async socket or stream):
79
+
80
+ ```rust
81
+ use tokio::sync::Mutex;
82
+
83
+ pub struct SocketSession {
84
+ stream: tokio::net::TcpStream,
85
+ }
86
+
87
+ // SAFE: tokio::sync::Mutex yields cooperatively to the reactor
88
+ pub async fn send_exclusive_packet(session: &Mutex<SocketSession>, data: &[u8]) {
89
+ // .lock().await yields the task if contended, freeing the OS worker thread!
90
+ let mut guard = session.lock().await;
91
+
92
+ // Safe to hold across async I/O
93
+ use tokio::io::AsyncWriteExt;
94
+ let _ = guard.stream.write_all(data).await;
95
+
96
+ // Lock released automatically when guard drops
97
+ }
98
+ ```
99
+
100
+ ### Selection Matrix: `parking_lot::Mutex` vs `tokio::sync::Mutex`
101
+ | Dimension | `parking_lot::Mutex` | `tokio::sync::Mutex` |
102
+ |---|---|---|
103
+ | **Memory Footprint** | **1 byte** | **64–88 bytes** |
104
+ | **Uncontended Lock Speed** | **~10 ns** (CPU atomic) | **~50–80 ns** (async machinery) |
105
+ | **Cross-`.await` Safety** | **DEADLOCK HAZARD** | **100% Safe** |
106
+ | **Best Production Use Case** | In-memory structs, fast state updates, cache maps | Shared network streams, exclusive async transactions |
107
+
108
+ ---
109
+
110
+ ## 4. Pattern C: Zero-Lock Architecture via Actor Channels
111
+
112
+ For high-throughput systems, the cleanest way to eliminate locks entirely is **single-writer message passing**:
113
+
114
+ ```rust
115
+ use tokio::sync::mpsc;
116
+
117
+ pub enum StateMsg {
118
+ Increment { respond_to: tokio::sync::oneshot::Sender<u64> },
119
+ }
120
+
121
+ pub struct StateActor {
122
+ counter: u64,
123
+ receiver: mpsc::Receiver<StateMsg>,
124
+ }
125
+
126
+ impl StateActor {
127
+ pub async fn run(mut self) {
128
+ while let Some(msg) = self.receiver.recv().await {
129
+ match msg {
130
+ StateMsg::Increment { respond_to } => {
131
+ self.counter += 1;
132
+ let _ = respond_to.send(self.counter);
133
+ }
134
+ }
135
+ }
136
+ }
137
+ }
138
+ ```
139
+
140
+ Only one task owns the state. All other tasks send messages via bounded channels with zero lock contention.
141
+
142
+ ---
143
+
144
+ ## 5. Architectural Checklist for Lock Safety
145
+
146
+ 1. Enforce `#![deny(clippy::await_holding_lock)]` in `src/lib.rs` and `src/main.rs`.
147
+ 2. Never call `std::sync::Mutex::lock()` inside an `async fn` without explicit RAII block scoping.
148
+ 3. Use `parking_lot::Mutex` for sub-microsecond in-memory state updates; never hold it across `.await`.
149
+ 4. Use `tokio::sync::Mutex` only when exclusive state must be preserved across async I/O boundaries.
@@ -2,7 +2,7 @@
2
2
 
3
3
  Achieving production efficiency requires minimizing **both runtime memory consumption (RSS) and physical Docker image size**. A bloated Docker image wastes registry bandwidth, slows CI/CD deployments, expands vulnerability attack surfaces, and invalidates build caches needlessly.
4
4
 
5
- This playbook documents the exact multi-stage container recipe and `.dockerignore` discipline used in high-throughput production services to achieve **sub-80MB Debian runtime images** and instant build context transfers.
5
+ This reference guide documents the exact multi-stage container recipe and `.dockerignore` discipline used in high-throughput production services to achieve **sub-80MB Debian runtime images** and instant build context transfers.
6
6
 
7
7
  ---
8
8
 
@@ -1,8 +1,8 @@
1
- # Scraper & DOM Optimization Playbook: Cutting 80% Memory Bloat
1
+ # Scraper & DOM Optimization Reference: Cutting 80% Memory Bloat
2
2
 
3
3
  Parsing full, unconstrained HTML documents (containing thousands of script tags, ads, comments, and footers) into an in-memory DOM tree allocates millions of transient AST nodes, severely stressing the memory allocator and bloating process RSS.
4
4
 
5
- This playbook demonstrates the exact patterns used to achieve sub-50MB RSS memory baselines by pruning raw text strings before AST instantiation.
5
+ This reference guide demonstrates the exact patterns used to achieve sub-50MB RSS memory baselines by pruning raw text strings before AST instantiation.
6
6
 
7
7
  ---
8
8
 
@@ -108,9 +108,17 @@ pub fn parse_direct_slice(bytes: &[u8]) -> Result<ApiResponse, serde_json::Error
108
108
 
109
109
  ---
110
110
 
111
- ## 4. Pattern D: Regression Unit Testing for Pruning Boundaries
111
+ ## 4. Pattern D: Real-World Testing & Dual-Assertion Invariants
112
112
 
113
- Always provide mock HTML tests to verify that your string pruning logic does not prematurely chop valid content cards:
113
+ > [!CAUTION]
114
+ > **Never use disconnected synthetic HTML mocks** (e.g., `<div class="item">Card 1</div>` or generic placeholders). Unit tests on hallucinated DOMs pass green while completely failing in production against live website changes or unexpected layouts. Always test with production fixtures and enforce **The Law of Real DOM Fixtures**.
115
+
116
+ For the comprehensive guide on eliminating synthetic test hallucinations, see [`real_world_testing_and_dom_fixtures.md`](real_world_testing_and_dom_fixtures.md).
117
+
118
+ ### Dual-Assertion Invariants & Self-Healing Architecture
119
+ 1. **Positive Assertions**: Verify that all essential extracted items reside within the slice and parse cleanly via compiled `LazyLock<Selector>` instances.
120
+ 2. **Negative Assertions**: Verify that bloat (trackers, recommendation carousels, heavy footers) is strictly excluded before AST instantiation.
121
+ 3. **Adaptive Fallback**: If a slice cuts off data due to an upstream layout shift, automatically fall back to full document parsing (Zero Downgrade).
114
122
 
115
123
  ```rust
116
124
  #[cfg(test)]
@@ -118,37 +126,53 @@ mod tests {
118
126
  use super::*;
119
127
 
120
128
  #[test]
121
- fn test_search_pruning_boundary() {
122
- let mock_html = r##"
123
- <html>
129
+ fn test_search_pruning_real_dom_dual_invariants() {
130
+ // Realistic DOM fixture reflecting production tag hierarchy and sibling bloat
131
+ let production_search_html = r##"
132
+ <!DOCTYPE html><html><head><title>Search Results - Target Service</title></head>
124
133
  <body>
125
- <div class="wrap"><a title="Video 1"></a></div>
126
- <div class="pagination">Page 1, 2, 3</div>
127
- <div class="unneeded-content">Heavy comments and footer links</div>
128
- <footer>Footer</footer>
129
- </body>
130
- </html>
134
+ <div id="results_wrapper">
135
+ <div class="wrap"><a title="Video 1" href="/v/101">Video 1</a></div>
136
+ <div class="wrap"><a title="Video 2" href="/v/102">Video 2</a></div>
137
+ </div>
138
+ <!-- Bloat starts here: pagination, comment trees, related carousels, and footers -->
139
+ <div class="pagination"><a href="?p=2">2</a><a href="?p=3">3</a></div>
140
+ <div id="comments"><div class="comment">Heavy user comments...</div></div>
141
+ <footer class="footer-wrap">
142
+ <div class="trackers"><script src="https://telemetry.cdn.com/t.js"></script></div>
143
+ </footer>
144
+ </body></html>
131
145
  "##;
132
146
 
133
- let results = parse_search_optimized(mock_html.as_bytes(), "https://example.com/search")
134
- .expect("Parsing should succeed");
135
- assert_eq!(results.len(), 1);
147
+ let results = parse_search_optimized(production_search_html.as_bytes(), "https://example.com/search")
148
+ .expect("Parsing should succeed on real DOM slice");
149
+
150
+ // Positive assertions: essential data extracted
151
+ assert_eq!(results.len(), 2);
136
152
  assert_eq!(results[0], "Video 1");
153
+ assert_eq!(results[1], "Video 2");
154
+
155
+ // Negative assertions: bloat excluded from sliced processing
156
+ let html_str = String::from_utf8_lossy(production_search_html.as_bytes());
157
+ let end_pos = html_str.find("class=\"pagination\"").unwrap_or(html_str.len());
158
+ let slice = &html_str[..end_pos];
159
+ assert!(!slice.contains("Heavy user comments"), "Comments must be excluded");
160
+ assert!(!slice.contains("footer-wrap"), "Footer must be excluded");
137
161
  }
138
162
 
139
163
  #[test]
140
164
  fn test_related_pruning_with_comment_pagination() {
141
- let mock_html = r##"
142
- <html>
165
+ let production_detail_html = r##"
166
+ <!DOCTYPE html><html><head><title>Detail Page</title></head>
143
167
  <body>
168
+ <div id="player-container"><h1>Main Video</h1></div>
144
169
  <div id="comments"><div class="pagination">Comment page 1</div></div>
145
- <div class="wrap"><a title="Related Video 1"></a></div>
146
- <footer>Footer</footer>
147
- </body>
148
- </html>
170
+ <div class="wrap"><a title="Related Video 1" href="/v/201">Related Video 1</a></div>
171
+ <footer class="footer-wrap">Footer</footer>
172
+ </body></html>
149
173
  "##;
150
174
 
151
- let results = parse_search_optimized(mock_html.as_bytes(), "https://example.com/view_video.php")
175
+ let results = parse_search_optimized(production_detail_html.as_bytes(), "https://example.com/view_video.php")
152
176
  .expect("Parsing should succeed without truncation from comment pagination");
153
177
  assert_eq!(results.len(), 1);
154
178
  assert_eq!(results[0], "Related Video 1");
@@ -0,0 +1,136 @@
1
+ # Enum Variant Boxing & Stack Squashing
2
+
3
+ In Rust systems architecture, an `enum`'s in-memory layout is determined by its largest variant:
4
+ $$\text{size\_of::<Enum>()} = \max(\text{size\_of::<Variant}_i\text{>()}) + \text{discriminant} + \text{alignment padding}$$
5
+
6
+ When a single oversized variant is added to a protocol, domain event, or state machine, **every single instance of that enum—even zero-sized unit variants—allocates that maximum size on the stack**.
7
+
8
+ In high-concurrency Tokio applications with 50,000+ active connections or recursive async task trees, oversized enums bloat the compiler-generated `Future` state machines, multiplying idle RAM consumption into tens of megabytes.
9
+
10
+ This reference guide documents how to squash enum footprints using variant boxing, compile-time size guards, and zero-cost pattern matching.
11
+
12
+ ---
13
+
14
+ ## 1. The Async Task Multiplication Trap
15
+
16
+ Consider a typical message event enum in a gateway or websocket server:
17
+
18
+ ```rust
19
+ use std::mem::size_of;
20
+
21
+ pub struct PingPayload; // 0 bytes
22
+
23
+ pub struct MessagePayload {
24
+ pub raw_buffer: [u8; 1024], // 1024 bytes!
25
+ pub header_len: usize,
26
+ }
27
+
28
+ // NAIVE: Size of Event is 1024 + 8 + 8 (discriminant + padding) = 1040 bytes!
29
+ pub enum NaiveEvent {
30
+ Ping(PingPayload),
31
+ Heartbeat,
32
+ Data(MessagePayload),
33
+ }
34
+
35
+ assert_eq!(size_of::<NaiveEvent>(), 1040);
36
+ ```
37
+
38
+ ### The Async Consequence
39
+ In Tokio, when an async task holds `NaiveEvent` across an `.await` boundary:
40
+ ```rust
41
+ async fn process_event(event: NaiveEvent) {
42
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
43
+ match event { /* ... */ }
44
+ }
45
+ ```
46
+ The compiler captures `NaiveEvent` inside the generator state machine:
47
+ - 50,000 idle tasks $\times$ 1,040 bytes $\approx$ **52 MB of RAM** consumed by empty padding while waiting on I/O.
48
+ - Even if 99.9% of messages are small `Heartbeat` or `Ping` packets, memory is allocated as if every message is a full 1KB payload.
49
+
50
+ ---
51
+
52
+ ## 2. The Solution: Boxing Oversized Variants
53
+
54
+ By wrapping variants exceeding 128 bytes in a `Box<T>`, the variant's stack footprint collapses into a single 8-byte heap pointer:
55
+
56
+ ```rust
57
+ use std::mem::size_of;
58
+
59
+ pub struct MessagePayload {
60
+ pub raw_buffer: [u8; 1024],
61
+ pub header_len: usize,
62
+ }
63
+
64
+ // SQUASHED: Maximum variant size is now 8 bytes (Box pointer)
65
+ pub enum SquashedEvent {
66
+ Ping,
67
+ Heartbeat,
68
+ Data(Box<MessagePayload>), // 8-byte pointer on 64-bit targets
69
+ }
70
+
71
+ // Size is 8 (pointer) + 8 (discriminant tag + padding) = 16 bytes!
72
+ const _: () = assert!(size_of::<SquashedEvent>() == 16);
73
+ ```
74
+
75
+ ### Memory Savings Comparison
76
+ | Metric | Naive Enum | Squashed (Boxed) Enum | Savings |
77
+ |---|---|---|---|
78
+ | **Single Enum Size** | 1,040 bytes | 16 bytes | **98.4% reduction** |
79
+ | **50,000 Tasks (Heartbeat)** | 52.0 MB | 0.8 MB | **51.2 MB reclaimed** |
80
+ | **L1 Data Cache (32KB)** | Holds ~30 events | Holds ~2,000 events | **66x cache density** |
81
+
82
+ Heap allocation is now triggered **only when the rare large variant is instantiated**, leaving the high-frequency ping/heartbeat paths 100% zero-allocation.
83
+
84
+ ---
85
+
86
+ ## 3. Pattern Matching and Moving Out of Box
87
+
88
+ Rust allows matching directly on boxed payloads without double-referencing:
89
+
90
+ ```rust
91
+ pub fn handle_event(event: SquashedEvent) {
92
+ match event {
93
+ SquashedEvent::Ping => {
94
+ // 0 heap, 0 pointer dereference
95
+ }
96
+ SquashedEvent::Heartbeat => {
97
+ // 0 heap, 0 pointer dereference
98
+ }
99
+ SquashedEvent::Data(boxed_payload) => {
100
+ // boxed_payload is Box<MessagePayload>
101
+ // Unbox value if needed, or process via deref
102
+ let payload: MessagePayload = *boxed_payload;
103
+ println!("Processed header len: {}", payload.header_len);
104
+ }
105
+ }
106
+ }
107
+ ```
108
+
109
+ ---
110
+
111
+ ## 4. Compile-Time Guard with Static Assertions
112
+
113
+ To prevent teammates or AI agents from accidentally adding unboxed bulky structs into the enum in the future, enforce a static size assertion:
114
+
115
+ ```rust
116
+ pub enum ServiceCommand {
117
+ ReloadConfig,
118
+ DrainConnections,
119
+ UpdateSession(Box<SessionUpdate>),
120
+ }
121
+
122
+ // Fails compilation if any future refactor pushes the enum above 24 bytes!
123
+ const _: () = assert!(
124
+ std::mem::size_of::<ServiceCommand>() <= 24,
125
+ "ServiceCommand exceeds 24-byte memory budget! Box large variants."
126
+ );
127
+ ```
128
+
129
+ ---
130
+
131
+ ## 5. Architectural Checklist for Enums
132
+
133
+ 1. Run `cargo clippy -- -W clippy::large_enum_variant` to find unboxed variants.
134
+ 2. If the size difference between the smallest and largest variant exceeds **128 bytes**, box the largest variant.
135
+ 3. For recursive data structures (trees, ASTs, JSON representations), always box child enum nodes.
136
+ 4. Enforce `const _: () = assert!(size_of::<MyEnum>() <= BUDGET);` for core protocol types.
@@ -6,7 +6,7 @@ A frequent failure mode in Rust backend engineering is choosing a web framework
6
6
 
7
7
  Reaching for Tokio and Axum for an ephemeral monitoring sidecar wastes 20MB–40MB of memory on unused thread pools. Conversely, hand-rolling HTTP/1.1 parsers with `std::net` for a complex SaaS application wastes months reinventing routing, OpenAPI schemas, and multipart streams.
8
8
 
9
- This playbook provides an objective, production-tested **Selection Matrix** comparing **Zero-Dependency Manual (`std::net`)**, **Axum**, **Actix Web**, **Salvo**, **Poem**, **Rocket**, and **Loco**.
9
+ This reference guide provides an objective, production-tested **Selection Matrix** comparing **Zero-Dependency Manual (`std::net`)**, **Axum**, **Actix Web**, **Salvo**, **Poem**, **Rocket**, and **Loco**.
10
10
 
11
11
  ---
12
12
 
@@ -4,7 +4,7 @@ In GraphQL APIs, memory efficiency cannot be guaranteed by standard HTTP body li
4
4
 
5
5
  Without strict schema-level containment, a single recursive GraphQL query can allocate hundreds of thousands of intermediate async futures, blowing process RSS past gigabytes in milliseconds.
6
6
 
7
- This playbook documents how to build a high-throughput, memory-contained GraphQL server using **`async-graphql`** and **`async-graphql-axum`**.
7
+ This reference guide documents how to build a high-throughput, memory-contained GraphQL server using **`async-graphql`** and **`async-graphql-axum`**.
8
8
 
9
9
  ---
10
10
 
@@ -0,0 +1,185 @@
1
+ # Lock-Free Circular Ring Buffers and Disruptor Pattern
2
+
3
+ In concurrent pipelines transferring millions of events, telemetry metrics, or network packets per second, standard synchronization channels (`tokio::sync::mpsc`, `crossbeam_channel`, or `std::sync::mpsc`) introduce noticeable performance bottlenecks:
4
+ 1. **Dynamic Node Allocations**: Many channel implementations allocate heap memory for queue segments or nodes during sustained bursts.
5
+ 2. **Lock & Atomic Bus Contention**: Producers and consumers competing on shared atomic cursors cause cache-line bouncing across multi-core CPU architectures.
6
+ 3. **Latency Jitter**: Memory allocators and thread wakeups create unpredictable p99/p99.99 latency spikes.
7
+
8
+ The **Disruptor Pattern** and **Fixed-Capacity Lock-Free Ring Buffers** eliminate dynamic allocations entirely by pre-allocating a contiguous circular buffer at startup and using hardware cache-aligned atomic sequence barriers.
9
+
10
+ ---
11
+
12
+ ## 1. Single-Producer Single-Consumer (SPSC) Ring Buffer with `rtrb`
13
+
14
+ For ultra-low-latency pipelines where a single dedicated reader thread receives messages from a single worker, an SPSC lock-free ring buffer provides sub-nanosecond operations with zero locks.
15
+
16
+ Add `rtrb` to `Cargo.toml`:
17
+ ```toml
18
+ [dependencies]
19
+ rtrb = "0.3"
20
+ ```
21
+
22
+ ### High-Throughput SPSC Pipeline
23
+
24
+ ```rust
25
+ use rtrb::{RingBuffer, Producer, Consumer};
26
+ use std::thread;
27
+
28
+ pub struct TelemetryEvent {
29
+ pub timestamp_ns: u64,
30
+ pub event_id: u32,
31
+ pub metric_value: f64,
32
+ }
33
+
34
+ pub fn create_spsc_telemetry_pipeline(capacity: usize) -> (Producer<TelemetryEvent>, Consumer<TelemetryEvent>) {
35
+ // Allocates fixed memory chunk once at startup. Zero allocations during runtime.
36
+ RingBuffer::new(capacity)
37
+ }
38
+
39
+ pub fn run_pipeline_demo() {
40
+ let (mut producer, mut consumer) = create_spsc_telemetry_pipeline(65_536);
41
+
42
+ // Producer Thread
43
+ let producer_handle = thread::spawn(move || {
44
+ for i in 0..1_000_000 {
45
+ let event = TelemetryEvent {
46
+ timestamp_ns: i,
47
+ event_id: (i % 256) as u32,
48
+ metric_value: 42.0,
49
+ };
50
+
51
+ // Non-blocking push. If buffer is full, backpressure strategy takes over.
52
+ while let Err(e) = producer.push(event) {
53
+ // Cooperative yield or micro-spin
54
+ std::hint::spin_loop();
55
+ }
56
+ }
57
+ });
58
+
59
+ // Consumer Thread
60
+ let consumer_handle = thread::spawn(move || {
61
+ let mut received = 0;
62
+ while received < 1_000_000 {
63
+ if let Ok(event) = consumer.pop() {
64
+ received += 1;
65
+ let _val = event.metric_value;
66
+ } else {
67
+ std::hint::spin_loop();
68
+ }
69
+ }
70
+ });
71
+
72
+ producer_handle.join().unwrap();
73
+ consumer_handle.join().unwrap();
74
+ }
75
+ ```
76
+
77
+ ---
78
+
79
+ ## 2. Multi-Producer Multi-Consumer (MPMC) with `crossbeam::queue::ArrayQueue`
80
+
81
+ When multiple Tokio worker threads or OS threads must push to a shared bounded queue without heap allocations or unbounded memory growth, use `ArrayQueue`.
82
+
83
+ Add `crossbeam-queue` to `Cargo.toml`:
84
+ ```toml
85
+ [dependencies]
86
+ crossbeam-queue = "0.3"
87
+ ```
88
+
89
+ ```rust
90
+ use crossbeam_queue::ArrayQueue;
91
+ use std::sync::Arc;
92
+
93
+ pub struct BoundedEventBroker<T> {
94
+ queue: Arc<ArrayQueue<T>>,
95
+ }
96
+
97
+ impl<T> BoundedEventBroker<T> {
98
+ pub fn new(capacity: usize) -> Self {
99
+ Self {
100
+ // Strictly bounded fixed-size heap allocation
101
+ queue: Arc::new(ArrayQueue::new(capacity)),
102
+ }
103
+ }
104
+
105
+ /// Pushes event without allocating. Returns Err(event) if at capacity (sheds load).
106
+ #[inline(always)]
107
+ pub fn try_publish(&self, item: T) -> Result<(), T> {
108
+ self.queue.push(item)
109
+ }
110
+
111
+ /// Pulls event with zero lock contention
112
+ #[inline(always)]
113
+ pub fn try_consume(&self) -> Option<T> {
114
+ self.queue.pop()
115
+ }
116
+
117
+ pub fn len(&self) -> usize {
118
+ self.queue.len()
119
+ }
120
+
121
+ pub fn is_full(&self) -> bool {
122
+ self.queue.is_full()
123
+ }
124
+ }
125
+ ```
126
+
127
+ ---
128
+
129
+ ## 3. Cache Line Alignment for Atomic Cursors (False Sharing Prevention)
130
+
131
+ When building custom ring buffers, producers and consumers maintain atomic sequence numbers (head and tail pointers). If the head and tail atomics share the same 64-byte CPU cache line, multi-core writes cause severe CPU cache invalidation loops:
132
+
133
+ ```rust
134
+ use std::sync::atomic::{AtomicU64, Ordering};
135
+
136
+ // CAUTION: False sharing hazard!
137
+ // head and tail reside on the same cache line. Every producer write invalidates consumer cache.
138
+ pub struct BadCursor {
139
+ pub head: AtomicU64, // Offset 0..8
140
+ pub tail: AtomicU64, // Offset 8..16
141
+ }
142
+
143
+ // CORRECT: Cache line alignment isolates each cursor to its own 64-byte line
144
+ #[repr(align(64))]
145
+ pub struct CacheAlignedCursor {
146
+ pub cursor: AtomicU64,
147
+ }
148
+
149
+ pub struct TrueDisruptorRing {
150
+ pub head: CacheAlignedCursor, // Occupies dedicated 64B cache line
151
+ pub tail: CacheAlignedCursor, // Occupies dedicated 64B cache line
152
+ pub mask: usize, // Power-of-two bitmask (capacity - 1)
153
+ }
154
+
155
+ impl TrueDisruptorRing {
156
+ pub fn new(power_of_two_capacity: usize) -> Self {
157
+ assert!(power_of_two_capacity.is_power_of_two(), "Capacity must be power of two");
158
+ Self {
159
+ head: CacheAlignedCursor { cursor: AtomicU64::new(0) },
160
+ tail: CacheAlignedCursor { cursor: AtomicU64::new(0) },
161
+ mask: power_of_two_capacity - 1,
162
+ }
163
+ }
164
+
165
+ #[inline(always)]
166
+ pub fn compute_slot_index(&self, sequence: u64) -> usize {
167
+ // Fast bitwise AND replaces expensive modulo operator (sequence % capacity)
168
+ (sequence as usize) & self.mask
169
+ }
170
+ }
171
+ ```
172
+
173
+ ---
174
+
175
+ ## 4. Architectural Rules for Ring Buffer Systems
176
+
177
+ 1. **Power-of-Two Capacity**:
178
+ - Always choose capacities that are powers of two ($2^{16} = 65,536$, $2^{20} = 1,048,576$). This replaces the expensive CPU division/modulo instruction (`% capacity`) with a single-cycle bitwise AND (`& mask`).
179
+ 2. **Explicit Backpressure Policy**:
180
+ - When the ring is full, make an explicit architectural decision:
181
+ - **Drop Oldest** (for live telemetry and market data feeds).
182
+ - **Fast-Fail / Shed Load** (return HTTP 503 / queue full).
183
+ - **Exponential Backoff** (`std::hint::spin_loop` ➔ `thread::yield_now` ➔ async sleep).
184
+ 3. **Batch Draining**:
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.