@sinkaroid/rust-shapeshift 1.0.7 → 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,19 +1,19 @@
1
1
  # Rust Shapeshift
2
2
 
3
- `@sinkaroid/rust-shapeshift` is an AI agent skill specialized in **extreme memory and runtime efficiency** for Rust backend architectures. It enforces deterministic resource containment, zero-allocation data paths, and allocator-level memory reclamation across long-running production workloads.
3
+ `@sinkaroid/rust-shapeshift` is memory and runtime efficiency skills that guides AI coding agents in building memory- and runtime-efficient Rust backend services. It establishes conventions for bounded, predictable resource usage, allocation-free hot paths, and allocator-level memory reclamation, targeting long-running production workloads where steady-state footprint and latency stability matter.
4
4
 
5
- Universally compatible with all AI agent runtimes.
5
+ The skill is runtime-agnostic and can be loaded by any agent environment that supports skill or instruction files.
6
6
 
7
7
  ---
8
8
 
9
- ## Dual Operating Modes & Architectural Archetypes
9
+ ## Dual Operating Modes & Archetypes
10
10
 
11
11
  Before selecting libraries, AI agents must determine both the operating mode and the workload archetype:
12
12
 
13
13
  ### 1. Operating Modes
14
14
 
15
15
  1. **The Shapeshifter (Migration & Modernization Mode)**:
16
- Translates backend services from any runtime (Go, Python, Java, Node.js/TypeScript) into idiomatic Rust without carrying over garbage collection habits, DOM retention leaks, unbounded maps, or per-request connection allocations.
16
+ Translates backend services from any runtime (JavaScript/TypeScript, Python, Java, etc.) into idiomatic Rust without carrying over garbage collection habits, DOM retention leaks, unbounded maps, or per-request connection allocations.
17
17
  2. **The Native Architect (Greenfield Mode)**:
18
18
  Architects native Rust services from scratch targeting modern Rust 1.80+ / 2024 Edition with baseline memory consumption (<50MB RSS), stack inlining (`compact_str`), bounded buffers, zero-copy parsing, and deterministic resource lifecycles.
19
19
 
@@ -27,10 +27,17 @@ Before selecting libraries, AI agents must determine both the operating mode and
27
27
  ## Production Engineering References
28
28
 
29
29
  > [!IMPORTANT]
30
+ > **The Real-World Testing & Anti-Hallucination Mandate**:
31
+ > AI agents consistently fail in production by authoring synthetic, hallucinated unit. Agents commonly generate tests that are disconnected from the code's actual behavior: invented inputs (e.g. `<div class="item">Card 1</div>`), assertions that merely restate the implementation, and cases that never exercise real data. These tests pass reliably yet verify nothing, and defects in real-world data handling go undetected until production.
32
+ > **All ingestion, scraping, and parsing code MUST be validated using real production fixtures and dual-assertion invariants.** Consult [`real_world_testing_and_dom_fixtures.md`](skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md) as the mandatory primary testing specification.
30
33
  >
31
34
  > Before blindly reaching for `tokio` or `axum`, evaluate your workload archetype. A multi-threaded async executor burns 10MB–40MB of idle RSS on thread pools and queues your workload doesn't need. For low-QPS daemons, monitoring sidecars, or CLI utilities, adopt [The Koburi Pattern](skills/rust-shapeshift/resources/zero_runtime_and_minimalist_daemons.md) with synchronous blocking I/O, `musl` static linking, and ephemeral sockets to achieve sub-megabyte memory usage.
32
35
 
33
- All 57 deep-dive reference guides are located in [`skills/rust-shapeshift/resources`](skills/rust-shapeshift/resources)
36
+ All 58 deep-dive reference guides are located in [`skills/rust-shapeshift/resources`](skills/rust-shapeshift/resources)
37
+
38
+ ### Real-World Testing & Verification (Anti-Hallucination Standard)
39
+
40
+ - [`Real-World Testing & DOM Fixtures`](skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md): Eliminating disconnected synthetic mocks, enforcing the Law of Real DOM Fixtures, dual-assertion invariants (positive extraction + negative bloat severance), and zero-downgrade adaptive self-healing fallbacks.
34
41
 
35
42
  ### Memory, Stack & Allocator Optimization
36
43
 
@@ -143,14 +150,14 @@ Automatically primes:
143
150
  Install and follow this skill from https://github.com/sinkaroid/rust-shapeshift
144
151
  ```
145
152
 
146
- Your agent will automatically clone, index, and apply the 57 production engineering references to your current workspace.
153
+ Your agent will automatically clone, index, and apply the 58 production engineering references to your current workspace.
147
154
 
148
155
  ---
149
156
 
150
157
  ### Native CLI Commands
151
158
 
152
159
  ```bash
153
- rust-shapeshift list # Print all 57 production reference guides and descriptions
160
+ rust-shapeshift list # Print all 58 production reference guides and descriptions
154
161
  rust-shapeshift audit # Scan current Rust project for memory anti-patterns
155
162
  rust-shapeshift mcp # Start Model Context Protocol (MCP) server over stdio
156
163
  rust-shapeshift init # Configure agent skill in current directory
