chore(pi): testing, benchmarking, and data-oriented skills live in the project
a39233868614b1d7e0e87ffa60e73fc0736a244a
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: bb32860e4b56
There are many coding harnesses - but this one is fast
a39233868614b1d7e0e87ffa60e73fc0736a244a
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+343 / −0 text lines
new file mode 100644+55 / −0 text lines
---name: benchmarkingdescription: "Use before claiming or chasing a performance difference, choosing between two implementations, layouts, or allocators, or pinning a performance budget: pick the signal that answers the question, compare fairly, and keep only what is reproducible."---# BenchmarkingMeasure the question, not the machine.## Pick the signal| question | signal | tool ||---|---|---|| does this path allocate more | allocation count, bytes | counting allocator in a test || did this change do more work | instructions, est. cycles, cache hits | callgrind via `gungraun`, one shot, deterministic || is A faster than B on this box | wall clock | `criterion` (lib), `hyperfine` (binary), same machine, same session || where does the time go | profile | `perf stat -d`, `perf record` + flamegraph, `callgrind_annotate` || is the type or record too big | size | `size_of` assertion |Wall clock answers "faster here, now"; instructions answer "less work"; only the second travels between machines.## Compare fairly- A/B on one machine, one session, back to back; interleave runs; nothing else running.- Same toolchain, same profile, same inputs; name baselines by change id (`--save-baseline <change>`), never `before`.- Warm up; report median and spread; a difference inside the spread is no difference.- Inputs at the sizes the spec names, and one size larger than fits in cache.- `black_box` inputs and outputs; check the loop was not optimized away.## Keep only what reproduces- Commit: instruction budgets with a tolerance band, allocation counts, size assertions.- Never commit wall-clock numbers; put them in a report or a commit message with the machine named.- A budget moves only by a deliberate commit that says why (toolchain, layout, algorithm).- An improvement beyond the band fails too until re-pinned; a pin that drifts down silently was never a pin.## Read the result- Fewer instructions but more time: memory-bound; look at cache misses and layout before code.- Fewer cache misses but more time: unpacking cost ate the win; drop the encoding.- Callgrind counts exclude wall-clock effects (I/O waits, contention, frequency scaling); pair with one wall-clock run before believing a win.- Binary benches include process start-up; that is the measurement for `--help`, noise for everything else.## Do not- Benchmark in CI for wall clock; CI containers share cores and vary by an order of magnitude.- Optimize before the profile names the hot path.- Add a benchmark without the spec sentence or bound it proves.## Sources- [gungraun guide](https://gungraun.github.io/gungraun/)- [criterion user guide](https://bheisler.github.io/criterion.rs/book/)- [The Rust Performance Book: benchmarking and profiling](https://nnethercote.github.io/perf-book/benchmarking.html)- [hyperfine](https://github.com/sharkdp/hyperfine)new file mode 100644+66 / −0 text lines
---name: data-oriented-rustdescription: "Use whenever a Rust struct, enum, collection, arena, or hot loop's data shape is written or edited: choose layout for cache lines and allocation count, then prove it with size and allocation tests."---# Data-oriented RustMemory is the cost; the CPU is free.Shape data for how it is accessed, not for how it is named.## Trigger- New or edited `struct` | `enum` | container field | `Box` | `Arc` | `Vec<Vec<_>>` | `HashMap` on a type with many instances or on a per-frame, per-turn, per-request path.- Choosing between `Vec`, arena, map, tree, linked structure.- Any loop over more than a cache's worth of records.## Before shaping1. Name the access pattern: which fields, in which order, how many instances, how often.2. Compute size and alignment by hand, then check with `size_of` (or `-Zprint-type-sizes` on nightly). Alignment is the largest field's; size rounds up to it; every `bool` in a padded struct costs a word.3. Say which lifetime group owns the data (process, session, turn, frame, request).## Shrink the hot record- Indexes (`u32` newtype) instead of pointers and `Box`; halves size, drops alignment to 4, no lifetime infection.- Smallest integer that fits; `usize` only at the use site.- Booleans and rare fields out of band: partition into two arrays, or a side table keyed by index for sparse data.- Box the one oversized enum variant; enum size is the largest variant plus tag.- Frozen `Vec` → `Box<[T]>`; often-empty `Vec` inside a hot type → `ThinVec`.- `Arc<str>` | `Arc<[T]>`, never `Arc<String>` | `Arc<Vec<T>>`.- Niches are free: `Option<NonZeroU32>`, `Option<&T>`, `Option<Box<T>>` add no bytes.- Types over 128 bytes are copied by `memcpy`; keep hot records under one or two cache lines.## Choose the layout- Contiguous `Vec<T>` beats any pointer structure for iteration; linked lists and `Vec<Box<T>>` lose an order of magnitude.- Record-at-a-time access → array of structs. Field-at-a-time hot loops → struct of arrays (one `Vec` per field; `soa-rs` when a derive earns it).- Tag checked inside a hot loop → split by variant into separate arrays; the tag becomes which array.- Nested `Vec<Vec<T>>` → one flat `Vec<T>` plus offsets.- Generic `T` over `dyn Trait` when the loop body vectorizes; `dyn` costs the indirection, not the vtable.- Sort or group for locality and branch prediction; after sorting owned pointers, rebuild into fresh contiguous storage or an arena so the heap order matches.## Allocate by lifetime- One arena per lifetime group; reset wholesale; handles are indexes into it.- `with_capacity` from a measured distribution; reuse workhorse collections with `clear()`.- `Cow` only at I/O edges; borrow in flight, own at rest.- Sharing order: move → `&T` → `Arc<immutable>` → atomic → channel.- Per-thread counters that share a cache line false-share; pad with `#[repr(align(64))]` only there.## Prove it- Size test: `assert_eq!(size_of::<Hot>(), N)` under `#[cfg(target_arch = "x86_64")]`; bounds only tighten.- Allocation-count test on the hot path; bounds only tighten.- `criterion` plus `perf stat -d` (cache misses, branch misses, instructions per cycle) before and after; a layout win with more instructions can lose.- Bit-packing and clever encodings only after a measured cache-miss problem; unpacking in the loop has cost the win before.## Do not- `#[repr(C)]` without FFI or a measured false-sharing case; it forbids the compiler's field reordering.- Shrink cold data; only the most-instantiated types pay back.- Trade a readable owned tree for a packed stream without the benchmark that demands it.Facts, numbers, and sources: [references/techniques.md](references/techniques.md).new file mode 100644+71 / −0 text lines
# Techniques and evidenceDurable facts behind `SKILL.md`, each with its source.Numbers are from the cited measurements; rerun on the target machine before relying on them.## Cost model- Cache line is 64 bytes on common targets (32 or 128 exist); every access goes through one; the question is only whether one gets evicted. [Kelley]- Latency ladder (2020 numbers): L1 ≈ 1 ns, branch mispredict ≈ 3 ns, L2 ≈ 4 ns, mutex lock/unlock ≈ 17 ns, main memory ≈ 100 ns; each level is an order of magnitude. [mnt.io], [Kelley]- Arithmetic, including multiplication, is faster than an L1 read; recomputing can beat memoizing. [Kelley]- A heap allocation typically takes a global lock and may reach a kernel call; small allocations are not cheaper than large ones. [perf-book]- L1 data cache is on the order of 32 KB; hot-loop data that does not fit there is data-bound, and layout work pays only when the workload is data-bound rather than compute-bound. [gendignoux]## Layout rules (Rust)- rustc reorders struct and enum fields to minimize padding unless `#[repr(C)]` is set. [perf-book]- Alignment of a struct is its largest field's alignment; size rounds up to a multiple of it; `u32, u64, u32` is 24 bytes, reordered 16; adding one `bool` to the 16-byte form costs 8 bytes. [Kelley]- Enum size is the largest variant plus discriminant, minus niches; one outsized variant inflates every value; box it when rare. [perf-book]- Types larger than 128 bytes are moved with `memcpy` rather than inline code. [perf-book]- `Vec` is three words (ptr, len, cap); `Box<[T]>` is two; `ThinVec` is one with len and cap in the allocation. [perf-book]- `-Zprint-type-sizes` (nightly) prints size, alignment, per-variant sizes, field order, and padding; `top-type-sizes` compacts the output. [perf-book]- Guard hot types with a static size assertion under `#[cfg(target_arch = "x86_64")]`; sizes differ per platform. [perf-book]## Shrinking strategies- Indexes instead of pointers: 64-bit pointers double a record on 64-bit targets; `u32` indexes halve it and drop alignment to 4, so a following `u32` field costs no padding. Type the index (newtype) or lose the compile-time safety pointers gave. [Kelley], [Weissflog]- Booleans out of band: keep alive and dead in two arrays; the bit lives in which array, the loop over the live array has no branch and no load. 24 → 16 → 12 bytes in the monster example. [Kelley]- Sparse fields in a side table keyed by index: with 10 % of records holding an item list, 366 KB → 198 KB for 10 000 records, overhead included. [Kelley]- Struct of arrays removes per-element padding: a pointer plus a one-byte enum in an array of structs pays 7 bytes of padding per element; as two arrays, none. 160 KB → 91 KB for 10 000 elements. [Kelley]- Small integers for indexes (`u8`, `u16`, `u32`) and coercion to `usize` at use points. [perf-book]- `smallvec` | `arrayvec` for many short vectors; `SmallVec` is slightly slower per operation and larger when `N` or `T` is big; `ArrayVec` when the maximum is known. [perf-book]- `smallstr` | `smartstring` (`compact_str` is the same idea) inline strings under 24 bytes. [perf-book]- Measure the length distribution at a hot `push` site before choosing capacity or inline size. [perf-book]## Access-pattern layout- Struct of arrays vs array of structs: position and velocity update over players ran in half the time as SoA because the loop vectorized over contiguous fields; with the wider target features the gap shrank to the cache-bandwidth difference; set `target-cpu` deliberately for benchmarks and deployment. [jamesmcm]- Branch on a kind tag inside a hot loop vs pre-split arrays per kind: about 4× faster split. [jamesmcm]- `LinkedList` vs `Vec` iteration: about 10× faster `Vec`. [jamesmcm]- `Vec<Box<dyn Trait>>` vs generic `Vec<T>`: about 4× faster monomorphized; `Vec<Box<T>>` monomorphized was nearly as slow as `dyn`, so the cost is the indirection, not the vtable. [jamesmcm]- `Vec<Vec<usize>>` for a 5-element ranked ballot is 216 bytes; flattened to `Box<[u8]>` values plus `Box<[u8]>` cut positions it is 48 bytes and ran up to 20 % faster on a data-bound workload. [gendignoux]- Bit-packing the same data to 3 bytes reduced cache misses and ran ≥ 30 % slower from unpacking cost and forced a GAT-heavy refactor; optimize one metric and others regress. [gendignoux]- Sorting records halved branch misses (16 % fewer cycles) but sorting owned pointers randomizes heap order: 2× L1 misses, 14× L3 misses. Cloning after the sort restored sequential heap order for another 10 %; production code should use an arena rather than rely on allocator order. [gendignoux]- Inlining is the root optimization; `#[inline(always)]` on tiny arithmetic newtype methods gave 30 % when rustc declined to inline. [gendignoux]## Allocation and sharing- `Rc`/`Arc` on rarely shared values raises allocation rate; `clone` of `Arc` is a count increment, `clone` of `Vec` is an allocation. [perf-book]- `clone_from` reuses the destination allocation. [perf-book]- Workhorse collections: declare outside the loop, `clear()` per iteration; or keep one in the struct. [perf-book]- `BufRead::lines` allocates per line; `read_line` into one reused `String` does not. [perf-book]- `Cow<'static, str>` holds literals and formatted strings in one `Vec` without promoting literals. [perf-book]- Cloning a 144-byte value under a read lock inside a comparator produced 322 042 allocations and 743 MiB for one sort of ~600 items, plus lock contention; the fix reads the needed fields into a compact, sortable record once (data-oriented view), then sorts: 98.7 % less time. [mnt.io]- DHAT identifies hot allocation sites; `dhat-rs` heap-usage tests pin allocation counts so they cannot regress. [perf-book]## Tools- `std::mem::size_of`, `-Zprint-type-sizes`, `top-type-sizes`, `static_assertions::assert_eq_size!`.- `criterion` for benchmarks; `perf stat -d` for cycles, IPC, branch misses, L1/LLC misses; `perf record` + flamegraph for where.- `cargo-show-asm` or Godbolt to confirm vectorization.- `soa-rs` | `soa_derive` for derived struct-of-arrays; `slotmap` | `id-arena` when generational handles are needed; plain `Vec` + `u32` newtype otherwise.## Sources- [Kelley] Andrew Kelley, "A Practical Guide to Applying Data Oriented Design", Handmade Seattle 2021; transcript at josherich.me.- [jamesmcm] James McMurray, "An introduction to Data Oriented Design with Rust", 2020, with criterion benchmarks and Godbolt links.- [gendignoux] Guillaume Endignoux, "Making a parallel Rust workload even faster with data-oriented design (and a sprinkle of unsafe)", 2024, with `perf stat` output.- [mnt.io] Ivan Enderlin, "About memory pressure, lock contention, and Data-oriented Design", 2026, Matrix Rust SDK room list.- [perf-book] Nicholas Nethercote, "The Rust Performance Book", chapters "Type Sizes" and "Heap Allocations".- [Weissflog] Andre Weissflog, "Handles are the better pointers", 2018.- [Fabian] Richard Fabian, "Data-Oriented Design" (dataorienteddesign.com/dodbook), the long form.new file mode 100644+31 / −0 text lines
---name: deflakedescription: "Use when a test sleeps, polls, retries, or is intermittently red: replace waiting on wall time with injected time or an explicit signal plus a deadline."---# DeflakeA flaky test is a bug with a random error message.## Find the wait- `sleep`, `poll until`, `retries = N`, `recv()` without timeout, "give it a moment" comments.- Timing assertions with tight margins on shared CI machines.## Replace it- Time-dependent logic → inject a clock or an instant; the test sets it.- "Wait for the system to settle" → the system emits a signal (channel item, atomic flag, end event); the test waits on that with a deadline (`recv_timeout`), never on a duration.- Ordering between threads → a channel handoff or a barrier, not a sleep.- Real socket or process fixtures → keep, but every read carries a deadline and the assertion is on order and content, not on elapsed time.- Elapsed-time assertions → assert a bound with a wide margin only where time is the contract (timeouts); otherwise drop them.## Rules- Retries are never the fix.- Run the test in a loop (`--test-threads` high, 20 iterations) before calling it fixed.- If the flake is in the code under test, that is the real finding; fix it there.## Sources- [nextest: flaky tests and retries](https://nexte.st/docs/features/retries/)new file mode 100644+29 / −0 text lines
---name: e2e-binarydescription: "Use when user-visible behavior of a CLI, eval, or RPC binary is added or changed: prove it end to end through the built binary with real files and sockets."---# End to end through the binaryOne workflow, one test, the real executable.## Shape- Spawn the built binary (`assert_cmd`); never call library fns from an e2e test.- Isolate: own temp dir per test, `XDG_*` pointed at it, every credential and selection env var removed, then set only what the scenario needs.- Real inputs: files on disk, a loopback socket, stdin bytes; providers scripted (`--mock` or a fixture server), never live.- Assert outcomes a user sees: exit status, stdout, stderr wording, files left behind, permissions. Not internals.- Name the test after the workflow: `eval_json_reports_cost`, `rpc_abort_ends_the_running_prompt`.- RPC: drive stdin line by line, read stdout until the expected `event`, then close stdin and assert clean exit.## Rules- Every user-visible workflow has exactly one e2e owner; unit tests cover the branches.- No sleeps; wait on output with a deadline.- Secrets never appear in stdout, stderr, or files; assert their absence.- Keep e2e binaries in their own tier (`e2e_*`); they are slower and run per push.## Sources- [assert_cmd](https://docs.rs/assert_cmd), [predicates](https://docs.rs/predicates)- [nextest filtersets](https://nexte.st/docs/filtersets/)new file mode 100644+33 / −0 text lines
---name: property-testingdescription: "Use when a pure function has a law: roundtrip, idempotence, order independence, monotonic bound, or an invariant over arbitrary input; state it as a proptest property."---# Property testingA law over all inputs beats ten examples.## Laws worth stating- roundtrip: `decode(encode(x)) == x`- idempotence: `f(f(x)) == f(x)`- order independence: `f(shuffle(x)) == f(x)`- bound: `len(compress(x)) <= len(x) + header`- invariant: after any operation sequence, the structure still validates## Shape- One property per law; the name is the law.- Strategies from the domain: build valid values by construction, not by filtering; filter only for rare exclusions.- Keep the default case count small enough for the commit tier; raise it via `PROPTEST_CASES` in nightly.- Check in the `proptest-regressions/` file; a shrunk counterexample is a permanent test.- When a property fails, add the shrunk input as a plain example test too; it reads better in a diff.## Do not- Re-implement the function inside the property; assert relations, not values.- Property-test I/O, time, or randomness sources; those are behavior tests with injected inputs.## Sources- [proptest book](https://proptest-rs.github.io/proptest/)new file mode 100644+32 / −0 text lines
---name: regression-firstdescription: "Use before fixing a bug, starting a refactor, or closing a security finding: write the test that pins the behavior first, watch it fail or hold, then change code."---# Regression firstThe test is the claim; the fix is the proof.## Bug1. Reproduce in a test at the smallest boundary that shows the symptom.2. Run it: it must fail for the reported reason, not for a setup error.3. Fix. Run again. Green.4. The test stays with the name of the symptom, not the fix.## Refactor1. Find the tests that already pin the behavior you will touch; run them.2. No test pins it → write one against the current behavior before editing.3. Refactor. The pinned tests do not change; if one must, the refactor changed behavior: stop and say so.## Security1. Encode the boundary as a test: what must never cross (secret in output, path outside root, unauthorized call).2. It fails on the vulnerable code, holds after the fix, and stays as the guard.## Rules- RED before GREEN, every time; a test that never failed proves nothing.- One symptom, one test; no drive-by assertions.- Never weaken an existing assertion to make a change pass.new file mode 100644+26 / −0 text lines
---name: snapshot-testingdescription: "Use when output is meant for human eyes or a stable wire: rendered frames, JSON lines, help text, traces; pin it with insta and review the diff."---# Snapshot testingThe snapshot is documentation that fails when it lies.## Shape- One snapshot per rendered surface; name it after the surface and state (`help_top_level`, `rpc_prompt_then_abort`).- Redact identity and time before snapshotting (ids, timestamps, paths, versions); a snapshot that changes every run is noise.- Use structured snapshots (`assert_json_snapshot!`, `assert_yaml_snapshot!`) for data; string snapshots for text people read.- Review every changed snapshot as code: `cargo insta review` or read the `.snap.new` diff; accept only what the change intended.- Snapshots live next to the test in `snapshots/`; commit them.## Do not- `INSTA_UPDATE=always` in CI or in a blind local run.- Snapshot volatile or huge output; cut to the part under test.- Use a snapshot where an assertion states the intent better.## Sources- [insta docs](https://insta.rs/docs/)