repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

chore(pi): testing, benchmarking, and data-oriented skills live in the project

a39233868614b1d7e0e87ffa60e73fc0736a244a

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (8)

+343 / −0 text lines

Diff layout

.pi/skills/benchmarking/SKILL.md

Added
new file mode 100644

+55 / −0 text lines

1---
2name: benchmarking
3description: "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."
4---
5
6# Benchmarking
7
8Measure the question, not the machine.
9
10## Pick the signal
12| question | signal | tool |
13|---|---|---|
14| does this path allocate more | allocation count, bytes | counting allocator in a test |
15| did this change do more work | instructions, est. cycles, cache hits | callgrind via `gungraun`, one shot, deterministic |
16| is A faster than B on this box | wall clock | `criterion` (lib), `hyperfine` (binary), same machine, same session |
17| where does the time go | profile | `perf stat -d`, `perf record` + flamegraph, `callgrind_annotate` |
18| is the type or record too big | size | `size_of` assertion |
20Wall clock answers "faster here, now"; instructions answer "less work"; only the second travels between machines.
22## Compare fairly
24- A/B on one machine, one session, back to back; interleave runs; nothing else running.
25- Same toolchain, same profile, same inputs; name baselines by change id (`--save-baseline <change>`), never `before`.
26- Warm up; report median and spread; a difference inside the spread is no difference.
27- Inputs at the sizes the spec names, and one size larger than fits in cache.
28- `black_box` inputs and outputs; check the loop was not optimized away.
30## Keep only what reproduces
32- Commit: instruction budgets with a tolerance band, allocation counts, size assertions.
33- Never commit wall-clock numbers; put them in a report or a commit message with the machine named.
34- A budget moves only by a deliberate commit that says why (toolchain, layout, algorithm).
35- An improvement beyond the band fails too until re-pinned; a pin that drifts down silently was never a pin.
37## Read the result
39- Fewer instructions but more time: memory-bound; look at cache misses and layout before code.
40- Fewer cache misses but more time: unpacking cost ate the win; drop the encoding.
41- Callgrind counts exclude wall-clock effects (I/O waits, contention, frequency scaling); pair with one wall-clock run before believing a win.
42- Binary benches include process start-up; that is the measurement for `--help`, noise for everything else.
44## Do not
46- Benchmark in CI for wall clock; CI containers share cores and vary by an order of magnitude.
47- Optimize before the profile names the hot path.
48- Add a benchmark without the spec sentence or bound it proves.
50## Sources
52- [gungraun guide](https://gungraun.github.io/gungraun/)
53- [criterion user guide](https://bheisler.github.io/criterion.rs/book/)
54- [The Rust Performance Book: benchmarking and profiling](https://nnethercote.github.io/perf-book/benchmarking.html)
55- [hyperfine](https://github.com/sharkdp/hyperfine)

.pi/skills/data-oriented-rust/SKILL.md

Added
new file mode 100644

+66 / −0 text lines

1---
2name: data-oriented-rust
3description: "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."
4---
5
6# Data-oriented Rust
7
8Memory is the cost; the CPU is free.
9Shape data for how it is accessed, not for how it is named.
11## Trigger
13- 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.
14- Choosing between `Vec`, arena, map, tree, linked structure.
15- Any loop over more than a cache's worth of records.
17## Before shaping
191. Name the access pattern: which fields, in which order, how many instances, how often.
202. Compute size and alignment by hand, then check with `size_of` (or `-Zprint-type-sizes` on nightly).
21 Alignment is the largest field's; size rounds up to it; every `bool` in a padded struct costs a word.
223. Say which lifetime group owns the data (process, session, turn, frame, request).
24## Shrink the hot record
26- Indexes (`u32` newtype) instead of pointers and `Box`; halves size, drops alignment to 4, no lifetime infection.
27- Smallest integer that fits; `usize` only at the use site.
28- Booleans and rare fields out of band: partition into two arrays, or a side table keyed by index for sparse data.
29- Box the one oversized enum variant; enum size is the largest variant plus tag.
30- Frozen `Vec` → `Box<[T]>`; often-empty `Vec` inside a hot type → `ThinVec`.
31- `Arc<str>` | `Arc<[T]>`, never `Arc<String>` | `Arc<Vec<T>>`.
32- Niches are free: `Option<NonZeroU32>`, `Option<&T>`, `Option<Box<T>>` add no bytes.
33- Types over 128 bytes are copied by `memcpy`; keep hot records under one or two cache lines.
35## Choose the layout
37- Contiguous `Vec<T>` beats any pointer structure for iteration; linked lists and `Vec<Box<T>>` lose an order of magnitude.
38- Record-at-a-time access → array of structs.
39 Field-at-a-time hot loops → struct of arrays (one `Vec` per field; `soa-rs` when a derive earns it).
40- Tag checked inside a hot loop → split by variant into separate arrays; the tag becomes which array.
41- Nested `Vec<Vec<T>>` → one flat `Vec<T>` plus offsets.
42- Generic `T` over `dyn Trait` when the loop body vectorizes; `dyn` costs the indirection, not the vtable.
43- 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.
45## Allocate by lifetime
47- One arena per lifetime group; reset wholesale; handles are indexes into it.
48- `with_capacity` from a measured distribution; reuse workhorse collections with `clear()`.
49- `Cow` only at I/O edges; borrow in flight, own at rest.
50- Sharing order: move → `&T` → `Arc<immutable>` → atomic → channel.
51- Per-thread counters that share a cache line false-share; pad with `#[repr(align(64))]` only there.
53## Prove it
55- Size test: `assert_eq!(size_of::<Hot>(), N)` under `#[cfg(target_arch = "x86_64")]`; bounds only tighten.
56- Allocation-count test on the hot path; bounds only tighten.
57- `criterion` plus `perf stat -d` (cache misses, branch misses, instructions per cycle) before and after; a layout win with more instructions can lose.
58- Bit-packing and clever encodings only after a measured cache-miss problem; unpacking in the loop has cost the win before.
60## Do not
62- `#[repr(C)]` without FFI or a measured false-sharing case; it forbids the compiler's field reordering.
63- Shrink cold data; only the most-instantiated types pay back.
64- Trade a readable owned tree for a packed stream without the benchmark that demands it.
66Facts, numbers, and sources: [references/techniques.md](references/techniques.md).

.pi/skills/data-oriented-rust/references/techniques.md

Added
new file mode 100644

+71 / −0 text lines

1# Techniques and evidence
2
3Durable facts behind `SKILL.md`, each with its source.
4Numbers are from the cited measurements; rerun on the target machine before relying on them.
5
6## Cost model
7
8- 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]
9- 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]
10- Arithmetic, including multiplication, is faster than an L1 read; recomputing can beat memoizing. [Kelley]
11- A heap allocation typically takes a global lock and may reach a kernel call; small allocations are not cheaper than large ones. [perf-book]
12- 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]
14## Layout rules (Rust)
16- rustc reorders struct and enum fields to minimize padding unless `#[repr(C)]` is set. [perf-book]
17- 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]
18- Enum size is the largest variant plus discriminant, minus niches; one outsized variant inflates every value; box it when rare. [perf-book]
19- Types larger than 128 bytes are moved with `memcpy` rather than inline code. [perf-book]
20- `Vec` is three words (ptr, len, cap); `Box<[T]>` is two; `ThinVec` is one with len and cap in the allocation. [perf-book]
21- `-Zprint-type-sizes` (nightly) prints size, alignment, per-variant sizes, field order, and padding; `top-type-sizes` compacts the output. [perf-book]
22- Guard hot types with a static size assertion under `#[cfg(target_arch = "x86_64")]`; sizes differ per platform. [perf-book]
24## Shrinking strategies
26- 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]
27- 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]
28- 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]
29- 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]
30- Small integers for indexes (`u8`, `u16`, `u32`) and coercion to `usize` at use points. [perf-book]
31- `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]
32- `smallstr` | `smartstring` (`compact_str` is the same idea) inline strings under 24 bytes. [perf-book]
33- Measure the length distribution at a hot `push` site before choosing capacity or inline size. [perf-book]
35## Access-pattern layout
37- 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]
38- Branch on a kind tag inside a hot loop vs pre-split arrays per kind: about 4× faster split. [jamesmcm]
39- `LinkedList` vs `Vec` iteration: about 10× faster `Vec`. [jamesmcm]
40- `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]
41- `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]
42- 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]
43- 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]
44- Inlining is the root optimization; `#[inline(always)]` on tiny arithmetic newtype methods gave 30 % when rustc declined to inline. [gendignoux]
46## Allocation and sharing
48- `Rc`/`Arc` on rarely shared values raises allocation rate; `clone` of `Arc` is a count increment, `clone` of `Vec` is an allocation. [perf-book]
49- `clone_from` reuses the destination allocation. [perf-book]
50- Workhorse collections: declare outside the loop, `clear()` per iteration; or keep one in the struct. [perf-book]
51- `BufRead::lines` allocates per line; `read_line` into one reused `String` does not. [perf-book]
52- `Cow<'static, str>` holds literals and formatted strings in one `Vec` without promoting literals. [perf-book]
53- 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]
54- DHAT identifies hot allocation sites; `dhat-rs` heap-usage tests pin allocation counts so they cannot regress. [perf-book]
56## Tools
58- `std::mem::size_of`, `-Zprint-type-sizes`, `top-type-sizes`, `static_assertions::assert_eq_size!`.
59- `criterion` for benchmarks; `perf stat -d` for cycles, IPC, branch misses, L1/LLC misses; `perf record` + flamegraph for where.
60- `cargo-show-asm` or Godbolt to confirm vectorization.
61- `soa-rs` | `soa_derive` for derived struct-of-arrays; `slotmap` | `id-arena` when generational handles are needed; plain `Vec` + `u32` newtype otherwise.
63## Sources
65- [Kelley] Andrew Kelley, "A Practical Guide to Applying Data Oriented Design", Handmade Seattle 2021; transcript at josherich.me.
66- [jamesmcm] James McMurray, "An introduction to Data Oriented Design with Rust", 2020, with criterion benchmarks and Godbolt links.
67- [gendignoux] Guillaume Endignoux, "Making a parallel Rust workload even faster with data-oriented design (and a sprinkle of unsafe)", 2024, with `perf stat` output.
68- [mnt.io] Ivan Enderlin, "About memory pressure, lock contention, and Data-oriented Design", 2026, Matrix Rust SDK room list.
69- [perf-book] Nicholas Nethercote, "The Rust Performance Book", chapters "Type Sizes" and "Heap Allocations".
70- [Weissflog] Andre Weissflog, "Handles are the better pointers", 2018.
71- [Fabian] Richard Fabian, "Data-Oriented Design" (dataorienteddesign.com/dodbook), the long form.