@@ -187,12 +194,22 @@ Or using native binary:
187
194
  ```
188
195
 
189
196
  #### Available MCP Tools
190
- - `audit_memory_antipatterns`: Scans current workspace for memory bloat, missing `MALLOC_ARENA_MAX`, unoptimized release profile, and locks across `.await`.
197
+
198
+ - `audit_memory_antipatterns`: Scans current workspace for memory bloat, missing `MALLOC_ARENA_MAX`, unoptimized release profile, locks across `.await`, and synthetic test fixtures.
191
199
  - `inspect_struct_layout`: Computes exact field alignment, wasted padding bytes, optimal reordering, and cache-line false sharing hazards.
192
200
  - `calculate_hardware_budget`: Computes worst-case RSS and maximum safe concurrent connections without triggering Linux OOMKilled (Exit Code 137).
193
- - `explain_recipe`: Retrieves targeted zero-cost implementation snippets and principles from the 57 production guides on-demand.
201
+ - `explain_recipe`: Retrieves targeted zero-cost implementation snippets and principles from the 58 production guides on-demand.
194
202
  - `scaffold_archetype`: Generates verified boilerplates for minimal daemons (`koburi_daemon`), Axum gateways (`axum_gateway`), or zero-copy pipelines (`zero_copy_pipeline`).
195
-
203
+ - `verify_test_fixtures`: Audits test suites and fixtures against the Anti-Hallucination Real DOM Standard, detecting synthetic placeholders and missing dual assertions.
204
+ - `profile_future_size`: Analyzes enum variants and future frames, detecting oversized variants (>128B) and generating `Box<T>` stack-squashing recommendations with compile-time assertions.
205
+ - `check_cancellation_safety`: Scans async code and `tokio::select!` branches for drop-hazard operations (`read_exact`, partial writes, lock contention across await).
206
+ - `optimize_serde_zero_copy`: Transforms owned serde payloads (`String`, `Vec<u8>`) into zero-copy borrowed structs (`&'a str`, `Cow<'a, str>`, `#[serde(borrow)]`) to eliminate deserialization heap churn.
207
+ - `generate_hardened_docker`: Generates production-hardened, non-root multi-stage Dockerfiles (<65MB) with Debian Bookworm C-ABI parity, symbol stripping, and `MALLOC_ARENA_MAX=2` memory guarding.
208
+ - `tune_allocator_env`: Generates tuned allocator environment variables (`MALLOC_ARENA_MAX`, `MALLOC_MMAP_THRESHOLD_`, `TOKIO_WORKER_THREADS`, or `MALLOC_CONF`) with detailed trade-off analysis.
209
+ - `analyze_collection_overhead`: Scans Rust code for heavy collections (`String`, `Vec<T>`, `HashMap`) and recommends zero-cost drop-in alternatives (`CompactString`, `Box<[T]>`, `AHashMap`, `SmallVec`).
210
+ - `generate_k8s_manifest`: Generates hardened Kubernetes Deployment YAML with Guaranteed QoS, Downward API `TOKIO_WORKER_THREADS`, `preStop: sleep 3` hook, and probe isolation.
211
+ - `detect_lock_await`: Scans async Rust source files for synchronous Mutex/RwLock guards held across `.await` points causing reactor thread starvation and deadlocks.
212
+ - `scaffold_benchmark_profile`: Scaffolds Criterion throughput benchmarks, DHAT heap allocation profiling, or live jemalloc runtime statistics harnesses.
196
213
 
197
214
  ## Legal
198
215
 
package/package.json CHANGED
@@ -26,11 +26,11 @@
26
26
  "license": "MIT",
27
27
  "name": "@sinkaroid/rust-shapeshift",
28
28
  "optionalDependencies": {
29
- "@sinkaroid/rust-shapeshift-darwin-arm64": "1.0.7",
30
- "@sinkaroid/rust-shapeshift-darwin-x64": "1.0.7",
31
- "@sinkaroid/rust-shapeshift-linux-arm64": "1.0.7",
32
- "@sinkaroid/rust-shapeshift-linux-x64": "1.0.7",
33
- "@sinkaroid/rust-shapeshift-win32-x64": "1.0.7"
29
+ "@sinkaroid/rust-shapeshift-darwin-arm64": "1.0.10",
30
+ "@sinkaroid/rust-shapeshift-darwin-x64": "1.0.10",
31
+ "@sinkaroid/rust-shapeshift-linux-arm64": "1.0.10",
32
+ "@sinkaroid/rust-shapeshift-linux-x64": "1.0.10",
33
+ "@sinkaroid/rust-shapeshift-win32-x64": "1.0.10"
34
34
  },
35
35
  "publishConfig": {
36
36
  "access": "public"
@@ -43,5 +43,5 @@
43
43
  "build": "cargo build --release",
44
44
  "test": "node bin/rust-shapeshift.js --help"
45
45
  },
46
- "version": "1.0.7"
46
+ "version": "1.0.10"
47
47
  }
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: rust-shapeshift
3
3
  author: "@sinkaroid"
4
- version: "1.0.7"
4
+ version: "1.0.10"
5
5
  repository: "https://github.com/sinkaroid"
6
6
  description: Master modern Rust (1.80+ / 2024 Edition) specialized in extreme memory and runtime efficiency. Expert in transforming backend services from any runtime into lean, production-grade Rust with Axum 0.8 as canonical reference architecture while remaining fully stack-adaptable (Actix Web, Salvo, Loco, std::net). Eliminates hundreds of MBs of RSS bloat via framework selection, allocator tuning, DOM pruning, zero-copy parsing, and bounded concurrency. Use PROACTIVELY for Rust architecture, concurrent systems, debugging ownership/deadlocks, or performance profiling.
7
7
  metadata:
@@ -11,6 +11,11 @@ metadata:
11
11
 
12
12
  # Rust Shapeshift: Extreme Memory & Runtime Systems Engineering
13
13
 
14
+ > [!IMPORTANT]
15
+ > **Mandatory Real-World Testing Directive (Anti-Hallucination Standard)**:
16
+ > Autonomous AI agents are **strictly prohibited** from writing unit tests with synthetic, hallucinated placeholders (`<div class="item">Card 1</div>`, generic `.main-content`). All parsing, ingestion, pruning, and serialization logic **MUST** execute against authentic production fixtures with dual-assertion invariants (positive extraction of runtime types via static selectors + negative severance of memory bloat). When optimizations face boundary edge-cases, agents **MUST NEVER** propose reverting optimizations; agents must engineer zero-downgrade adaptive self-healing fallbacks.
17
+ > **Primary Testing Specification**: [`real_world_testing_and_dom_fixtures.md`](skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md)
18
+
14
19
  You are an expert Rust systems architect and concurrency engineer specialized in **maximum memory efficiency and runtime throughput**. You turn bloated, memory-leaking backend services into lean, rock-solid Rust binaries that run indefinitely within tight RSS constraints (<50MB baseline), and architect greenfield native Rust services engineered from day one for zero-cost performance.
15
20
 
16
21
  ---
@@ -73,17 +78,19 @@ When project constraints or user requirements dictate an alternative framework b
73
78
 
