@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,378 @@
1
+ # Real-World Testing & DOM Fixtures: Eliminating Synthetic Mock Anti-Patterns
2
+
3
+ > *"A unit test that passes green against an invented, synthetic DOM fixture proves nothing, validates nothing, and protects no one. It breeds false confidence while leaving production ingestion pipelines vulnerable to silent failures and layout drifts."*
4
+
5
+ When optimizing data ingestion pipelines, HTML scrapers, and DOM tree parsers for extreme memory efficiency, the primary optimization is pre-parse string slicing (`&html[..end_pos]`), which eliminates 80%–90% of heap AST allocations.
6
+
7
+ However, unit testing these boundaries frequently falls victim to the **Disconnected Placeholder Anti-Pattern**: engineers and autonomous AI agents construct trivial, synthetic HTML snippets that bear zero structural resemblance to real production targets.
8
+
9
+ This reference guide establishes the mandatory engineering standards for **Real-World Testing**, the curation of production DOM fixtures, dual-assertion invariants, and zero-downgrade adaptive fallbacks in Rust.
10
+
11
+ ---
12
+
13
+ ## 1. The Disconnected Placeholder Anti-Pattern
14
+
15
+ The root flaw in naive parser testing is the generation of synthetic, idealized HTML snippets:
16
+
17
+ ```rust
18
+ // ❌ ANTI-PATTERN: DISCONNECTED SYNTHETIC MOCK (DO NOT REPLICATE)
19
+ #[test]
20
+ fn test_naive_pruning_boundary() {
21
+ let mock_html = r#"
22
+ <html><body>
23
+ <div class="main-content"><div class="item">Card 1</div><div class="item">Card 2</div></div>
24
+ <div class="pagination"><a>1</a><a>2</a></div>
25
+ <footer>Heavy footer with tracker scripts and links</footer>
26
+ </body></html>
27
+ "#;
28
+
29
+ let pruned = prune_search_html(mock_html);
30
+ assert!(pruned.contains("Card 1"));
31
+ assert!(!pruned.contains("Heavy footer"));
32
+ }
33
+ ```
34
+
35
+ ### Technical Autopsy: Why Synthetic Fixtures Fail in Production
36
+
37
+ 1. **Zero Real-World Selector Coverage**:
38
+ Production websites never use generic structures like `.main-content` or `.item`. Target platforms employ deep nesting, framework-generated class signatures, or vendor-specific naming conventions. Testing against generic placeholders leaves 100% of the compiled CSS selector AST (`static SEL: LazyLock<Selector>`) unexercised against realistic token streams.
39
+
40
+ 2. **False-Positive Green Tests**:
41
+ The test passes with `100% Ok` in CI. However, because the test verifies the agent's own hallucinated markup rather than target layout topography, breaking structural changes or invalid selectors in production code pass silently into production.
42
+
43
+ 3. **Masking Preceding Sibling Layout Boundaries**:
44
+ *Production Case Study:* Web targets frequently place massive dynamic blocks (recommendation carousels, related media grids, nested comment feeds) **prior** to the semantic `<footer>`. In production parsers, slicing strictly at `<footer>` fails to prune thousands of DOM nodes because the heaviest bloat sits inside preceding sibling containers (e.g. `<div id="related">`). Synthetic mocks omit these preceding sibling blocks, completely masking severe memory leaks and buffer over-allocations.
45
+
46
+ 4. **Blindness to Modern Frontend Hydration Architectures**:
47
+ - Modern web architectures migrate away from static JSON blocks (such as `<script id="__NEXT_DATA__">`) to **React Server Components (RSC)** streaming payloads (`self.__next_f.push(...)`) or **Laravel Inertia.js** root attributes (`<div id="app" data-page="...">`).
48
+ - Synthetic mocks validate stale legacy assumptions, creating pipelines that fail on live production deployments.
49
+
50
+ 5. **Defeatist Engineering (The Revert Trap)**:
51
+ When questioned about edge-case safety in pre-parse string slicing, developers frequently propose abandoning the optimization entirely and reverting to full DOM parsing. Reversion is an engineering failure. The correct architectural response is **Zero-Downgrade Adaptive Fallback**.
52
+
53
+ ---
54
+
55
+ ## 2. The Real-World Fixture Protocol
56
+
57
+ All unit and integration tests for HTML scrapers, DOM pruners, and streaming text decoders **MUST** execute against realistic production DOM fixtures.
58
+
59
+ ### Fixture Curation Guidelines
60
+
61
+ 1. **Capture Live Topography**:
62
+ Capture representative production markup directly from the target domain using standard HTTP tooling:
63
+ ```bash
64
+ curl -sL -A "Mozilla/5.0 (X11; Linux x86_64)" "https://target-domain.com/item/1024" -o tests/fixtures/item_target.html
65
+ ```
66
+ 2. **Preserve Authentic Structural Hierarchies**:
67
+ - Retain exact tag hierarchies, class names, and attribute namespaces (`data-*`, `rel`, `canonical`).
68
+ - Preserve adjacent bloat structures (recommendation carousels, related items, script tags, trackers) to exercise boundary pruning edge cases.
69
+ - For repository size efficiency, truncate repetitive repeating item rows (e.g., retain 2–3 cards rather than 50), while strictly preserving container boundaries and footer siblings.
70
+
71
+ ---
72
+
73
+ ## 3. Dual-Assertion Invariant Verification
74
+
75
+ Scraper and pruning unit tests must enforce symmetrical positive and negative verification invariants:
76
+
77
+ | Verification Stage | Target Invariant | Assertion Rule |
78
+ |---|---|---|
79
+ | **Positive Invariant** | Essential Domain Data | Assert that primary fields (Title, ID, Cover URL, Canonical Link, Metadata) **remain within the slice** AND are **successfully extracted** via production `LazyLock<Selector>` instances. |
80
+ | **Negative Invariant** | Unwanted Memory Bloat | Assert that heavy non-essential DOM nodes (Related carousels, tracker scripts, ads, footers) are **strictly severed outside the slice** (`!pruned.contains(...)`). |
81
+
82
+ ### Canonical Real-World Test Blueprint
83
+
84
+ ```rust
85
+ use scraper::{Html, Selector};
86
+ use std::sync::LazyLock;
87
+
88
+ // Canonical production selectors compiled once via LazyLock
89
+ static SEL_CONTAINER: LazyLock<Selector> =
90
+ LazyLock::new(|| Selector::parse("div.gallery_right").unwrap());
91
+ static SEL_TITLE: LazyLock<Selector> =
92
+ LazyLock::new(|| Selector::parse("div.info h1, h2.g_title").unwrap());
93
+ static SEL_THUMB: LazyLock<Selector> =
94
+ LazyLock::new(|| Selector::parse("div.gallery_thumb img").unwrap());
95
+ static SEL_PAGES: LazyLock<Selector> =
96
+ LazyLock::new(|| Selector::parse("span.i_text.pages").unwrap());
97
+ static SEL_TAGS: LazyLock<Selector> =
98
+ LazyLock::new(|| Selector::parse("a.tag_btn").unwrap());
99
+
100
+ /// Pre-parse slice boundary eliminating 80%+ DOM AST allocations
101
+ pub fn prune_gallery_html(html: &str) -> &str {
102
+ let end_pos = html
103
+ .find("<div id=\"related\"")
104
+ .or_else(|| html.find("id=\"related\""))
105
+ .or_else(|| html.find("<footer"))
106
+ .or_else(|| html.find("id=\"footer\""))
107
+ .unwrap_or(html.len());
108
+ &html[..end_pos]
109
+ }
110
+
111
+ #[cfg(test)]
112
+ mod tests {
113
+ use super::*;
114
+
115
+ #[test]
116
+ fn test_real_world_dom_dual_invariants() {
117
+ // Realistic production DOM fixture preserving live structural hierarchies
118
+ let production_fixture = r#"
119
+ <!DOCTYPE html>
120
+ <html lang="en">
121
+ <head>
122
+ <title>Sample Item Release - Target Platform</title>
123
+ <link rel="canonical" href="https://target-platform.com/item/59026/">
124
+ </head>
125
+ <body>
126
+ <div id="content_wrapper">
127
+ <div class="gallery_right">
128
+ <div class="info">
129
+ <h1>Sample Production Item 59026</h1>
130
+ </div>
131
+ <div class="gallery_thumb">
132
+ <img src="//cdn.target-platform.com/covers/59026/cover.jpg"
133
+ data-src="//cdn.target-platform.com/covers/59026/cover.jpg"
134
+ alt="Cover Thumbnail" />
135
+ </div>
136
+ <span class="i_text pages">Pages: 42</span>
137
+ <div class="tag_list">
138
+ <a class="tag_btn" href="/tag/system/">System <span>1,200</span></a>
139
+ <a class="tag_btn" href="/tag/runtime/">Runtime <span>850</span></a>
140
+ </div>
141
+ </div>
142
+ </div>
143
+
144
+ <!-- Heavy Bloat Boundary: Recommendation Carousel (thousands of AST nodes) -->
145
+ <div id="related">
146
+ <div class="related_card"><a href="/item/99001/">Related Item 1</a></div>
147
+ <div class="related_card"><a href="/item/99002/">Related Item 2</a></div>
148
+ </div>
149
+
150
+ <footer id="footer">
151
+ <div class="tracker_scripts">
152
+ <script src="https://telemetry.thirdparty.com/analytics.js"></script>
153
+ </div>
154
+ </footer>
155
+ </body>
156
+ </html>
157
+ "#;
158
+
159
+ // 1. Execute Memory-Bounded Text Slicing
160
+ let pruned = prune_gallery_html(production_fixture);
161
+
162
+ // 2. Negative Assertions: Verify bloat nodes are severed from memory
163
+ assert!(!pruned.contains("Related Item 1"), "Recommendation carousel must be severed");
164
+ assert!(!pruned.contains("telemetry.thirdparty.com"), "Trackers must be severed");
165
+ assert!(!pruned.contains("id=\"footer\""), "Footer must be severed");
166
+
167
+ // 3. Positive Assertions: Verify essential textual tokens persist
168
+ assert!(pruned.contains("Sample Production Item 59026"));
169
+ assert!(pruned.contains("//cdn.target-platform.com/covers/59026/cover.jpg"));
170
+ assert!(pruned.contains("Pages: 42"));
171
+
172
+ // 4. Selector Verification: Parse pruned slice into scoped AST
173
+ let doc = Html::parse_document(pruned);
174
+
175
+ let title = doc
176
+ .select(&SEL_TITLE)
177
+ .next()
178
+ .map(|el| el.text().collect::<String>())
179
+ .unwrap_or_default();
180
+ assert_eq!(title.trim(), "Sample Production Item 59026");
181
+
182
+ let cover_url = doc
183
+ .select(&SEL_THUMB)
184
+ .next()
185
+ .and_then(|el| el.value().attr("src"))
186
+ .unwrap_or_default();
187
+ assert_eq!(cover_url, "//cdn.target-platform.com/covers/59026/cover.jpg");
188
+
189
+ let tags: Vec<String> = doc
190
+ .select(&SEL_TAGS)
191
+ .map(|el| el.text().collect::<String>().trim().to_string())
192
+ .collect();
193
+ assert!(tags.iter().any(|t| t.contains("System")));
194
+ assert!(tags.iter().any(|t| t.contains("Runtime")));
195
+ }
196
+ }
197
+ ```
198
+
199
+ ---
200
+
201
+ ## 4. Zero-Downgrade Adaptive Self-Healing Fallback
202
+
203
+ To eliminate the risk of upstream website layout drift cutting off valid content without abandoning memory optimization, production architectures employ a **two-tier self-healing parser**:
204
+
205
+ ```
206
+ Inbound Raw HTML Payload
207
+ │
208
+ ▼
209
+ ┌─────────────────────────┐
210
+ │ Fast Path: Text Pruning │ <- Slashes 80%-90% RSS Allocations
211
+ │ (&html[..end_pos]) │
212
+ └────────────┬────────────┘
213
+ │
214
+ ▼
215
+ ┌─────────────────────────┐
216
+ │ Html::parse_document │
217
+ │ (Tuned Sub-AST Tree) │
218
+ └────────────┬────────────┘
219
+ │
220
+ ▼
221
+ Domain Model Extracted?
222
+ ╱ ╲
223
+ ╱ ╲
224
+ YES╱ ╲NO (Empty & String Was Sliced)
225
+ │ │
226
+ ▼ ▼
227
+ Return Data ┌─────────────────────────┐
228
+ │ Self-Healing Tier: │ <- Zero Data Loss
229
+ │ Re-Parse Full Document │
230
+ │ (Emit Metric Alert) │
231
+ └────────────┬────────────┘
232
+ │
233
+ ▼
234
+ Return Extracted Data
235
+ ```
236
+
237
+ ### Self-Healing Pipeline Implementation
238
+
239
+ ```rust
240
+ use scraper::{Html, Selector};
241
+ use std::sync::LazyLock;
242
+ use tracing::warn;
243
+
244
+ #[derive(Debug, Clone, PartialEq, Eq)]
245
+ pub struct ScrapedPayload {
246
+ pub title: String,
247
+ pub cover_url: String,
248
+ pub page_count: u32,
249
+ }
250
+
251
+ static SEL_TITLE: LazyLock<Selector> =
252
+ LazyLock::new(|| Selector::parse("div.info h1, meta[property='og:title']").unwrap());
253
+ static SEL_COVER: LazyLock<Selector> =
254
+ LazyLock::new(|| Selector::parse("div.gallery_thumb img, .cover img").unwrap());
255
+ static SEL_PAGES: LazyLock<Selector> =
256
+ LazyLock::new(|| Selector::parse("span.i_text.pages").unwrap());
257
+
258
+ pub fn parse_gallery_adaptive(raw_html: &str) -> Option<ScrapedPayload> {
259
+ // 1. FAST PATH: Slice HTML string (cuts 80%+ AST memory overhead)
260
+ let end_pos = raw_html
261
+ .find("<div id=\"related\"")
262
+ .or_else(|| raw_html.find("<footer"))
263
+ .or_else(|| raw_html.find("id=\"footer\""))
264
+ .unwrap_or(raw_html.len());
265
+
266
+ let pruned = &raw_html[..end_pos];
267
+ let fast_doc = Html::parse_document(pruned);
268
+ let extracted = extract_domain_fields(&fast_doc);
269
+
270
+ // 2. SELF-HEALING FALLBACK: If extraction yielded empty data but the payload was sliced,
271
+ // automatically re-parse the full document to guarantee zero data loss.
272
+ if extracted.is_none() && pruned.len() < raw_html.len() {
273
+ warn!(
274
+ pruned_bytes = pruned.len(),
275
+ total_bytes = raw_html.len(),
276
+ "Pruning boundary dropped valid data; executing self-healing full document parse"
277
+ );
278
+ let full_doc = Html::parse_document(raw_html);
279
+ return extract_domain_fields(&full_doc);
280
+ }
281
+
282
+ extracted
283
+ }
284
+
285
+ fn extract_domain_fields(doc: &Html) -> Option<ScrapedPayload> {
286
+ let title = doc
287
+ .select(&SEL_TITLE)
288
+ .next()?
289
+ .text()
290
+ .collect::<String>()
291
+ .trim()
292
+ .to_string();
293
+
294
+ let cover_url = doc
295
+ .select(&SEL_COVER)
296
+ .next()
297
+ .and_then(|el| el.value().attr("src").or_else(|| el.value().attr("data-src")))?
298
+ .to_string();
299
+
300
+ let page_count = doc
301
+ .select(&SEL_PAGES)
302
+ .next()
303
+ .and_then(|el| {
304
+ let txt = el.text().collect::<String>();
305
+ txt.chars().filter(|c| c.is_ascii_digit()).collect::<String>().parse().ok()
306
+ })
307
+ .unwrap_or(1);
308
+
309
+ Some(ScrapedPayload {
310
+ title,
311
+ cover_url,
312
+ page_count,
313
+ })
314
+ }
315
+ ```
316
+
317
+ ---
318
+
319
+ ## 5. Modern Hydration Payload Extraction
320
+
321
+ Target platforms that migrate to modern frontend frameworks must be tested against realistic streaming or serialized state payloads.
322
+
323
+ ### 5.1 Next.js App Router (React Server Component Streaming)
324
+
325
+ Modern Next.js platforms stream serialized component state via `self.__next_f.push`:
326
+
327
+ ```rust
328
+ /// Extracts serialized JSON payloads from React Server Component streaming chunks
329
+ pub fn extract_next_rsc_payload(html: &str, target_key: &str) -> Option<String> {
330
+ let mut search_idx = 0;
331
+ while let Some(pos) = html[search_idx..].find("self.__next_f.push(") {
332
+ let absolute_pos = search_idx + pos;
333
+ let window = &html[absolute_pos..];
334
+ if window.contains(target_key) {
335
+ if let Some(start_quote) = window.find('"') {
336
+ if let Some(end_quote) = window[start_quote + 1..].find("\"]") {
337
+ let escaped = &window[start_quote + 1..start_quote + 1 + end_quote];
338
+ return Some(escaped.replace("\\\"", "\"").replace("\\\\", "\\"));
339
+ }
340
+ }
341
+ }
342
+ search_idx = absolute_pos + 20;
343
+ }
344
+ None
345
+ }
346
+ ```
347
+
348
+ ### 5.2 Laravel Inertia.js Hydration Payloads
349
+
350
+ Applications built on Inertia.js pass full view-model state through HTML root attributes:
351
+
352
+ ```rust
353
+ use scraper::{Html, Selector};
354
+ use std::sync::LazyLock;
355
+
356
+ static SEL_INERTIA: LazyLock<Selector> =
357
+ LazyLock::new(|| Selector::parse("div#app[data-page]").unwrap());
358
+
359
+ pub fn extract_inertia_view_model(doc: &Html) -> Option<String> {
360
+ doc.select(&SEL_INERTIA)
361
+ .next()
362
+ .and_then(|el| el.value().attr("data-page"))
363
+ .map(|raw| html_escape::decode_html_entities(raw).to_string())
364
+ }
365
+ ```
366
+
367
+ ---
368
+
369
+ ## 6. Engineering Verification Checklist
370
+
371
+ Before completing any task touching HTML parsing, scraping, or string pruning, verify:
372
+
373
+ - [ ] **Zero Synthetic Mocks**: No test uses invented generic placeholders (`.main-content`, `.item`, `Card 1`).
374
+ - [ ] **Real-World Fixture Topography**: Test fixtures mirror the exact class names, tag hierarchies, and data attributes of production targets.
375
+ - [ ] **Dual-Assertion Invariants**: Every pruning test verifies that target data is within the slice AND bloat is cleanly excluded.
376
+ - [ ] **Static Selector Alignment**: Selectors tested in unit suites match the exact `static SEL: LazyLock<Selector>` instances used in runtime code.
377
+ - [ ] **Zero-Downgrade Fallback**: Text slicing fast paths are paired with adaptive full-document fallbacks to guard against upstream layout shifts.
378
+ - [ ] **Architectural Integrity**: Never propose reverting memory optimizations when edge cases appear; implement resilient self-healing tiers.
@@ -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 playbook documents the architecture required to achieve **< 4KB RSS per concurrent connection** and sub-millisecond zero-copy broadcast fan-out.
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
 
@@ -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 playbook establishes the **Zero-Allocation Type Discipline** required for sub-50MB RSS baseline operations.
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 playbook 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.
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
 
@@ -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 playbook documents how to construct lean, zero-allocation error hierarchies.
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 playbook documents how to eliminate allocation churn during serialization and achieve zero-copy JSON parsing.
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**.