From f08f38df3c0420cddbfac7ddcf6bb1dc6a4d5267 Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Tue, 17 Nov 2026 10:18:26 +0000 Subject: [PATCH 1/3] Add a write_zipper benchmark for movement over shared nodes A WriteZipper clones every node it descends into that has another owner, even when it never writes. No existing benchmark exercises this: none of them moves a WriteZipper through shared nodes. shared_descend_to_* runs the same 16 descents, 15 nodes deep, as a ReadZipper, as a WriteZipper over nodes it owns, and as a WriteZipper over the same trie with every node shared, sweeping the width of the nodes passed through from 1 to 256. Nothing writes to the trie. On a Xeon 6975P-C at width 256 the shared WriteZipper takes 381 us against 4.15 us owned and 3.2 us for the ReadZipper; at width 1 it is 0.73 us against 0.41 us and 0.28 us. The owned and read cases stay flat in width. Co-Authored-By: Claude Fable 5.2 --- Cargo.toml | 4 ++ benches/write_zipper.rs | 97 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 benches/write_zipper.rs diff --git a/Cargo.toml b/Cargo.toml index 8b9d32cf..859b8b5d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -146,6 +146,10 @@ harness = false name = "restrict" harness = false +[[bench]] +name = "write_zipper" +harness = false + [[bench]] name = "act_paths" harness = false diff --git a/benches/write_zipper.rs b/benches/write_zipper.rs new file mode 100644 index 00000000..6bac6103 --- /dev/null +++ b/benches/write_zipper.rs @@ -0,0 +1,97 @@ +//! WriteZipper benchmarks +//! +//! # Movement over nodes the zipper doesn't own (`shared_descend_to_*`) +//! +//! Moving a zipper doesn't change the trie, so a WriteZipper that only moves should cost about what a +//! ReadZipper does. Over shared nodes it costs far more: the WriteZipper holds a stack of mutable +//! node references and takes each one with `make_mut`, which clones a node that has another owner. +//! Descending into a cloned map or a grafted subtrie therefore copies every node on the way down, +//! before anything is written and even if nothing ever is. See "Scouting write zipper" in the book. +//! +//! The same descents are run three ways: +//! - `rz`: a ReadZipper, the baseline +//! - `wz_owned`: a WriteZipper over nodes it owns, which is what its movement costs without clones +//! - `wz_shared`: a WriteZipper over the same trie when every node has another owner +//! +//! The argument is the width of the nodes the zipper passes through. A ReadZipper doesn't care how +//! wide a node is, and neither does a WriteZipper that owns it, but a clone costs the node's width. +//! So `wz_shared` ought to match `wz_owned` and stay flat; the gap between them is the cost of the +//! clones. Nothing writes to the trie in any of the three. +//! +//! Descents are the movement that shows this. A walk over a whole shared trie copies all of it, but +//! it visits every child of a node it cloned, which hides the cost of the clone. + +use divan::{Bencher, Divan, black_box}; +use pathmap::PathMap; +use pathmap::zipper::*; +use rand::{Rng, SeedableRng, rngs::StdRng}; + +fn main() { + Divan::from_args().main(); +} + +const BRANCHING: [usize; 5] = [1, 4, 16, 64, 256]; +const SPINES: usize = 16; +const DEPTH: usize = 16; + +/// `SPINES` random paths of `DEPTH` bytes that start with distinct bytes and end in a value. Each +/// step of a path after the first has `branching - 1` siblings, and each sibling leads to a node of +/// its own, like the children in the upper levels of a big trie do. From a `branching` of 4 up, +/// each path crosses `DEPTH - 1` nodes below the root +fn spine_trie(branching: usize) -> (PathMap, Vec>) { + let mut rng = StdRng::seed_from_u64(1); + let mut map = PathMap::new(); + let mut paths = Vec::with_capacity(SPINES); + for i in 0..SPINES { + let mut path = vec![(i * (256 / SPINES)) as u8]; + path.extend((1..DEPTH).map(|_| rng.random::())); + map.set_val_at(&path, 0); + for depth in 1..DEPTH { + let mut sibling = path[..=depth].to_vec(); + sibling.extend([0, 0]); + for t in 1..branching { + sibling[depth] = path[depth].wrapping_add(t as u8); + map.set_val_at(&sibling, 0); + } + } + paths.push(path); + } + (map, paths) +} + +/// Descends from the root to the end of each path +fn descend_to_each(z: &mut Z, paths: &[Vec]) -> usize { + let mut found = 0; + for path in paths { + z.descend_to(path); + found += z.is_val() as usize; + z.reset(); + } + assert_eq!(found, paths.len()); + found +} + +#[divan::bench(args = BRANCHING)] +fn shared_descend_to_rz(bencher: Bencher, branching: usize) { + let (map, paths) = spine_trie(branching); + bencher.bench_local(|| descend_to_each(&mut black_box(&map).read_zipper(), &paths)); +} + +#[divan::bench(args = BRANCHING)] +fn shared_descend_to_wz_owned(bencher: Bencher, branching: usize) { + let (mut map, paths) = spine_trie(branching); + bencher.bench_local(|| descend_to_each(&mut black_box(&mut map).write_zipper(), &paths)); +} + +/// The first descent through shared nodes leaves the map it went through owning a private copy of +/// them, so every run gets a fresh handle to the shared trie, which is a refcount bump on the root +/// made outside the timing. The run returns its handle so that freeing the copies isn't timed +/// either: what is measured is the movement plus allocating and filling the clones. +#[divan::bench(args = BRANCHING)] +fn shared_descend_to_wz_shared(bencher: Bencher, branching: usize) { + let (map, paths) = spine_trie(branching); + bencher.with_inputs(|| map.clone()).bench_local_values(|mut map| { + black_box(descend_to_each(&mut map.write_zipper(), &paths)); + map + }); +} From 5d7bf77de2ecca9eecad0c3b293bf7f958e6b391 Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Tue, 17 Nov 2026 13:43:48 +0000 Subject: [PATCH 2/3] Add write_zipper benchmarks for writes below shared nodes shared_set_val_* runs the descents of shared_descend_to_*, each followed by set_val at the end of the path, as a WriteZipper over nodes it owns and over the same trie with every node shared. Here the clones are needed, so this is the cost that movement over shared nodes should not have. It also guards the other side of that trade: a WriteZipper that stops cloning on the way down has to walk the shared part of its path again when it writes, and these cases show what that costs. Co-Authored-By: Claude Fable 5.2 --- benches/write_zipper.rs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/benches/write_zipper.rs b/benches/write_zipper.rs index 6bac6103..309153c7 100644 --- a/benches/write_zipper.rs +++ b/benches/write_zipper.rs @@ -20,6 +20,13 @@ //! //! Descents are the movement that shows this. A walk over a whole shared trie copies all of it, but //! it visits every child of a node it cloned, which hides the cost of the clone. +//! +//! # Writes below nodes the zipper doesn't own (`shared_set_val_*`) +//! +//! The same descents, each followed by setting the value at the end of the path. Here the clones +//! are needed: `wz_shared` copies every node on each path, and `wz_owned` copies none. This is the +//! cost that `shared_descend_to_wz_shared` shouldn't have. It is here so that a change to how a +//! WriteZipper moves over shared nodes also shows what it does to the write that follows. use divan::{Bencher, Divan, black_box}; use pathmap::PathMap; @@ -95,3 +102,32 @@ fn shared_descend_to_wz_shared(bencher: Bencher, branching: usize) { map }); } + +/// Descends from the root to the end of each path, and sets the value there +fn set_val_at_each>(z: &mut Z, paths: &[Vec]) -> usize { + let mut replaced = 0; + for path in paths { + z.descend_to(path); + replaced += z.set_val(1).is_some() as usize; + z.reset(); + } + assert_eq!(replaced, paths.len()); + replaced +} + +#[divan::bench(args = BRANCHING)] +fn shared_set_val_wz_owned(bencher: Bencher, branching: usize) { + let (mut map, paths) = spine_trie(branching); + bencher.bench_local(|| set_val_at_each(&mut black_box(&mut map).write_zipper(), &paths)); +} + +/// As in [shared_descend_to_wz_shared], every run gets a fresh handle to the shared trie and hands +/// it back, so the timing covers the movement, the clones and the writes, but not freeing the clones +#[divan::bench(args = BRANCHING)] +fn shared_set_val_wz_shared(bencher: Bencher, branching: usize) { + let (map, paths) = spine_trie(branching); + bencher.with_inputs(|| map.clone()).bench_local_values(|mut map| { + black_box(set_val_at_each(&mut map.write_zipper(), &paths)); + map + }); +} From b7d2bb7b84fbc48f5b83cb6bbc41a8e57e3fec7d Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Tue, 17 Nov 2026 13:59:52 +0000 Subject: [PATCH 3/3] CI bench: run every single-core divan bench, and benches a PR adds The default set gains write_zipper, graft_masked_branches, restrict, prune, oeis, byte_mask, serde and pointcloud, which the bench job did not run. parallel, sla and multiplicities stay out; the comment on DEFAULT_BENCHES says why. bench_ab.py required every bench target to exist at base and at head, so a PR that adds a bench could not have it run. A target that only head has now runs for head alone and its numbers are reported without a comparison; one that only base has is skipped. A target that neither side has is still an error. Several of the added benches finish in under a second, which exposes a bias in how a pair is run: the side that goes first starts on an idle core and measures its first cases up to 50% slower (prune_path: 141 ns against 92 ns for the same binary run right after). Each pair now starts with a half-second spin on its core. Co-Authored-By: Claude Fable 5.2 --- .github/scripts/bench_ab.py | 93 +++++++++++++++++++++++++++++++------ 1 file changed, 78 insertions(+), 15 deletions(-) diff --git a/.github/scripts/bench_ab.py b/.github/scripts/bench_ab.py index 191548b9..31002090 100755 --- a/.github/scripts/bench_ab.py +++ b/.github/scripts/bench_ab.py @@ -8,7 +8,8 @@ target dirs changes crate hashes and code layout, which alone moved cases by 5-25% in an A/A run. Then runs them for ROUNDS rounds. Benches run in parallel, each on its own core from BENCH_CPUS (the base and head runs of a bench share that core, back -to back, alternating which side goes first each round). As soon as both +to back, alternating which side goes first each round, after a short spin to +bring the core up to speed). As soon as both sides of a bench have run in a round, its compare table (per-round divan medians averaged over the rounds finished so far, via benches/divan_fmt.py) is printed and saved as $BENCH_OUT/cmp-.txt; $BENCH_OUT/compare.txt, the concatenation, is @@ -17,10 +18,14 @@ pr_comment.py posts to the PR) and summary.json. Progress lines go to $BENCH_OUT/progress.txt. +A bench target that only HEAD has (one the change adds) is run for HEAD alone +and its numbers are reported without a comparison; one that only BASE has is +skipped. A target that neither side has is an error. + usage: bench_ab.py env: BENCH_ROUNDS rounds per side (default 3) - BENCHES space separated bench targets (default: the set used in BENCH_BUGFIXES) + BENCHES space separated bench targets (default: DEFAULT_BENCHES below) BENCH_CPUS cores to pin to, e.g. "0,2,4-8"; one bench pair runs per core at a time (default: one SMT thread per physical core, every other core, at most 16) BENCH_OUT output directory (default ./bench-out) @@ -32,7 +37,11 @@ from pathlib import Path from queue import Queue -DEFAULT_BENCHES = 'shakespeare cities sparse_keys binary_keys superdense_keys act_paths zipper_head_owned product_zipper' +# Every divan bench that runs on one core. Left out: `parallel` (its cases spawn up to 256 threads, +# and each bench here is pinned to one core), and `sla` and `multiplicities` (plain `main`s that +# print no divan table). +DEFAULT_BENCHES = ('shakespeare cities sparse_keys binary_keys superdense_keys act_paths zipper_head_owned product_zipper ' + 'write_zipper graft_masked_branches restrict prune oeis byte_mask serde pointcloud') THRESH = 0.05 # a case is listed in the summary when |change| exceeds this @@ -74,8 +83,8 @@ def __init__(self, base, head): self.out = Path(os.environ.get('BENCH_OUT', self.repo / 'bench-out')).resolve() self.target = Path(os.environ.get('CARGO_TARGET_DIR', self.repo / 'target')).resolve() self.src = self.out / 'src' # one worktree for both sides - self.bins = {} - self.results = {} # bench -> {'group/case': {'base': ns, 'head': ns, 'pct': float}} + self.bins = {} # side -> {bench: executable}, for the requested benches that side has + self.results = {} # bench -> {'group/case': {'base': ns, 'head': ns, 'pct': float}}; 'head' alone for a new bench os.environ.setdefault('DIVAN_SAMPLE_COUNT', '40') sys.path.insert(0, str(self.repo / 'benches')) import divan_fmt @@ -92,6 +101,11 @@ def cleanup(self): subprocess.run(['git', 'worktree', 'remove', '--force', str(self.src)], cwd=self.repo, capture_output=True) + def bench_targets(self, src): + """The requested benches that the tree at `src` has: declared in Cargo.toml, or a file cargo discovers.""" + declared = {b.get('name') for b in tomllib.loads((src / 'Cargo.toml').read_text()).get('bench', [])} + return [b for b in self.benches if b in declared or (src / 'benches' / f'{b}.rs').is_file()] + def required_features(self, src): """Features the requested benches declare via required-features, limited to those the tree has.""" t = tomllib.loads((src / 'Cargo.toml').read_text()) @@ -106,12 +120,17 @@ def build_side(self, side, sha): """Check `sha` out in the shared worktree, build, and copy the bench executables to bins//.""" src = self.src git('checkout', '--detach', '-f', sha, cwd=src) + benches = self.bench_targets(src) + self.bins[side] = {} + if not benches: + log(f'== {side} ({self.short(sha)}) has none of the requested benches') + return feats = self.required_features(src) target = self.target / 'ab' log(f'== building {side} ({self.short(sha)}) in {src} into {target}' + (f' with features {",".join(feats)}' if feats else '')) cmd = ['cargo', 'bench', '--no-run', '--message-format=json', '--target-dir', str(target)] - for b in self.benches: + for b in benches: cmd += ['--bench', b] if feats: cmd += ['--features', ','.join(feats)] @@ -124,16 +143,15 @@ def build_side(self, side, sha): m = json.loads(line) if m.get('reason') == 'compiler-artifact' and m.get('executable') and 'bench' in m['target']['kind']: exes[m['target']['name']] = m['executable'] - missing = [b for b in self.benches if b not in exes] + missing = [b for b in benches if b not in exes] if missing: sys.exit(f'no executable for bench(es) {missing} on {side}') bindir = self.out / 'bins' / side bindir.mkdir(parents=True, exist_ok=True) - self.bins[side] = {} - for b in self.benches: + for b in benches: shutil.copy2(exes[b], bindir / b) self.bins[side][b] = str(bindir / b) - (self.out / f'bins-{side}.txt').write_text(''.join(f'{b} {exes[b]}\n' for b in self.benches)) + (self.out / f'bins-{side}.txt').write_text(''.join(f'{b} {exes[b]}\n' for b in benches)) def run(self, side, bench, rnd, cpu): t0 = time.time() @@ -142,11 +160,22 @@ def run(self, side, bench, rnd, cpu): cwd=self.repo, stdout=out, stderr=err, check=True) self.progress(f'round {rnd}/{self.rounds} {bench} {side} {time.time() - t0:.0f}s cpu {cpu}') + def warm_up(self, cpu, seconds=0.5): + """Spin on `cpu` so that it has left its idle state and is at speed when the first side starts. + On a cold core the side that goes first measures its first cases up to 50% slower, and a + bench that is over in under a second has no later samples to make up for it.""" + spin = f'import time\nt = time.perf_counter()\nwhile time.perf_counter() - t < {seconds}: pass' + subprocess.run(['taskset', '-c', str(cpu), sys.executable, '-c', spin], check=True) + def run_pair(self, bench, rnd, free): - """Both sides of one bench, back to back on one core taken from the pool, then its compare table.""" + """Both sides of one bench, back to back on one core taken from the pool, then its compare table. + A bench that base lacks runs for head alone.""" cpu = free.get() try: + self.warm_up(cpu) for side in (('base', 'head') if rnd % 2 else ('head', 'base')): + if bench not in self.bins[side]: + continue with self.lock: log(f'== round {rnd}/{self.rounds} {bench} {side} (cpu {cpu})') self.run(side, bench, rnd, cpu) @@ -158,10 +187,21 @@ def compare_bench(self, bench, rounds_so_far): """Average each side's rounds so far, compare medians, save and print the table.""" avg = {} for side in ('base', 'head'): + if bench not in self.bins[side]: + continue files = sorted(self.out.glob(f'{side}-{bench}-r*.txt')) data = [self.fmt.parse_divan_output(f.read_text()) for f in files] avg[side] = self.fmt.average_fields(data) (self.out / f'{side}-{bench}-avg.txt').write_text(self.fmt.render_divan_table(avg[side]) + '\n') + if 'base' not in avg: + # a bench the change adds: nothing to compare against, so report what it measures + self.results[bench] = {f'{g}/{c}': {'head': r['median_ns']} for (g, c), r in avg['head'].items()} + text = (f'{bench} (new in head {self.short(self.head_sha)}, not in base {self.short(self.base_sha)}' + f' rounds {rounds_so_far})\n{self.fmt.render_divan_table(avg["head"])}\n\n') + (self.out / f'cmp-{bench}.txt').write_text(text) + with self.lock: + log(text, end='') + return cmp = self.fmt.compare_fields(avg['base'], avg['head'], 'median_ns') self.results[bench] = {f'{g}/{c}': {'base': r['base'], 'head': r['other'], 'pct': r['pct']} for (g, c), r in cmp.items()} table = re.sub(r'\x1b\[[0-9;]*m', '', self.fmt.render_divan_table(cmp)) @@ -178,7 +218,7 @@ def compare_bench(self, bench, rounds_so_far): def compare_rounds(self, rounds_so_far): tmp = self.out / 'compare.tmp' - tmp.write_text(''.join((self.out / f'cmp-{b}.txt').read_text() for b in self.benches)) + tmp.write_text(''.join((self.out / f'cmp-{b}.txt').read_text() for b in self.benches if b in self.bins['head'])) tmp.rename(self.out / 'compare.txt') (self.out / 'summary.json').write_text(json.dumps( {'base': self.short(self.base_sha), 'head': self.short(self.head_sha), 'rounds': rounds_so_far, @@ -193,9 +233,16 @@ def pct(v): f'median of each run averaged; negative is faster', '', '| bench | cases | geomean | largest gain | largest loss | >5% faster | >5% slower |', '|---|---:|---:|---|---|---:|---:|'] - movers = [] + movers, added = [], [] for b in self.benches: cases = self.results.get(b, {}) + if b not in self.bins['head']: + L.append(f'| {b} | | not in head, skipped | | | | |') + continue + if b not in self.bins['base']: + L.append(f'| {b} | {len(cases)} | new in head | | | | |') + added += [(b, name, r) for name, r in cases.items()] + continue if not cases: L.append(f'| {b} | 0 | | | | | |') continue @@ -217,6 +264,13 @@ def pct(v): if len(movers) > 60: L.append(f'| | … and {len(movers) - 60} more, see compare.txt in the bench-out artifact | | | |') L += ['', ''] + if added: + L += ['', f'
{len(added)} case(s) of benches new in head', '', + '| bench | case | head |', '|---|---|---:|'] + L += [f'| {b} | `{name}` | {self.fmt.format_ns(r["head"])} |' for b, name, r in added[:60]] + if len(added) > 60: + L.append(f'| | … and {len(added) - 60} more, see compare.txt in the bench-out artifact | |') + L += ['', '
'] L += ['', 'Full tables per bench are in the job log and the bench-out artifact.'] return '\n'.join(L) + '\n' @@ -235,12 +289,21 @@ def main(self): self.build_side('base', self.base_sha) self.progress(f'building head {self.short(self.head_sha)}') self.build_side('head', self.head_sha) + unknown = [b for b in self.benches if b not in self.bins['base'] and b not in self.bins['head']] + if unknown: + sys.exit(f'no bench target named {" ".join(unknown)} at base or head') + runs = [b for b in self.benches if b in self.bins['head']] + for b in self.benches: + if b not in self.bins['base']: + self.progress(f'{b} is new in head: running head alone') + elif b not in self.bins['head']: + self.progress(f'{b} is not in head: skipped') free = Queue() for cpu in self.cpus: free.put(cpu) for rnd in range(1, self.rounds + 1): - with ThreadPoolExecutor(min(len(self.cpus), len(self.benches))) as pool: - for r in pool.map(lambda b: self.run_pair(b, rnd, free), self.benches): + with ThreadPoolExecutor(max(1, min(len(self.cpus), len(runs)))) as pool: + for r in pool.map(lambda b: self.run_pair(b, rnd, free), runs): pass # re-raises a worker's exception self.compare_rounds(rnd) self.progress(f'round {rnd}/{self.rounds} done, compare.txt refreshed')