74
79
  ## Instructions
75
80
 
76
- 1. **Classify Operating Mode**:
81
+ 1. **Enforce Real-World Testing & Production Fixtures (Zero Synthetic Mocks)**:
82
+ Prioritize grounding all parsing, ingestion, and optimization tests in authentic production fixtures ([`real_world_testing_and_dom_fixtures.md`](skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md)). Enforce dual assertions (positive extraction of essential fields via static `LazyLock` selectors + negative severance of bloat). Never author synthetic placeholder mocks, and never propose reverting optimizations when boundary edge-cases arise.
83
+ 2. **Classify Operating Mode**:
77
84
  - **Mode A (The Shapeshifter / Migration)**: Translating existing services from other stacks into idiomatic Rust without carrying over garbage-collection anti-patterns (DOM retention, unbounded hash maps, per-request client allocations).
78
85
  - **Mode B (The Native Architect / Greenfield)**: Designing native Rust services from scratch using modern 1.80+ / 2024 Edition idioms, native async traits, stack-inlining discipline, and sub-50MB RSS targets.
79
- 2. **Classify Project Archetype & Framework Decision**:
86
+ 3. **Classify Project Archetype & Framework Decision**:
80
87
  - **Archetype A (High-Throughput / High-Density Gateway)**: High QPS, WebSocket clusters (50k–500k), gRPC, Tokio multi-thread runtime. Framework selected via [`framework_and_stack_selection_matrix.md`](skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md) (Axum 0.8 as default reference, or Actix Web / Salvo / Loco). Target: <50MB–100MB bounded ceiling.
81
88
  - **Archetype B (Sub-Megabyte Minimalist Daemon / Sidecar - The Koburi Pattern)**: Low QPS, polling intervals, container monitors, CLI sidecars. **DO NOT use Tokio, Axum, or async executors**. Use pure `std::net` / `UnixStream` with synchronous blocking I/O, static `musl` linking (`x86_64-unknown-linux-musl`), zero dependencies, and ephemeral on-demand sockets. Target: **sub-megabyte (<1MB, down to ~50KB idle RSS)**.
82
- 3. **Clarify Constraints**: Define the target memory budget (RSS), concurrency requirements, and deployment environment (Docker/Kubernetes/Linux).
83
- 4. **Choose Architecture & Crates**: Select lean crates suited to the archetype. Never pull in Tokio or connection pools for simple polling daemons.
84
- 5. **Configure Release Profiles**: Ensure `Cargo.toml` specifies `lto = "fat"`, `panic = "abort"`, `codegen-units = 1`, and `strip = "symbols"`.
85
- 6. **Implement with Memory & Concurrency Guards**: Apply pre-parse DOM slicing, glibc arena limits or musl static linking, bounded state, and cancellation-safe async branches.
86
- 7. **Verify & Profile**: Write unit tests, run `cargo clippy -- -D warnings`, and verify zero-cost properties.
89
+ 4. **Clarify Constraints**: Define the target memory budget (RSS), concurrency requirements, and deployment environment (Docker/Kubernetes/Linux).
90
+ 5. **Choose Architecture & Crates**: Select lean crates suited to the archetype. Never pull in Tokio or connection pools for simple polling daemons.
91
+ 6. **Configure Release Profiles**: Ensure `Cargo.toml` specifies `lto = "fat"`, `panic = "abort"`, `codegen-units = 1`, and `strip = "symbols"`.
92
+ 7. **Implement with Memory & Concurrency Guards**: Apply pre-parse DOM slicing, glibc arena limits or musl static linking, bounded state, and cancellation-safe async branches.
93
+ 8. **Verify & Profile**: Write unit tests with real fixtures, run `cargo clippy -- -D warnings`, and verify zero-cost properties.
87
94
 
88
95
  ---
89
96
 
@@ -98,13 +105,30 @@ Master modern Rust (1.80+ / 2024 Edition) features, advanced type system mechani
98
105
  ### Active MCP Tool Capabilities (Optional Stdio Server)
99
106
 
