Elffuss BraidHub

utopia-ia/elffuss-braid public

bceec3f3d91e · 58.0 KiB · executableRawPermalink
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0
3# Copyright (c) 2026 UtopiaIA
4"""Benchmarks braid against git on the same machine.
5
6 python3 bench/run.py # every scenario, full size
7 python3 bench/run.py --quick # small inputs, a smoke run
8 python3 bench/run.py --only status,commit # some scenarios
9
10Every scenario does the same work with braid and with git several times,
11alternating which goes first, and compares the medians as a ratio, braid
12divided by git: below 1 means braid is faster, or smaller. The table goes to
13standard output. The raw measurements go to bench/results/, which is not
14tracked: they describe this machine and stay on it. bench/README.md says
15what each scenario measures.
16
17It needs Python 3.9 or newer (standard library only), git, and cargo, which
18builds braid in release mode first.
19"""
20
21from __future__ import annotations
22
23import argparse
24import datetime
25import json
26import math
27import os
28import platform
29import resource
30import shutil
31import statistics
32import subprocess
33import sys
34import tempfile
35import threading
36import time
37import traceback
38from pathlib import Path
39
40ROOT = Path(__file__).resolve().parent.parent
41RESULTS = ROOT / "bench" / "results"
42
43NAME = "Bench"
44EMAIL = "bench@example.org"
45
46# The medium public repository of the import, store and history scenarios,
47# pinned to one release so that every run imports the same history.
48PINNED = {
49 "url": "https://github.com/tmux/tmux",
50 "ref": "refs/tags/3.5a",
51 "commit": "549c35b06165f6ae023115eb76f83f2cbf945395",
52 "name": "tmux 3.5a",
53}
54
55SCENARIOS = {
56 "import": "import a repository: braid git import against git clone --no-local",
57 "status": "status on a large tree, clean and with files modified",
58 "commit": "commit one changed file in the large tree",
59 "wide": "one new file per commit in a single wide directory",
60 "agents": "N agents landing K commits each, all at once",
61 "store": "store size after the import",
62 "history": "history queries on the imported repository",
63}
64
65FULL = {
66 "import_rounds": 3,
67 "tree_files": 100_000,
68 "modified": 10,
69 "status_rounds": 9,
70 "commit_rounds": 9,
71 "wide_files": 20_000,
72 "wide_commits": 200,
73 "wide_sweep": [2_500, 5_000, 10_000],
74 "wide_sweep_commits": 30,
75 "agents": [4, 8, 16],
76 "agent_commits": 10,
77 "agent_rounds": 3,
78 "history_rounds": 9,
79 "warmup": 2,
80}
81
82QUICK = {
83 "import_rounds": 1,
84 "tree_files": 2_000,
85 "modified": 10,
86 "status_rounds": 2,
87 "commit_rounds": 2,
88 "wide_files": 500,
89 "wide_commits": 6,
90 "wide_sweep": [125, 250],
91 "wide_sweep_commits": 3,
92 "agents": [2, 4],
93 "agent_commits": 3,
94 "agent_rounds": 1,
95 "history_rounds": 2,
96 "warmup": 1,
97}
98
99# Free space the work directory needs, in bytes: the large tree is checked
100# out twice, and every small file takes a whole block.
101NEEDED_SPACE = {"full": 6 << 30, "quick": 1 << 30}
102
103# Files per directory of the large tree.
104FILES_PER_DIR = 25
105
106# A fixed date for the commits the generators make, so that their ids are
107# the same on every run.
108SEED_DATE = "1767225600 +0000"
109
110# Enough for "every changeset" in log queries.
111ALL = "1000000"
112
113
114class Failure(Exception):
115 """A command failed, or a scenario's premise did not hold."""
116
117
118# ---------------------------------------------------------------------------
119# Running and timing commands
120
121
122class Run:
123 """How long a command took, in wall-clock seconds and in CPU seconds
124 (user and system, of the command and its children)."""
125
126 __slots__ = ("wall", "cpu", "code", "out", "err")
127
128 def __init__(self, wall, cpu, code=0, out=b"", err=b""):
129 self.wall = wall
130 self.cpu = cpu
131 self.code = code
132 self.out = out
133 self.err = err
134
135 def __add__(self, other):
136 cpu = None if self.cpu is None or other.cpu is None else self.cpu + other.cpu
137 return Run(self.wall + other.wall, cpu)
138
139 def text(self):
140 return self.out.decode("utf-8", "replace")
141
142 def lines(self):
143 return [line for line in self.text().splitlines() if line.strip()]
144
145 def json(self):
146 return json.loads(self.out)
147
148
149def clean_environment():
150 """The environment every command runs in: no configuration of the
151 user's or the system's git, a fixed identity, and nothing that points
152 git or braid somewhere else."""
153 env = {
154 key: value
155 for key, value in os.environ.items()
156 if not key.startswith(("GIT_", "BRAID_"))
157 }
158 env.update(
159 {
160 "GIT_CONFIG_GLOBAL": os.devnull,
161 "GIT_CONFIG_NOSYSTEM": "1",
162 "GIT_AUTHOR_NAME": NAME,
163 "GIT_AUTHOR_EMAIL": EMAIL,
164 "GIT_COMMITTER_NAME": NAME,
165 "GIT_COMMITTER_EMAIL": EMAIL,
166 "GIT_TERMINAL_PROMPT": "0",
167 "GIT_PAGER": "cat",
168 "PAGER": "cat",
169 "LC_ALL": "C",
170 "BRAID_AUTHOR": f"{NAME} <{EMAIL}>",
171 "BRAID_AGENT": "bench",
172 }
173 )
174 return env
175
176
177def children_cpu():
178 """CPU seconds of every child process that has exited so far."""
179 usage = resource.getrusage(resource.RUSAGE_CHILDREN)
180 return usage.ru_utime + usage.ru_stime
181
182
183class Tools:
184 """Runs braid and git, and times them.
185
186 The CPU time of a run is what the children that exited during it used,
187 so it is only right while one command runs at a time; the agents
188 scenario, which runs many at once, only uses wall time."""
189
190 def __init__(self, braid, git):
191 self.braid = str(braid)
192 self.git = git
193 self.env = clean_environment()
194
195 def run(self, argv, cwd, check=True, capture=False, env=None):
196 argv = [str(arg) for arg in argv]
197 cpu_before = children_cpu()
198 start = time.perf_counter()
199 proc = subprocess.run(
200 argv,
201 cwd=cwd,
202 env=env or self.env,
203 stdin=subprocess.DEVNULL,
204 stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
205 stderr=subprocess.PIPE,
206 )
207 wall = time.perf_counter() - start
208 cpu = children_cpu() - cpu_before
209 if check and proc.returncode != 0:
210 raise Failure(
211 f"`{' '.join(argv[:6])}` exited with {proc.returncode}: "
212 + proc.stderr.decode("utf-8", "replace").strip()[-800:]
213 )
214 return Run(wall, cpu, proc.returncode, proc.stdout or b"", proc.stderr)
215
216 def braid_run(self, cwd, *args, **kwargs):
217 return self.run([self.braid, *args], cwd, **kwargs)
218
219 def git_run(self, cwd, *args, **kwargs):
220 return self.run([self.git, *args], cwd, **kwargs)
221
222
223def round_order(names, round_index):
224 """The order of the contestants in one round, so that a machine growing
225 warmer or its caches filling favour none: A B, then B A, for two
226 (braid, git, git, braid, ...); for more, every rotation of the list and
227 then every rotation of it reversed, so that in each run of len(names)
228 rounds every contestant takes every place once."""
229 names = list(names)
230 if len(names) == 2:
231 return names if round_index % 2 == 0 else names[::-1]
232 cycle = round_index % (2 * len(names))
233 shift = cycle % len(names)
234 order = names[shift:] + names[:shift]
235 return order if cycle < len(names) else order[::-1]
236
237
238class LoadGate:
239 """With --max-load, waits before each timed round until the load average
240 of the last minute drops below the limit, so that on a machine shared
241 with other work the rounds run in its quieter moments. It changes when
242 a round runs, never what it measures."""
243
244 # The longest wait before one round runs anyway, and the longest wait of
245 # a whole run, after which rounds no longer wait, in seconds.
246 PATIENCE = 300
247 BUDGET = 3600
248
249 def __init__(self):
250 self.limit = None
251 self.waited = 0.0
252 self.gave_up = 0
253
254 def wait(self):
255 if self.limit is None or not hasattr(os, "getloadavg"):
256 return
257 start = time.monotonic()
258 while os.getloadavg()[0] >= self.limit:
259 waited = time.monotonic() - start
260 if waited > self.PATIENCE or self.waited + waited > self.BUDGET:
261 self.gave_up += 1
262 break
263 time.sleep(2)
264 self.waited += time.monotonic() - start
265
266
267GATE = LoadGate()
268
269
270def alternate(rounds, contestants, warmup=0):
271 """Runs each contestant `warmup` times untimed, then `rounds` times in
272 alternating order. `contestants` maps a name to a function of the round
273 number that returns a Run. Returns the Runs of each name, by round."""
274 names = list(contestants)
275 for index in range(warmup):
276 for name in round_order(names, index):
277 contestants[name](-1 - index)
278 out = {name: [] for name in names}
279 for index in range(rounds):
280 GATE.wait()
281 for name in round_order(names, index):
282 out[name].append(contestants[name](index))
283 return out
284
285
286# ---------------------------------------------------------------------------
287# Results
288
289
290class Row:
291 """One line of the table: braid against git in one case."""
292
293 def __init__(
294 self,
295 scenario,
296 case,
297 compared,
298 braid=(),
299 git=(),
300 kind="time",
301 note="",
302 skipped="",
303 extra=None,
304 ):
305 self.scenario = scenario
306 self.case = case
307 self.compared = compared
308 self.braid = list(braid)
309 self.git = list(git)
310 self.kind = kind # "time" (Runs), "size" (bytes) or "info"
311 self.note = note
312 self.skipped = skipped
313 self.extra = extra or {}
314
315 def _values(self, side):
316 return [run.wall for run in side] if self.kind == "time" else list(side)
317
318 def ratio(self):
319 if self.skipped or not self.braid or not self.git:
320 return None
321 braid = statistics.median(self._values(self.braid))
322 git = statistics.median(self._values(self.git))
323 return braid / git if git else None
324
325 def spread(self):
326 """The smallest and largest ratio of a single round."""
327 if self.kind != "time" or len(self.braid) != len(self.git) or len(self.braid) < 2:
328 return None
329 ratios = [b.wall / g.wall for b, g in zip(self.braid, self.git) if g.wall]
330 return (min(ratios), max(ratios)) if ratios else None
331
332 def cpu_ratio(self):
333 if self.kind != "time" or self.skipped or not self.braid or not self.git:
334 return None
335 if any(run.cpu is None for run in self.braid + self.git):
336 return None
337 braid = statistics.median(run.cpu for run in self.braid)
338 git = statistics.median(run.cpu for run in self.git)
339 return braid / git if git else None
340
341 def to_json(self):
342 out = {
343 "scenario": self.scenario,
344 "case": self.case,
345 "compared": self.compared,
346 "kind": self.kind,
347 "ratio": self.ratio(),
348 "spread": self.spread(),
349 "cpu_ratio": self.cpu_ratio(),
350 "note": self.note,
351 "skipped": self.skipped or None,
352 "extra": self.extra,
353 }
354 for side, runs in (("braid", self.braid), ("git", self.git)):
355 if self.kind == "time":
356 out[side] = {
357 "wall_seconds": [run.wall for run in runs],
358 "cpu_seconds": [run.cpu for run in runs],
359 "median_wall_seconds": (
360 statistics.median(run.wall for run in runs) if runs else None
361 ),
362 }
363 else:
364 out[side] = runs
365 return out
366
367
368def fmt(value, digits=2):
369 return "-" if value is None else f"{value:.{digits}f}"
370
371
372def print_table(rows, out=sys.stdout):
373 print("", file=out)
374 print("braid / git on this machine: below 1 means braid is faster or smaller.", file=out)
375 print("spread: smallest and largest ratio of a single round; cpu: the same ratio", file=out)
376 print("for CPU time (user and system) instead of wall time.", file=out)
377 print("", file=out)
378 header = f"{'scenario':<8} {'case':<44} {'braid/git':>9} {'spread':>13} {'cpu':>6} note"
379 print(header, file=out)
380 print("-" * len(header), file=out)
381 for row in rows:
382 spread = row.spread()
383 spread_text = f"{spread[0]:.2f}-{spread[1]:.2f}" if spread else "-"
384 if row.skipped:
385 line = (
386 f"{row.scenario:<8} {row.case:<44} {'skipped':>9} {'':>13} {'':>6} "
387 f"{row.skipped}"
388 )
389 else:
390 line = (
391 f"{row.scenario:<8} {row.case:<44} {fmt(row.ratio()):>9} "
392 f"{spread_text:>13} {fmt(row.cpu_ratio()):>6} {row.note}"
393 )
394 print(line.rstrip(), file=out)
395 print("", file=out)
396
397
398def print_markdown(rows, out=sys.stdout):
399 """The table for the README: ratios rounded to one decimal."""
400 print("| What was compared | braid / git | Reproduce |", file=out)
401 print("|---|---|---|", file=out)
402 for row in rows:
403 if row.skipped or row.kind == "info":
404 continue
405 reproduce = f"`python3 bench/run.py --only {row.scenario}`"
406 print(f"| {row.compared} | {row.ratio():.1f} | {reproduce} |", file=out)
407 for row in rows:
408 if row.kind == "info" and row.note:
409 print(f"\n{row.case}: {row.note}", file=out)
410 if row.skipped:
411 print(f"\nNot measured, {row.case}: {row.skipped}", file=out)
412
413
414# ---------------------------------------------------------------------------
415# Generated inputs
416
417
418class SplitMix64:
419 """A small deterministic generator: the same numbers on every platform
420 and Python version."""
421
422 MASK = (1 << 64) - 1
423
424 def __init__(self, seed):
425 self.state = seed & self.MASK
426
427 def next(self):
428 self.state = (self.state + 0x9E3779B97F4A7C15) & self.MASK
429 z = self.state
430 z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & self.MASK
431 z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & self.MASK
432 return z ^ (z >> 31)
433
434
435def text_pool(size, seed):
436 """`size` bytes of text lines that look like data, always the same."""
437 rng = SplitMix64(seed)
438 lines = []
439 total = 0
440 while total < size:
441 line = f"{rng.next():016x} {rng.next() % 100_000:05d} {rng.next():016x}\n"
442 lines.append(line)
443 total += len(line)
444 return "".join(lines).encode()[:size]
445
446
447def tree_path(index):
448 """Where file `index` of the large tree lives: 25 files per directory,
449 three levels of directories under src/."""
450 leaf, number = divmod(index, FILES_PER_DIR)
451 return (
452 f"src/m{leaf // 400:02d}/p{leaf // 20 % 20:02d}/"
453 f"l{leaf % 20:02d}/f{number:02d}.txt"
454 )
455
456
457def tree_files(count):
458 """The large tree: `count` text files of 100 to 3,000 bytes, the same
459 bytes on every run."""
460 pool = text_pool(1 << 20, seed=1)
461 rng = SplitMix64(seed=2)
462 for index in range(count):
463 size = 100 + rng.next() % 2_900
464 offset = rng.next() % (len(pool) - size)
465 header = f"file {index}\n".encode()
466 yield tree_path(index), header + pool[offset : offset + size]
467
468
469def wide_path(index):
470 return f"wide/f{index:05d}.txt"
471
472
473def wide_content(index):
474 return f"wide file {index}\n".encode()
475
476
477def wide_files(count):
478 yield "README.md", b"A single wide directory.\n"
479 for index in range(count):
480 yield wide_path(index), wide_content(index)
481
482
483def agent_file(index):
484 return f"agents/agent-{index:02d}.txt"
485
486
487def agents_files(count):
488 yield "README.md", b"Agents landing at once.\n"
489 for index in range(1, count + 1):
490 yield agent_file(index), f"agent {index}\n".encode()
491
492
493def append(path, data):
494 with open(path, "ab") as file:
495 file.write(data)
496
497
498# ---------------------------------------------------------------------------
499# Repositories
500
501
502def configure_git(tools, repo):
503 """Settings of every git repository the benchmark makes: no automatic
504 maintenance or garbage collection that could land in a measurement,
505 and no file system monitor or untracked cache unless a case asks."""
506 for key, value in (
507 ("gc.auto", "0"),
508 ("maintenance.auto", "false"),
509 ("receive.autogc", "false"),
510 ("core.fsmonitor", "false"),
511 ("core.untrackedCache", "false"),
512 ):
513 tools.git_run(repo, "config", key, value)
514
515
516def git_seed(tools, repo, files, bare=False):
517 """Makes a git repository whose main branch has one commit with these
518 files, written with git fast-import, and checks it out unless bare."""
519 repo.parent.mkdir(parents=True, exist_ok=True)
520 tools.git_run(
521 repo.parent, "init", "-q", "-b", "main", *(["--bare"] if bare else []), repo
522 )
523 configure_git(tools, repo)
524 with tempfile.TemporaryFile() as errors:
525 proc = subprocess.Popen(
526 [tools.git, "fast-import", "--quiet", "--done"],
527 cwd=repo,
528 env=tools.env,
529 stdin=subprocess.PIPE,
530 stdout=subprocess.DEVNULL,
531 stderr=errors,
532 )
533 try:
534 stream = proc.stdin
535 marks = []
536 for mark, (path, data) in enumerate(files, start=1):
537 stream.write(b"blob\nmark :%d\ndata %d\n" % (mark, len(data)))
538 stream.write(data)
539 stream.write(b"\n")
540 marks.append((path, mark))
541 message = b"Seed"
542 stream.write(b"commit refs/heads/main\n")
543 for who in (b"author", b"committer"):
544 stream.write(
545 b"%s %s <%s> %s\n"
546 % (who, NAME.encode(), EMAIL.encode(), SEED_DATE.encode())
547 )
548 stream.write(b"data %d\n%s\n" % (len(message), message))
549 for path, mark in marks:
550 stream.write(b"M 100644 :%d %s\n" % (mark, path.encode()))
551 stream.write(b"done\n")
552 stream.close()
553 except BrokenPipeError:
554 pass
555 if proc.wait() != 0:
556 errors.seek(0)
557 raise Failure("git fast-import failed: " + errors.read().decode()[-800:])
558 if not bare:
559 tools.git_run(repo, "reset", "-q", "--hard")
560
561
562def braid_from_git(tools, repo, git_repo, workspace=None, name="ws"):
563 """A braid repository that imported `git_repo`, with a workspace on main
564 when one is asked for."""
565 tools.braid_run(repo.parent, "init", repo)
566 tools.braid_run(repo, "git", "import", git_repo)
567 if workspace is not None:
568 tools.braid_run(repo, "workspace", "add", name, workspace)
569
570
571def disk_usage(path):
572 """Bytes `du` counts for `path`, and the sum of the sizes of its files."""
573 out = subprocess.run(
574 ["du", "-sk", str(path)], capture_output=True, check=True, text=True
575 ).stdout
576 blocks = int(out.split()[0]) * 1024
577 apparent = 0
578 for parent, _dirs, names in os.walk(path):
579 for name in names:
580 try:
581 apparent += os.lstat(os.path.join(parent, name)).st_size
582 except FileNotFoundError:
583 pass
584 return blocks, apparent
585
586
587def remove(*paths):
588 for path in paths:
589 shutil.rmtree(path, ignore_errors=True)
590
591
592def count_files(root):
593 """Files and symlinks under `root`, never following a symlink."""
594 count = 0
595 pending = [root]
596 while pending:
597 with os.scandir(pending.pop()) as entries:
598 for entry in entries:
599 if entry.is_dir(follow_symlinks=False):
600 pending.append(entry.path)
601 else:
602 count += 1
603 return count
604
605
606# ---------------------------------------------------------------------------
607# What the scenarios share
608
609
610class LargeTree:
611 """The large tree, checked out by git and by braid: a git repository
612 with its working tree, and a braid repository with one workspace."""
613
614 def __init__(self, ctx):
615 count = ctx.settings["tree_files"]
616 base = ctx.work / "tree"
617 self.git = base / "git"
618 self.repo = base / "braid"
619 self.ws = base / "braid-ws"
620 self.count = count
621 ctx.log(f"writing a tree of {count} files with git, then importing it into braid")
622 git_seed(ctx.tools, self.git, tree_files(count))
623 braid_from_git(ctx.tools, self.repo, self.git, self.ws)
624 self.base = base
625
626 def both(self, path):
627 return self.git / path, self.ws / path
628
629
630class Context:
631 """What the scenarios share: the tools, the settings, the work directory,
632 and inputs made once."""
633
634 def __init__(self, tools, settings, work, source, keep):
635 self.tools = tools
636 self.settings = settings
637 self.work = work
638 self.source_spec = source
639 self.keep = keep
640 self.extra = {}
641 self._source = None
642 self._imported = None
643 self._gc = False
644 self._tree = None
645
646 def log(self, message):
647 print(f" {message}", file=sys.stderr, flush=True)
648
649 def source(self):
650 """The git repository to import, as a bare repository with one
651 branch, main, at the pinned commit: fetched once."""
652 if self._source is None:
653 spec = self.source_spec
654 path = self.work / "source.git"
655 self.log(f"fetching {spec['name']} once, as the local source")
656 self.tools.git_run(self.work, "init", "-q", "--bare", "-b", "main", path)
657 configure_git(self.tools, path)
658 self.tools.git_run(
659 path, "fetch", "-q", "--no-tags", spec["url"], f"+{spec['ref']}:refs/bench/pinned"
660 )
661 commit = self.tools.git_run(
662 path, "rev-parse", "refs/bench/pinned^{commit}", capture=True
663 ).text().strip()
664 if spec.get("commit") and commit != spec["commit"]:
665 raise Failure(f"{spec['name']} is at {commit}, not the pinned {spec['commit']}")
666 self.tools.git_run(path, "update-ref", "refs/heads/main", commit)
667 self.tools.git_run(path, "update-ref", "-d", "refs/bench/pinned")
668 self.tools.git_run(path, "symbolic-ref", "HEAD", "refs/heads/main")
669 commits = int(
670 self.tools.git_run(path, "rev-list", "--count", "main", capture=True).text()
671 )
672 # Files and symlinks: a checkout writes a gitlink as a directory.
673 entries = self.tools.git_run(path, "ls-tree", "-r", "main", capture=True).lines()
674 files = sum(1 for entry in entries if entry.split()[1] == "blob")
675 self.extra["source"] = {
676 "name": spec["name"],
677 "commit": commit,
678 "commits": commits,
679 "files": files,
680 }
681 self._source = path
682 return self._source
683
684 def imported(self):
685 """A braid repository that imported the source, and a bare git clone
686 of it: the ones the import scenario made, or new ones."""
687 if self._imported is None:
688 source = self.source()
689 braid_repo = self.work / "imported-braid"
690 git_repo = self.work / "imported-git.git"
691 self.log("importing the source once with braid, cloning it once with git")
692 braid_from_git(self.tools, braid_repo, source)
693 self.tools.git_run(
694 self.work, "clone", "-q", "--no-local", "--bare", source, git_repo
695 )
696 configure_git(self.tools, git_repo)
697 self._imported = (braid_repo, git_repo)
698 return self._imported
699
700 def gc_git(self):
701 """`git gc --aggressive` on the bare clone, once."""
702 _braid_repo, git_repo = self.imported()
703 if not self._gc:
704 self.extra.setdefault("store", {})["git_as_cloned"] = disk_usage(git_repo)
705 self.log("git gc --aggressive on the clone")
706 self.tools.git_run(git_repo, "gc", "-q", "--aggressive", "--prune=now")
707 self._gc = True
708 return git_repo
709
710 def tree(self):
711 if self._tree is None:
712 self._tree = LargeTree(self)
713 return self._tree
714
715 def drop(self, remaining):
716 """Removes inputs that no scenario still to run needs."""
717 if self.keep:
718 return
719 if self._tree is not None and not {"status", "commit"} & remaining:
720 remove(self._tree.base)
721 self._tree = None
722 if self._imported is not None and not {"store", "history"} & remaining:
723 remove(*self._imported)
724 self._imported = None
725 self._gc = False
726 if self._source is not None and not {"import", "store", "history"} & remaining:
727 remove(self._source)
728 self._source = None
729
730
731# ---------------------------------------------------------------------------
732# 1. Import
733
734
735def scenario_import(ctx):
736 tools = ctx.tools
737 source = ctx.source()
738 info = ctx.extra["source"]
739 rounds = ctx.settings["import_rounds"]
740 work = ctx.work
741 out = {"braid": [], "braid-checkout": [], "git-bare": [], "git-full": []}
742 kept = None
743 for index in range(rounds):
744 made = {}
745 GATE.wait()
746 for who in round_order(["braid", "git-bare", "git-full"], index):
747 ctx.log(f"import round {index + 1}/{rounds}: {who}")
748 if who == "braid":
749 repo = work / f"import-{index}-braid"
750 ws = work / f"import-{index}-braid-ws"
751 init = tools.braid_run(work, "init", repo)
752 imported = tools.braid_run(repo, "git", "import", source, "--json", capture=True)
753 checkout = tools.braid_run(repo, "workspace", "add", "ws", ws)
754 if imported.json()["commits"] != info["commits"]:
755 raise Failure(
756 f"braid imported {imported.json()['commits']} commits, "
757 f"git has {info['commits']}"
758 )
759 out["braid"].append(init + imported)
760 out["braid-checkout"].append(init + imported + checkout)
761 made["braid"] = (repo, ws)
762 elif who == "git-bare":
763 target = work / f"import-{index}-git.git"
764 out["git-bare"].append(
765 tools.git_run(work, "clone", "-q", "--no-local", "--bare", source, target)
766 )
767 made["git-bare"] = target
768 else:
769 target = work / f"import-{index}-git"
770 out["git-full"].append(
771 tools.git_run(work, "clone", "-q", "--no-local", source, target)
772 )
773 made["git-full"] = target
774 repo, ws = made["braid"]
775 if index == 0:
776 fsck = tools.braid_run(repo, "fsck", "--json", capture=True).json()
777 if not fsck["clean"]:
778 raise Failure(f"braid fsck after the import: {fsck['problems'][:3]}")
779 files = count_files(ws) - 1 # less the workspace's .braid file
780 if files != info["files"]:
781 raise Failure(f"the workspace has {files} files, git's tree {info['files']}")
782 configure_git(tools, made["git-bare"])
783 kept = (repo, made["git-bare"])
784 remove(ws, made["git-full"])
785 else:
786 remove(repo, ws, made["git-bare"], made["git-full"])
787 # The first round's repositories serve the store and history scenarios.
788 if ctx._imported is None:
789 ctx._imported = kept
790 elif kept is not None:
791 remove(*kept)
792 name = f"{info['name']}, {info['commits']:,} commits"
793 return [
794 Row(
795 "import",
796 "history only",
797 f"Import {name}: `braid init` + `braid git import` vs "
798 "`git clone --no-local --bare`",
799 out["braid"],
800 out["git-bare"],
801 ),
802 Row(
803 "import",
804 "history and a working copy",
805 f"Import {name} and check it out: `braid init` + `braid git import` + "
806 "`braid workspace add` vs `git clone --no-local`",
807 out["braid-checkout"],
808 out["git-full"],
809 ),
810 ]
811
812
813# ---------------------------------------------------------------------------
814# 2. Status
815
816
817def check_status(tools, tree, modified):
818 """Both tools must see the same thing: a clean tree, or exactly the
819 modified files."""
820 braid = tools.braid_run(tree.ws, "status", "--json", capture=True).json()
821 git = tools.git_run(tree.git, "status", "--porcelain", capture=True).lines()
822 want = sorted(modified)
823 if sorted(braid["modified"]) != want or braid["added"] or braid["deleted"]:
824 raise Failure(f"braid status does not list exactly the {len(want)} modified files")
825 if sorted(line[3:] for line in git) != want or any(line[:2] != " M" for line in git):
826 raise Failure(f"git status does not list exactly the {len(want)} modified files")
827
828
829def scenario_status(ctx):
830 tools = ctx.tools
831 tree = ctx.tree()
832 count = tree.count
833 rounds = ctx.settings["status_rounds"]
834 warmup = ctx.settings["warmup"]
835 rows = []
836 # Modified files, spread over the tree.
837 many = ctx.settings["modified"]
838 changed = [tree_path((k * count // many + 7) % count) for k in range(many)]
839 originals = {}
840 for case in ("clean", "modified"):
841 if case == "modified":
842 for path in changed:
843 for full in tree.both(path):
844 originals[full] = full.read_bytes()
845 append(full, b"modified\n")
846 modified = changed if case == "modified" else []
847 check_status(tools, tree, modified)
848 label = "clean" if case == "clean" else f"{len(changed)} files modified"
849 for untracked_cache in (False, True):
850 tools.git_run(tree.git, "config", "core.untrackedCache", str(untracked_cache).lower())
851 setting = "untracked cache on" if untracked_cache else "no untracked cache"
852 ctx.log(f"status, {label}, git with {setting}")
853 runs = alternate(
854 rounds,
855 {
856 "braid": lambda _r: tools.braid_run(tree.ws, "status"),
857 "git": lambda _r: tools.git_run(tree.git, "status"),
858 },
859 warmup=warmup,
860 )
861 git_text = (
862 "`git status` with `core.untrackedCache=true`"
863 if untracked_cache
864 else "`git status` with no untracked cache"
865 )
866 rows.append(
867 Row(
868 "status",
869 f"{label}, git {setting}",
870 f"Status of {count:,} files, {label}: `braid status` vs {git_text} "
871 "and no fsmonitor",
872 runs["braid"],
873 runs["git"],
874 )
875 )
876 if case == "modified":
877 for full, data in originals.items():
878 full.write_bytes(data)
879 check_status(tools, tree, [])
880 tools.git_run(tree.git, "config", "core.untrackedCache", "false")
881 return rows
882
883
884# ---------------------------------------------------------------------------
885# 3. Commit
886
887
888def scenario_commit(ctx):
889 tools = ctx.tools
890 tree = ctx.tree()
891 count = tree.count
892 rounds = ctx.settings["commit_rounds"]
893 warmup = ctx.settings["warmup"]
894 check_status(tools, tree, [])
895 before = int(tools.git_run(tree.git, "rev-list", "--count", "main", capture=True).text())
896 ctx.log(f"commit one changed file of {count}, {rounds} rounds")
897 picked = {}
898
899 def pick(index):
900 if index not in picked:
901 path = tree_path((len(picked) * 7_919 + 4_242) % count)
902 picked[index] = path
903 for full in tree.both(path):
904 append(full, f"edit {index}\n".encode())
905 return picked[index]
906
907 def braid(index):
908 pick(index)
909 run = tools.braid_run(tree.ws, "commit", "-m", f"Edit {index}", "--json", capture=True)
910 if run.json()["changes"] != 1:
911 raise Failure("braid commit did not record exactly one path")
912 return run
913
914 def git(index):
915 path = pick(index)
916 return tools.git_run(tree.git, "add", path) + tools.git_run(
917 tree.git, "commit", "-q", "-m", f"Edit {index}"
918 )
919
920 runs = alternate(rounds, {"braid": braid, "git": git}, warmup=warmup)
921 after = int(tools.git_run(tree.git, "rev-list", "--count", "main", capture=True).text())
922 if after - before != rounds + warmup:
923 raise Failure(f"git made {after - before} commits, not {rounds + warmup}")
924 check_status(tools, tree, [])
925 return [
926 Row(
927 "commit",
928 f"one changed file of {count:,}",
929 f"Commit one changed file in a tree of {count:,} files: `braid commit` vs "
930 "`git add` + `git commit`",
931 runs["braid"],
932 runs["git"],
933 )
934 ]
935
936
937# ---------------------------------------------------------------------------
938# 4. Wide directory
939
940
941def wide_series(ctx, size, commits, warmup):
942 """Appends one new file to a directory of `size` files and commits it,
943 `commits` times, with git (add and commit), with a braid workspace
944 (commit), and without a working copy (change create --land). Returns
945 the timed Runs of each, in order."""
946 tools = ctx.tools
947 base = ctx.work / f"wide-{size}"
948 git_repo = base / "git"
949 ws_repo = base / "braid"
950 ws = base / "braid-ws"
951 change_repo = base / "braid-change"
952 scratch = base / "new-file"
953 ctx.log(f"wide directory of {size} files: {commits} commits each")
954 git_seed(tools, git_repo, wide_files(size))
955 braid_from_git(tools, ws_repo, git_repo, ws)
956 braid_from_git(tools, change_repo, git_repo)
957 # One new file per round, written when the round's first contestant
958 # starts: every contestant commits the same file in that round.
959 written = {}
960
961 def write(index):
962 if index not in written:
963 number = size + len(written)
964 path = wide_path(number)
965 data = wide_content(number)
966 (git_repo / path).write_bytes(data)
967 (ws / path).write_bytes(data)
968 scratch.write_bytes(data)
969 written[index] = path
970 return written[index]
971
972 def braid_commit(index):
973 write(index)
974 run = tools.braid_run(ws, "commit", "-m", f"Add file {index}", "--json", capture=True)
975 if run.json()["changes"] != 1:
976 raise Failure("braid commit did not record exactly one path")
977 return run
978
979 def braid_change(index):
980 path = write(index)
981 run = tools.braid_run(
982 change_repo,
983 "change",
984 "create",
985 "--base",
986 "main",
987 "--set",
988 f"{path}=@{scratch}",
989 "-m",
990 f"Add file {index}",
991 "--land",
992 "main",
993 capture=True,
994 )
995 if run.json()["land"]["outcome"] != "fast-forward":
996 raise Failure("braid change create --land did not fast-forward")
997 return run
998
999 def git(index):
1000 path = write(index)
1001 return tools.git_run(git_repo, "add", path) + tools.git_run(
1002 git_repo, "commit", "-q", "-m", f"Add file {index}"
1003 )
1004
1005 contestants = {"braid-commit": braid_commit, "git": git, "braid-change": braid_change}
1006 runs = alternate(commits, contestants, warmup=warmup)
1007 total = commits + warmup
1008 made = int(tools.git_run(git_repo, "rev-list", "--count", "main", capture=True).text()) - 1
1009 landed = len(tools.braid_run(change_repo, "log", "main", "-n", ALL, capture=True).lines()) - 1
1010 unlanded = len(tools.braid_run(ws, "status", "--json", capture=True).json()["unlanded"])
1011 if (made, landed, unlanded) != (total, total, total):
1012 raise Failure(
1013 f"expected {total} commits each; git made {made}, change create landed "
1014 f"{landed}, the workspace has {unlanded}"
1015 )
1016 if not ctx.keep:
1017 remove(base)
1018 return runs
1019
1020
1021def median_of(runs):
1022 return statistics.median(run.wall for run in runs)
1023
1024
1025def trend(runs):
1026 """How much slower the last quarter of a series is than the first, from
1027 the medians of each: 0.1 means 10% slower."""
1028 quarter = max(1, len(runs) // 4)
1029 first = median_of(runs[:quarter])
1030 last = median_of(runs[-quarter:])
1031 return last / first - 1 if first else None
1032
1033
1034def exponent(sizes, costs):
1035 """The slope of log(cost) against log(size), by least squares: 0 when the
1036 cost does not grow with the directory, 1 when it grows in proportion."""
1037 xs = [math.log(size) for size in sizes]
1038 ys = [math.log(cost) for cost in costs]
1039 mean_x = sum(xs) / len(xs)
1040 mean_y = sum(ys) / len(ys)
1041 den = sum((x - mean_x) ** 2 for x in xs)
1042 return sum((x - mean_x) * (y - mean_y) for x, y in zip(xs, ys)) / den if den else None
1043
1044
1045def scenario_wide(ctx):
1046 settings = ctx.settings
1047 size = settings["wide_files"]
1048 commits = settings["wide_commits"]
1049 warmup = settings["warmup"]
1050 main = wide_series(ctx, size, commits, warmup)
1051 rows = [
1052 Row(
1053 "wide",
1054 f"new file in {size:,}: braid commit",
1055 f"One new file per commit in a directory of {size:,} files, {commits} times: "
1056 "`braid commit` vs `git add` + `git commit`",
1057 main["braid-commit"],
1058 main["git"],
1059 ),
1060 Row(
1061 "wide",
1062 f"new file in {size:,}: change create --land",
1063 f"The same, without a working copy: `braid change create --land` vs "
1064 "`git add` + `git commit`",
1065 main["braid-change"],
1066 main["git"],
1067 ),
1068 ]
1069
1070 # Does the cost of one commit grow with the directory? The same series,
1071 # shorter, on smaller directories, against the start of the main one.
1072 sweep_commits = settings["wide_sweep_commits"]
1073 sizes = list(settings["wide_sweep"]) + [size]
1074 medians = {name: [] for name in main}
1075 for sweep_size in settings["wide_sweep"]:
1076 series = wide_series(ctx, sweep_size, sweep_commits, warmup)
1077 for name in medians:
1078 medians[name].append(median_of(series[name]))
1079 for name in medians:
1080 medians[name].append(median_of(main[name][:sweep_commits]))
1081 growth = {name: medians[name][-1] / medians[name][0] for name in medians}
1082 slopes = {name: exponent(sizes, medians[name]) for name in medians}
1083 drift = {name: trend(main[name]) for name in main}
1084 ctx.extra["wide"] = {
1085 "sizes": sizes,
1086 "median_seconds_by_size": medians,
1087 "growth": growth,
1088 "exponent": slopes,
1089 "trend_over_main_series": drift,
1090 }
1091 labels = {"git": "git", "braid-commit": "braid commit", "braid-change": "change create"}
1092 note = ", ".join(f"{labels[name]} x{growth[name]:.2f}" for name in labels)
1093 rows.append(
1094 Row(
1095 "wide",
1096 f"growth from {sizes[0]:,} to {size:,} files",
1097 f"Cost of one commit in a directory of {size:,} files divided by its cost "
1098 f"in one of {sizes[0]:,}",
1099 kind="info",
1100 note=note,
1101 extra={"growth": growth, "exponent": slopes},
1102 )
1103 )
1104 note = ", ".join(f"{labels[name]} {drift[name]:+.0%}" for name in labels)
1105 rows.append(
1106 Row(
1107 "wide",
1108 f"drift over the {commits} commits",
1109 f"Last quarter of the {commits} commits against the first",
1110 kind="info",
1111 note=note,
1112 extra={"trend": drift},
1113 )
1114 )
1115 return rows
1116
1117
1118# ---------------------------------------------------------------------------
1119# 5. Agents
1120
1121
1122def run_agents(count, agent):
1123 """Runs `agent(i)` for i in 1..count on as many threads, released at
1124 once. Returns the wall time until the last one finished."""
1125 barrier = threading.Barrier(count + 1)
1126 errors = []
1127
1128 def body(index):
1129 try:
1130 barrier.wait(timeout=600)
1131 agent(index)
1132 except BaseException as err: # reported below, from the main thread
1133 errors.append(err)
1134
1135 threads = [threading.Thread(target=body, args=(i,)) for i in range(1, count + 1)]
1136 GATE.wait()
1137 for thread in threads:
1138 thread.start()
1139 barrier.wait(timeout=600)
1140 start = time.perf_counter()
1141 for thread in threads:
1142 thread.join()
1143 wall = time.perf_counter() - start
1144 if errors:
1145 raise errors[0]
1146 return wall
1147
1148
1149def braid_agents(ctx, base, count, commits):
1150 tools = ctx.tools
1151 seed = base / "seed"
1152 repo = base / "braid"
1153 git_seed(tools, seed, agents_files(count))
1154 braid_from_git(tools, repo, seed)
1155 for index in range(1, count + 1):
1156 tools.braid_run(repo, "workspace", "add", f"agent-{index:02d}", base / f"ws-{index:02d}")
1157 outcomes = {}
1158 lock = threading.Lock()
1159
1160 def agent(index):
1161 ws = base / f"ws-{index:02d}"
1162 env = dict(
1163 tools.env,
1164 BRAID_AGENT=f"agent-{index:02d}",
1165 BRAID_AUTHOR=f"Agent {index} <agent-{index:02d}@example.org>",
1166 )
1167 for change in range(commits):
1168 append(ws / agent_file(index), f"agent {index} change {change}\n".encode())
1169 tools.braid_run(ws, "commit", "-m", f"Agent {index}, change {change}", env=env)
1170 landed = tools.braid_run(ws, "land", "--json", env=env, capture=True)
1171 outcome = landed.json()["outcome"]
1172 with lock:
1173 outcomes[outcome] = outcomes.get(outcome, 0) + 1
1174
1175 wall = run_agents(count, agent)
1176 total = 1 + count * commits
1177 landed = len(tools.braid_run(repo, "log", "main", "-n", ALL, capture=True).lines())
1178 if landed != total:
1179 raise Failure(f"main has {landed} changesets after the agents, not {total}")
1180 check = base / "check"
1181 tools.braid_run(repo, "workspace", "add", "check", check)
1182 for index in range(1, count + 1):
1183 lines = (check / agent_file(index)).read_text().splitlines()
1184 if len(lines) != 1 + commits:
1185 raise Failure(f"agent {index}'s file has {len(lines)} lines on main")
1186 return Run(wall, None), outcomes
1187
1188
1189def git_agents(ctx, base, count, commits):
1190 tools = ctx.tools
1191 seed = base / "seed"
1192 hub = base / "hub.git"
1193 git_seed(tools, seed, agents_files(count))
1194 tools.git_run(base, "clone", "-q", "--bare", seed, hub)
1195 configure_git(tools, hub)
1196 for index in range(1, count + 1):
1197 clone = base / f"clone-{index:02d}"
1198 tools.git_run(base, "clone", "-q", hub, clone)
1199 configure_git(tools, clone)
1200 retries = []
1201 lock = threading.Lock()
1202
1203 def agent(index):
1204 clone = base / f"clone-{index:02d}"
1205 mine = 0
1206 for change in range(commits):
1207 append(clone / agent_file(index), f"agent {index} change {change}\n".encode())
1208 tools.git_run(clone, "commit", "-q", "-a", "-m", f"Agent {index}, change {change}")
1209 while tools.git_run(clone, "push", "-q", "origin", "main", check=False).code != 0:
1210 mine += 1
1211 if mine > 1_000 * commits:
1212 raise Failure(f"agent {index} could not push")
1213 tools.git_run(clone, "pull", "-q", "--rebase", "origin", "main")
1214 with lock:
1215 retries.append(mine)
1216
1217 wall = run_agents(count, agent)
1218 total = 1 + count * commits
1219 landed = int(tools.git_run(hub, "rev-list", "--count", "main", capture=True).text())
1220 if landed != total:
1221 raise Failure(f"the hub's main has {landed} commits after the agents, not {total}")
1222 for index in range(1, count + 1):
1223 text = tools.git_run(hub, "show", f"main:{agent_file(index)}", capture=True).text()
1224 if len(text.splitlines()) != 1 + commits:
1225 raise Failure(f"agent {index}'s file is wrong on the hub's main")
1226 return Run(wall, None), sum(retries)
1227
1228
1229def scenario_agents(ctx):
1230 settings = ctx.settings
1231 commits = settings["agent_commits"]
1232 rounds = settings["agent_rounds"]
1233 rows = []
1234 for count in settings["agents"]:
1235 walls = {"braid": [], "git": []}
1236 retries = []
1237 outcomes = {}
1238 for index in range(rounds):
1239 for who in round_order(["braid", "git"], index):
1240 ctx.log(f"{count} agents, round {index + 1}/{rounds}: {who}")
1241 base = ctx.work / f"agents-{count}-{index}-{who}"
1242 if who == "braid":
1243 run, landed = braid_agents(ctx, base, count, commits)
1244 for outcome, number in landed.items():
1245 outcomes[outcome] = outcomes.get(outcome, 0) + number
1246 else:
1247 run, retried = git_agents(ctx, base, count, commits)
1248 retries.append(retried)
1249 walls[who].append(run)
1250 if not ctx.keep:
1251 remove(base)
1252 pushes = count * commits
1253 per_push = statistics.median(retries) / pushes
1254 rebased = outcomes.get("rebased", 0) / max(1, sum(outcomes.values()))
1255 rows.append(
1256 Row(
1257 "agents",
1258 f"{count} agents x {commits} commits",
1259 f"{count} agents land {commits} commits each, at once: `braid commit` + "
1260 "`braid land` in a workspace each, vs `git commit` + `git push` from a "
1261 "clone each, with `git pull --rebase` and a new push when rejected",
1262 walls["braid"],
1263 walls["git"],
1264 note=f"git retried {per_push:.2f} times per push; "
1265 f"braid rebased {rebased:.0%} of its landings, retrying none",
1266 extra={
1267 "git_retries_per_round": retries,
1268 "git_retries_per_push": per_push,
1269 "braid_land_outcomes": outcomes,
1270 },
1271 )
1272 )
1273 return rows
1274
1275
1276# ---------------------------------------------------------------------------
1277# 6. Store size
1278
1279
1280def scenario_store(ctx):
1281 braid_repo, _ = ctx.imported()
1282 git_repo = ctx.gc_git()
1283 info = ctx.extra["source"]
1284 braid_blocks, braid_bytes = disk_usage(braid_repo / ".braid" / "store")
1285 git_blocks, git_bytes = disk_usage(git_repo)
1286 store = ctx.extra.setdefault("store", {})
1287 store.update(
1288 {
1289 "braid_store": [braid_blocks, braid_bytes],
1290 "git_after_gc_aggressive": [git_blocks, git_bytes],
1291 }
1292 )
1293 return [
1294 Row(
1295 "store",
1296 "after the import",
1297 f"Size of {info['name']}: `du` of `.braid/store` after `braid git import` vs "
1298 "the bare clone after `git gc --aggressive`",
1299 [braid_blocks],
1300 [git_blocks],
1301 kind="size",
1302 note=f"file sizes alone: {braid_bytes / git_bytes:.2f}",
1303 )
1304 ]
1305
1306
1307# ---------------------------------------------------------------------------
1308# 7. History
1309
1310
1311def unsupported(run):
1312 """Whether braid refused the command line itself: a subcommand or an
1313 argument it does not have yet."""
1314 err = run.err.decode("utf-8", "replace")
1315 return run.code == 2 and (
1316 "unrecognized subcommand" in err or "unexpected argument" in err
1317 )
1318
1319
1320def pick_paths(tools, git_repo):
1321 """The file of main that most first-parent commits changed, and one that
1322 only one of them touched, with how many changed each file."""
1323 present = set(
1324 tools.git_run(git_repo, "ls-tree", "-r", "--name-only", "main", capture=True).lines()
1325 )
1326 counts = {}
1327 names = tools.git_run(
1328 git_repo, "log", "--first-parent", "--format=", "--name-only", "main", capture=True
1329 ).lines()
1330 for name in names:
1331 if name in present:
1332 counts[name] = counts.get(name, 0) + 1
1333 hot = min(counts, key=lambda name: (-counts[name], name))
1334 cold = min(counts, key=lambda name: (counts[name], name))
1335 return hot, cold, counts
1336
1337
1338def with_json(args):
1339 """Braid arguments with --json, before any `--`."""
1340 if "--" in args:
1341 at = args.index("--")
1342 return [*args[:at], "--json", *args[at:]]
1343 return [*args, "--json"]
1344
1345
1346def scenario_history(ctx):
1347 tools = ctx.tools
1348 braid_repo, _ = ctx.imported()
1349 git_repo = ctx.gc_git()
1350 info = ctx.extra["source"]
1351 rounds = ctx.settings["history_rounds"]
1352 warmup = ctx.settings["warmup"]
1353 hot, cold, counts = pick_paths(tools, git_repo)
1354 ctx.extra["history"] = {"hot": [hot, counts[hot]], "cold": [cold, counts[cold]]}
1355 name = info["name"]
1356 # Braid follows first parents, so git does too: both list the same
1357 # changesets. The last item is what git lists, to check braid against.
1358 queries = [
1359 (
1360 "log -n 1000",
1361 f"Newest 1000 changesets of {name}: `braid log -n 1000` vs "
1362 "`git log --first-parent -n 1000 --format=%H`",
1363 ["log", "main", "-n", "1000"],
1364 ["log", "--first-parent", "-n", "1000", "--format=%H", "main"],
1365 ["log", "--first-parent", "-n", "1000", "--format=%H", "main"],
1366 ),
1367 (
1368 "log -- the most changed file",
1369 f"History of the file most changed in {name}: "
1370 "`braid log -- <path>` vs `git log --first-parent -- <path>`",
1371 ["log", "main", "-n", ALL, "--", hot],
1372 ["log", "--first-parent", "-n", ALL, "main", "--", hot],
1373 ["log", "--first-parent", "--format=%H", "main", "--", hot],
1374 ),
1375 (
1376 "log -- a file one commit touched",
1377 f"History of a file one commit touched in {name}: "
1378 "`braid log -- <path>` vs `git log --first-parent -- <path>`",
1379 ["log", "main", "-n", ALL, "--", cold],
1380 ["log", "--first-parent", "-n", ALL, "main", "--", cold],
1381 ["log", "--first-parent", "--format=%H", "main", "--", cold],
1382 ),
1383 (
1384 "blame the most changed file",
1385 f"Blame of the file most changed in {name}: `braid blame main <path>` vs "
1386 "`git blame --first-parent <path>`",
1387 ["blame", "main", hot],
1388 ["blame", "--first-parent", "main", "--", hot],
1389 None,
1390 ),
1391 ]
1392 rows = []
1393 for case, compared, braid_args, git_args, listing in queries:
1394 # A log query is checked through --json, one entry per changeset,
1395 # against git's list; blame only has to succeed, since its output
1396 # is braid's own.
1397 probe_args = with_json(braid_args) if listing else braid_args
1398 probe = tools.braid_run(braid_repo, *probe_args, check=False, capture=True)
1399 if unsupported(probe):
1400 reason = probe.err.decode("utf-8", "replace").strip().splitlines()[0]
1401 rows.append(Row("history", case, compared, skipped=f"not in braid yet ({reason})"))
1402 continue
1403 if probe.code != 0:
1404 raise Failure(f"braid {case}: {probe.err.decode('utf-8', 'replace')[-400:]}")
1405 if listing:
1406 expected = len(tools.git_run(git_repo, *listing, capture=True).lines())
1407 got = len(probe.json())
1408 if got != expected:
1409 raise Failure(f"braid {case}: {got} changesets, git lists {expected} commits")
1410 elif not probe.out.strip():
1411 raise Failure(f"braid {case} printed nothing")
1412 ctx.log(f"history: {case}")
1413 runs = alternate(
1414 rounds,
1415 {
1416 "braid": lambda _r, a=braid_args: tools.braid_run(braid_repo, *a),
1417 "git": lambda _r, a=git_args: tools.git_run(git_repo, *a),
1418 },
1419 warmup=warmup,
1420 )
1421 rows.append(Row("history", case, compared, runs["braid"], runs["git"]))
1422 return rows
1423
1424
1425RUNNERS = {
1426 "import": scenario_import,
1427 "status": scenario_status,
1428 "commit": scenario_commit,
1429 "wide": scenario_wide,
1430 "agents": scenario_agents,
1431 "store": scenario_store,
1432 "history": scenario_history,
1433}
1434
1435
1436# ---------------------------------------------------------------------------
1437# Main
1438
1439
1440def build_braid():
1441 """Builds braid in release mode and returns the binary's path."""
1442 print("building braid in release mode", file=sys.stderr, flush=True)
1443 subprocess.run(
1444 ["cargo", "build", "--release", "--locked", "-p", "elffuss-braid-cli"],
1445 cwd=ROOT,
1446 check=True,
1447 )
1448 meta = subprocess.run(
1449 ["cargo", "metadata", "--format-version", "1", "--no-deps"],
1450 cwd=ROOT,
1451 check=True,
1452 capture_output=True,
1453 )
1454 target = Path(json.loads(meta.stdout)["target_directory"])
1455 return target / "release" / ("braid.exe" if os.name == "nt" else "braid")
1456
1457
1458def describe_build(git):
1459 """Which braid was measured: the commit, and whether the tree differed."""
1460 def ask(*args):
1461 out = subprocess.run(
1462 [git, "-C", str(ROOT), *args],
1463 capture_output=True,
1464 text=True,
1465 env=clean_environment(),
1466 )
1467 return out.stdout.strip() if out.returncode == 0 else None
1468
1469 status = ask("status", "--porcelain", "--untracked-files=no")
1470 return {
1471 "commit": ask("rev-parse", "HEAD"),
1472 "modified": None if status is None else bool(status),
1473 }
1474
1475
1476def parse_args(argv):
1477 parser = argparse.ArgumentParser(
1478 description="Benchmarks braid against git on this machine and prints braid/git ratios.",
1479 )
1480 parser.add_argument("--quick", action="store_true", help="small inputs, for a smoke run")
1481 parser.add_argument(
1482 "--only",
1483 metavar="LIST",
1484 help="comma-separated scenarios to run (default: all): " + ", ".join(SCENARIOS),
1485 )
1486 parser.add_argument("--list", action="store_true", help="list the scenarios and exit")
1487 parser.add_argument("--rounds", type=int, metavar="N", help="rounds of every scenario")
1488 parser.add_argument(
1489 "--braid", type=Path, metavar="PATH", help="a braid binary to use instead of building one"
1490 )
1491 parser.add_argument(
1492 "--git", default="git", metavar="PATH", help="the git binary (default: git)"
1493 )
1494 parser.add_argument(
1495 "--source",
1496 metavar="URL_OR_PATH",
1497 help="the git repository to import, instead of the pinned one (or, with --quick, "
1498 "this repository's own history)",
1499 )
1500 parser.add_argument(
1501 "--source-ref", default="HEAD", metavar="REF", help="what to import from --source"
1502 )
1503 parser.add_argument(
1504 "--workdir",
1505 type=Path,
1506 metavar="DIR",
1507 help="where to make the inputs (default: a new temporary directory)",
1508 )
1509 parser.add_argument(
1510 "--keep", action="store_true", help="keep the inputs instead of removing them"
1511 )
1512 parser.add_argument(
1513 "--markdown", action="store_true", help="also print the table as Markdown, rounded"
1514 )
1515 parser.add_argument(
1516 "--max-load",
1517 type=float,
1518 metavar="N",
1519 help="before each timed round, wait until the load average of the last minute "
1520 "is below N (on a machine shared with other work)",
1521 )
1522 args = parser.parse_args(argv)
1523 if args.only:
1524 chosen = {name.strip() for name in args.only.split(",") if name.strip()}
1525 unknown = sorted(chosen - set(SCENARIOS))
1526 if unknown:
1527 parser.error(f"unknown scenarios: {', '.join(unknown)}")
1528 # Always in the same order, which is also the order inputs are
1529 # shared in.
1530 args.only = [name for name in SCENARIOS if name in chosen]
1531 else:
1532 args.only = list(SCENARIOS)
1533 return args
1534
1535
1536def main(argv=None):
1537 args = parse_args(argv)
1538 if args.list:
1539 for name, text in SCENARIOS.items():
1540 print(f"{name:<8} {text}")
1541 return 0
1542 mode = "quick" if args.quick else "full"
1543 settings = dict(QUICK if args.quick else FULL)
1544 if args.rounds:
1545 for key in settings:
1546 if key.endswith("_rounds"):
1547 settings[key] = args.rounds
1548 if args.source:
1549 source = {"url": args.source, "ref": args.source_ref, "commit": None, "name": "the source"}
1550 elif args.quick:
1551 source = {"url": str(ROOT), "ref": "HEAD", "commit": None, "name": "this repository"}
1552 else:
1553 source = dict(PINNED)
1554
1555 git = shutil.which(args.git)
1556 if git is None:
1557 print(f"bench: {args.git} not found", file=sys.stderr)
1558 return 1
1559 braid = args.braid.resolve() if args.braid else build_braid()
1560
1561 if args.workdir:
1562 args.workdir.mkdir(parents=True, exist_ok=True)
1563 work = Path(tempfile.mkdtemp(prefix="braid-bench-", dir=args.workdir))
1564 else:
1565 work = Path(tempfile.mkdtemp(prefix="braid-bench-"))
1566 work = work.resolve()
1567 free = shutil.disk_usage(work).free
1568 if free < NEEDED_SPACE[mode]:
1569 remove(work)
1570 print(
1571 f"bench: the work directory has {free >> 20} MiB free, and a {mode} run needs "
1572 f"{NEEDED_SPACE[mode] >> 20} MiB; pass --workdir elsewhere",
1573 file=sys.stderr,
1574 )
1575 return 1
1576
1577 GATE.limit = args.max_load
1578 tools = Tools(braid, git)
1579 ctx = Context(tools, settings, work, source, args.keep)
1580 started = datetime.datetime.now(datetime.timezone.utc)
1581 load_before = os.getloadavg() if hasattr(os, "getloadavg") else None
1582 rows = []
1583 errors = {}
1584 try:
1585 for position, name in enumerate(args.only):
1586 print(f"{name}: {SCENARIOS[name]}", file=sys.stderr, flush=True)
1587 try:
1588 rows.extend(RUNNERS[name](ctx))
1589 except Failure as err:
1590 print(f"bench: {name} failed: {err}", file=sys.stderr, flush=True)
1591 errors[name] = str(err)
1592 except Exception as err: # a bug here, or in braid's output
1593 traceback.print_exc()
1594 errors[name] = f"{type(err).__name__}: {err}"
1595 ctx.drop(set(args.only[position + 1 :]))
1596 finally:
1597 if not args.keep:
1598 remove(work)
1599 else:
1600 print(f"inputs kept in {work}", file=sys.stderr)
1601
1602 print_table(rows)
1603 if args.markdown:
1604 print_markdown(rows)
1605 for name, err in errors.items():
1606 print(f"FAILED {name}: {err}")
1607
1608 results = {
1609 "format": 1,
1610 "mode": mode,
1611 "started": started.isoformat(timespec="seconds"),
1612 "finished": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"),
1613 "scenarios": args.only,
1614 "settings": settings,
1615 "braid": describe_build(git),
1616 "git": subprocess.run(
1617 [git, "--version"], capture_output=True, text=True, env=tools.env
1618 ).stdout.strip(),
1619 "system": platform.system(),
1620 "cpus": os.cpu_count(),
1621 "load_before": load_before,
1622 "load_after": os.getloadavg() if hasattr(os, "getloadavg") else None,
1623 "max_load": GATE.limit,
1624 "seconds_waited_for_load": round(GATE.waited, 1),
1625 "rounds_run_above_max_load": GATE.gave_up,
1626 "rows": [row.to_json() for row in rows],
1627 "extra": ctx.extra,
1628 "errors": errors,
1629 }
1630 RESULTS.mkdir(parents=True, exist_ok=True)
1631 stamp = started.strftime("%Y%m%d-%H%M%S")
1632 path = RESULTS / f"{stamp}-{mode}.json"
1633 path.write_text(json.dumps(results, indent=2) + "\n")
1634 print(f"raw measurements: {path.relative_to(ROOT)}")
1635 return 1 if errors else 0
1636
1637
1638if __name__ == "__main__":
1639 sys.exit(main())