.pi/skills/deflake/SKILL.md

Added
new file mode 100644

+31 / −0 text lines

1---
2name: deflake
3description: "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."
4---
5
6# Deflake
7
8A flaky test is a bug with a random error message.
9
10## Find the wait
12- `sleep`, `poll until`, `retries = N`, `recv()` without timeout, "give it a moment" comments.
13- Timing assertions with tight margins on shared CI machines.
15## Replace it
17- Time-dependent logic → inject a clock or an instant; the test sets it.
18- "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.
19- Ordering between threads → a channel handoff or a barrier, not a sleep.
20- Real socket or process fixtures → keep, but every read carries a deadline and the assertion is on order and content, not on elapsed time.
21- Elapsed-time assertions → assert a bound with a wide margin only where time is the contract (timeouts); otherwise drop them.
23## Rules
25- Retries are never the fix.
26- Run the test in a loop (`--test-threads` high, 20 iterations) before calling it fixed.
27- If the flake is in the code under test, that is the real finding; fix it there.
29## Sources
31- [nextest: flaky tests and retries](https://nexte.st/docs/features/retries/)

.pi/skills/e2e-binary/SKILL.md

Added
new file mode 100644

+29 / −0 text lines

1---
2name: e2e-binary
3description: "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."
4---
5
6# End to end through the binary
7
8One workflow, one test, the real executable.
9
10## Shape
12- Spawn the built binary (`assert_cmd`); never call library fns from an e2e test.
13- Isolate: own temp dir per test, `XDG_*` pointed at it, every credential and selection env var removed, then set only what the scenario needs.
14- Real inputs: files on disk, a loopback socket, stdin bytes; providers scripted (`--mock` or a fixture server), never live.
15- Assert outcomes a user sees: exit status, stdout, stderr wording, files left behind, permissions. Not internals.
16- Name the test after the workflow: `eval_json_reports_cost`, `rpc_abort_ends_the_running_prompt`.
17- RPC: drive stdin line by line, read stdout until the expected `event`, then close stdin and assert clean exit.
19## Rules
21- Every user-visible workflow has exactly one e2e owner; unit tests cover the branches.
22- No sleeps; wait on output with a deadline.
23- Secrets never appear in stdout, stderr, or files; assert their absence.
24- Keep e2e binaries in their own tier (`e2e_*`); they are slower and run per push.
26## Sources
28- [assert_cmd](https://docs.rs/assert_cmd), [predicates](https://docs.rs/predicates)
29- [nextest filtersets](https://nexte.st/docs/filtersets/)

.pi/skills/property-testing/SKILL.md

Added
new file mode 100644

+33 / −0 text lines

1---
2name: property-testing
3description: "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."
4---
5
6# Property testing
7
8A law over all inputs beats ten examples.
9
10## Laws worth stating
12- roundtrip: `decode(encode(x)) == x`
13- idempotence: `f(f(x)) == f(x)`
14- order independence: `f(shuffle(x)) == f(x)`
15- bound: `len(compress(x)) <= len(x) + header`
16- invariant: after any operation sequence, the structure still validates
18## Shape
20- One property per law; the name is the law.
21- Strategies from the domain: build valid values by construction, not by filtering; filter only for rare exclusions.
22- Keep the default case count small enough for the commit tier; raise it via `PROPTEST_CASES` in nightly.
23- Check in the `proptest-regressions/` file; a shrunk counterexample is a permanent test.
24- When a property fails, add the shrunk input as a plain example test too; it reads better in a diff.
26## Do not
28- Re-implement the function inside the property; assert relations, not values.
29- Property-test I/O, time, or randomness sources; those are behavior tests with injected inputs.
31## Sources
33- [proptest book](https://proptest-rs.github.io/proptest/)

.pi/skills/regression-first/SKILL.md

Added
new file mode 100644

+32 / −0 text lines

1---
2name: regression-first
3description: "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."
4---
5
6# Regression first
7
8The test is the claim; the fix is the proof.
9
10## Bug
121. Reproduce in a test at the smallest boundary that shows the symptom.
132. Run it: it must fail for the reported reason, not for a setup error.
143. Fix. Run again. Green.
154. The test stays with the name of the symptom, not the fix.
17## Refactor
191. Find the tests that already pin the behavior you will touch; run them.
202. No test pins it → write one against the current behavior before editing.
213. Refactor. The pinned tests do not change; if one must, the refactor changed behavior: stop and say so.
23## Security
251. Encode the boundary as a test: what must never cross (secret in output, path outside root, unauthorized call).
262. It fails on the vulnerable code, holds after the fix, and stays as the guard.
28## Rules
30- RED before GREEN, every time; a test that never failed proves nothing.
31- One symptom, one test; no drive-by assertions.
32- Never weaken an existing assertion to make a change pass.

.pi/skills/snapshot-testing/SKILL.md

Added
new file mode 100644

+26 / −0 text lines

1---
2name: snapshot-testing
3description: "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."
4---
5
6# Snapshot testing
7
8The snapshot is documentation that fails when it lies.
9
10## Shape
12- One snapshot per rendered surface; name it after the surface and state (`help_top_level`, `rpc_prompt_then_abort`).
13- Redact identity and time before snapshotting (ids, timestamps, paths, versions); a snapshot that changes every run is noise.
14- Use structured snapshots (`assert_json_snapshot!`, `assert_yaml_snapshot!`) for data; string snapshots for text people read.
15- Review every changed snapshot as code: `cargo insta review` or read the `.snap.new` diff; accept only what the change intended.
16- Snapshots live next to the test in `snapshots/`; commit them.
18## Do not
20- `INSTA_UPDATE=always` in CI or in a blind local run.
21- Snapshot volatile or huge output; cut to the part under test.
22- Use a snapshot where an assertion states the intent better.
24## Sources
26- [insta docs](https://insta.rs/docs/)