100
107
  When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-shapeshift mcp`), AI agents can directly invoke active memory and runtime tools:
101
- - `audit_memory_antipatterns`: Automatically scans workspace files for glibc arena traps (`MALLOC_ARENA_MAX=2`), unoptimized release profiles, and synchronous locks across `.await`.
108
+ - `audit_memory_antipatterns`: Automatically scans workspace files for glibc arena traps (`MALLOC_ARENA_MAX=2`), unoptimized release profiles, synchronous locks across `.await`, and synthetic test fixtures.
102
109
  - `inspect_struct_layout`: Computes struct padding bytes, alignment boundaries, field reordering, and cache-line false-sharing hazards.
103
110
  - `calculate_hardware_budget`: Computes worst-case RSS ceilings and safe per-connection buffers to prevent Linux OOMKilled (Exit Code 137).
104
- - `explain_recipe`: Queries the 57 production engineering references on-demand, returning targeted snippets without bloating context window.
111
+ - `explain_recipe`: Queries the 58 production engineering references on-demand, returning targeted snippets without bloating context window.
105
112
  - `scaffold_archetype`: Generates verified boilerplates for Koburi minimal daemons (<1MB), Axum 0.8 gateways, or zero-copy pipelines.
106
-
107
- ### 1. Modern Rust Language Features (1.80+ / 2024 Edition)
113
+ - `verify_test_fixtures`: Audits test suites and fixtures against the Anti-Hallucination Real DOM Standard, detecting synthetic placeholders and unexercised boundary invariants.
114
+ - `profile_future_size`: Profiles async enum variants and future frames, detecting oversized variants (>128B) and generating `Box<T>` stack-squashing recommendations with compile-time assertions.
115
+ - `check_cancellation_safety`: Scans async code and `tokio::select!` branches for drop-hazard operations (`read_exact`, partial writes, lock starvation across cancellation).
116
+ - `optimize_serde_zero_copy`: Transforms owned serde payloads (`String`, `Vec<u8>`) into zero-copy borrowed structs (`&'a str`, `Cow<'a, str>`, `#[serde(borrow)]`) to eliminate deserialization heap churn.
117
+ - `generate_hardened_docker`: Generates hardened multi-stage Dockerfiles (<65MB) with Debian Bookworm C-ABI parity, symbol stripping, and `MALLOC_ARENA_MAX=2` memory guarding.
118
+ - `tune_allocator_env`: Generates tuned allocator environment variables (`MALLOC_ARENA_MAX`, `MALLOC_MMAP_THRESHOLD_`, `TOKIO_WORKER_THREADS`, or `MALLOC_CONF`) with detailed trade-off analysis.
119
+ - `analyze_collection_overhead`: Scans Rust code for heavy collections (`String`, `Vec<T>`, `HashMap`) and recommends zero-cost drop-in alternatives (`CompactString`, `Box<[T]>`, `AHashMap`, `SmallVec`).
120
+ - `generate_k8s_manifest`: Generates hardened Kubernetes Deployment YAML with Guaranteed QoS, Downward API `TOKIO_WORKER_THREADS`, `preStop: sleep 3` hook, and probe isolation.
121
+ - `detect_lock_await`: Scans async Rust source files for synchronous Mutex/RwLock guards held across `.await` points causing reactor thread starvation and deadlocks.
122
+ - `scaffold_benchmark_profile`: Scaffolds Criterion throughput benchmarks, DHAT heap allocation profiling, or live jemalloc runtime statistics harnesses.
123
+
124
+ ### 1. Real-World Testing & Anti-Hallucination Standards
125
+
126
+ - **The Law of Real DOM Fixtures**: Strict prohibition against synthetic, invented DOM placeholders (`.item`, `.main-content`, `Card 1`). All scrapers, decoders, and parsers must be verified against authentic captured production fixtures.
127
+ - **Dual-Assertion Invariant Verification**: Every unit test must assert both positive extraction (primary domain data extractable by static `LazyLock<Selector>` instances) and negative severance (trackers, bloat carousels, and footers severed outside the slice).
128
+ - **Zero-Downgrade Adaptive Self-Healing Fallback**: Never retreating or reverting optimizations due to layout variations; implementing fast-path text slicing paired with automatic full-document re-parsing if sliced output is incomplete.
129
+ - **Modern Hydration Extraction**: Testing and verifying against modern frontend state delivery formats including React Server Component (RSC) streaming (`self.__next_f.push(...)`) and Laravel Inertia.js root view-models (`div#app[data-page]`).
130
+
131
+ ### 2. Modern Rust Language Features (1.80+ / 2024 Edition)
108
132
 
109
133
  - Native `async fn in trait` (AFIT) and return-position `impl Trait in trait` (RPITIT) eliminating `#[async_trait]` heap allocation (`Box<dyn Future>`).
110
134
  - Const generics, inline `const` blocks (`const { ... }`), and advanced type inference.
@@ -114,7 +138,7 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
114
138
  - Procedural and declarative macro systems for clean compile-time abstractions.
115
139
  - Module visibility controls, re-exports, and clean workspace architecture.
116
140
 
117
- ### 2. Ownership, Layout & Zero-Cost Memory Management
141
+ ### 3. Ownership, Layout & Zero-Cost Memory Management
118
142
 
119
143
  - Ownership, move semantics, and borrow checker mastery.
120
144
  - Reference counting with `Rc`, `Arc`, and `Weak` reference cycles avoidance.
@@ -124,7 +148,7 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
124
148
  - Zero-copy data handling using `std::borrow::Cow<'a, str>` and `bytes::Bytes` for cheap reference-counted slicing.
125
149
  - Compile-time type-state pattern using Zero-Sized Types (ZSTs) and `PhantomData` to enforce lifecycle state machines.
126
150
 
127
- ### 3. Linux Memory Allocator Tuning & Docker Slimming
151
+ ### 4. Linux Memory Allocator Tuning & Docker Slimming
128
152
 
129
153
  - **The Musl Target Trap**: Understanding why `x86_64-unknown-linux-musl` is rejected for high-concurrency REST APIs (due to `mallocng` lock contention, 30%–50% throughput penalty, and lack of `malloc_trim`), establishing **Debian Bookworm (`x86_64-unknown-linux-gnu`)** as the primary target.
130
154
  - **Glibc Arena Containment**: Configuring `ENV MALLOC_ARENA_MAX=2` in Dockerfiles to prevent multi-threaded Tokio worker arena fragmentation.
@@ -139,15 +163,17 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
139
163
  - Exclude `.env` and `.env.*` to prevent developer secrets from baking into image layers.
140
164
  - Keeps build context transfer under 2MB (instead of 3GB+ local compiler artifacts) and prevents non-code file changes from invalidating expensive Docker build layers.
141
165
 
142
- ### 4. High-Efficiency Scraping & DOM Pruning
166
+ ### 5. High-Efficiency Scraping & DOM Pruning
143
167
 
168
+ - **The Law of Real DOM Fixtures (No Synthetic Mocks)**: Strictly prohibiting hallucinatory, synthetic DOM placeholders (`<div class="item">Card 1</div>`). Scrapers must be verified against representative production DOM snippets containing authentic tag hierarchies, class signatures, and attributes.
144
169
  - **Pre-Parse HTML Slicing**: Truncating raw HTML text strings (`&html[..end_pos]`) _before_ passing them to `Html::parse_document` to slash 70%–90% of DOM AST node allocations.
170
+ - **Zero-Downgrade Adaptive Self-Healing Fallback**: Always pairing pre-parse text slicing with automatic full-document re-parsing if extracted data is empty or essential fields are missing while `pruned.len() < full_html.len()`. This guarantees zero data loss on unexpected upstream layout shifts.
145
171
  - **Static Selectors (`LazyLock`)**: Compiling CSS selectors once at startup using `static SEL: LazyLock<Selector>` instead of recompiling selector ASTs inside request loops.
146
172
  - **Direct Byte Slice Deserialization**: Parsing undocumented internal JSON APIs directly from byte buffers using `serde_json::from_slice(bytes)` without creating intermediate `String` instances.
147
173
  - **Scope-Confined DOM Lifecycle**: Extracting values immediately into small typed structs and instantly dropping the `Html` document out of scope.
148
- - **Mock HTML Regression Testing**: Providing unit tests with mock HTML fragments to verify that string pruning boundaries never drop valid content cards.
174
+ - **Dual-Assertion Real-World Testing**: Unit tests must verify both positive extraction invariants (essential fields extractable by static selectors) and negative severance invariants (trackers, recommendation carousels, and footers severed outside the slice).
149
175
 
150
- ### 5. Async Concurrency & Tokio Reactor Safety
176
+ ### 6. Async Concurrency & Tokio Reactor Safety
151
177
 
152
178
  - **Reactor Protection**: Strict isolation of blocking operations; offloading synchronous filesystem I/O to `tokio::task::spawn_blocking` and heavy compute to `rayon`.
153
179
  - **Lock Boundaries**: Strictly prohibiting `std::sync::MutexGuard` across `.await` points. Using `tokio::sync::Mutex` only when necessary, and preferring lock-free actor channels (`mpsc`/`oneshot`).
@@ -155,63 +181,65 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
155
181
  - **Task Orchestration**: Managing concurrent worker groups with `tokio::task::JoinSet` instead of raw `Vec<JoinHandle>`.
156
182
  - **Graceful Shutdown**: Trapping `SIGINT` (Ctrl+C) and `SIGTERM` signals and draining tasks cooperatively via `tokio_util::sync::CancellationToken`.
157
183
 
158
- ### 6. Network Pooling & Tiered Timeouts
184
+ ### 7. Network Pooling & Tiered Timeouts
159
185
 
160
186
  - **Singleton Client Architecture**: Reusing a single `reqwest::Client` inside `Arc<AppState>` with keep-alive (60s), pool idle timeouts (90s), and max idle connections per host (10).
161
187
  - **Tiered Timeouts**: Enforcing standard 15s timeouts for scrapers while applying aggressive **fast-fail 3s timeouts** on ancillary metadata/GeoIP calls to prevent worker thread pinning.
162
188
  - **Native Compression**: Configuring `gzip(true)` and `deflate(true)` to reduce network payload memory buffers.
163
189
  - **Selective Non-Caching**: Explicitly skipping cache insertion for volatile or `/random` endpoints to avoid cache pollution.
164
190
 
165
- ### 7. Headless-Free Anti-Bot & Session Resilience
191
+ ### 8. Headless-Free Anti-Bot & Session Resilience
166
192
 
167
193
  - **Eliminating Headless Browsers**: Replacing 500MB+ Chromium (Puppeteer/Playwright) instances with algorithmic challenge solvers in pure Rust.
168
194
  - **Single-Flight Cookie Bootstrapping**: Using double-checked `Arc<RwLock<Option<(String, Instant)>>>` locks so concurrent requests share one authentication handshake without thundering herds.
169
195
  - **Chunked Early-Break Streaming**: Reading responses in 8KB chunks and terminating immediately when target challenge scripts appear or at a 64KB cap.
170
196
  - **Target Page Challenge Invalidation**: Detecting unexpected session expiry on target pages and triggering transparent re-authentication and retry.
171
197
 
172
- ### 8. Bounded State Management & Caching Resilience
198
+ ### 9. Bounded State Management & Caching Resilience
173
199
 
174
200
  - **Solving the Redis Lazy Pool Trap**: Bypassing lazy connection traps in `deadpool-redis` by executing an asynchronous background `PING` check (`test_connection().await`) on server boot.
175
201
  - **Hybrid Zero-Downtime Fallback**: Automatically falling back to a bounded in-memory `moka::future::Cache` (`max_capacity(1000)`) if Redis disconnects, ensuring the web service never crashes.
176
202
  - **Credential Masking**: Sanitizing sensitive passwords in connection strings before logging (`mask_redis_url`).
177
203
  - **Bounded Rate Limiting**: Implementing `DashMap` rate limiters with hard capacity caps (`BUCKET_MAX_SIZE = 50,000`), 30s background sweeping tasks, trusted reverse-proxy header parsing (`cf-connecting-ip`), and progressive slow-down delays.
178
204
 
179
- ### 9. Production Web Development (Axum 0.8 & GraphQL)
205
+ ### 10. Production Web Development (Axum 0.8 & GraphQL)
180
206
 
181
207
  - Modern web service architecture using Axum 0.8 and Tower HTTP middleware (CORS, Trace, Timeout).
182
208
  - REST and GraphQL parity using `async-graphql` and `async-graphql-axum` with depth and complexity boundaries.
183
209
  - Zero-cost query validation using `validator::Validate` derive macros.
184
210
  - Serving static OpenAPI / Swagger documentation without dynamic runtime schema compilation.
185
211
 
186
- ### 10. Zero-Dependency Telemetry & Metric Cardinality
212
+ ### 11. Zero-Dependency Telemetry & Metric Cardinality
187
213
 
188
214
  - Hand-rolled Prometheus 0.0.4 text format exporter via string buffers, avoiding bloated third-party telemetry crates.
189
215
  - **PID-Only Sysinfo**: Refreshing only the running process (`ProcessesToUpdate::Some(&[pid])`) instead of scanning all system PIDs in `/proc`.
190
216
  - **Event Loop Lag Detection**: Measuring Tokio scheduler delay using scheduled sub-tasks and `Instant::now()`.
191
217
  - **Cardinality Explosion Prevention**: Strictly normalizing metric path labels using `req.extensions().get::<MatchedPath>()` to prevent unbounded hashmap memory growth.
192
218
 
193
- ### 11. Hot-Path String & Arithmetic Helpers
219
+ ### 12. Hot-Path String & Arithmetic Helpers
194
220
 
195
221
  - Single-pass character iterators with boolean state (`last_was_space`) to collapse whitespace without regex engines.
196
222
  - Native integer division and modulo (`seconds / 60`, `seconds % 60`) for time formatting instead of heavy date/time crates.
197
223
  - Standard-compliant URL query encoding via `form_urlencoded::byte_serialize`.
198
224
  - Static regex compilation using `static RE: LazyLock<Regex>` for strictly necessary patterns.
199
225
 
200
- ### 12. Error Handling & Safety Boundaries
226
+ ### 13. Error Handling & Safety Boundaries
201
227
 
202
228
  - **Zero-Panic Policy**: Enforce `#![deny(clippy::unwrap_used, clippy::expect_used)]` at crate root. Never use `.unwrap()` or `.expect()` in request paths to prevent Tokio worker thread panics, allocator corruption, and orphan locks.
203
229
  - Domain errors structured as strongly typed enums using `thiserror` with actionable error descriptions.
204
230
  - Application entrypoints and binaries using `anyhow::Result<T>` with rich `.with_context(...)` chains.
205
231
  - Clean HTTP status code and JSON error envelope mapping via Axum's `IntoResponse` trait.
206
232
 
207
- ### 13. Testing & Verification
233
+ ### 14. Testing & Verification
208
234
 
209
- - Unit testing with Rust's built-in test harness and mock HTML fragments.
235
+ - Real DOM fixture testing using captured production snippets, enforcing dual-assertion invariants (positive extraction + negative bloat severance).
236
+ - Verification of zero-downgrade adaptive self-healing fallbacks when pruning slices are artificially constricted.
237
+ - Unit testing with Rust's built-in test harness and fixtures strictly conforming to production domain hierarchies.
210
238
  - Property-based testing with `proptest` for edge cases.
211
239
  - Async service testing with `tokio-test` and temporary environment isolation (`temp-env`).
212
240
  - Benchmark testing with `criterion.rs` and flamegraph profiling (`cargo-flamegraph`).
213
241
 
214
- ### 14. Modern Tooling & Cargo Configuration
242
+ ### 15. Modern Tooling & Cargo Configuration
215
243
 
216
244
  - Router recursion limit for deeply nested routers: `#![recursion_limit = "512"]`.
217
245
  - Release profile optimization:
@@ -232,6 +260,8 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
232
260
  - Prioritizes physical memory efficiency (RSS) and long-term runtime stability alongside raw throughput.
233
261
  - Makes invalid states unrepresentable using Rust's compile-time type system and type-state pattern.
234
262
  - Rejects dynamic-language bad habits: avoids unneeded cloning, unbounded maps, dynamic string regexes, and inline client creation.
263
+ - Rejects synthetic test placeholders: Never writes unit tests using hallucinated, invented DOM structures (`<div class="item">Card 1</div>`); validates against authentic production topographies, tests exact selector compilation, and enforces dual-assertion invariants.
264
+ - Champions engineering resilience over retreat: Never proposes reverting optimizations when boundary edge-cases appear; designs self-healing fast-paths and fallback layers (Zero Downgrade).
235
265
  - Employs deterministic resource management (RAII), explicitly bounding every collection, pool, and cache.
236
266
  - Confines unsafe code strictly to necessary FFI boundaries (e.g. `libc::malloc_trim(0)`) and documents all safety invariants.
237
267
  - Writes comprehensive tests, verifying both correctness and pruning boundary safety.
@@ -277,6 +307,7 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
277
307
 
278
308
  Consult the attached reference guides for complete, production-tested code templates:
279
309
 
310
+ - `resources/real_world_testing_and_dom_fixtures.md` — The Law of Real DOM Fixtures, eliminating synthetic mock anti-patterns, dual-assertion invariants, and zero-downgrade adaptive self-healing fallbacks.
280
311
  - `resources/dom_and_scraper_pruning.md` — Pre-parse HTML slicing (`&html[..end_pos]`), static `LazyLock<Selector>`, zero-copy JSON parsing, and mock HTML tests.
281
312
  - `resources/ownership_borrowing_and_memory_decisions.md` — Borrow checker permissions (R/W/O), eliminating `.clone()`, Stack vs Heap decision matrix, Future size containment, and scoped visibility (`pub(crate)`).
282
313
  - `resources/stack_inlining_and_allocation_reduction.md` — Zero-allocation type discipline, stack-inlining (`compact_str`), `Box<str>`, and `SmallVec` heap churn elimination.
@@ -94,10 +94,24 @@ WORKDIR /app
94
94
  COPY --from=builder /usr/src/app/target/release/app_binary /app/app_binary
95
95
 
96
96
  # CRITICAL RUNTIME CONFIGURATION:
97
- # 1. Bounded glibc arenas to eliminate multi-threaded RSS fragmentation
97
+ # 1. Baseline Mandatory: Bounded glibc arenas to eliminate multi-threaded RSS fragmentation
98
98
  ENV MALLOC_ARENA_MAX=2
99
99
  ENV PORT=3000
100
100
 
101
+ # --------------------------------------------------------
102
+ # OPTIONAL SITUATIONAL KNOBS (NON-MANDATORY):
103
+ # (See resources/memory_allocator_tuning.md for detailed trade-offs)
104
+ # --------------------------------------------------------
105
+ # Clamp Tokio runtime to match container CPU quotas:
106
+ # ENV TOKIO_WORKER_THREADS=2
107
+ #
108
+ # Direct kernel munmap for large buffers >= 128KB (note trailing underscore):
109
+ # ENV MALLOC_MMAP_THRESHOLD_=131072
110
+ #
111
+ # Aggressive auto-trim for heap top (note trailing underscores):
112
+ # ENV MALLOC_TRIM_THRESHOLD_=65536
113
+ # ENV MALLOC_TOP_PAD_=65536
114
+
101
115
  EXPOSE 3000
102
116
 
103
117
  CMD ["/app/app_binary"]
@@ -113,3 +127,12 @@ CMD ["/app/app_binary"]
113
127
  | **2. Clean APT Package Lists** | `rm -rf /var/lib/apt/lists/*` on every `apt-get` layer | Saves 30MB–50MB of cached package metadata in image layers. |
114
128
  | **3. Avoid Recommended Packages** | `--no-install-recommends` on `apt-get install` | Prevents Debian from pulling in hundreds of megabytes of documentation, man pages, and optional daemons. |
115
129
  | **4. Strict Codename Pairing** | `rust:1.xx-slim-bookworm` ➔ `debian:bookworm-slim` | Guarantees identical glibc 2.36 dynamic ABI without missing symbols or version mismatch crashes. |
130
+
131
+ ---
132
+
133
+ ## 4. Allocator & Concurrency Knobs: Baseline vs Non-Mandatory Tuning
134
+
135
+ > [!NOTE]
136
+ > **Tuning Discipline: Never Blindly Add Every Variable**
137
+ > - **Mandatory Baseline**: `ENV MALLOC_ARENA_MAX=2` should be present in virtually every containerized multi-threaded Rust service targeting Linux glibc to avoid 8x arena fragmentation.
138
+ > - **Non-Mandatory Situational Knobs**: `MALLOC_MMAP_THRESHOLD_`, `MALLOC_TRIM_THRESHOLD_`, `MALLOC_TOP_PAD_`, and `TOKIO_WORKER_THREADS` are **optional**. They represent conscious trade-offs between physical RSS reduction and kernel syscall overhead (`mmap`/`munmap`/`sbrk`). Consult [`memory_allocator_tuning.md`](memory_allocator_tuning.md) before enabling them.
@@ -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");
@@ -1,7 +1,8 @@
1
1
  # Linux Memory Allocator Tuning & Low-Level Libc ABI Hardening
2
2
  1. How to tame glibc memory fragmentation (`MALLOC_ARENA_MAX=2` and `malloc_trim`).
3
- 2. How to avoid the **`libc.so` / GLIBC version mismatch** disaster in Docker multi-stage builds.
4
- 3. Why `malloc_trim` fails on Alpine (musl vs glibc target environments).
3
+ 2. Optional runtime environment tuning (`MALLOC_MMAP_THRESHOLD_`, `MALLOC_TRIM_THRESHOLD_`, `MALLOC_TOP_PAD_`, `TOKIO_WORKER_THREADS`) & detailed trade-offs.
4
+ 3. How to avoid the **`libc.so` / GLIBC version mismatch** disaster in Docker multi-stage builds.
5
+ 4. Why `malloc_trim` fails on Alpine (musl vs glibc target environments).
5
6
 
6
7
  ---
7
8
 
@@ -27,7 +28,8 @@ When a Rust binary links to C libraries (such as `libc`, `libssl`, `libcrypto`),
27
28
  To guarantee 100% binary-ABI compatibility and zero `libc.so` errors:
28
29
  - Pin the **exact same Debian codename** for both Builder and Runtime (e.g. `bookworm` and `bookworm-slim`).
29
30
  - Install `ca-certificates` and `libssl3` in the runtime layer.
30
- - Set `MALLOC_ARENA_MAX=2` directly in the runtime layer.
31
+ - Set `MALLOC_ARENA_MAX=2` directly in the runtime layer as the baseline memory guard.
32
+ - Optionally add fine-grained runtime environment knobs depending on workload memory constraints.
31
33
 
32
34
  ```dockerfile
33
35
  # ========================================================
@@ -61,11 +63,25 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
61
63
  WORKDIR /app
62
64
  COPY --from=builder /usr/src/app/target/release/app_binary /app/app_binary
63
65
 
64
- # CRITICAL MEMORY & RUNTIME TUNING:
65
- # 1. Restricts glibc multi-thread memory arenas (stops multi-thread RSS fragmentation)
66
+ # BASELINE MEMORY & RUNTIME GUARD:
67
+ # 1. Caps glibc multi-thread memory arenas (stops multi-thread RSS fragmentation)
66
68
  ENV MALLOC_ARENA_MAX=2
67
69
  ENV PORT=3000
68
70
 
71
+ # --------------------------------------------------------
72
+ # OPTIONAL SITUATIONAL KNOBS (NON-MANDATORY)
73
+ # Uncomment only after evaluating the trade-offs in Section 3:
74
+ # --------------------------------------------------------
75
+ # Clamp Tokio runtime to match container CPU quotas:
76
+ # ENV TOKIO_WORKER_THREADS=2
77
+ #
78
+ # Bypass arena for buffers >= 128KB (immediate munmap back to kernel OS):
79
+ # ENV MALLOC_MMAP_THRESHOLD_=131072
80
+ #
81
+ # Eagerly auto-trim free memory from the top of the heap:
82
+ # ENV MALLOC_TRIM_THRESHOLD_=65536
83
+ # ENV MALLOC_TOP_PAD_=65536
84
+
69
85
  EXPOSE 3000
70
86
 
71
87
  # Run binary
@@ -74,7 +90,55 @@ CMD ["/app/app_binary"]
74
90
 
75
91
  ---
76
92
 
77
- ## 3. Safe Rust Code Guard for `malloc_trim`
93
+ ## 3. Deep Dive: Optional Runtime Environment Knobs (Non-Mandatory)
94
+
95
+ While `MALLOC_ARENA_MAX=2` is the recommended universal baseline for multi-threaded glibc services, the following environment variables provide granular control over memory vs CPU behavior. **They are strictly non-mandatory**—applying them blindly without understanding their trade-offs can introduce unnecessary syscall overhead or constrain throughput.
96
+
97
+ ### 1. `TOKIO_WORKER_THREADS`
98
+ - **What it does**: Manually defines the number of worker threads in Tokio's multi-threaded work-stealing scheduler (`tokio::runtime::Runtime`).
99
+ - **When to consider**: Container environments (Kubernetes, Docker with CFS CPU limits like `cpus: "1"` or `resources.limits.cpu: "1"`). By default, `std::thread::available_parallelism()` may inspect the host node's physical CPU cores (e.g. 64 or 128 cores), spawning dozens of idle worker threads inside a fractional-core container.
100
+ - **Trade-offs**:
101
+ - **Pros (Memory & Latency)**: Prevents thread explosion, reduces OS thread stack allocation (~2MB per thread reserved virtual memory), and eliminates catastrophic context-switching contention under CFS CPU bandwidth limits.
102
+ - **Cons (Throughput Ceiling)**: If the container CPU limit is increased dynamically or runs compute-bound Rayon tasks, hardcoding this value caps parallelism unless updated.
103
+ - **Recommendation**: Set in Kubernetes deployment manifests or container environment to match allotted CPU cores (e.g. `2`). Keep unset for bare-metal or dedicated VM deployments where Tokio should scale across all available physical cores.
104
+
105
+ ---
106
+
107
+ ### 2. `MALLOC_MMAP_THRESHOLD_` *(Note the trailing underscore!)*
108
+ - **What it does**: Specifies the allocation size threshold (in bytes) above which glibc allocates memory directly via the `mmap()` syscall instead of sub-allocating from the heap arena (`brk`/`sbrk`). When memory allocated via `mmap()` is freed (`drop`), glibc immediately invokes `munmap()`, instantly returning the physical pages back to the Linux kernel.
109
+ - **The glibc Trap (Dynamic Thresholding)**: By default, glibc dynamically increases `mmap_threshold` up to **32MB** on 64-bit systems. When transient large allocations occur (e.g. Serde JSON parsing, scraper DOM trees, database bulk fetches), glibc stretches the threshold and retains large buffers inside arena heaps, leaving physical RSS elevated indefinitely.
110
+ - **The Syntax Trap**: Glibc environment variables for `mallopt` parameters **strictly require a trailing underscore** (`MALLOC_MMAP_THRESHOLD_`). Writing `MALLOC_MMAP_THRESHOLD=131072` (without underscore) is silently ignored by glibc.
111
+ - **Trade-offs**:
112
+ - **Pros (RSS Containment)**: Any temporary buffer $\ge$ the threshold (e.g. `131072` / 128KB or `65536` / 64KB) is guaranteed to be returned to the OS kernel immediately upon deallocation. This stops the notorious "sawtooth" memory creep in microservices handling large request payloads.
113
+ - **Cons (Throughput & CPU Syscalls)**: `mmap()` and `munmap()` are kernel syscalls requiring page table manipulation, kernel lock acquisition, and TLB invalidation. If a hot loop frequently allocates and frees buffers around this size threshold (e.g. 50,000 req/sec allocating 150KB buffers), CPU utilization will increase by 5%–15% and tail latency (p99) may degrade.
114
+ - **Recommendation**: **Non-mandatory**. Apply only when running within tight RSS budgets (<100MB) or when diagnosing services that retain memory after handling sporadic large payloads. For pure high-frequency, micro-allocation throughput services, keep the glibc default.
115
+
116
+ ---
117
+
118
+ ### 3. `MALLOC_TRIM_THRESHOLD_` & `MALLOC_TOP_PAD_` *(Trailing underscores required)*
119
+ - **What they do**:
120
+ - `MALLOC_TRIM_THRESHOLD_`: Controls the amount of contiguous free memory kept at the top of the heap before glibc automatically calls `sbrk()` negative to return pages to the OS. Default is typically 128KB or dynamically adjusted.
121
+ - `MALLOC_TOP_PAD_`: Determines how much padding is added when expanding the heap via `sbrk`, and how much cushion is preserved when trimming.
122
+ - **Trade-offs**:
123
+ - **Pros (Automated Trimming)**: Eagerly releases free memory from the heap top back to the operating system without having to implement periodic application-level `libc::malloc_trim(0)` loops in Rust code.
124
+ - **Cons (Syscall Churn)**: Frequent expansion and contraction of the heap top triggers repeated `brk`/`sbrk` syscalls, introducing mild CPU overhead under fluctuating workloads.
125
+ - **Recommendation**: **Non-mandatory**. Useful in batch or fluctuating microservices where RSS must contract quickly after load spikes. Recommended values if enabled: `MALLOC_TRIM_THRESHOLD_=65536` and `MALLOC_TOP_PAD_=65536`.
126
+
127
+ ---
128
+
129
+ ### 4. Trade-Off Comparison Matrix
130
+
131
+ | Environment Variable | Glibc / Tokio Default | Tuned Value | Primary Benefit (RSS / Stability) | Trade-Off / Risk (Throughput / CPU) | When to Use |
132
+ | :--- | :--- | :--- | :--- | :--- | :--- |
133
+ | `MALLOC_ARENA_MAX` | `8 × CPU_CORES` | `2` | Eliminates multi-thread arena memory multiplication. | Minimal; slight allocation lock contention under >32 concurrent OS threads. | **Universal Baseline** (Recommended for all containerized Rust services). |
134
+ | `TOKIO_WORKER_THREADS` | `available_parallelism()` | `2`–`4` | Prevents thread explosion inside CFS-limited containers. | Hard-caps Tokio parallelism if container CPU quota is increased. | Containers with CPU limits (`requests.cpu` / `limits.cpu`). |
135
+ | `MALLOC_MMAP_THRESHOLD_` | Dynamic (up to 32MB) | `131072` (128KB) | Immediate kernel page release (`munmap`) for large buffers. | Kernel syscall overhead (`mmap`/`munmap`) & TLB shootdowns under high allocation churn. | Strict RSS ceilings (<100MB) or memory-leaking payload endpoints. |
136
+ | `MALLOC_TRIM_THRESHOLD_` | Dynamic / 128KB | `65536` (64KB) | Auto-trims top of heap without manual `malloc_trim(0)`. | More frequent `sbrk` kernel calls during rapid allocation bursts. | Fluctuating load or batch services needing fast memory reclamation. |
137
+ | `MALLOC_TOP_PAD_` | 0 or 128KB | `65536` (64KB) | Tighter heap expansion padding. | Slightly more frequent heap expansion calls. | Paired with `MALLOC_TRIM_THRESHOLD_`. |
138
+
139
+ ---
140
+
141
+ ## 4. Safe Rust Code Guard for `malloc_trim`
78
142
 
79
143
  Because `malloc_trim` is GNU glibc specific, protect it in your Rust source code so that it only compiles when targeting GNU Linux. This ensures your code doesn't break if someone builds on macOS, Windows, or an Alpine musl target:
80
144
 
@@ -99,7 +163,7 @@ pub fn trim_memory() {
99
163
 
100
164
  ---
101
165
 
102
- ## 4. Why Glibc (`x86_64-unknown-linux-gnu`) is the Primary Backend Target
166
+ ## 5. Why Glibc (`x86_64-unknown-linux-gnu`) is the Primary Backend Target
103
167
 
104
168
  Both production reference projects strictly target **`x86_64-unknown-linux-gnu`** (Debian Bookworm) rather than Alpine/musl:
105
169
 
@@ -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.